Files
workspace/create_gitea_repo_and_push.py

130 lines
3.5 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""使用Gitea API创建workspace仓库并推送代码"""
import requests
import json
import subprocess
import os
# 从ENV.xlsx中读取的Git配置
GIT_SERVER = "git.alicorns.co.jp"
GIT_USER = "aitest"
GIT_PASSWORD = "Aitest123456"
REPO_NAME = "workspace"
# API端点
GITEA_API_URL = f"https://{GIT_SERVER}/api/v1"
# 工作目录
WORKSPACE_DIR = r"C:\Users\ALC\.openclaw\workspace"
def create_repository():
"""使用Gitea API创建仓库"""
url = f"{GITEA_API_URL}/user/repos"
# 构造Basic Auth头
import base64
credentials = f"{GIT_USER}:{GIT_PASSWORD}"
auth_header = base64.b64encode(credentials.encode()).decode()
headers = {
"Authorization": f"Basic {auth_header}",
"Content-Type": "application/json"
}
payload = {
"name": REPO_NAME,
"description": "OpenClaw workspace configuration and tools",
"private": False,
"auto_init": False,
"readme": "none"
}
try:
print(f"Creating repository: {REPO_NAME}...")
response = requests.post(url, headers=headers, json=payload, timeout=30)
if response.status_code == 201:
result = response.json()
print(f"Repository created successfully!")
print(f"Name: {result['name']}")
print(f"Clone URL: {result['clone_url']}")
return True
elif response.status_code == 409:
print(f"Repository '{REPO_NAME}' already exists")
return True
else:
print(f"Failed to create repository")
print(f"Status: {response.status_code}")
print(f"Response: {response.text}")
return False
except Exception as e:
print(f"Error creating repository: {e}")
return False
def push_to_remote():
"""推送到远程仓库"""
os.chdir(WORKSPACE_DIR)
# 设置远程仓库URL
remote_url = f"https://{GIT_USER}:{GIT_PASSWORD}@{GIT_SERVER}/{GIT_USER}/{REPO_NAME}.git"
try:
# 添加或更新远程仓库
result = subprocess.run(
["git", "remote", "set-url", "origin", remote_url],
capture_output=True,
text=True,
timeout=10
)
print(f"Remote URL set to: origin")
# 推送代码
print("\nPushing to remote repository...")
result = subprocess.run(
["git", "push", "-u", "origin", "master"],
capture_output=False,
text=True,
timeout=120
)
if result.returncode == 0:
print("Push successful!")
return True
else:
print("Push failed")
return False
except Exception as e:
print(f"Error during push: {e}")
return False
def main():
print("=== Gitea Repository Creation and Push ===")
print(f"Git Server: {GIT_SERVER}")
print(f"User: {GIT_USER}")
print(f"Repository: {REPO_NAME}")
print(f"Workspace: {WORKSPACE_DIR}")
print("")
# Step 1: 创建仓库
if create_repository():
print("\n=== Repository Ready ===")
# Step 2: 推送代码
print("\n=== Pushing Code ===")
if push_to_remote():
print("\n=== SUCCESS ===")
print("Repository created and code pushed successfully!")
else:
print("\n=== PUSH FAILED ===")
print("Repository was created but push failed")
else:
print("\n=== CREATION FAILED ===")
print("Could not create repository")
if __name__ == "__main__":
main()