-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_github_repo.py
More file actions
169 lines (137 loc) · 5.47 KB
/
create_github_repo.py
File metadata and controls
169 lines (137 loc) · 5.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""
Script para crear repositorio en GitHub usando la API y hacer push del código.
"""
import os
import json
import requests
import subprocess
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
# Obtener token de GitHub del .env
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN") or os.getenv("GITHUB_API_TOKEN") or os.getenv("GH_TOKEN")
if not GITHUB_TOKEN:
print("[ERROR] No se encontró GITHUB_TOKEN en el archivo .env")
print("Por favor, agrega: GITHUB_TOKEN=tu_token_aqui")
exit(1)
# Configuración del repositorio
REPO_NAME = "instinct"
REPO_DESCRIPTION = "Telegram-controlled intelligence orchestration bot with Macrocosmos MCP and Chutes API integration"
REPO_PRIVATE = False # Cambiar a True si quieres privado
USERNAME = "jmarcos01" # Tu username de GitHub
def create_repo():
"""Crea el repositorio en GitHub usando la API."""
url = f"https://api.github.com/user/repos"
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json"
}
data = {
"name": REPO_NAME,
"description": REPO_DESCRIPTION,
"private": REPO_PRIVATE,
"auto_init": False # No inicializar con README, ya tenemos uno
}
print(f"[*] Creando repositorio '{REPO_NAME}' en GitHub...")
try:
response = requests.post(url, headers=headers, json=data, timeout=30)
response.raise_for_status()
repo_data = response.json()
repo_url = repo_data.get("clone_url")
ssh_url = repo_data.get("ssh_url")
print(f"[OK] Repositorio creado exitosamente!")
print(f" URL: {repo_data.get('html_url')}")
print(f" Clone URL: {repo_url}")
return repo_url, ssh_url
except requests.exceptions.HTTPError as e:
if response.status_code == 422:
error_data = response.json()
if "already exists" in str(error_data).lower() or "name already exists" in str(error_data).lower():
print(f"[!] El repositorio '{REPO_NAME}' ya existe.")
print(f" Usando repositorio existente: https://github.com/{USERNAME}/{REPO_NAME}")
return f"https://github.com/{USERNAME}/{REPO_NAME}.git", f"git@github.com:{USERNAME}/{REPO_NAME}.git"
print(f"[ERROR] Error HTTP {response.status_code}: {response.text}")
raise
except Exception as e:
print(f"[ERROR] Error al crear repositorio: {e}")
raise
def setup_git_remote(repo_url):
"""Configura el remote de git y hace push."""
repo_dir = Path(__file__).parent
print(f"\n[*] Configurando git remote...")
# Verificar si ya existe un remote origin
result = subprocess.run(
["git", "remote", "get-url", "origin"],
cwd=repo_dir,
capture_output=True,
text=True
)
if result.returncode == 0:
existing_url = result.stdout.strip()
print(f"[!] Remote existente encontrado: {existing_url}")
if existing_url != repo_url:
print(f"[*] Eliminando remote existente...")
subprocess.run(["git", "remote", "remove", "origin"], cwd=repo_dir, check=True)
else:
print(f"[OK] Remote ya esta configurado correctamente.")
return
# Agregar nuevo remote
print(f"[+] Agregando remote: {repo_url}")
subprocess.run(["git", "remote", "add", "origin", repo_url], cwd=repo_dir, check=True)
# Verificar remote
result = subprocess.run(["git", "remote", "-v"], cwd=repo_dir, capture_output=True, text=True)
print(f"\n[*] Remotes configurados:")
print(result.stdout)
def push_to_github():
"""Hace push del código a GitHub."""
repo_dir = Path(__file__).parent
print(f"\n[*] Haciendo push a GitHub...")
# Verificar que estamos en la rama main
result = subprocess.run(
["git", "branch", "--show-current"],
cwd=repo_dir,
capture_output=True,
text=True
)
current_branch = result.stdout.strip()
if current_branch != "main":
print(f"[!] Estas en la rama '{current_branch}', cambiando a 'main'...")
subprocess.run(["git", "checkout", "-b", "main"], cwd=repo_dir, check=True)
# Hacer push
try:
subprocess.run(
["git", "push", "-u", "origin", "main"],
cwd=repo_dir,
check=True
)
print(f"[OK] Push completado exitosamente!")
except subprocess.CalledProcessError as e:
print(f"[ERROR] Error al hacer push: {e}")
print(f"\n[*] Intenta ejecutar manualmente:")
print(f" git push -u origin main")
raise
def main():
"""Función principal."""
print("=" * 60)
print("Creando Repositorio en GitHub")
print("=" * 60)
try:
# 1. Crear repositorio
repo_url, ssh_url = create_repo()
# 2. Configurar git remote
setup_git_remote(repo_url)
# 3. Hacer push
push_to_github()
print("\n" + "=" * 60)
print("[OK] Proceso completado exitosamente!")
print("=" * 60)
print(f"\n[*] Repositorio: https://github.com/{USERNAME}/{REPO_NAME}")
print(f"[*] Clone URL: {repo_url}")
except Exception as e:
print(f"\n[ERROR] Error durante el proceso: {e}")
print(f"\n[*] Puedes intentar manualmente:")
print(f" 1. git remote add origin {repo_url}")
print(f" 2. git push -u origin main")
exit(1)
if __name__ == "__main__":
main()