build: 新增 deploy.py 一键部署脚本(固化本地push→服务器pull,根治commit交叉)

This commit is contained in:
Ubuntu
2026-09-17 10:52:00 +08:00
parent fae5b0cb3b
commit 9510d7509e
+123 -111
View File
@@ -1,111 +1,123 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Step C: 一键部署 — 本地 commit+push → 服务器 git pull 同步 """Step C: 一键部署 — 本地 commit+push → 服务器 git pull 同步
工作流(根治 git 交叉): 工作流(根治 git 交叉):
本地 git add/commit/push → 服务器 git pull --ff-only 本地 git add/commit/push → 服务器 git pull --ff-only
服务器只做 pull 不做 commit —— pull 只移动引用,不产生新 commit。 服务器只做 pull 不做 commit —— pull 只移动引用,不产生新 commit。
这是交叉问题的根源修复:旧流程是 SFTP 上传后服务器再 commit 一次, 这是交叉问题的根源修复:旧流程是 SFTP 上传后服务器再 commit 一次,
同一改动被提交两次,author/committer 时间戳不同 → 同 tree 两个 commit ID 同一改动被提交两次,author/committer 时间戳不同 → 同 tree 两个 commit ID
→ ahead 1 behind 1。 → ahead 1 behind 1。
依赖(已配置,非交互): 依赖(已配置,非交互):
本地: credential.helper=store, ~/.git-credentials 本地: credential.helper=store, ~/.git-credentials
服务器: credential.helper=store, ~/.git-credentials, remote → 127.0.0.1:3000 服务器: credential.helper=store, ~/.git-credentials, remote → 127.0.0.1:3000
(Gitea 与服务器同机,走 loopback 避免外部网络波动) (Gitea 与服务器同机,走 loopback 避免外部网络波动)
用法: python deploy.py "提交信息" 用法: python deploy.py "提交信息"
python deploy.py # 用默认信息 python deploy.py # 用默认信息
""" """
import os import os
import subprocess import subprocess
import sys import sys
ROOT = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.abspath(__file__))
os.chdir(ROOT) os.chdir(ROOT)
# .gitignore 已排除本机脚本与备份目录,git add -A 会自动跳过,无需额外 pathspec。 # .gitignore 已排除本机脚本与备份目录,git add -A 会自动跳过,无需额外 pathspec。
# (pathspec 排除 ':!x.py' 在文件已被 .gitignore 忽略时会报错: # (pathspec 排除 ':!x.py' 在文件已被 .gitignore 忽略时会报错:
# "The following paths are ignored by one of your .gitignore files") # "The following paths are ignored by one of your .gitignore files")
DEFAULT_MSG = 'chore: 部署更新' DEFAULT_MSG = 'chore: 部署更新'
SSH_BASE = ("ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null " SSH_BASE = ("ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "
"-o ConnectTimeout=10 ubuntu@106.55.169.92") "-o ConnectTimeout=10 ubuntu@106.55.169.92")
REMOTE_DIR = "/var/www/qianshi" REMOTE_DIR = "/var/www/qianshi"
TIMEOUT = 60 TIMEOUT = 60
ENV = dict(os.environ, GIT_TERMINAL_PROMPT='0') # 禁凭据交互,缺凭据立即失败而非挂起 ENV = dict(os.environ, GIT_TERMINAL_PROMPT='0') # 禁凭据交互,缺凭据立即失败而非挂起
def sh(args, timeout=TIMEOUT): def sh(args, timeout=TIMEOUT):
"""跑命令,返回 (exit, stdout)""" """跑本地命令,返回 (exit, stdout)。args 为 list,shell=False。
r = subprocess.run(args, capture_output=True, text=True,
timeout=timeout, env=ENV) Windows 上 shell=True 交给 cmd.exe,引号语义与 POSIX 不同,
return r.returncode, (r.stdout + r.stderr).strip() 提交信息等参数若用 shlex.quote 反而会出错 —— 统一用 list 直传。
"""
r = subprocess.run(args, capture_output=True, text=True,
def log(msg): timeout=timeout, env=ENV)
print(' %s' % msg, flush=True) return r.returncode, (r.stdout + r.stderr).strip()
def remote(cmd, timeout=TIMEOUT): def log(msg):
"""在服务器上执行命令,返回 (exit, stdout)""" print(' %s' % msg, flush=True)
return sh([SSH_BASE, '"cd %s && %s"' % (REMOTE_DIR, cmd)], timeout)
def remote(cmd, timeout=TIMEOUT):
def deploy(msg=DEFAULT_MSG): """在服务器上执行命令,返回 (exit, stdout)
log('[1/4] 检查改动')
_, st = sh(['git', 'status', '--porcelain']) ssh 远程命令必须作为单个 argv 元素传(shell=False),
if not st: 否则 Windows 的 cmd.exe 会先解析掉引号,ssh 拿不到完整命令。
log('工作区干净,无需提交') cd 与 cmd 的拼接在 Python 里完成,不走任何 shell 解析。
else: """
log('[2/4] 提交') args = SSH_BASE.split() + ['cd %s && %s' % (REMOTE_DIR, cmd)]
# .gitignore 已排除本机脚本与备份目录,git add -A 无需额外 pathspec r = subprocess.run(args, capture_output=True, text=True,
c, out = sh(['git', 'add', '-A']) timeout=timeout, env=ENV)
if c: return r.returncode, (r.stdout + r.stderr).strip()
log('add 失败: %s' % out)
return False
_, staged = sh(['git', 'diff', '--cached', '--name-only']) def deploy(msg=DEFAULT_MSG):
if not staged: log('[1/4] 检查改动')
log('排除项之外无改动') _, st = sh(['git', 'status', '--porcelain'])
else: if not st:
log(' %d 个文件' % len(staged.splitlines())) log('工作区干净,无需提交')
c, out = sh(['git', 'commit', '-m', msg]) else:
if c: log('[2/4] 提交')
log('commit 失败: %s' % out) # .gitignore 已排除本机脚本与备份目录,git add -A 无需额外 pathspec
return False c, out = sh(['git', 'add', '-A'])
_, commit = sh(['git', 'rev-parse', '--short', 'HEAD']) if c:
log('本地 HEAD: %s' % commit) log('add 失败: %s' % out)
return False
log('[3/4] push origin main') _, staged = sh(['git', 'diff', '--cached', '--name-only'])
c, out = sh(['git', 'push', 'origin', 'main']) if not staged:
if c: log('排除项之外无改动')
log('push 失败: %s' % out) else:
return False log(' %d 个文件' % len(staged.splitlines()))
log(' pushed') c, out = sh(['git', 'commit', '-m', msg])
if c:
log('[4/4] 服务器 git pull --ff-only') log('commit 失败: %s' % out)
c, out = remote('GIT_TERMINAL_PROMPT=0 git pull --ff-only origin main') return False
if c: _, commit = sh(['git', 'rev-parse', '--short', 'HEAD'])
log('pull 失败(若报 diverging,说明服务器产生过本地 commit,需人工处理)') log('本地 HEAD: %s' % commit)
log(out)
return False log('[3/4] push origin main')
log(' %s' % out.splitlines()[-1] if out else ' ok') c, out = sh(['git', 'push', 'origin', 'main'])
if c:
# 校验三端一致 log('push 失败: %s' % out)
_, local = sh(['git', 'rev-parse', '--short', 'HEAD']) return False
_, srv = remote('git rev-parse --short HEAD', 30) log(' pushed')
srv = srv.strip().splitlines()[-1] if srv else '?'
if local != srv: log('[4/4] 服务器 git pull --ff-only')
log('!! 本地 %s != 服务器 %s,同步失败' % (local, srv)) c, out = remote('GIT_TERMINAL_PROMPT=0 git pull --ff-only origin main')
return False if c:
log('') log('pull 失败(若报 diverging,说明服务器产生过本地 commit,需人工处理)')
log('=== 部署完成 ===') log(out)
log('提交: %s %s' % (local, msg)) return False
log('本地/服务器 已同步,工作流无 commit 交叉') log(' %s' % out.splitlines()[-1] if out else ' ok')
return True
# 校验三端一致
_, local = sh(['git', 'rev-parse', '--short', 'HEAD'])
if __name__ == '__main__': _, srv = remote('git rev-parse --short HEAD', 30)
msg = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_MSG srv = srv.strip().splitlines()[-1] if srv else '?'
sys.exit(0 if deploy(msg) else 1) if local != srv:
log('!! 本地 %s != 服务器 %s,同步失败' % (local, srv))
return False
log('')
log('=== 部署完成 ===')
log('提交: %s %s' % (local, msg))
log('本地/服务器 已同步,工作流无 commit 交叉')
return True
if __name__ == '__main__':
msg = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_MSG
sys.exit(0 if deploy(msg) else 1)