From 815f5f40b531788c43eed27737ed27d4ef712d21 Mon Sep 17 00:00:00 2001 From: Steve White Date: Wed, 22 Jan 2025 09:01:20 -0600 Subject: [PATCH] Initial Commit --- .env.example | 2 + .gitignore | 1 + README.md | 44 +++++++++++++++++ gitea_cli.py | 123 +++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 3 ++ 5 files changed, 173 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 README.md create mode 100644 gitea_cli.py create mode 100644 requirements.txt diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..862b538 --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +GITEA_URL=https://gitea.yourdomain.com +GITEA_TOKEN=your_access_token_here diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4c49bd7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.env diff --git a/README.md b/README.md new file mode 100644 index 0000000..1e3bace --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# Gitea CLI + +A command line interface for interacting with Gitea servers. + +## Installation + +1. Clone this repository +2. Install dependencies: + ```bash + pip install -r requirements.txt + ``` + +## Configuration + +Create a `.env` file in the project root with your Gitea credentials: + +```env +GITEA_URL=https://your-gitea-instance.com +GITEA_TOKEN=your_access_token +``` + +To get an access token: +1. Log into your Gitea instance +2. Go to Settings > Applications +3. Generate a new token + +## Usage + +### Create a new repository: +```bash +python gitea_cli.py create-repo --name my-repo --description "My new repository" --private +``` + +### Create a repository and set it as remote: +If you're in a git repository and want to create a new Gitea repository and set it as the remote origin: +```bash +python gitea_cli.py create-repo --name my-repo --description "My new repository" --set-remote +``` + +This will: +1. Create a new repository on Gitea +2. Check if the current directory is a git repository +3. Remove any existing 'origin' remote +4. Add the new Gitea repository as 'origin' diff --git a/gitea_cli.py b/gitea_cli.py new file mode 100644 index 0000000..aa42aa8 --- /dev/null +++ b/gitea_cli.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 + +import os +import sys +import click +import requests +import subprocess +from dotenv import load_dotenv + +# Load environment variables +load_dotenv() + +# Get Gitea configuration from environment +GITEA_URL = os.getenv('GITEA_URL') +GITEA_TOKEN = os.getenv('GITEA_TOKEN') + +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 validate_environment(): + """Validate that required environment variables are set.""" + if not GITEA_URL: + click.echo("Error: GITEA_URL environment variable is not set") + sys.exit(1) + if not GITEA_TOKEN: + click.echo("Error: GITEA_TOKEN environment variable is not set") + sys.exit(1) + +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""" + 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') +def create_repo(name, description, private, set_remote): + """Create a new repository on Gitea.""" + validate_environment() + + try: + gitea = GiteaAPI(GITEA_URL, GITEA_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:{GITEA_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() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..4e016c4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +requests>=2.31.0 +click>=8.1.0 +python-dotenv>=1.0.0