Initial commit
This commit is contained in:
4
.gitignore
vendored
4
.gitignore
vendored
@@ -5,4 +5,6 @@ __pycache__/
|
||||
.vscode/
|
||||
.idea/
|
||||
*.log
|
||||
.env
|
||||
.env
|
||||
create_repo.py
|
||||
.mp4
|
||||
173
create_repo.py
173
create_repo.py
@@ -3,41 +3,67 @@ import json
|
||||
import subprocess
|
||||
import os
|
||||
|
||||
# Configuration
|
||||
# ==========================================
|
||||
# 配置部分
|
||||
# 这里存放脚本运行需要的基本信息
|
||||
# ==========================================
|
||||
|
||||
# 远程 Git 仓库的 API 地址,用来创建新仓库
|
||||
API_URL = "https://git.aitosuv.com/api/v1/user/repos"
|
||||
|
||||
# 你的用户名和密码
|
||||
# 格式是 ('用户名', '密码')
|
||||
AUTH = ('admin', 'lsy123123')
|
||||
|
||||
# 要创建的仓库信息
|
||||
REPO_DATA = {
|
||||
"name": "geminiWX",
|
||||
"description": "微信小程序项目",
|
||||
"private": False,
|
||||
"auto_init": False
|
||||
"name": "geminiWX", # 仓库的名字
|
||||
"description": "微信小程序项目", # 仓库的描述
|
||||
"private": False, # 是否是私有仓库(False表示公开)
|
||||
"auto_init": False # 是否自动初始化(False表示创建一个空仓库)
|
||||
}
|
||||
|
||||
# ==========================================
|
||||
# 工具函数部分
|
||||
# ==========================================
|
||||
|
||||
def run_command(command):
|
||||
"""Run a shell command and return the output."""
|
||||
print(f"Running: {command}")
|
||||
"""
|
||||
运行一个系统命令(比如 git 命令),并返回它的输出结果。
|
||||
就像你在黑窗口(终端)里敲命令一样。
|
||||
"""
|
||||
print(f"正在运行命令: {command}") # 打印正在运行什么命令,方便查看进度
|
||||
try:
|
||||
# subprocess.run 用来执行命令
|
||||
result = subprocess.run(
|
||||
command,
|
||||
check=True,
|
||||
shell=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
encoding='utf-8',
|
||||
errors='replace'
|
||||
check=True, # 如果命令执行出错,就抛出异常
|
||||
shell=True, # 在 Shell 中运行
|
||||
stdout=subprocess.PIPE, # 捕获标准输出(命令成功时的返回信息)
|
||||
stderr=subprocess.PIPE, # 捕获错误输出(命令出错时的报错信息)
|
||||
text=True, # 结果以文本形式返回
|
||||
encoding='utf-8', # 使用 UTF-8 编码,防止中文乱码
|
||||
errors='replace' # 如果遇到无法解码的字符,就用特殊符号代替,防止程序崩溃
|
||||
)
|
||||
# 如果命令有输出结果,就打印出来
|
||||
if result.stdout:
|
||||
print(result.stdout.strip())
|
||||
return result.stdout.strip()
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Error running command: {command}")
|
||||
# 如果命令执行失败了,打印错误信息
|
||||
print(f"命令执行出错: {command}")
|
||||
print(e.stderr)
|
||||
return None
|
||||
|
||||
def create_gitignore():
|
||||
"""Create .gitignore if it doesn't exist."""
|
||||
"""
|
||||
创建一个名为 .gitignore 的文件。
|
||||
这个文件的作用是告诉 Git:哪些文件不需要上传到仓库里。
|
||||
比如临时文件、缓存文件、密码文件等。
|
||||
"""
|
||||
# 如果文件不存在,才创建
|
||||
if not os.path.exists(".gitignore"):
|
||||
# 下面是需要忽略的文件列表
|
||||
content = """
|
||||
.venv/
|
||||
__pycache__/
|
||||
@@ -51,99 +77,136 @@ __pycache__/
|
||||
.node_modules/
|
||||
create_repo.py
|
||||
"""
|
||||
# 写入文件
|
||||
with open(".gitignore", "w") as f:
|
||||
f.write(content.strip())
|
||||
print("Created .gitignore")
|
||||
print("已创建 .gitignore 文件")
|
||||
else:
|
||||
print(".gitignore already exists")
|
||||
print(".gitignore 文件已存在,跳过创建")
|
||||
|
||||
# ==========================================
|
||||
# 主程序部分
|
||||
# 程序的入口,逻辑从这里开始
|
||||
# ==========================================
|
||||
|
||||
def main():
|
||||
clone_url = None
|
||||
clone_url = None # 用来存储仓库的克隆地址(上传地址)
|
||||
|
||||
# Initialize session and disable proxy
|
||||
# 初始化一个网络请求会话
|
||||
# session 就像一个浏览器,可以记住你的登录状态(如果有的话)
|
||||
session = requests.Session()
|
||||
session.trust_env = False
|
||||
session.trust_env = False # 不使用系统的代理设置,防止连接失败
|
||||
|
||||
# 1. Create Repository via API
|
||||
# --------------------------------------
|
||||
# 第一步:通过 API 在服务器上创建一个空仓库
|
||||
# --------------------------------------
|
||||
try:
|
||||
# 发送一个 POST 请求来创建仓库
|
||||
response = session.post(API_URL, auth=AUTH, json=REPO_DATA)
|
||||
|
||||
# 状态码 201 表示创建成功
|
||||
if response.status_code == 201:
|
||||
print("Repository created successfully")
|
||||
clone_url = response.json()['clone_url']
|
||||
elif response.status_code == 422 or response.status_code == 409: # Already exists
|
||||
print("Repository already exists")
|
||||
# Fetch existing repo details
|
||||
print("仓库创建成功!")
|
||||
clone_url = response.json()['clone_url'] # 获取仓库的克隆地址
|
||||
|
||||
# 状态码 422 或 409 通常表示仓库已经存在了
|
||||
elif response.status_code == 422 or response.status_code == 409:
|
||||
print("仓库已存在")
|
||||
# 如果仓库已存在,我们需要去获取它的信息(主要是为了拿到 clone_url)
|
||||
user = AUTH[0]
|
||||
repo_name = REPO_DATA["name"]
|
||||
# 拼接获取仓库详情的 API 地址
|
||||
get_url = f"https://git.aitosuv.com/api/v1/repos/{user}/{repo_name}"
|
||||
resp_get = session.get(get_url, auth=AUTH)
|
||||
|
||||
if resp_get.status_code == 200:
|
||||
clone_url = resp_get.json()['clone_url']
|
||||
clone_url = resp_get.json()['clone_url'] # 成功拿到了地址
|
||||
else:
|
||||
print(f"Could not fetch existing repository details. Status: {resp_get.status_code}")
|
||||
print(f"无法获取现有仓库详情。状态码: {resp_get.status_code}")
|
||||
else:
|
||||
print(f"Failed to create repository: {response.status_code}")
|
||||
print(response.text)
|
||||
# 其他错误情况
|
||||
print(f"创建仓库失败,状态码: {response.status_code}")
|
||||
print(response.text) # 打印服务器返回的错误信息
|
||||
return
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
print(f"发生错误: {e}")
|
||||
return
|
||||
|
||||
# 如果没有拿到克隆地址,后面的操作没法进行,直接退出
|
||||
if not clone_url:
|
||||
print("Could not determine clone URL. Exiting.")
|
||||
print("无法获取仓库地址,程序退出。")
|
||||
return
|
||||
|
||||
# Embed credentials into the URL for automatic authentication
|
||||
# Assuming clone_url format: https://git.aitosuv.com/admin/geminiWX.git
|
||||
# We want: https://admin:lsy123123@git.aitosuv.com/admin/geminiWX.git
|
||||
# --------------------------------------
|
||||
# 准备上传用的 URL
|
||||
# 为了避免每次推送代码都输入密码,我们把账号密码拼接到 URL 里
|
||||
# 原始格式: https://git.aitosuv.com/admin/geminiWX.git
|
||||
# 目标格式: https://admin:lsy123123@git.aitosuv.com/admin/geminiWX.git
|
||||
# --------------------------------------
|
||||
if "://" in clone_url:
|
||||
protocol, rest = clone_url.split("://", 1)
|
||||
auth_url = f"{protocol}://{AUTH[0]}:{AUTH[1]}@{rest}"
|
||||
else:
|
||||
auth_url = clone_url # Fallback if format is unexpected
|
||||
auth_url = clone_url # 如果格式不对,就用原来的
|
||||
|
||||
print(f"目标远程仓库地址: {clone_url}")
|
||||
|
||||
print(f"Target Remote URL: {clone_url}")
|
||||
|
||||
# 2. Local Git Operations
|
||||
# --------------------------------------
|
||||
# 第二步:本地 Git 操作
|
||||
# 把电脑上的文件变成一个 Git 仓库,并上传
|
||||
# --------------------------------------
|
||||
|
||||
# 1. 如果当前目录还没有 .git 文件夹,说明还没初始化,执行 git init
|
||||
if not os.path.exists(".git"):
|
||||
print("Initializing git repository...")
|
||||
print("正在初始化本地 Git 仓库...")
|
||||
run_command("git init")
|
||||
|
||||
# Configure git user for this repository
|
||||
print("Configuring git user...")
|
||||
# 2. 设置 Git 的用户名和邮箱(提交记录里会显示是谁提交的)
|
||||
print("正在配置 Git 用户信息...")
|
||||
run_command(f'git config user.email "{AUTH[0]}@aitosuv.com"')
|
||||
run_command(f'git config user.name "{AUTH[0]}"')
|
||||
|
||||
# 3. 创建忽略文件列表
|
||||
create_gitignore()
|
||||
|
||||
print("Adding files...")
|
||||
# 4. 把所有文件加入到暂存区(相当于把文件放入"待提交"的篮子里)
|
||||
print("正在添加文件...")
|
||||
run_command("git add .")
|
||||
|
||||
print("Committing changes...")
|
||||
# 5. 提交更改(把篮子里的文件正式存档,并附上一句说明 "Initial commit")
|
||||
print("正在提交更改...")
|
||||
run_command('git commit -m "Initial commit"')
|
||||
|
||||
# Check and configure remote
|
||||
# 6. 关联远程仓库
|
||||
# 先看看是不是已经关联过了
|
||||
remotes = run_command("git remote -v")
|
||||
if remotes and "origin" in remotes:
|
||||
print("Updating remote 'origin'...")
|
||||
# 如果已经有了叫 origin 的远程仓库,就更新它的地址
|
||||
print("正在更新远程仓库 'origin' 的地址...")
|
||||
run_command(f"git remote set-url origin {auth_url}")
|
||||
else:
|
||||
print("Adding remote 'origin'...")
|
||||
# 如果没有,就添加一个新的叫 origin 的远程仓库
|
||||
print("正在添加远程仓库 'origin'...")
|
||||
run_command(f"git remote add origin {auth_url}")
|
||||
|
||||
# Push to remote
|
||||
print("Pushing to remote...")
|
||||
# Try pushing to master first, then main if that fails (or vice versa depending on default branch)
|
||||
# Usually 'master' is default for older git, 'main' for newer.
|
||||
# We can try checking current branch name.
|
||||
# 7. 推送代码到服务器
|
||||
print("正在推送到远程仓库...")
|
||||
|
||||
# 获取当前分支的名字(通常是 master 或 main)
|
||||
current_branch = run_command("git rev-parse --abbrev-ref HEAD")
|
||||
|
||||
if current_branch:
|
||||
# 尝试推送到当前分支
|
||||
# -u origin {current_branch} 表示把本地分支和远程分支关联起来
|
||||
# -f 表示强制推送(覆盖远程的内容),慎用,但这里是初始化所以没关系
|
||||
if run_command(f"git push -u origin {current_branch} -f") is None:
|
||||
print("Push failed.")
|
||||
print("推送失败。")
|
||||
else:
|
||||
# Fallback if we couldn't get branch name
|
||||
# 如果获取不到分支名,就盲猜 master 或 main 试一下
|
||||
if run_command("git push -u origin master -f") is None:
|
||||
run_command("git push -u origin main -f")
|
||||
|
||||
# 只有直接运行这个脚本时,才会执行 main()
|
||||
# 如果被别的脚本 import 导入,则不会执行
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user