autogit.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. autogit —— 一键提交当前目录并推送到远端分支(Windows / 双击 bat 运行)
  5. ================================================================
  6. 改代码前先读这一段。下面几条都是踩过的坑,不是理论注意事项。
  7. ================================================================
  8. 1. 「有文件变更」和「有未推送提交」是两件事。
  9. 第一次 push 失败(断网 / 被拒)后,本地会留下已 commit 但未推送的提交。
  10. 第二次运行如果只看「有没有文件变更」,就会显示「无变更」然后退出,
  11. 那个 commit 永远推不上去。
  12. => 必须独立统计 <remote>/<branch>..HEAD 的提交数。
  13. 2. push 被拒(non-fast-forward)只代表本地落后,此时还没有冲突。
  14. 必须 fetch 之后分成两种情况:本地无待推内容 / 双方都有(分叉)。
  15. 「问用户 y/n」也必须拆成两次:先问要不要合并,合并真冲突了再问一次。
  16. 3. 不提供 force push。
  17. 用户选 y「用本地覆盖」时用 `git merge -s ours` —— 结果树 100% 等于本地树,
  18. 但远端那几个提交仍作为第二父提交留在历史里,不会被删掉。
  19. (`-s ours` 与 `-X ours` 不是一回事:`-X ours` 只覆盖冲突的片段,
  20. 非冲突处仍会采用远端版本,不符合「整个文件夹我替换过了」的语义。)
  21. 4. token 只允许存在于配置文件里。
  22. - 远端地址不带 token 写进 .git/config,push / fetch 时用显式 URL 传 token,
  23. 这样 `git remote -v` 永远是干净的。
  24. - 提交前扫描暂存区:配置文件本身进 commit、或暂存内容里出现 token 明文,一律中止。
  25. - 自动维护 .gitignore,保证配置文件和日志文件不会被 `git add -A` 收进去。
  26. 5. 所有 git 输出按 bytes 捕获后手动解码(utf-8 优先,失败退 gbk)。
  27. subprocess 的 text 模式在中文 Windows 上会按 cp936 解 UTF-8 路径,直接抛
  28. UnicodeDecodeError。同时统一加 core.quotepath=false,否则中文路径会变成
  29. \\344\\270\\255 这种八进制转义,日志没法看。
  30. 6. push 结果靠重新 ls-remote 比对 SHA 验证,不相信命令返回码。
  31. """
  32. from __future__ import annotations
  33. import argparse
  34. import datetime as dt
  35. import json
  36. import os
  37. import re
  38. import shutil
  39. import subprocess
  40. import sys
  41. import traceback
  42. from pathlib import Path
  43. from urllib.parse import quote, urlsplit
  44. __version__ = "1.0.0"
  45. PROG = "autogit"
  46. SCRIPT_DIR = Path(__file__).resolve().parent
  47. DEFAULT_CONFIG_NAME = "autogit.json"
  48. EXAMPLE_CONFIG_NAME = "autogit.json.example"
  49. DEFAULT_LOG_NAME = "autogit.log"
  50. GITIGNORE_BEGIN = "# >>> autogit >>>"
  51. GITIGNORE_END = "# <<< autogit <<<"
  52. GITIGNORE_NOTE = "# 由 autogit 自动维护:这些文件含本机路径与访问令牌,绝不能入库。"
  53. # 配置文件的内置模板。这是唯一真源 —— autogit.ini.example 只是它的一个
  54. # 人类可读副本,丢了会自动补回来。不要把生成配置的逻辑改回去读那个文件,
  55. # 它一旦被改名/误删,工具就没法自举了。
  56. CONFIG_TEMPLATE = r"""
  57. {
  58. // ==================================================================
  59. // autogit 配置
  60. //
  61. // 只需要改 repo.url 这一处,其余全都有默认值,不用动。
  62. // (目录里已经配过 remote 的仓库,连 url 都不用填)
  63. //
  64. // 支持 // 行注释和 /* */ 块注释,写不写都不影响运行。
  65. // ⚠ 文件里可能出现访问令牌,脚本会自动把它写进 .gitignore。
  66. // ==================================================================
  67. "repo": {
  68. // 远端仓库地址。留空 = 用仓库现有的 remote 配置
  69. // 形如 https://gitee.com/你的用户名/仓库名.git
  70. "url": "",
  71. // 推送到哪条分支。留空 = 跟着仓库当前分支走
  72. "branch": "",
  73. // 远端名。一个仓库挂多个远端才需要改
  74. "remote": "origin",
  75. // 访问令牌(Gitee / GitHub 的私人令牌)
  76. // 留空 = 用系统已保存的凭据,首次推送会弹一次登录窗
  77. "token": "",
  78. // 令牌对应的用户名。留空用 oauth2(GitHub 建议填你的用户名)
  79. "username": "",
  80. // 仓库目录。留空 = 脚本所在目录
  81. "path": "",
  82. // 目录还不是 git 仓库时,自动 git init
  83. "autoInit": true,
  84. // 把 url 同步进 git 的 remote 配置
  85. "syncRemoteUrl": true
  86. },
  87. "commit": {
  88. // 提交信息模板。可用占位符:
  89. // {datetime} {date} {time} {branch} {remote} {count} {dir}
  90. "message": "sync: {datetime}",
  91. // 提交者。留空 = 用 git 的全局配置
  92. "name": "",
  93. "email": ""
  94. },
  95. "sync": {
  96. // 远端有你没有的提交、同时你也有待推送内容时(也就是分叉)怎么办:
  97. // "ask" 问你:y 合并后再推 / n 放弃本次推送 ← 推荐
  98. // "merge" 不问,直接合并
  99. // "abort" 不问,直接放弃
  100. "onRemoteAhead": "ask",
  101. // 合并真的冲突了怎么办:
  102. // "ask" 问你:y 用你本地的文件覆盖 / n 中止合并 ← 推荐
  103. // "ours" 不问,一律用本地文件覆盖
  104. // "abort" 不问,一律中止
  105. // 「用本地覆盖」走的是 git merge -s ours:结果文件 100% 是你本地的,
  106. // 而远端那几个提交仍然作为历史保留,不会被删。脚本永远不会强推。
  107. "onConflict": "ask",
  108. // 单条 git 网络命令的超时(秒)
  109. "timeoutSec": 300,
  110. // 推送成功后重新问一次远端,确认 SHA 对得上
  111. "verifyAfterPush": true
  112. },
  113. "ui": {
  114. // 命令行直接跑 python 时,结束是否等回车(双击 .bat 时由 bat 负责)
  115. "pauseOnExit": false,
  116. // 彩色输出:"auto" / "always" / "never"
  117. "color": "auto",
  118. // 日志文件。留空 = 不写日志
  119. "logFile": "autogit.log",
  120. // 日志超过这个大小(KB)就轮转成 .log.1
  121. "logSizeKb": 1024
  122. },
  123. "guard": {
  124. // 提交前扫描暂存区,这些文件一旦要被提交就中止
  125. "blockFiles": ["autogit.json", "autogit.log"],
  126. // 提交前扫描暂存区内容,发现令牌明文就中止
  127. "blockSecret": true
  128. }
  129. }
  130. """
  131. # 退出码 —— bat 会原样打印,方便判断卡在哪一步
  132. RC_OK = 0 # 成功(含「已是最新」)
  133. RC_ABORT = 1 # 用户主动放弃 / 中止
  134. RC_CONFIG = 2 # 配置或环境自检不通过
  135. RC_CONFLICT = 3 # 合并冲突未处理
  136. RC_NETWORK = 4 # 网络或推送失败
  137. RC_INTERNAL = 5 # 脚本内部异常
  138. VALID_ON_REMOTE_AHEAD = ("ask", "merge", "abort")
  139. VALID_ON_CONFLICT = ("ask", "ours", "abort")
  140. VALID_COLOR = ("auto", "always", "never")
  141. VALID_INIT_BRANCH_NOTE = "master"
  142. _ANSI = {
  143. "reset": "\033[0m",
  144. "bold": "\033[1m",
  145. "dim": "\033[2m",
  146. "red": "\033[31m",
  147. "green": "\033[32m",
  148. "yellow": "\033[33m",
  149. "blue": "\033[36m",
  150. "gray": "\033[90m",
  151. }
  152. # URL 里内嵌凭据的形态:http(s)://user:pass@host/...
  153. _INLINE_CRED_RE = re.compile(r"(https?://)([^/\s:@]+):([^/\s@]+)@")
  154. # --------------------------------------------------------------- 异常与退出码
  155. class AutogitError(Exception):
  156. rc = RC_INTERNAL
  157. class ConfigFatal(AutogitError):
  158. """配置或环境自检不通过,不能继续。"""
  159. rc = RC_CONFIG
  160. class UserAbort(AutogitError):
  161. """用户在交互里选择了放弃。"""
  162. rc = RC_ABORT
  163. class ConflictFatal(AutogitError):
  164. """合并冲突且没有处理掉。"""
  165. rc = RC_CONFLICT
  166. class PushFail(AutogitError):
  167. """网络或推送失败。"""
  168. rc = RC_NETWORK
  169. # ------------------------------------------------------------------ 基础工具
  170. def enable_vt() -> bool:
  171. """打开 Windows 控制台的 ANSI 转义支持,失败就退化到无色输出。"""
  172. if os.name != "nt":
  173. return True
  174. try:
  175. import ctypes
  176. k32 = ctypes.windll.kernel32
  177. handle = k32.GetStdHandle(-11)
  178. if handle in (0, -1):
  179. return False
  180. mode = ctypes.c_uint32()
  181. if not k32.GetConsoleMode(handle, ctypes.byref(mode)):
  182. return False
  183. return bool(k32.SetConsoleMode(handle, mode.value | 0x0004))
  184. except Exception:
  185. return False
  186. def decode_bytes(data) -> str:
  187. """git 的输出统一走这里。utf-8 优先,失败退 gbk,再失败用替换字符。"""
  188. if data is None:
  189. return ""
  190. if isinstance(data, str):
  191. return data
  192. for enc in ("utf-8", "gbk"):
  193. try:
  194. return data.decode(enc)
  195. except UnicodeDecodeError:
  196. continue
  197. return data.decode("utf-8", errors="replace")
  198. def mask_text(text: str, secrets=()) -> str:
  199. """脱敏:先抹掉已知密钥,再把 URL 内嵌的 user:pass 换成 user:***。"""
  200. out = text or ""
  201. for secret in secrets:
  202. if secret:
  203. out = out.replace(secret, "***")
  204. return _INLINE_CRED_RE.sub(r"\1\2:***@", out)
  205. def read_text_any(path: Path) -> str:
  206. """按 utf-8-sig / utf-8 / gbk 顺序读。用户拿记事本存 GBK 是常态。"""
  207. raw = path.read_bytes()
  208. for enc in ("utf-8-sig", "utf-8", "gbk"):
  209. try:
  210. return raw.decode(enc)
  211. except UnicodeDecodeError:
  212. continue
  213. return raw.decode("utf-8", errors="replace")
  214. def write_text_atomic(path: Path, text: str) -> None:
  215. """先写临时件、再原子替换。中途异常不留 0 字节文件。"""
  216. tmp = path.with_name(path.name + ".tmp~")
  217. with tmp.open("w", encoding="utf-8", newline="\n") as handle:
  218. handle.write(text)
  219. os.replace(str(tmp), str(path))
  220. def is_blank(value) -> bool:
  221. return value is None or str(value).strip() == ""
  222. # ---------------------------------------------------------------------- 输出
  223. class UI:
  224. """控制台 + 日志文件的统一出口。日志文件里不带 ANSI 颜色。"""
  225. def __init__(self, color="auto", log_path=None, log_size_kb=1024):
  226. self.use_color = self._decide_color(color)
  227. self.log_path = Path(log_path) if log_path else None
  228. self.log_size_kb = int(log_size_kb or 0)
  229. self.warn_count = 0
  230. self.err_count = 0
  231. @staticmethod
  232. def _decide_color(color: str) -> bool:
  233. if color == "never":
  234. return False
  235. if color == "always":
  236. return enable_vt()
  237. return sys.stdout.isatty() and enable_vt()
  238. def c(self, tone: str, text: str) -> str:
  239. if not self.use_color or tone not in _ANSI:
  240. return text
  241. return _ANSI[tone] + text + _ANSI["reset"]
  242. def raw(self, text: str = "") -> None:
  243. try:
  244. sys.stdout.write(text + "\n")
  245. sys.stdout.flush()
  246. except Exception:
  247. pass
  248. self._log(text)
  249. def _log(self, plain: str) -> None:
  250. if not self.log_path:
  251. return
  252. try:
  253. self.log_path.parent.mkdir(parents=True, exist_ok=True)
  254. if self.log_size_kb > 0 and self.log_path.exists():
  255. if self.log_path.stat().st_size > self.log_size_kb * 1024:
  256. bak = self.log_path.with_name(self.log_path.name + ".1")
  257. try:
  258. if bak.exists():
  259. bak.unlink()
  260. self.log_path.replace(bak)
  261. except OSError:
  262. pass
  263. with self.log_path.open("a", encoding="utf-8", newline="\n") as handle:
  264. handle.write(plain + "\n")
  265. except OSError:
  266. self.log_path = None
  267. # ---- 分级输出 ----
  268. def title(self, text: str) -> None:
  269. self.raw("")
  270. self.raw(self.c("bold", text))
  271. def info(self, text: str = "") -> None:
  272. self.raw(text)
  273. def dim(self, text: str) -> None:
  274. self.raw(self.c("dim", text))
  275. def ok(self, text: str) -> None:
  276. self.raw(self.c("green", "[ OK ] ") + text)
  277. def warn(self, text: str) -> None:
  278. self.warn_count += 1
  279. self.raw(self.c("yellow", "[WARN] ") + text)
  280. def err(self, text: str) -> None:
  281. self.err_count += 1
  282. self.raw(self.c("red", "[FAIL] ") + text)
  283. def step(self, idx: int, total: int, text: str) -> None:
  284. self.raw(self.c("blue", "[%d/%d] " % (idx, total)) + self.c("bold", text))
  285. def bullet(self, text: str, tone="gray") -> None:
  286. self.raw(self.c(tone, " · " + text))
  287. # ---- 交互 ----
  288. def ask_yn(self, question: str, default=None, auto_yes=False) -> bool:
  289. if auto_yes:
  290. self.raw(self.c("yellow", "[AUTO] ") + question + " -> y")
  291. return True
  292. if default is None:
  293. suffix = " [y/n] "
  294. else:
  295. suffix = " [Y/n] " if default else " [y/N] "
  296. while True:
  297. try:
  298. raw = input(self.c("bold", question + suffix))
  299. except (EOFError, KeyboardInterrupt):
  300. self.raw("")
  301. self.warn("没有收到输入,按「放弃」处理")
  302. return False
  303. ans = raw.strip().lower()
  304. if not ans and default is not None:
  305. return bool(default)
  306. if ans in ("y", "yes"):
  307. return True
  308. if ans in ("n", "no"):
  309. return False
  310. self.warn("请输入 y 或 n")
  311. def pause(self, enabled: bool) -> None:
  312. if not enabled:
  313. return
  314. try:
  315. input(self.c("dim", "\n按回车键关闭窗口 ..."))
  316. except (EOFError, KeyboardInterrupt):
  317. pass
  318. # ---------------------------------------------------------------------- 配置
  319. KNOWN_KEYS = {
  320. "repo": {"url", "branch", "remote", "token", "username", "path",
  321. "autoInit", "syncRemoteUrl"},
  322. "commit": {"message", "name", "email"},
  323. "sync": {"onRemoteAhead", "onConflict", "timeoutSec", "verifyAfterPush"},
  324. "ui": {"pauseOnExit", "color", "logFile", "logSizeKb"},
  325. "guard": {"blockFiles", "blockSecret"},
  326. }
  327. MESSAGE_PLACEHOLDERS = ("date", "time", "datetime", "branch", "remote", "count", "dir")
  328. VALID_ON_REMOTE_AHEAD = ("ask", "merge", "abort")
  329. VALID_ON_CONFLICT = ("ask", "ours", "abort")
  330. VALID_COLOR = ("auto", "always", "never")
  331. def strip_json_comments(text: str) -> str:
  332. """剥掉 JSONC 里的 // 和 /* */ 注释,得到标准 JSON。
  333. 不能用正则直接替换:字符串里的 // 必须原样留住,否则
  334. "url": "https://gitee.com/x/y.git"
  335. 会被腰斩成
  336. "url": "https:
  337. 所以这里用一个状态机,跟踪「是否在字符串内」以及「上一个字符是不是转义符」。
  338. 块注释里的换行要原样吐回去,不然 JSON 报错的列号会全部错位。
  339. """
  340. out = []
  341. i, n = 0, len(text)
  342. in_string = False
  343. while i < n:
  344. ch = text[i]
  345. if in_string:
  346. out.append(ch)
  347. if ch == "\\" and i + 1 < n:
  348. out.append(text[i + 1])
  349. i += 2
  350. continue
  351. if ch == '"':
  352. in_string = False
  353. i += 1
  354. continue
  355. if ch == '"':
  356. in_string = True
  357. out.append(ch)
  358. i += 1
  359. continue
  360. if ch == "/" and i + 1 < n:
  361. nxt = text[i + 1]
  362. if nxt == "/":
  363. while i < n and text[i] != "\n":
  364. i += 1
  365. continue
  366. if nxt == "*":
  367. out.append(" ")
  368. i += 2
  369. while i + 1 < n and not (text[i] == "*" and text[i + 1] == "/"):
  370. if text[i] == "\n":
  371. out.append("\n")
  372. i += 1
  373. i += 2
  374. continue
  375. out.append(ch)
  376. i += 1
  377. return "".join(out)
  378. class Conf:
  379. """JSON 配置。取值一律用点号路径,比如 conf.s("repo.url")。
  380. 整个文件都可以不存在 —— 每一项都有默认值,url 和 branch 还能从
  381. 仓库现状推出来(见 resolve_remote_url / resolve_branch)。
  382. 只有「文件存在但 JSON 坏了」才算致命,因为那说明你确实写了东西、
  383. 只是写错了,静默忽略比报错更危险。
  384. """
  385. def __init__(self, path: Path):
  386. self.path = Path(path)
  387. self.exists = False
  388. self.data = {}
  389. def load(self) -> None:
  390. self.exists = self.path.is_file()
  391. if not self.exists:
  392. return
  393. text = read_text_any(self.path)
  394. try:
  395. self.data = json.loads(strip_json_comments(text))
  396. except json.JSONDecodeError as exc:
  397. raise ConfigFatal("%s 不是合法 JSON:第 %d 行第 %d 列 —— %s"
  398. % (self.path.name, exc.lineno, exc.colno, exc.msg))
  399. if not isinstance(self.data, dict):
  400. raise ConfigFatal("%s 的最外层必须是一个 { } 对象" % self.path.name)
  401. # ---- 取值 ----
  402. def _raw(self, path: str):
  403. node = self.data
  404. for part in path.split("."):
  405. if not isinstance(node, dict) or part not in node:
  406. return None
  407. node = node[part]
  408. return node
  409. def s(self, path: str, default: str = "") -> str:
  410. value = self._raw(path)
  411. if value is None:
  412. return default
  413. if isinstance(value, bool):
  414. return "true" if value else "false"
  415. if isinstance(value, (int, float)):
  416. return str(value)
  417. if not isinstance(value, str):
  418. raise ConfigFatal("%s 需要是字符串,当前是 %s" % (path, type(value).__name__))
  419. return value.strip() or default
  420. def b(self, path: str, default: bool = False) -> bool:
  421. value = self._raw(path)
  422. if value is None:
  423. return default
  424. if isinstance(value, bool):
  425. return value
  426. if isinstance(value, str):
  427. low = value.strip().lower()
  428. if low in ("true", "yes", "y", "1", "on"):
  429. return True
  430. if low in ("false", "no", "n", "0", "off"):
  431. return False
  432. raise ConfigFatal("%s 需要是 true 或 false,当前是 %r" % (path, value))
  433. def i(self, path: str, default: int = 0) -> int:
  434. value = self._raw(path)
  435. if value is None:
  436. return default
  437. if isinstance(value, bool):
  438. raise ConfigFatal("%s 需要是整数,当前是 true/false" % path)
  439. if isinstance(value, int):
  440. return value
  441. if isinstance(value, str):
  442. try:
  443. return int(value.strip())
  444. except ValueError:
  445. pass
  446. raise ConfigFatal("%s 需要是整数,当前是 %r" % (path, value))
  447. def list_of(self, path: str, default=()) -> list:
  448. value = self._raw(path)
  449. if value is None:
  450. return list(default)
  451. if isinstance(value, str):
  452. return [item.strip() for item in re.split(r"[,;\n]", value) if item.strip()]
  453. if isinstance(value, list):
  454. return [str(item).strip() for item in value if str(item).strip()]
  455. raise ConfigFatal("%s 需要是数组,或者逗号分隔的字符串" % path)
  456. # ---- 自检:只看配置本身,不碰 git ----
  457. def check(self) -> tuple:
  458. """只校验「你写了的东西」,不要求你必须写什么。"""
  459. fatals, warns = [], []
  460. if not self.exists:
  461. return fatals, warns
  462. if not self.data:
  463. warns.append("%s 是空对象,全部按默认值来" % self.path.name)
  464. return fatals, warns
  465. # 不认识的段 / 键。拼错一个字母不会有任何报错、只会被静默忽略,
  466. # 所以这里列全已知键,见到不认识的就提醒一句。
  467. for section, value in self.data.items():
  468. if section not in KNOWN_KEYS:
  469. warns.append("配置里有未知的段 %r,会被忽略" % section)
  470. continue
  471. if not isinstance(value, dict):
  472. fatals.append("%r 需要是一个 { } 对象" % section)
  473. continue
  474. for key in value:
  475. if key not in KNOWN_KEYS[section]:
  476. warns.append("%s 里有未知的键 %r(拼错了?),会被忽略" % (section, key))
  477. branch = self.s("repo.branch")
  478. if branch:
  479. if branch.startswith("-") or branch.endswith("/") or ".." in branch:
  480. fatals.append("repo.branch 不是合法分支名:%r" % branch)
  481. elif re.search(r"[\s~^:?*\[\\]", branch):
  482. fatals.append("repo.branch 含非法字符:%r" % branch)
  483. url = self.s("repo.url")
  484. if url and not self._looks_like_remote(url):
  485. fatals.append("repo.url 认不出来:%r" % url)
  486. warns.append(" 支持 https://… http://… git@host:path ssh://… 本地路径")
  487. remote = self.s("repo.remote", "origin")
  488. if not re.match(r"^[A-Za-z0-9._-]+$", remote):
  489. fatals.append("repo.remote 只能包含字母数字和 . _ -:%r" % remote)
  490. for path, allowed in (("sync.onRemoteAhead", VALID_ON_REMOTE_AHEAD),
  491. ("sync.onConflict", VALID_ON_CONFLICT),
  492. ("ui.color", VALID_COLOR)):
  493. value = self.s(path)
  494. if value and value not in allowed:
  495. fatals.append("%s 只能是 %s 之一,当前是 %r"
  496. % (path, " / ".join(allowed), value))
  497. message = self.s("commit.message", "sync: {datetime}")
  498. for placeholder in re.findall(r"\{([^}]*)\}", message):
  499. if placeholder not in MESSAGE_PLACEHOLDERS:
  500. warns.append("提交信息里的占位符 {%s} 不认识,会原样保留" % placeholder)
  501. token = self.s("repo.token")
  502. if token and len(token) < 8:
  503. warns.append("token 只有 %d 位,确认一下是不是填漏了" % len(token))
  504. return fatals, warns
  505. @staticmethod
  506. def _looks_like_remote(url: str) -> bool:
  507. if re.match(r"^(https?|ssh|git|file)://", url, re.I):
  508. return True
  509. if re.match(r"^[A-Za-z0-9._-]+@[A-Za-z0-9._-]+:", url):
  510. return True
  511. if re.match(r"^[A-Za-z]:[\\/]", url):
  512. return True
  513. return url.startswith(("/", "\\\\", "./", "../"))
  514. class Git:
  515. """git 命令包装。命令不经 shell,输出统一 bytes -> decode_bytes。"""
  516. def __init__(self, exe: str, cwd: Path, ui: UI, dry_run=False):
  517. self.exe = exe
  518. self.cwd = Path(cwd)
  519. self.ui = ui
  520. self.dry = dry_run
  521. self.secrets = []
  522. def _argv(self, args):
  523. # core.quotepath=false -> 中文路径原样输出,不变八进制转义
  524. # core.pager=cat -> 绝不启动分页器把脚本挂住
  525. return [self.exe, "-c", "core.quotepath=false", "-c", "core.pager=cat"] + list(args)
  526. def _env(self):
  527. env = os.environ.copy()
  528. # 不让 git 在控制台等输入;凭据交互交给 GCM 的图形窗口
  529. env["GIT_TERMINAL_PROMPT"] = "0"
  530. return env
  531. def mask(self, text: str) -> str:
  532. return mask_text(text, self.secrets)
  533. def run(self, args, timeout=None):
  534. try:
  535. proc = subprocess.run(
  536. self._argv(args),
  537. cwd=str(self.cwd),
  538. stdin=subprocess.DEVNULL,
  539. stdout=subprocess.PIPE,
  540. stderr=subprocess.PIPE,
  541. timeout=timeout,
  542. env=self._env(),
  543. )
  544. except FileNotFoundError:
  545. raise ConfigFatal("找不到 git 可执行文件:%s" % self.exe)
  546. except subprocess.TimeoutExpired:
  547. raise PushFail("git 命令超时(%s 秒):git %s"
  548. % (timeout, " ".join(self.mask(a) for a in args)))
  549. proc.out = decode_bytes(proc.stdout).strip()
  550. proc.err = decode_bytes(proc.stderr).strip()
  551. return proc
  552. def out(self, args, timeout=None) -> str:
  553. return self.run(args, timeout=timeout).out
  554. def ok(self, args, timeout=None) -> bool:
  555. try:
  556. return self.run(args, timeout=timeout).returncode == 0
  557. except AutogitError:
  558. return False
  559. def wait(self, args, what: str, timeout=None):
  560. """跑一条命令,非 0 退出就抛异常(附带脱敏后的 stderr)。"""
  561. proc = self.run(args, timeout=timeout)
  562. if proc.returncode != 0:
  563. raise PushFail("%s 失败:%s" % (what, self.mask(proc.err or proc.out)))
  564. return proc
  565. # ---- 只读查询 ----
  566. def version(self) -> str:
  567. return self.out(["--version"]).replace("git version ", "")
  568. def is_repo(self) -> bool:
  569. return self.ok(["rev-parse", "--is-inside-work-tree"])
  570. def current_branch(self) -> str:
  571. """当前分支名。空仓库里 HEAD 已经指向分支,这里同样能取到名字。"""
  572. return self.out(["symbolic-ref", "--short", "-q", "HEAD"])
  573. def is_detached(self) -> bool:
  574. """detached HEAD 的判据是「HEAD 不是符号引用」。
  575. 不能用 rev-parse --abbrev-ref —— 空仓库里它也会返回 HEAD。"""
  576. return not self.ok(["symbolic-ref", "-q", "HEAD"])
  577. def head_sha(self) -> str:
  578. """当前提交的 SHA,空仓库返回空串。
  579. 不能只判断「输出非空」:空仓库里 `git rev-parse HEAD` 会先把字面量
  580. "HEAD" 打到 stdout,然后才 fatal 退出。于是这个字符串会被当成提交 ID,
  581. 空仓库被误判成「已经有提交」,后面的切分支/首次推送全乱套。
  582. 所以这里用 --verify --quiet 并且校验它确实是一串十六进制。
  583. """
  584. proc = self.run(["rev-parse", "--verify", "--quiet", "HEAD"])
  585. if proc.returncode != 0:
  586. return ""
  587. value = proc.out.strip()
  588. if not value or not re.fullmatch(r"[0-9a-fA-F]{7,64}", value):
  589. return ""
  590. return value
  591. def ref_exists(self, ref: str) -> bool:
  592. return self.ok(["rev-parse", "--verify", "--quiet", ref])
  593. def config_get(self, key: str) -> str:
  594. return self.out(["config", "--get", key])
  595. def in_progress_operation(self) -> str:
  596. gitdir = self.out(["rev-parse", "--git-dir"])
  597. if not gitdir:
  598. return ""
  599. base = Path(gitdir)
  600. if not base.is_absolute():
  601. base = self.cwd / base
  602. probes = (
  603. ("MERGE_HEAD", "合并(merge)"),
  604. ("rebase-merge", "变基(rebase)"),
  605. ("rebase-apply", "变基(rebase)"),
  606. ("CHERRY_PICK_HEAD", "遴选(cherry-pick)"),
  607. ("REVERT_HEAD", "回退(revert)"),
  608. )
  609. for name, label in probes:
  610. if (base / name).exists():
  611. return label
  612. return ""
  613. def staged_entries(self) -> list:
  614. rows = []
  615. for line in self.out(["diff", "--cached", "--name-status", "--no-renames"]).splitlines():
  616. parts = line.split("\t")
  617. if len(parts) >= 2:
  618. rows.append((parts[0].strip(), parts[-1].strip()))
  619. return rows
  620. def dirty_entries(self) -> list:
  621. """工作区相对 HEAD 的全部差异(含未暂存),dry-run 下用它估算。"""
  622. rows = []
  623. for line in self.out(["status", "--porcelain", "--untracked-files=all"]).splitlines():
  624. if len(line) >= 4:
  625. rows.append((line[:2].strip() or "??", line[3:].strip()))
  626. return rows
  627. def count_commits(self, rng: str):
  628. """数提交个数。**算不出来返回 None,不能悄悄当成 0**。
  629. 这里的静默失败非常危险:如果 rev-list 因为对象缺失或参数错误失败,
  630. 返回 0 就会被读成「两边一样多」,于是本该合并的分叉被当成「已是最新」,
  631. 本该推送的提交被跳过。宁可让调用方看到 None 然后停下来。
  632. """
  633. proc = self.run(["rev-list", "--count", rng])
  634. if proc.returncode != 0:
  635. return None
  636. try:
  637. return int(proc.out.strip())
  638. except ValueError:
  639. return None
  640. def ls_remote_head(self, remote_or_url: str, branch: str, timeout=None):
  641. """一次调用同时拿到:连通性、分支是否存在、远端 SHA。"""
  642. proc = self.run(["ls-remote", "--heads", remote_or_url, "refs/heads/%s" % branch],
  643. timeout=timeout)
  644. if proc.returncode != 0:
  645. return None, self.mask(proc.err or proc.out)
  646. for line in proc.out.splitlines():
  647. parts = line.split()
  648. if len(parts) >= 2 and parts[1].rstrip("/").endswith("/" + branch):
  649. return parts[0], ""
  650. return "", ""
  651. def conflicted_files(self) -> list:
  652. return [x for x in self.out(["diff", "--name-only", "--diff-filter=U"]).splitlines()
  653. if x.strip()]
  654. # ---- 写操作(dry-run 只打印)----
  655. def _write(self, args, what: str, timeout=None, check=True):
  656. printable = " ".join(self.mask(a) for a in args)
  657. if self.dry:
  658. self.ui.dim(" [dry-run] 将执行:git %s" % printable)
  659. return None
  660. self.ui.dim(" $ git %s" % printable)
  661. proc = self.run(args, timeout=timeout)
  662. if check and proc.returncode != 0:
  663. raise PushFail("%s 失败:%s" % (what, self.mask(proc.err or proc.out)))
  664. return proc
  665. def add_all(self):
  666. return self._write(["add", "-A"], "git add")
  667. def commit(self, message: str):
  668. return self._write(["commit", "-m", message], "git commit")
  669. def merge(self, ref: str, strategy=None, timeout=None, allow_unrelated=False):
  670. args = ["merge", "--no-edit"]
  671. # 两边各自 git init 出来的历史没有共同祖先,git 默认拒绝合并。
  672. # 新一代 git 还会把「拒绝合并不相关历史」写成一堆注释塞进 MERGE_MSG,
  673. # 看起来像冲突但其实不是,所以这个开关必须能显式打开。
  674. if allow_unrelated:
  675. args.append("--allow-unrelated-histories")
  676. if strategy:
  677. args += ["-s", strategy]
  678. args.append(ref)
  679. return self._write(args, "git merge", timeout=timeout, check=False)
  680. def merge_abort(self):
  681. return self._write(["merge", "--abort"], "git merge --abort", check=False)
  682. def push(self, url: str, branch: str, timeout=None):
  683. # 显式 URL 推送:token 不落进 .git/config
  684. return self._write(["push", url, "refs/heads/%s:refs/heads/%s" % (branch, branch)],
  685. "git push", timeout=timeout, check=False)
  686. def fetch_branch(self, remote: str, branch: str, timeout=None) -> bool:
  687. """把远端分支抓成 refs/remotes/<remote>/<branch>。只动 refs,不碰工作区。"""
  688. refspec = "+refs/heads/%s:refs/remotes/%s/%s" % (branch, remote, branch)
  689. if self.dry:
  690. self.ui.dim(" [dry-run] 将执行:git fetch %s %s" % (remote, refspec))
  691. return True
  692. proc = self.run(["fetch", "--no-tags", remote, refspec], timeout=timeout)
  693. if proc.returncode != 0:
  694. self.ui.dim(" fetch 输出:%s" % self.mask(proc.err or proc.out))
  695. return False
  696. return True
  697. def find_git() -> str:
  698. """PATH -> 常见安装位置,逐个实测能跑起来才算数。"""
  699. candidates = []
  700. for name in ("git", "git.exe"):
  701. found = shutil.which(name)
  702. if found:
  703. candidates.append(found)
  704. for guess in (r"D:\software\git\cmd\git.exe",
  705. r"C:\Program Files\Git\cmd\git.exe",
  706. r"C:\Program Files (x86)\Git\cmd\git.exe"):
  707. if os.path.isfile(guess):
  708. candidates.append(guess)
  709. seen = set()
  710. for exe in candidates:
  711. key = os.path.normcase(os.path.abspath(exe))
  712. if key in seen:
  713. continue
  714. seen.add(key)
  715. try:
  716. proc = subprocess.run([exe, "--version"], stdin=subprocess.DEVNULL,
  717. stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
  718. if proc.returncode == 0:
  719. return exe
  720. except Exception:
  721. continue
  722. return ""
  723. # ---------------------------------------------------------------------- 上下文
  724. class Ctx:
  725. def __init__(self, args):
  726. self.args = args
  727. self.conf_path = Path(args.config).resolve() if args.config \
  728. else (SCRIPT_DIR / DEFAULT_CONFIG_NAME)
  729. self.conf = Conf(self.conf_path)
  730. self.ui = None
  731. self.git = None
  732. self.repo_dir = SCRIPT_DIR
  733. self.remote = "origin"
  734. self.branch = "master"
  735. self.url = ""
  736. self.token = ""
  737. self.username = ""
  738. self.authed_url = ""
  739. self.log_name = DEFAULT_LOG_NAME
  740. self.block_files = []
  741. self.block_secret = True
  742. self.timeout = 300
  743. # -------------------------------------------------------------------- .gitignore
  744. def merge_ignore_block(text: str, entries) -> str:
  745. """把 entries 并进 autogit 标记块(只增不减,保留用户手工加的其它规则)。"""
  746. kept, in_block, current = [], False, []
  747. for line in text.splitlines():
  748. stripped = line.strip()
  749. if stripped == GITIGNORE_BEGIN:
  750. in_block = True
  751. continue
  752. if stripped == GITIGNORE_END:
  753. in_block = False
  754. continue
  755. if in_block:
  756. # 以 ! 开头的是「取消忽略」,语义跟忽略正好相反,不能当成有效条目收进块里
  757. if stripped and not stripped.startswith("#") and not stripped.startswith("!"):
  758. current.append(stripped)
  759. continue
  760. kept.append(line)
  761. merged = sorted(set(current) | {str(e).replace("\\", "/") for e in entries},
  762. key=lambda x: x.lower())
  763. block = [GITIGNORE_BEGIN, GITIGNORE_NOTE] + merged + [GITIGNORE_END]
  764. while kept and not kept[-1].strip():
  765. kept.pop()
  766. return "\n".join(kept + ([""] if kept else []) + block) + "\n"
  767. def ignore_rules(text: str) -> set:
  768. """收集 .gitignore 里真正生效的忽略规则。
  769. 注意跳过以 ! 开头的行 —— 那是「不要忽略」,含义跟忽略相反。
  770. 要是把它也收进来,用户写了 !autogit.ini 反而会被判成「已经排除好了」,
  771. 结果令牌文件就这么进了仓库。
  772. """
  773. rules = set()
  774. for line in text.splitlines():
  775. stripped = line.strip()
  776. if not stripped or stripped.startswith("#") or stripped.startswith("!"):
  777. continue
  778. rules.add(stripped.replace("\\", "/").lower())
  779. return rules
  780. def check_gitignore(ctx: Ctx) -> None:
  781. """确保 .gitignore 覆盖了禁入文件。已被追踪的先拦住,否则自动补规则。"""
  782. ui, git = ctx.ui, ctx.git
  783. entries = ctx.block_files
  784. if not entries:
  785. return
  786. tracked = [name for name in entries
  787. if git.out(["ls-files", "--error-unmatch", name])]
  788. if tracked:
  789. ui.err("这些文件已经被 git 追踪,光写 .gitignore 拦不住:" + "、".join(tracked))
  790. for name in tracked:
  791. ui.bullet('git rm --cached "%s"' % name, tone="yellow")
  792. ui.bullet("token 就在这些文件里,先执行上面的命令再从暂存区提交", tone="yellow")
  793. raise ConfigFatal("禁入文件已被 git 追踪")
  794. ignore_path = ctx.repo_dir / ".gitignore"
  795. text = read_text_any(ignore_path) if ignore_path.is_file() else ""
  796. missing = [name for name in entries
  797. if name.replace("\\", "/").lower() not in ignore_rules(text)]
  798. if not missing:
  799. ui.ok(".gitignore 已排除 %s" % "、".join(entries))
  800. return
  801. new_text = merge_ignore_block(text, missing)
  802. if git.dry:
  803. ui.dim(" [dry-run] 将往 .gitignore 追加:" + "、".join(missing))
  804. return
  805. try:
  806. write_text_atomic(ignore_path, new_text)
  807. except OSError as exc:
  808. raise ConfigFatal("写入 .gitignore 失败:%s" % exc)
  809. ui.warn(".gitignore 缺少排除项,已自动补上:" + "、".join(missing))
  810. def resolve_remote_url(ctx: Ctx) -> None:
  811. """决定往哪儿推。
  812. 优先级:配置里的 repo.url > 仓库现有的 remote > 都没有就报错。
  813. 无论走哪条路,脚本都不会中途停下来问你 —— 需要你决定的东西一律
  814. 写在 autogit.json 里,运行过程只负责读它、报告读了什么。
  815. """
  816. ui, git = ctx.ui, ctx.git
  817. from_conf = ctx.conf.s("repo.url")
  818. if from_conf:
  819. ctx.url = from_conf
  820. ui.ok("远端地址 %s(来自 %s)" % (mask_text(ctx.url), ctx.conf_path.name))
  821. return
  822. existing = git.config_get("remote.%s.url" % ctx.remote).strip()
  823. if existing:
  824. ctx.url = existing
  825. ui.ok("远端地址 %s(取自仓库现有的 remote %s)" % (mask_text(ctx.url), ctx.remote))
  826. return
  827. ui.warn("还不知道往哪个仓库推")
  828. ui.bullet("在 %s 里把 url 填上就行:" % ctx.conf_path.name, tone="yellow")
  829. ui.bullet(' "url": "https://gitee.com/你的用户名/仓库名.git"', tone="yellow")
  830. ui.bullet("(或者先执行 git remote add %s <地址>)" % ctx.remote)
  831. if ctx.args.check:
  832. return
  833. raise ConfigFatal("没有可用的远端地址")
  834. def resolve_branch(ctx: Ctx) -> None:
  835. """决定推哪条分支。
  836. 优先级:autogit.ini 里写的 branch > 仓库当前分支 > master。
  837. 空仓库里 HEAD 也已经指向某个分支名(git init 时定的,你机器上是 master),
  838. 所以「你在哪条分支上就推哪条」对空仓库同样成立 —— 通常完全不用操心。
  839. """
  840. ui, git = ctx.ui, ctx.git
  841. from_conf = ctx.conf.s("repo.branch")
  842. if from_conf:
  843. ctx.branch = from_conf
  844. ui.ok("目标分支:%s(来自 %s)" % (ctx.branch, ctx.conf_path.name))
  845. return
  846. current = git.current_branch()
  847. if current:
  848. ctx.branch = current
  849. ui.ok("目标分支:%s(跟着仓库当前分支走)" % ctx.branch)
  850. return
  851. ctx.branch = "master"
  852. ui.ok("目标分支:master(默认值)")
  853. def build_authed_url(ctx: Ctx) -> str:
  854. """裸 URL + username + token 拼成带凭据的 URL。只在内存里存在。"""
  855. if is_blank(ctx.token):
  856. return ctx.url
  857. split = urlsplit(ctx.url)
  858. if split.scheme.lower() not in ("http", "https"):
  859. ctx.ui.warn("url 不是 http(s),token 只对 http(s) 仓库生效,本次忽略 token")
  860. return ctx.url
  861. host = split.hostname or ""
  862. if split.port:
  863. host += ":%d" % split.port
  864. netloc = "%s:%s@%s" % (quote(ctx.username or "oauth2", safe=""),
  865. quote(ctx.token, safe=""), host)
  866. return split._replace(netloc=netloc).geturl()
  867. def guard_staged(ctx: Ctx) -> None:
  868. """最后一道闸门:提交前确认配置文件和 token 明文没混进暂存区。"""
  869. ui, git = ctx.ui, ctx.git
  870. if ctx.args.dry_run:
  871. rows = git.dirty_entries()
  872. else:
  873. rows = git.staged_entries()
  874. staged_names = {Path(name).name.lower() for _status, name in rows}
  875. hit = [name for name in ctx.block_files if name.lower() in staged_names]
  876. if hit:
  877. ui.err("暂存区里有不该提交的文件:" + "、".join(hit))
  878. ui.bullet("这些文件含本机路径和访问令牌,提交出去等于把钥匙贴公告栏", tone="yellow")
  879. ui.bullet("真要提交,就把它们从 [guard] block_files 里去掉", tone="yellow")
  880. raise ConfigFatal("禁入文件进了暂存区")
  881. if not ctx.block_secret or is_blank(ctx.token) or ctx.args.dry_run:
  882. return
  883. # 在 index 里直接搜 token 明文,比 dump 整个 diff 快得多。
  884. # 末尾的 -- 是防止 token 本身以 - 开头时被 git 当成选项。
  885. proc = git.run(["grep", "--cached", "-F", "-I", "-e", ctx.token, "--"], timeout=120)
  886. if proc.returncode == 0 and proc.out.strip():
  887. ui.err("暂存区的内容里出现了 token 明文,已中止提交")
  888. for line in proc.out.splitlines()[:5]:
  889. ui.bullet(mask_text(line, [ctx.token]), tone="yellow")
  890. ui.bullet("把 token 从该文件里删掉;确实需要就设 [guard] block_secret = false",
  891. tone="yellow")
  892. raise ConfigFatal("token 明文进了暂存区")
  893. # --------------------------------------------------------------------- 主流程
  894. def render_message(template: str, ctx: Ctx, count: int, now: dt.datetime) -> str:
  895. mapping = {
  896. "{date}": now.strftime("%Y-%m-%d"),
  897. "{time}": now.strftime("%H:%M:%S"),
  898. "{datetime}": now.strftime("%Y-%m-%d %H:%M:%S"),
  899. "{branch}": ctx.branch,
  900. "{remote}": ctx.remote,
  901. "{count}": str(count),
  902. "{dir}": ctx.repo_dir.name,
  903. }
  904. out = template
  905. for key, value in mapping.items():
  906. out = out.replace(key, value)
  907. return out
  908. def do_commit_if_needed(ctx: Ctx) -> int:
  909. """有变更就提交,返回涉及的变更文件数(0 = 没有变更)。"""
  910. ui, git = ctx.ui, ctx.git
  911. if git.dry:
  912. rows = git.dirty_entries()
  913. else:
  914. git.add_all()
  915. rows = git.staged_entries()
  916. if not rows:
  917. ui.ok("没有文件变更")
  918. return 0
  919. guard_staged(ctx)
  920. label = {"A": "新增", "M": "修改", "D": "删除", "R": "重命名", "C": "复制",
  921. "T": "类型变更", "??": "未跟踪"}
  922. counts = {}
  923. for status, _name in rows:
  924. counts[status[:1] if status in label else status] = \
  925. counts.get(status[:1] if status in label else status, 0) + 1
  926. detail = "、".join("%s %d" % (label.get(key, key), value)
  927. for key, value in sorted(counts.items()))
  928. ui.info(" 本次变更 %d 个文件(%s)" % (len(rows), detail))
  929. for status, name in rows[:12]:
  930. ui.bullet("%s %s" % (status.ljust(2), name))
  931. if len(rows) > 12:
  932. ui.bullet("… 其余 %d 个" % (len(rows) - 12))
  933. if git.dry:
  934. ui.dim(" [dry-run] 跳过 commit(否则提交信息会是:%s)"
  935. % render_message(ctx.conf.s("commit.message", "sync: {datetime}"),
  936. ctx, len(rows), dt.datetime.now()))
  937. return len(rows)
  938. name = ctx.conf.s("commit.name")
  939. email = ctx.conf.s("commit.email")
  940. if name and not git.config_get("user.name"):
  941. git.run(["config", "user.name", name])
  942. if email and not git.config_get("user.email"):
  943. git.run(["config", "user.email", email])
  944. message = render_message(ctx.conf.s("commit.message", "sync: {datetime}"),
  945. ctx, len(rows), dt.datetime.now())
  946. git.commit(message)
  947. ui.ok("已提交:%s" % message)
  948. return len(rows)
  949. def check_remote_default_branch(ctx: Ctx, url: str, branch: str) -> None:
  950. """首次推送后看一眼远端默认分支的指向。
  951. 托管平台新建仓库时可能已经把默认分支定成 main。我们把内容推到了
  952. master,如果远端 HEAD 还指着 main,别人(或你换台机器)克隆下来会得到
  953. 一个空目录,看着就像推送没成功。
  954. 实测两种形态:
  955. HEAD 指向存在的分支 -> `ref: refs/heads/xxx\tHEAD`
  956. HEAD 指向不存在的分支 -> 输出为空(退出码仍是 0)
  957. 所以「拿到空的 ref: 行」本身就是信号。这个检查只在首次推送后跑一次,
  958. 属于锦上添花,任何异常都静默略过。
  959. """
  960. ui, git = ctx.ui, ctx.git
  961. proc = git.run(["ls-remote", "--symref", url, "HEAD"], timeout=ctx.timeout)
  962. if proc.returncode != 0:
  963. return
  964. target = ""
  965. for line in proc.out.splitlines():
  966. parts = line.split()
  967. if len(parts) >= 2 and parts[0] == "ref:":
  968. target = parts[1].replace("refs/heads/", "").strip()
  969. break
  970. if not target:
  971. # 刚推成功,分支肯定在,HEAD 却是悬空的
  972. ui.warn("远端的默认分支没有指向任何一个存在的分支(HEAD 悬空)")
  973. ui.bullet("换台机器克隆下来会是个空目录,看着像推送没成功", tone="yellow")
  974. ui.bullet("去仓库的「设置 → 默认分支」改成 %s 就好了" % branch, tone="yellow")
  975. return
  976. if target == branch:
  977. return
  978. ui.warn("远端默认分支指向 %s,而我们推的是 %s" % (target, branch))
  979. ui.bullet("换台机器克隆下来默认会检出 %s,看着像是空的" % target, tone="yellow")
  980. ui.bullet("去仓库的「设置 → 默认分支」改成 %s 就好了" % branch, tone="yellow")
  981. def sync_with_remote(ctx: Ctx, auto_yes: bool) -> None:
  982. """fetch -> 按需合并 -> push -> 用远端 SHA 验证。"""
  983. ui, git = ctx.ui, ctx.git
  984. remote, branch, timeout = ctx.remote, ctx.branch, ctx.timeout
  985. tracking = "refs/remotes/%s/%s" % (remote, branch)
  986. query_url = ctx.authed_url or ctx.url
  987. # ---- 1. 连通性 + 远端分支是否存在 + 远端 SHA,一次问清楚 ----
  988. ui.step(5, 6, "检查远端仓库")
  989. remote_head, error = git.ls_remote_head(query_url, branch, timeout=timeout)
  990. if remote_head is None:
  991. ui.err("连不上远端仓库,或者认证没通过")
  992. ui.bullet("地址:%s" % mask_text(ctx.url))
  993. ui.bullet("检查网络、仓库地址、token 是否过期", tone="yellow")
  994. if error:
  995. ui.dim(" git 返回:%s" % error.splitlines()[0])
  996. raise PushFail("ls-remote 失败")
  997. if remote_head:
  998. first_push = False
  999. ui.ok("远端 %s/%s 存在,SHA %s" % (remote, branch, remote_head[:8]))
  1000. # fetch 必须成功。曾经这里失败会退化成「把 ls-remote 的 SHA 直接塞进
  1001. # refs/remotes/<remote>/<branch>」,可那个对象本地根本没有,紧接着
  1002. # rev-list 会失败、差数被算成 0 —— 于是分叉被读成「已是最新」,
  1003. # 该合并的直接跳过。状态不明就不允许做合并/推送的决定。
  1004. if not git.fetch_branch(remote, branch, timeout=timeout) and not git.dry:
  1005. ui.dim(" fetch 失败,重试一次…")
  1006. if not git.fetch_branch(remote, branch, timeout=timeout):
  1007. ui.err("拉取远端状态失败,现在说不准远端是什么情况")
  1008. ui.bullet("状态不明的时候合并或推送都可能出错,这次先停", tone="yellow")
  1009. ui.bullet("确认网络后直接重跑一次就行,本地提交不会丢", tone="yellow")
  1010. raise PushFail("fetch 远端失败")
  1011. else:
  1012. first_push = True
  1013. ui.info(" 远端还没有 %s 分支,本次将是首次推送" % branch)
  1014. head = git.head_sha()
  1015. if not head:
  1016. raise ConfigFatal("HEAD 读不出来,仓库是空的而且没有可提交的内容")
  1017. # ---- 2. 算两边的差 ----
  1018. if not remote_head:
  1019. # 远端没有这个分支:本地所有提交都要推上去。
  1020. # 这里绝不能去看 refs/remotes/<remote>/<branch> —— 远端要是被清空重建过,
  1021. # 本地还留着上一次的陈旧引用,照它算会算出「待推送 0 个」然后什么都不做。
  1022. local_ahead = git.count_commits("HEAD")
  1023. remote_ahead = 0
  1024. else:
  1025. local_ahead = git.count_commits("%s..HEAD" % tracking)
  1026. remote_ahead = git.count_commits("HEAD..%s" % tracking)
  1027. if local_ahead is None or remote_ahead is None:
  1028. ui.err("算不清本地和远端的提交差,状态不明,不敢继续")
  1029. ui.bullet("先手动看一眼:git status 和 git ls-remote %s" % remote, tone="yellow")
  1030. raise ConfigFatal("提交差算不出来")
  1031. ui.info(" 本地待推送 %d 个提交,远端多出 %d 个提交" % (local_ahead, remote_ahead))
  1032. # ---- 3. 分叉 -> 按配置决定合并 ----
  1033. if local_ahead > 0 and remote_ahead > 0:
  1034. ui.warn("本地与远端已经分叉:本地 %d 个待推,远端 %d 个你没拉过"
  1035. % (local_ahead, remote_ahead))
  1036. mode = ctx.conf.s("sync.onRemoteAhead", "ask")
  1037. if mode == "merge":
  1038. ui.info(" [sync] on_remote_ahead = merge,按配置直接合并")
  1039. do_merge = True
  1040. elif mode == "abort":
  1041. ui.info(" [sync] on_remote_ahead = abort,按配置放弃本次推送")
  1042. do_merge = False
  1043. else:
  1044. do_merge = ui.ask_yn("是否先把远端的 %d 个提交合并进来?" % remote_ahead,
  1045. default=True, auto_yes=auto_yes)
  1046. if not do_merge:
  1047. ui.warn("已放弃推送。本地提交保留着,下次双击会自动重试。")
  1048. ui.bullet("想手动处理:git fetch %s && git merge %s/%s" % (remote, remote, branch))
  1049. raise UserAbort("用户放弃推送")
  1050. ui.step(6, 6, "合并远端提交")
  1051. # 本地是自己 git init 出来的、远端是平台新建时自带了一个初始提交
  1052. # (常见的「新建仓库顺手勾了初始化 README」),这种两边没有共同祖先,
  1053. # git 会直接拒绝合并。它不是冲突,加个开关就能正常合。
  1054. allow_unrelated = False
  1055. proc = git.merge("%s/%s" % (remote, branch), timeout=timeout)
  1056. if proc is not None and proc.returncode != 0:
  1057. blob = (proc.err or "") + (proc.out or "")
  1058. if "unrelated histories" in blob or "refusing to merge" in blob:
  1059. ui.warn("本地和远端是两条互不相关的历史(远端仓库带了个初始提交)")
  1060. ui.info(" 加上 --allow-unrelated-histories 重新合并")
  1061. allow_unrelated = True
  1062. proc = git.merge("%s/%s" % (remote, branch), timeout=timeout,
  1063. allow_unrelated=True)
  1064. if proc is not None and proc.returncode != 0:
  1065. conflicts = git.conflicted_files()
  1066. if not conflicts:
  1067. ui.err("合并失败,而且没识别出冲突文件")
  1068. ui.dim(" %s" % mask_text(proc.err or proc.out)[:400])
  1069. git.merge_abort()
  1070. raise ConflictFatal("合并失败")
  1071. ui.err("有 %d 个文件合并冲突:" % len(conflicts))
  1072. for name in conflicts[:15]:
  1073. ui.bullet(name, tone="yellow")
  1074. if len(conflicts) > 15:
  1075. ui.bullet("… 其余 %d 个" % (len(conflicts) - 15))
  1076. mode = ctx.conf.s("sync.onConflict", "ask")
  1077. if mode == "ours":
  1078. ui.info(" [sync] on_conflict = ours,按配置用本地版本覆盖")
  1079. use_ours = True
  1080. elif mode == "abort":
  1081. ui.info(" [sync] on_conflict = abort,按配置中止")
  1082. use_ours = False
  1083. else:
  1084. use_ours = ui.ask_yn("是否用你本地的文件覆盖这些冲突(保留远端历史)?",
  1085. default=None, auto_yes=auto_yes)
  1086. if not use_ours:
  1087. ui.warn("已中止合并,工作区恢复到合并前,本地提交保留。")
  1088. git.merge_abort()
  1089. raise UserAbort("用户放弃合并")
  1090. # -s ours:结果树 100% 等于本地树,远端那几个提交仍作为第二父保留
  1091. git.merge_abort()
  1092. ui.info(" 改用「内容以本地为准」的方式重新合并…")
  1093. proc = git.merge("%s/%s" % (remote, branch), strategy="ours", timeout=timeout,
  1094. allow_unrelated=allow_unrelated)
  1095. if proc is not None and proc.returncode != 0:
  1096. ui.err("以本地为准的合并也失败了")
  1097. ui.dim(" %s" % mask_text(proc.err or proc.out)[:400])
  1098. git.merge_abort()
  1099. raise ConflictFatal("merge -s ours 失败")
  1100. ui.ok("已合并:内容取本地版本,远端提交保留在历史里")
  1101. if not git.dry:
  1102. local_ahead = git.count_commits("%s..HEAD" % tracking)
  1103. if local_ahead is None:
  1104. raise ConfigFatal("合并后算不出待推送提交数,状态不明,先停")
  1105. elif remote_ahead > 0:
  1106. ui.warn("本地落后远端 %d 个提交,而本地没有待推送的内容" % remote_ahead)
  1107. ui.bullet("文件是旧的,要不要拉一下你自己定", tone="yellow")
  1108. # ---- 4. 推送 ----
  1109. if local_ahead <= 0:
  1110. if remote_ahead > 0:
  1111. ui.ok("本地没有要推的东西(远端比你新)")
  1112. else:
  1113. ui.ok("已经是最新,无需推送")
  1114. return
  1115. ui.step(6, 6, "推送到远端")
  1116. proc = git.push(query_url, branch, timeout=timeout)
  1117. if proc is not None and proc.returncode != 0:
  1118. ui.err("推送失败")
  1119. ui.dim(" %s" % mask_text(proc.err or proc.out)[:600])
  1120. ui.bullet("本地提交保留着,下次双击会自动重试", tone="yellow")
  1121. raise PushFail("push 失败")
  1122. # ---- 5. 验证:不信返回码,重新问远端 ----
  1123. if git.dry or not ctx.conf.b("sync.verifyAfterPush", True):
  1124. return
  1125. after, err = git.ls_remote_head(query_url, branch, timeout=timeout)
  1126. head = git.head_sha()
  1127. if after is None:
  1128. # 复核时连不上 ≠ 推送失败。这里必须分开说,笼统报「对不上」就是撒谎。
  1129. ui.warn("推送命令返回成功,但复核时连不上远端,暂时无法确认")
  1130. if err:
  1131. ui.dim(" git 返回:%s" % err.splitlines()[0])
  1132. ui.bullet("稍后自己确认一次:git ls-remote %s %s" % (remote, branch), tone="yellow")
  1133. elif after and head and after.startswith(head[:8]):
  1134. ui.ok("远端已确认更新到 %s" % head[:8])
  1135. else:
  1136. ui.warn("推送命令返回成功,但远端 SHA 和本地对不上")
  1137. ui.bullet("本地 %s / 远端 %s" % (head[:8] or "?", (after or "无")[:8]))
  1138. ui.bullet("请手动 git ls-remote 复核一次", tone="yellow")
  1139. # 首次推送额外确认远端默认分支的指向
  1140. if first_push:
  1141. check_remote_default_branch(ctx, query_url, branch)
  1142. # ------------------------------------------------------------------ 启动与编排
  1143. def banner(ui: UI, subtitle: str) -> None:
  1144. ui.raw("")
  1145. ui.raw(ui.c("bold", "=" * 64))
  1146. ui.raw(ui.c("bold", " autogit v%s · %s" % (__version__, subtitle)))
  1147. ui.raw(ui.c("bold", "=" * 64))
  1148. def ensure_example_exists() -> None:
  1149. """旁边没有参考模板就补一份。
  1150. 纯参考用 —— 生成配置的逻辑早就改成读内置常量了,这个文件在不在
  1151. 都不影响运行。丢了就静默补回来,不打扰任何人。
  1152. """
  1153. example = SCRIPT_DIR / EXAMPLE_CONFIG_NAME
  1154. if example.is_file():
  1155. return
  1156. try:
  1157. write_text_atomic(example, CONFIG_TEMPLATE)
  1158. except OSError:
  1159. pass
  1160. def should_pause(conf, args) -> bool:
  1161. """「结束时等回车」由谁负责。
  1162. 被 .bat 包着的时候(AUTOGIT_WRAPPED=1)一律交给 bat —— 它在所有路径上
  1163. 都会 pause,包括 python 根本没启动起来的情况。这样做的好处是双击时
  1164. 只会停一次,而 python 崩在启动阶段也不会一闪而过。
  1165. 独立跑 python 时才看配置和 --no-pause。
  1166. """
  1167. if not is_blank(os.environ.get("AUTOGIT_WRAPPED")):
  1168. return False
  1169. if args.no_pause:
  1170. return False
  1171. return conf.b("ui.pauseOnExit", False) if conf else False
  1172. def run(args) -> int:
  1173. ctx = Ctx(args)
  1174. # 配置文件不存在已经不算错误了 —— Conf.load 会安静地把 exists 置 False,
  1175. # 后面 url / branch 各自从仓库现状推断。只有语法坏了才在这里拦下。
  1176. try:
  1177. ctx.conf.load()
  1178. except ConfigFatal as exc:
  1179. boot = UI(color="never" if args.no_color else "auto")
  1180. boot.err(str(exc))
  1181. boot.pause(should_pause(None, args))
  1182. return RC_CONFIG
  1183. # 顺手补一份参考模板。纯粹给人抄,不参与运行,失败也不出声。
  1184. ensure_example_exists()
  1185. # ---- 日志路径 ----
  1186. ctx.log_name = ctx.conf.s("ui.logFile", DEFAULT_LOG_NAME)
  1187. if args.no_log:
  1188. log_path = None
  1189. elif os.path.isabs(ctx.log_name):
  1190. log_path = Path(ctx.log_name)
  1191. else:
  1192. log_path = SCRIPT_DIR / ctx.log_name
  1193. ui = UI(color="never" if args.no_color else ctx.conf.s("ui.color", "auto"),
  1194. log_path=log_path,
  1195. log_size_kb=ctx.conf.i("ui.logSizeKb", 1024))
  1196. ctx.ui = ui
  1197. banner(ui, "配置自检 → 提交 → 推送")
  1198. ui.info("配置文件:%s" % ctx.conf_path)
  1199. ui.info("运行时间:%s" % dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  1200. if args.dry_run:
  1201. ui.warn("dry-run:只打印将要执行的操作,不真正落盘")
  1202. if args.check:
  1203. ui.warn("check:只做自检,不提交不推送")
  1204. try:
  1205. code = flow(ctx)
  1206. except AutogitError as exc:
  1207. ui.info("")
  1208. ui.err(str(exc))
  1209. code = exc.rc
  1210. except KeyboardInterrupt:
  1211. ui.info("")
  1212. ui.err("被中断")
  1213. code = RC_ABORT
  1214. except Exception:
  1215. ui.info("")
  1216. ui.err("脚本内部异常,下面是堆栈:")
  1217. ui.info(traceback.format_exc())
  1218. code = RC_INTERNAL
  1219. ui.info("")
  1220. ui.raw(ui.c("bold", "─" * 64))
  1221. if code == RC_OK:
  1222. ui.raw(ui.c("green", " 完成 ") + "(警告 %d 条)" % ui.warn_count)
  1223. else:
  1224. ui.raw(ui.c("red", " 未完成 ") + "退出码 %d" % code)
  1225. ui.pause(should_pause(ctx.conf, args))
  1226. return code
  1227. def flow(ctx: Ctx) -> int:
  1228. ui = ctx.ui
  1229. # ============================================ 1. 配置自检
  1230. ui.step(1, 6, "读配置")
  1231. if not ctx.conf.exists:
  1232. ui.ok("没有 %s —— 全部按默认值来,下面会告诉你最终用了什么"
  1233. % ctx.conf_path.name)
  1234. else:
  1235. ui.ok("读到 %s" % ctx.conf_path.name)
  1236. fatals, warns = ctx.conf.check()
  1237. for item in warns:
  1238. ui.warn(item)
  1239. if fatals:
  1240. for item in fatals:
  1241. ui.err(item)
  1242. ui.info("")
  1243. raise ConfigFatal("配置文件有问题,已停止。修好上面这些再运行。")
  1244. ctx.remote = ctx.conf.s("repo.remote", "origin")
  1245. ctx.url = ctx.conf.s("repo.url") # 允许为空:后面 resolve_ 会去推断
  1246. ctx.token = ctx.conf.s("repo.token")
  1247. ctx.username = ctx.conf.s("repo.username")
  1248. ctx.timeout = ctx.conf.i("sync.timeoutSec", 300) or 300
  1249. ctx.block_secret = ctx.conf.b("guard.blockSecret", True)
  1250. ctx.block_files = ctx.conf.list_of("guard.blockFiles", [ctx.conf_path.name, ctx.log_name])
  1251. repo_setting = ctx.conf.s("repo.path")
  1252. ctx.repo_dir = Path(repo_setting).expanduser().resolve() if repo_setting else SCRIPT_DIR
  1253. # ============================================ 2. 环境自检
  1254. ui.step(2, 6, "自检运行环境")
  1255. git_exe = find_git()
  1256. if not git_exe:
  1257. ui.bullet("PATH 和常见安装位置里都没找到能用的 git", tone="yellow")
  1258. raise ConfigFatal("找不到 git")
  1259. ctx.git = Git(git_exe, ctx.repo_dir, ui,
  1260. dry_run=(ctx.args.dry_run or ctx.args.check))
  1261. ctx.git.secrets = [s for s in (ctx.token, ctx.username) if not is_blank(s)]
  1262. git = ctx.git
  1263. ui.ok("git %s" % git.version())
  1264. ui.bullet(str(git_exe))
  1265. if not ctx.repo_dir.is_dir():
  1266. raise ConfigFatal("仓库目录不存在:%s" % ctx.repo_dir)
  1267. ui.ok("仓库目录 %s" % ctx.repo_dir)
  1268. if not git.is_repo():
  1269. if not ctx.conf.b("repo.autoInit", True):
  1270. ui.bullet("目录还不是 git 仓库,而 [repo] auto_init = false", tone="yellow")
  1271. raise ConfigFatal("目录不是 git 仓库")
  1272. ui.warn("目录还不是 git 仓库" + ("(正式运行时会自动初始化)" if git.dry else ",正在初始化…"))
  1273. if git._write(["init"], "git init") is not None:
  1274. ui.ok("已初始化,分支将设为 %s" % ctx.branch)
  1275. author_name = git.config_get("user.name")
  1276. author_email = git.config_get("user.email")
  1277. if author_name and author_email:
  1278. ui.ok("提交者 %s <%s>" % (author_name, author_email))
  1279. else:
  1280. fallback_name = ctx.conf.s("commit.name")
  1281. fallback_email = ctx.conf.s("commit.email")
  1282. if not fallback_name or not fallback_email:
  1283. ui.bullet('git config --global user.name "你的名字"', tone="yellow")
  1284. ui.bullet('git config --global user.email "你的邮箱"', tone="yellow")
  1285. ui.bullet("或者在 [commit] 里填 name / email", tone="yellow")
  1286. raise ConfigFatal("没有提交者身份,commit 会被 git 拒绝")
  1287. git.run(["config", "user.name", fallback_name])
  1288. git.run(["config", "user.email", fallback_email])
  1289. ui.ok("提交者取自配置文件:%s <%s>" % (fallback_name, fallback_email))
  1290. if git.is_repo():
  1291. pending = git.in_progress_operation()
  1292. if pending:
  1293. ui.bullet("先手动看一眼 git status,再 git merge --abort / git rebase --abort",
  1294. tone="yellow")
  1295. raise ConfigFatal("仓库里有个没做完的%s操作" % pending)
  1296. ui.ok("没有卡在半截的 merge / rebase")
  1297. else:
  1298. ui.dim(" 仓库还没初始化,merge / rebase 检查留到正式运行时")
  1299. if git.is_repo() and git.is_detached():
  1300. ui.bullet("先切回分支:git checkout %s" % ctx.branch, tone="yellow")
  1301. raise ConfigFatal("当前处于分离头指针(detached HEAD)状态")
  1302. current = git.current_branch()
  1303. if git.config_get("core.autocrlf").lower() == "true":
  1304. ui.warn("core.autocrlf = true,纯 LF 文件提交时会被改写成 CRLF")
  1305. ui.bullet("不想被改就在仓库里放 .gitattributes,写一行:* -text")
  1306. credential = git.config_get("credential.helper")
  1307. if is_blank(ctx.token):
  1308. if is_blank(credential):
  1309. ui.warn("没填 token,系统也没有 credential.helper,推送时可能没人问你要密码")
  1310. ui.bullet("建议在 [repo] 里填 url_token", tone="yellow")
  1311. else:
  1312. ui.ok("认证:系统凭据助手 %s" % credential)
  1313. else:
  1314. ui.ok("认证:配置文件里的 token(不会写进 .git/config)")
  1315. # token 就在配置文件里,这道闸门是硬性的
  1316. check_gitignore(ctx)
  1317. # ---- 远端地址:配置里有就用,没有就用现成 remote,都没有就报错 ----
  1318. resolve_remote_url(ctx)
  1319. if ctx.url and ctx.conf.b("repo.syncRemoteUrl", True):
  1320. existing = git.config_get("remote.%s.url" % ctx.remote).strip()
  1321. if not existing:
  1322. if git._write(["remote", "add", ctx.remote, ctx.url],
  1323. "git remote add") is not None:
  1324. ui.ok("已写入 remote %s → %s" % (ctx.remote, mask_text(ctx.url)))
  1325. elif existing != ctx.url.strip():
  1326. # 只有「配置文件里显式写了 url 且和现有 remote 不一致」才会走到这里
  1327. ui.warn("remote %s 现在是 %s,跟 %s 里写的不一样"
  1328. % (ctx.remote, mask_text(existing), ctx.conf_path.name))
  1329. if ctx.args.auto_yes or ui.ask_yn("改成配置文件里的地址?", default=True):
  1330. if git._write(["remote", "set-url", ctx.remote, ctx.url],
  1331. "git remote set-url") is not None:
  1332. ui.ok("已更新远程地址")
  1333. else:
  1334. ui.warn("保留原地址,本次按原地址推送")
  1335. ctx.url = existing
  1336. ctx.authed_url = build_authed_url(ctx)
  1337. # ---- 目标分支:配置文件里没写就跟着仓库走 ----
  1338. resolve_branch(ctx)
  1339. if ctx.authed_url != ctx.url:
  1340. ui.dim(" 推送地址 %s" % mask_text(ctx.authed_url))
  1341. # ============================================ check 模式出口
  1342. if ctx.args.check:
  1343. ui.step(3, 6, "自检完成(check 模式)")
  1344. ui.info("")
  1345. ui.ok("可以正式运行了。要跑的话,把 --check 去掉就行")
  1346. ui.info(" 警告 %d 条,错误 %d 条" % (ui.warn_count, ui.err_count))
  1347. return RC_OK
  1348. # ============================================ 3. 分支
  1349. ui.step(3, 6, "确认分支")
  1350. if not git.head_sha():
  1351. # 空仓库:HEAD 只是个还没落地的符号引用,直接指到目标分支就行。
  1352. # 这里不要用 checkout —— 没有提交时 checkout 一个不存在的分支必然失败。
  1353. if current != ctx.branch:
  1354. ui.info(" 仓库还没有提交,把 HEAD 指向 %s" % ctx.branch)
  1355. if git.dry:
  1356. ui.dim(" [dry-run] 将执行:git symbolic-ref HEAD refs/heads/%s"
  1357. % ctx.branch)
  1358. else:
  1359. git.run(["symbolic-ref", "HEAD", "refs/heads/%s" % ctx.branch])
  1360. elif current != ctx.branch:
  1361. ui.warn("当前在 %s,切到 %s" % (current, ctx.branch))
  1362. git.wait(["checkout", ctx.branch], "git checkout %s" % ctx.branch)
  1363. ui.ok("分支 %s" % ctx.branch)
  1364. # ============================================ 4. 提交
  1365. ui.step(4, 6, "提交本地变更")
  1366. do_commit_if_needed(ctx)
  1367. # ============================================ 5/6. 同步
  1368. sync_with_remote(ctx, auto_yes=ctx.args.auto_yes)
  1369. ui.ok("全部完成")
  1370. ui.info(" %s → %s" % (ctx.branch, mask_text(ctx.url)))
  1371. if ui.warn_count:
  1372. ui.info(" 本次有 %d 条警告,往上看一眼" % ui.warn_count)
  1373. return RC_OK
  1374. # ------------------------------------------------------------------------ CLI
  1375. def parse_args(argv):
  1376. parser = argparse.ArgumentParser(
  1377. prog=PROG,
  1378. description="一键提交当前目录并推送到远端分支(双击 bat 时不需要任何参数)",
  1379. formatter_class=argparse.RawDescriptionHelpFormatter,
  1380. epilog=("退出码:\n"
  1381. " 0 成功(含「已是最新」)\n"
  1382. " 1 你选择了放弃 / 中止\n"
  1383. " 2 配置或环境自检不通过\n"
  1384. " 3 合并冲突且未处理\n"
  1385. " 4 网络或推送失败\n"
  1386. " 5 脚本内部异常\n"),
  1387. )
  1388. parser.add_argument("-c", "--config", help="配置文件路径,默认脚本旁边的 autogit.ini")
  1389. parser.add_argument("--check", action="store_true", help="只做自检,不提交不推送")
  1390. parser.add_argument("--dry-run", action="store_true", help="打印将要执行的操作,不真正执行")
  1391. parser.add_argument("-y", "--auto-yes", action="store_true",
  1392. help="所有提问一律回答 y(无人值守用,慎用)")
  1393. parser.add_argument("--no-pause", action="store_true", help="结束时不等回车")
  1394. parser.add_argument("--no-log", action="store_true", help="本次不写日志文件")
  1395. parser.add_argument("--no-color", action="store_true", help="关闭彩色输出")
  1396. parser.add_argument("-V", "--version", action="version", version="%(prog)s " + __version__)
  1397. return parser.parse_args(argv)
  1398. def main(argv=None) -> int:
  1399. for stream in (sys.stdout, sys.stderr):
  1400. try:
  1401. stream.reconfigure(encoding="utf-8", errors="replace")
  1402. except Exception:
  1403. pass
  1404. args = parse_args(sys.argv[1:] if argv is None else argv)
  1405. try:
  1406. return run(args)
  1407. except AutogitError as exc:
  1408. print("[FAIL] %s" % exc)
  1409. return exc.rc
  1410. except KeyboardInterrupt:
  1411. print("[ABORT] 被用户中断")
  1412. return RC_ABORT
  1413. except Exception:
  1414. print("[FAIL] 脚本内部异常:")
  1415. traceback.print_exc()
  1416. return RC_INTERNAL
  1417. if __name__ == "__main__":
  1418. sys.exit(main())