""" Gitea repository initialization script Creates a new repository on Gitea server and sets up git remote """ import os import requests import subprocess from dotenv import load_dotenv # Load environment variables load_dotenv() def create_gitea_repo(): """Create a new repository on Gitea""" gitea_url = os.getenv('GITEA_URL').rstrip('/') gitea_token = os.getenv('GITEA_TOKEN') gitea_user = os.getenv('GITEA_USER') # Repository details repo_name = 'hr-position-system' repo_description = 'HR基礎資料維護系統 - 崗位與職務管理系統' # API endpoint api_url = f"{gitea_url}/api/v1/user/repos" # Request headers headers = { 'Authorization': f'token {gitea_token}', 'Content-Type': 'application/json' } # Repository data data = { 'name': repo_name, 'description': repo_description, 'private': False, 'auto_init': False, 'default_branch': 'main' } print(f"Creating repository on Gitea: {gitea_url}") print(f"Repository name: {repo_name}") try: # Create repository response = requests.post(api_url, json=data, headers=headers) if response.status_code == 201: repo_info = response.json() print(f"✓ Repository created successfully!") print(f" Repository URL: {repo_info.get('html_url')}") print(f" Clone URL (HTTPS): {repo_info.get('clone_url')}") print(f" Clone URL (SSH): {repo_info.get('ssh_url')}") return repo_info elif response.status_code == 409: print(f"✓ Repository '{repo_name}' already exists") # Get existing repository info repo_url = f"{gitea_url}/api/v1/repos/{gitea_user}/{repo_name}" response = requests.get(repo_url, headers=headers) if response.status_code == 200: return response.json() return None else: print(f"✗ Failed to create repository: {response.status_code}") print(f" Error: {response.text}") return None except Exception as e: print(f"✗ Error creating repository: {str(e)}") return None def init_git_local(): """Initialize local git repository""" repo_path = os.path.dirname(os.path.abspath(__file__)) try: # Check if git is already initialized git_dir = os.path.join(repo_path, '.git') if os.path.exists(git_dir): print("✓ Git repository already initialized") return True # Initialize git subprocess.run(['git', 'init'], cwd=repo_path, check=True) subprocess.run(['git', 'checkout', '-b', 'main'], cwd=repo_path, check=True) print("✓ Git repository initialized") return True except Exception as e: print(f"✗ Error initializing git: {str(e)}") return False def add_git_remote(repo_info): """Add Gitea remote to local repository""" if not repo_info: return False repo_path = os.path.dirname(os.path.abspath(__file__)) clone_url = repo_info.get('clone_url') try: # Check if remote already exists result = subprocess.run( ['git', 'remote', 'get-url', 'origin'], cwd=repo_path, capture_output=True, text=True ) if result.returncode == 0: current_remote = result.stdout.strip() if current_remote == clone_url: print(f"✓ Remote 'origin' already configured: {clone_url}") return True else: # Update remote URL subprocess.run( ['git', 'remote', 'set-url', 'origin', clone_url], cwd=repo_path, check=True ) print(f"✓ Remote 'origin' updated: {clone_url}") return True else: # Add new remote subprocess.run( ['git', 'remote', 'add', 'origin', clone_url], cwd=repo_path, check=True ) print(f"✓ Remote 'origin' added: {clone_url}") return True except Exception as e: print(f"✗ Error adding remote: {str(e)}") return False def create_initial_commit(): """Create initial commit with project files""" repo_path = os.path.dirname(os.path.abspath(__file__)) try: # Check if there are already commits result = subprocess.run( ['git', 'rev-parse', 'HEAD'], cwd=repo_path, capture_output=True, text=True ) if result.returncode == 0: print("✓ Repository already has commits") return True # Add files subprocess.run(['git', 'add', '.gitignore'], cwd=repo_path, check=True) subprocess.run(['git', 'add', 'database_schema.sql'], cwd=repo_path, check=True) subprocess.run(['git', 'add', 'init_database.py'], cwd=repo_path, check=True) subprocess.run(['git', 'add', 'init_gitea.py'], cwd=repo_path, check=True) subprocess.run(['git', 'add', 'SDD.md'], cwd=repo_path, check=True) # Create initial commit subprocess.run( ['git', 'commit', '-m', 'Initial commit: Project setup and database schema'], cwd=repo_path, check=True ) print("✓ Initial commit created") return True except Exception as e: print(f"✗ Error creating initial commit: {str(e)}") return False def test_gitea_connection(): """Test connection to Gitea server""" gitea_url = os.getenv('GITEA_URL').rstrip('/') gitea_token = os.getenv('GITEA_TOKEN') headers = { 'Authorization': f'token {gitea_token}' } try: response = requests.get(f"{gitea_url}/api/v1/user", headers=headers) if response.status_code == 200: user_info = response.json() print(f"✓ Gitea connection test successful") print(f" User: {user_info.get('login')}") print(f" Email: {user_info.get('email')}") return True else: print(f"✗ Gitea connection test failed: {response.status_code}") return False except Exception as e: print(f"✗ Gitea connection test failed: {str(e)}") return False if __name__ == '__main__': print("=" * 60) print("HR Position System - Gitea Repository Initialization") print("=" * 60) print() # Test connection print("Step 1: Testing Gitea connection...") if not test_gitea_connection(): print("\nPlease check your Gitea configuration in .env file") exit(1) # Initialize local git print("\nStep 2: Initializing local git repository...") if not init_git_local(): exit(1) # Create Gitea repository print("\nStep 3: Creating Gitea repository...") repo_info = create_gitea_repo() if not repo_info: exit(1) # Add remote print("\nStep 4: Configuring git remote...") if not add_git_remote(repo_info): exit(1) # Create initial commit print("\nStep 5: Creating initial commit...") create_initial_commit() print("\n" + "=" * 60) print("✓ Gitea repository setup completed!") print("=" * 60) print("\nNext steps:") print(" 1. Run: git push -u origin main") print(" 2. Visit:", repo_info.get('html_url'))