gitea-cli/gitea_cli.py

158 lines
5.5 KiB
Python
Executable File

#!/opt/homebrew/anaconda3/bin/python
import os
import sys
import click
import requests
import subprocess
class GiteaAPI:
def __init__(self, base_url, token):
self.base_url = base_url.rstrip('/')
self.token = token
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'token {token}',
'Content-Type': 'application/json',
})
def create_repository(self, name, description="", private=False):
"""Create a new repository on Gitea."""
endpoint = f"{self.base_url}/api/v1/user/repos"
data = {
"name": name,
"description": description,
"private": private,
"auto_init": True
}
response = self.session.post(endpoint, json=data)
if response.status_code == 201:
return response.json()
else:
response.raise_for_status()
def get_gitea_config(url=None, token=None):
"""Get Gitea configuration from environment or command line arguments."""
config = {
'url': url or os.environ.get('GITEA_URL'),
'token': token or os.environ.get('GITEA_TOKEN')
}
missing = []
if not config['url']:
missing.append('GITEA_URL')
if not config['token']:
missing.append('GITEA_TOKEN')
if missing:
missing_str = ', '.join(missing)
click.echo(f"Error: Missing required configuration: {missing_str}")
click.echo("Please either:")
click.echo("1. Set environment variables for the missing values")
click.echo("2. Provide them as command line arguments:")
click.echo(" --gitea-url URL --gitea-token TOKEN")
sys.exit(1)
return config
def is_git_repository():
"""Check if current directory is a git repository."""
try:
subprocess.run(['git', 'rev-parse', '--git-dir'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True)
return True
except subprocess.CalledProcessError:
return False
def set_git_remote(repo_url):
"""Set or update the git remote 'origin' for the current repository."""
try:
# Check if remote exists
result = subprocess.run(['git', 'remote'],
stdout=subprocess.PIPE,
text=True,
check=True)
if 'origin' in result.stdout.split():
# Remove existing origin
subprocess.run(['git', 'remote', 'remove', 'origin'],
check=True)
# Add new origin
subprocess.run(['git', 'remote', 'add', 'origin', repo_url],
check=True)
click.echo(f"Successfully set remote 'origin' to: {repo_url}")
return True
except subprocess.CalledProcessError as e:
click.echo(f"Error setting git remote: {str(e)}")
return False
@click.group()
def cli():
"""Gitea CLI - Command line interface for Gitea
Configuration can be provided in two ways:
1. Environment variables:
- GITEA_URL: Your Gitea server URL
- GITEA_TOKEN: Your Gitea API token
2. Command line arguments:
--gitea-url and --gitea-token
(These override environment variables if both are present)
"""
pass
@cli.command()
@click.option('--name', required=True, help='Name of the repository')
@click.option('--description', default="", help='Repository description')
@click.option('--private', is_flag=True, default=False, help='Make repository private')
@click.option('--set-remote', is_flag=True, default=False,
help='Set the remote origin for the current git repository')
@click.option('--gitea-url',
help='Gitea server URL (overrides GITEA_URL environment variable)')
@click.option('--gitea-token',
help='Gitea API token (overrides GITEA_TOKEN environment variable)')
def create_repo(name, description, private, set_remote, gitea_url, gitea_token):
"""Create a new repository on Gitea.
Examples:
Using environment variables:
$ export GITEA_URL=https://gitea.example.com
$ export GITEA_TOKEN=your_token
$ gitea_cli.py create-repo --name my-repo
Using command line arguments:
$ gitea_cli.py create-repo --gitea-url https://gitea.example.com --gitea-token your_token --name my-repo
Create private repo and set as remote:
$ gitea_cli.py create-repo --name my-repo --private --set-remote
"""
config = get_gitea_config(gitea_url, gitea_token)
try:
gitea = GiteaAPI(config['url'], config['token'])
repo = gitea.create_repository(name, description, private)
click.echo(f"Successfully created repository: {repo['html_url']}")
if set_remote:
if not is_git_repository():
click.echo("Error: Current directory is not a git repository")
sys.exit(1)
clone_url = repo['clone_url']
# Replace HTTPS URL with token-based URL for authentication
if clone_url.startswith('https://'):
parsed_url = clone_url.split('://')
clone_url = f"{parsed_url[0]}://oauth2:{config['token']}@{parsed_url[1]}"
set_git_remote(clone_url)
except requests.exceptions.RequestException as e:
click.echo(f"Error creating repository: {str(e)}")
sys.exit(1)
if __name__ == '__main__':
cli()