| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- autogit —— 一键提交当前目录并推送到远端分支(Windows / 双击 bat 运行)
- ================================================================
- 改代码前先读这一段。下面几条都是踩过的坑,不是理论注意事项。
- ================================================================
- 1. 「有文件变更」和「有未推送提交」是两件事。
- 第一次 push 失败(断网 / 被拒)后,本地会留下已 commit 但未推送的提交。
- 第二次运行如果只看「有没有文件变更」,就会显示「无变更」然后退出,
- 那个 commit 永远推不上去。
- => 必须独立统计 <remote>/<branch>..HEAD 的提交数。
- 2. push 被拒(non-fast-forward)只代表本地落后,此时还没有冲突。
- 必须 fetch 之后分成两种情况:本地无待推内容 / 双方都有(分叉)。
- 「问用户 y/n」也必须拆成两次:先问要不要合并,合并真冲突了再问一次。
- 3. 不提供 force push。
- 用户选 y「用本地覆盖」时用 `git merge -s ours` —— 结果树 100% 等于本地树,
- 但远端那几个提交仍作为第二父提交留在历史里,不会被删掉。
- (`-s ours` 与 `-X ours` 不是一回事:`-X ours` 只覆盖冲突的片段,
- 非冲突处仍会采用远端版本,不符合「整个文件夹我替换过了」的语义。)
- 4. token 只允许存在于配置文件里。
- - 远端地址不带 token 写进 .git/config,push / fetch 时用显式 URL 传 token,
- 这样 `git remote -v` 永远是干净的。
- - 提交前扫描暂存区:配置文件本身进 commit、或暂存内容里出现 token 明文,一律中止。
- - 自动维护 .gitignore,保证配置文件和日志文件不会被 `git add -A` 收进去。
- 5. 所有 git 输出按 bytes 捕获后手动解码(utf-8 优先,失败退 gbk)。
- subprocess 的 text 模式在中文 Windows 上会按 cp936 解 UTF-8 路径,直接抛
- UnicodeDecodeError。同时统一加 core.quotepath=false,否则中文路径会变成
- \\344\\270\\255 这种八进制转义,日志没法看。
- 6. push 结果靠重新 ls-remote 比对 SHA 验证,不相信命令返回码。
- """
- from __future__ import annotations
- import argparse
- import datetime as dt
- import json
- import os
- import re
- import shutil
- import subprocess
- import sys
- import traceback
- from pathlib import Path
- from urllib.parse import quote, urlsplit
- __version__ = "1.0.0"
- PROG = "autogit"
- SCRIPT_DIR = Path(__file__).resolve().parent
- DEFAULT_CONFIG_NAME = "autogit.json"
- EXAMPLE_CONFIG_NAME = "autogit.json.example"
- DEFAULT_LOG_NAME = "autogit.log"
- GITIGNORE_BEGIN = "# >>> autogit >>>"
- GITIGNORE_END = "# <<< autogit <<<"
- GITIGNORE_NOTE = "# 由 autogit 自动维护:这些文件含本机路径与访问令牌,绝不能入库。"
- # 配置文件的内置模板。这是唯一真源 —— autogit.ini.example 只是它的一个
- # 人类可读副本,丢了会自动补回来。不要把生成配置的逻辑改回去读那个文件,
- # 它一旦被改名/误删,工具就没法自举了。
- CONFIG_TEMPLATE = r"""
- {
- // ==================================================================
- // autogit 配置
- //
- // 只需要改 repo.url 这一处,其余全都有默认值,不用动。
- // (目录里已经配过 remote 的仓库,连 url 都不用填)
- //
- // 支持 // 行注释和 /* */ 块注释,写不写都不影响运行。
- // ⚠ 文件里可能出现访问令牌,脚本会自动把它写进 .gitignore。
- // ==================================================================
- "repo": {
- // 远端仓库地址。留空 = 用仓库现有的 remote 配置
- // 形如 https://gitee.com/你的用户名/仓库名.git
- "url": "",
- // 推送到哪条分支。留空 = 跟着仓库当前分支走
- "branch": "",
- // 远端名。一个仓库挂多个远端才需要改
- "remote": "origin",
- // 访问令牌(Gitee / GitHub 的私人令牌)
- // 留空 = 用系统已保存的凭据,首次推送会弹一次登录窗
- "token": "",
- // 令牌对应的用户名。留空用 oauth2(GitHub 建议填你的用户名)
- "username": "",
- // 仓库目录。留空 = 脚本所在目录
- "path": "",
- // 目录还不是 git 仓库时,自动 git init
- "autoInit": true,
- // 把 url 同步进 git 的 remote 配置
- "syncRemoteUrl": true
- },
- "commit": {
- // 提交信息模板。可用占位符:
- // {datetime} {date} {time} {branch} {remote} {count} {dir}
- "message": "sync: {datetime}",
- // 提交者。留空 = 用 git 的全局配置
- "name": "",
- "email": ""
- },
- "sync": {
- // 远端有你没有的提交、同时你也有待推送内容时(也就是分叉)怎么办:
- // "ask" 问你:y 合并后再推 / n 放弃本次推送 ← 推荐
- // "merge" 不问,直接合并
- // "abort" 不问,直接放弃
- "onRemoteAhead": "ask",
- // 合并真的冲突了怎么办:
- // "ask" 问你:y 用你本地的文件覆盖 / n 中止合并 ← 推荐
- // "ours" 不问,一律用本地文件覆盖
- // "abort" 不问,一律中止
- // 「用本地覆盖」走的是 git merge -s ours:结果文件 100% 是你本地的,
- // 而远端那几个提交仍然作为历史保留,不会被删。脚本永远不会强推。
- "onConflict": "ask",
- // 单条 git 网络命令的超时(秒)
- "timeoutSec": 300,
- // 推送成功后重新问一次远端,确认 SHA 对得上
- "verifyAfterPush": true
- },
- "ui": {
- // 命令行直接跑 python 时,结束是否等回车(双击 .bat 时由 bat 负责)
- "pauseOnExit": false,
- // 彩色输出:"auto" / "always" / "never"
- "color": "auto",
- // 日志文件。留空 = 不写日志
- "logFile": "autogit.log",
- // 日志超过这个大小(KB)就轮转成 .log.1
- "logSizeKb": 1024
- },
- "guard": {
- // 提交前扫描暂存区,这些文件一旦要被提交就中止
- "blockFiles": ["autogit.json", "autogit.log"],
- // 提交前扫描暂存区内容,发现令牌明文就中止
- "blockSecret": true
- }
- }
- """
- # 退出码 —— bat 会原样打印,方便判断卡在哪一步
- RC_OK = 0 # 成功(含「已是最新」)
- RC_ABORT = 1 # 用户主动放弃 / 中止
- RC_CONFIG = 2 # 配置或环境自检不通过
- RC_CONFLICT = 3 # 合并冲突未处理
- RC_NETWORK = 4 # 网络或推送失败
- RC_INTERNAL = 5 # 脚本内部异常
- VALID_ON_REMOTE_AHEAD = ("ask", "merge", "abort")
- VALID_ON_CONFLICT = ("ask", "ours", "abort")
- VALID_COLOR = ("auto", "always", "never")
- VALID_INIT_BRANCH_NOTE = "master"
- _ANSI = {
- "reset": "\033[0m",
- "bold": "\033[1m",
- "dim": "\033[2m",
- "red": "\033[31m",
- "green": "\033[32m",
- "yellow": "\033[33m",
- "blue": "\033[36m",
- "gray": "\033[90m",
- }
- # URL 里内嵌凭据的形态:http(s)://user:pass@host/...
- _INLINE_CRED_RE = re.compile(r"(https?://)([^/\s:@]+):([^/\s@]+)@")
- # --------------------------------------------------------------- 异常与退出码
- class AutogitError(Exception):
- rc = RC_INTERNAL
- class ConfigFatal(AutogitError):
- """配置或环境自检不通过,不能继续。"""
- rc = RC_CONFIG
- class UserAbort(AutogitError):
- """用户在交互里选择了放弃。"""
- rc = RC_ABORT
- class ConflictFatal(AutogitError):
- """合并冲突且没有处理掉。"""
- rc = RC_CONFLICT
- class PushFail(AutogitError):
- """网络或推送失败。"""
- rc = RC_NETWORK
- # ------------------------------------------------------------------ 基础工具
- def enable_vt() -> bool:
- """打开 Windows 控制台的 ANSI 转义支持,失败就退化到无色输出。"""
- if os.name != "nt":
- return True
- try:
- import ctypes
- k32 = ctypes.windll.kernel32
- handle = k32.GetStdHandle(-11)
- if handle in (0, -1):
- return False
- mode = ctypes.c_uint32()
- if not k32.GetConsoleMode(handle, ctypes.byref(mode)):
- return False
- return bool(k32.SetConsoleMode(handle, mode.value | 0x0004))
- except Exception:
- return False
- def decode_bytes(data) -> str:
- """git 的输出统一走这里。utf-8 优先,失败退 gbk,再失败用替换字符。"""
- if data is None:
- return ""
- if isinstance(data, str):
- return data
- for enc in ("utf-8", "gbk"):
- try:
- return data.decode(enc)
- except UnicodeDecodeError:
- continue
- return data.decode("utf-8", errors="replace")
- def mask_text(text: str, secrets=()) -> str:
- """脱敏:先抹掉已知密钥,再把 URL 内嵌的 user:pass 换成 user:***。"""
- out = text or ""
- for secret in secrets:
- if secret:
- out = out.replace(secret, "***")
- return _INLINE_CRED_RE.sub(r"\1\2:***@", out)
- def read_text_any(path: Path) -> str:
- """按 utf-8-sig / utf-8 / gbk 顺序读。用户拿记事本存 GBK 是常态。"""
- raw = path.read_bytes()
- for enc in ("utf-8-sig", "utf-8", "gbk"):
- try:
- return raw.decode(enc)
- except UnicodeDecodeError:
- continue
- return raw.decode("utf-8", errors="replace")
- def write_text_atomic(path: Path, text: str) -> None:
- """先写临时件、再原子替换。中途异常不留 0 字节文件。"""
- tmp = path.with_name(path.name + ".tmp~")
- with tmp.open("w", encoding="utf-8", newline="\n") as handle:
- handle.write(text)
- os.replace(str(tmp), str(path))
- def is_blank(value) -> bool:
- return value is None or str(value).strip() == ""
- # ---------------------------------------------------------------------- 输出
- class UI:
- """控制台 + 日志文件的统一出口。日志文件里不带 ANSI 颜色。"""
- def __init__(self, color="auto", log_path=None, log_size_kb=1024):
- self.use_color = self._decide_color(color)
- self.log_path = Path(log_path) if log_path else None
- self.log_size_kb = int(log_size_kb or 0)
- self.warn_count = 0
- self.err_count = 0
- @staticmethod
- def _decide_color(color: str) -> bool:
- if color == "never":
- return False
- if color == "always":
- return enable_vt()
- return sys.stdout.isatty() and enable_vt()
- def c(self, tone: str, text: str) -> str:
- if not self.use_color or tone not in _ANSI:
- return text
- return _ANSI[tone] + text + _ANSI["reset"]
- def raw(self, text: str = "") -> None:
- try:
- sys.stdout.write(text + "\n")
- sys.stdout.flush()
- except Exception:
- pass
- self._log(text)
- def _log(self, plain: str) -> None:
- if not self.log_path:
- return
- try:
- self.log_path.parent.mkdir(parents=True, exist_ok=True)
- if self.log_size_kb > 0 and self.log_path.exists():
- if self.log_path.stat().st_size > self.log_size_kb * 1024:
- bak = self.log_path.with_name(self.log_path.name + ".1")
- try:
- if bak.exists():
- bak.unlink()
- self.log_path.replace(bak)
- except OSError:
- pass
- with self.log_path.open("a", encoding="utf-8", newline="\n") as handle:
- handle.write(plain + "\n")
- except OSError:
- self.log_path = None
- # ---- 分级输出 ----
- def title(self, text: str) -> None:
- self.raw("")
- self.raw(self.c("bold", text))
- def info(self, text: str = "") -> None:
- self.raw(text)
- def dim(self, text: str) -> None:
- self.raw(self.c("dim", text))
- def ok(self, text: str) -> None:
- self.raw(self.c("green", "[ OK ] ") + text)
- def warn(self, text: str) -> None:
- self.warn_count += 1
- self.raw(self.c("yellow", "[WARN] ") + text)
- def err(self, text: str) -> None:
- self.err_count += 1
- self.raw(self.c("red", "[FAIL] ") + text)
- def step(self, idx: int, total: int, text: str) -> None:
- self.raw(self.c("blue", "[%d/%d] " % (idx, total)) + self.c("bold", text))
- def bullet(self, text: str, tone="gray") -> None:
- self.raw(self.c(tone, " · " + text))
- # ---- 交互 ----
- def ask_yn(self, question: str, default=None, auto_yes=False) -> bool:
- if auto_yes:
- self.raw(self.c("yellow", "[AUTO] ") + question + " -> y")
- return True
- if default is None:
- suffix = " [y/n] "
- else:
- suffix = " [Y/n] " if default else " [y/N] "
- while True:
- try:
- raw = input(self.c("bold", question + suffix))
- except (EOFError, KeyboardInterrupt):
- self.raw("")
- self.warn("没有收到输入,按「放弃」处理")
- return False
- ans = raw.strip().lower()
- if not ans and default is not None:
- return bool(default)
- if ans in ("y", "yes"):
- return True
- if ans in ("n", "no"):
- return False
- self.warn("请输入 y 或 n")
- def pause(self, enabled: bool) -> None:
- if not enabled:
- return
- try:
- input(self.c("dim", "\n按回车键关闭窗口 ..."))
- except (EOFError, KeyboardInterrupt):
- pass
- # ---------------------------------------------------------------------- 配置
- KNOWN_KEYS = {
- "repo": {"url", "branch", "remote", "token", "username", "path",
- "autoInit", "syncRemoteUrl"},
- "commit": {"message", "name", "email"},
- "sync": {"onRemoteAhead", "onConflict", "timeoutSec", "verifyAfterPush"},
- "ui": {"pauseOnExit", "color", "logFile", "logSizeKb"},
- "guard": {"blockFiles", "blockSecret"},
- }
- MESSAGE_PLACEHOLDERS = ("date", "time", "datetime", "branch", "remote", "count", "dir")
- VALID_ON_REMOTE_AHEAD = ("ask", "merge", "abort")
- VALID_ON_CONFLICT = ("ask", "ours", "abort")
- VALID_COLOR = ("auto", "always", "never")
- def strip_json_comments(text: str) -> str:
- """剥掉 JSONC 里的 // 和 /* */ 注释,得到标准 JSON。
- 不能用正则直接替换:字符串里的 // 必须原样留住,否则
- "url": "https://gitee.com/x/y.git"
- 会被腰斩成
- "url": "https:
- 所以这里用一个状态机,跟踪「是否在字符串内」以及「上一个字符是不是转义符」。
- 块注释里的换行要原样吐回去,不然 JSON 报错的列号会全部错位。
- """
- out = []
- i, n = 0, len(text)
- in_string = False
- while i < n:
- ch = text[i]
- if in_string:
- out.append(ch)
- if ch == "\\" and i + 1 < n:
- out.append(text[i + 1])
- i += 2
- continue
- if ch == '"':
- in_string = False
- i += 1
- continue
- if ch == '"':
- in_string = True
- out.append(ch)
- i += 1
- continue
- if ch == "/" and i + 1 < n:
- nxt = text[i + 1]
- if nxt == "/":
- while i < n and text[i] != "\n":
- i += 1
- continue
- if nxt == "*":
- out.append(" ")
- i += 2
- while i + 1 < n and not (text[i] == "*" and text[i + 1] == "/"):
- if text[i] == "\n":
- out.append("\n")
- i += 1
- i += 2
- continue
- out.append(ch)
- i += 1
- return "".join(out)
- class Conf:
- """JSON 配置。取值一律用点号路径,比如 conf.s("repo.url")。
- 整个文件都可以不存在 —— 每一项都有默认值,url 和 branch 还能从
- 仓库现状推出来(见 resolve_remote_url / resolve_branch)。
- 只有「文件存在但 JSON 坏了」才算致命,因为那说明你确实写了东西、
- 只是写错了,静默忽略比报错更危险。
- """
- def __init__(self, path: Path):
- self.path = Path(path)
- self.exists = False
- self.data = {}
- def load(self) -> None:
- self.exists = self.path.is_file()
- if not self.exists:
- return
- text = read_text_any(self.path)
- try:
- self.data = json.loads(strip_json_comments(text))
- except json.JSONDecodeError as exc:
- raise ConfigFatal("%s 不是合法 JSON:第 %d 行第 %d 列 —— %s"
- % (self.path.name, exc.lineno, exc.colno, exc.msg))
- if not isinstance(self.data, dict):
- raise ConfigFatal("%s 的最外层必须是一个 { } 对象" % self.path.name)
- # ---- 取值 ----
- def _raw(self, path: str):
- node = self.data
- for part in path.split("."):
- if not isinstance(node, dict) or part not in node:
- return None
- node = node[part]
- return node
- def s(self, path: str, default: str = "") -> str:
- value = self._raw(path)
- if value is None:
- return default
- if isinstance(value, bool):
- return "true" if value else "false"
- if isinstance(value, (int, float)):
- return str(value)
- if not isinstance(value, str):
- raise ConfigFatal("%s 需要是字符串,当前是 %s" % (path, type(value).__name__))
- return value.strip() or default
- def b(self, path: str, default: bool = False) -> bool:
- value = self._raw(path)
- if value is None:
- return default
- if isinstance(value, bool):
- return value
- if isinstance(value, str):
- low = value.strip().lower()
- if low in ("true", "yes", "y", "1", "on"):
- return True
- if low in ("false", "no", "n", "0", "off"):
- return False
- raise ConfigFatal("%s 需要是 true 或 false,当前是 %r" % (path, value))
- def i(self, path: str, default: int = 0) -> int:
- value = self._raw(path)
- if value is None:
- return default
- if isinstance(value, bool):
- raise ConfigFatal("%s 需要是整数,当前是 true/false" % path)
- if isinstance(value, int):
- return value
- if isinstance(value, str):
- try:
- return int(value.strip())
- except ValueError:
- pass
- raise ConfigFatal("%s 需要是整数,当前是 %r" % (path, value))
- def list_of(self, path: str, default=()) -> list:
- value = self._raw(path)
- if value is None:
- return list(default)
- if isinstance(value, str):
- return [item.strip() for item in re.split(r"[,;\n]", value) if item.strip()]
- if isinstance(value, list):
- return [str(item).strip() for item in value if str(item).strip()]
- raise ConfigFatal("%s 需要是数组,或者逗号分隔的字符串" % path)
- # ---- 自检:只看配置本身,不碰 git ----
- def check(self) -> tuple:
- """只校验「你写了的东西」,不要求你必须写什么。"""
- fatals, warns = [], []
- if not self.exists:
- return fatals, warns
- if not self.data:
- warns.append("%s 是空对象,全部按默认值来" % self.path.name)
- return fatals, warns
- # 不认识的段 / 键。拼错一个字母不会有任何报错、只会被静默忽略,
- # 所以这里列全已知键,见到不认识的就提醒一句。
- for section, value in self.data.items():
- if section not in KNOWN_KEYS:
- warns.append("配置里有未知的段 %r,会被忽略" % section)
- continue
- if not isinstance(value, dict):
- fatals.append("%r 需要是一个 { } 对象" % section)
- continue
- for key in value:
- if key not in KNOWN_KEYS[section]:
- warns.append("%s 里有未知的键 %r(拼错了?),会被忽略" % (section, key))
- branch = self.s("repo.branch")
- if branch:
- if branch.startswith("-") or branch.endswith("/") or ".." in branch:
- fatals.append("repo.branch 不是合法分支名:%r" % branch)
- elif re.search(r"[\s~^:?*\[\\]", branch):
- fatals.append("repo.branch 含非法字符:%r" % branch)
- url = self.s("repo.url")
- if url and not self._looks_like_remote(url):
- fatals.append("repo.url 认不出来:%r" % url)
- warns.append(" 支持 https://… http://… git@host:path ssh://… 本地路径")
- remote = self.s("repo.remote", "origin")
- if not re.match(r"^[A-Za-z0-9._-]+$", remote):
- fatals.append("repo.remote 只能包含字母数字和 . _ -:%r" % remote)
- for path, allowed in (("sync.onRemoteAhead", VALID_ON_REMOTE_AHEAD),
- ("sync.onConflict", VALID_ON_CONFLICT),
- ("ui.color", VALID_COLOR)):
- value = self.s(path)
- if value and value not in allowed:
- fatals.append("%s 只能是 %s 之一,当前是 %r"
- % (path, " / ".join(allowed), value))
- message = self.s("commit.message", "sync: {datetime}")
- for placeholder in re.findall(r"\{([^}]*)\}", message):
- if placeholder not in MESSAGE_PLACEHOLDERS:
- warns.append("提交信息里的占位符 {%s} 不认识,会原样保留" % placeholder)
- token = self.s("repo.token")
- if token and len(token) < 8:
- warns.append("token 只有 %d 位,确认一下是不是填漏了" % len(token))
- return fatals, warns
- @staticmethod
- def _looks_like_remote(url: str) -> bool:
- if re.match(r"^(https?|ssh|git|file)://", url, re.I):
- return True
- if re.match(r"^[A-Za-z0-9._-]+@[A-Za-z0-9._-]+:", url):
- return True
- if re.match(r"^[A-Za-z]:[\\/]", url):
- return True
- return url.startswith(("/", "\\\\", "./", "../"))
- class Git:
- """git 命令包装。命令不经 shell,输出统一 bytes -> decode_bytes。"""
- def __init__(self, exe: str, cwd: Path, ui: UI, dry_run=False):
- self.exe = exe
- self.cwd = Path(cwd)
- self.ui = ui
- self.dry = dry_run
- self.secrets = []
- def _argv(self, args):
- # core.quotepath=false -> 中文路径原样输出,不变八进制转义
- # core.pager=cat -> 绝不启动分页器把脚本挂住
- return [self.exe, "-c", "core.quotepath=false", "-c", "core.pager=cat"] + list(args)
- def _env(self):
- env = os.environ.copy()
- # 不让 git 在控制台等输入;凭据交互交给 GCM 的图形窗口
- env["GIT_TERMINAL_PROMPT"] = "0"
- return env
- def mask(self, text: str) -> str:
- return mask_text(text, self.secrets)
- def run(self, args, timeout=None):
- try:
- proc = subprocess.run(
- self._argv(args),
- cwd=str(self.cwd),
- stdin=subprocess.DEVNULL,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=timeout,
- env=self._env(),
- )
- except FileNotFoundError:
- raise ConfigFatal("找不到 git 可执行文件:%s" % self.exe)
- except subprocess.TimeoutExpired:
- raise PushFail("git 命令超时(%s 秒):git %s"
- % (timeout, " ".join(self.mask(a) for a in args)))
- proc.out = decode_bytes(proc.stdout).strip()
- proc.err = decode_bytes(proc.stderr).strip()
- return proc
- def out(self, args, timeout=None) -> str:
- return self.run(args, timeout=timeout).out
- def ok(self, args, timeout=None) -> bool:
- try:
- return self.run(args, timeout=timeout).returncode == 0
- except AutogitError:
- return False
- def wait(self, args, what: str, timeout=None):
- """跑一条命令,非 0 退出就抛异常(附带脱敏后的 stderr)。"""
- proc = self.run(args, timeout=timeout)
- if proc.returncode != 0:
- raise PushFail("%s 失败:%s" % (what, self.mask(proc.err or proc.out)))
- return proc
- # ---- 只读查询 ----
- def version(self) -> str:
- return self.out(["--version"]).replace("git version ", "")
- def is_repo(self) -> bool:
- return self.ok(["rev-parse", "--is-inside-work-tree"])
- def current_branch(self) -> str:
- """当前分支名。空仓库里 HEAD 已经指向分支,这里同样能取到名字。"""
- return self.out(["symbolic-ref", "--short", "-q", "HEAD"])
- def is_detached(self) -> bool:
- """detached HEAD 的判据是「HEAD 不是符号引用」。
- 不能用 rev-parse --abbrev-ref —— 空仓库里它也会返回 HEAD。"""
- return not self.ok(["symbolic-ref", "-q", "HEAD"])
- def head_sha(self) -> str:
- """当前提交的 SHA,空仓库返回空串。
- 不能只判断「输出非空」:空仓库里 `git rev-parse HEAD` 会先把字面量
- "HEAD" 打到 stdout,然后才 fatal 退出。于是这个字符串会被当成提交 ID,
- 空仓库被误判成「已经有提交」,后面的切分支/首次推送全乱套。
- 所以这里用 --verify --quiet 并且校验它确实是一串十六进制。
- """
- proc = self.run(["rev-parse", "--verify", "--quiet", "HEAD"])
- if proc.returncode != 0:
- return ""
- value = proc.out.strip()
- if not value or not re.fullmatch(r"[0-9a-fA-F]{7,64}", value):
- return ""
- return value
- def ref_exists(self, ref: str) -> bool:
- return self.ok(["rev-parse", "--verify", "--quiet", ref])
- def config_get(self, key: str) -> str:
- return self.out(["config", "--get", key])
- def in_progress_operation(self) -> str:
- gitdir = self.out(["rev-parse", "--git-dir"])
- if not gitdir:
- return ""
- base = Path(gitdir)
- if not base.is_absolute():
- base = self.cwd / base
- probes = (
- ("MERGE_HEAD", "合并(merge)"),
- ("rebase-merge", "变基(rebase)"),
- ("rebase-apply", "变基(rebase)"),
- ("CHERRY_PICK_HEAD", "遴选(cherry-pick)"),
- ("REVERT_HEAD", "回退(revert)"),
- )
- for name, label in probes:
- if (base / name).exists():
- return label
- return ""
- def staged_entries(self) -> list:
- rows = []
- for line in self.out(["diff", "--cached", "--name-status", "--no-renames"]).splitlines():
- parts = line.split("\t")
- if len(parts) >= 2:
- rows.append((parts[0].strip(), parts[-1].strip()))
- return rows
- def dirty_entries(self) -> list:
- """工作区相对 HEAD 的全部差异(含未暂存),dry-run 下用它估算。"""
- rows = []
- for line in self.out(["status", "--porcelain", "--untracked-files=all"]).splitlines():
- if len(line) >= 4:
- rows.append((line[:2].strip() or "??", line[3:].strip()))
- return rows
- def count_commits(self, rng: str):
- """数提交个数。**算不出来返回 None,不能悄悄当成 0**。
- 这里的静默失败非常危险:如果 rev-list 因为对象缺失或参数错误失败,
- 返回 0 就会被读成「两边一样多」,于是本该合并的分叉被当成「已是最新」,
- 本该推送的提交被跳过。宁可让调用方看到 None 然后停下来。
- """
- proc = self.run(["rev-list", "--count", rng])
- if proc.returncode != 0:
- return None
- try:
- return int(proc.out.strip())
- except ValueError:
- return None
- def ls_remote_head(self, remote_or_url: str, branch: str, timeout=None):
- """一次调用同时拿到:连通性、分支是否存在、远端 SHA。"""
- proc = self.run(["ls-remote", "--heads", remote_or_url, "refs/heads/%s" % branch],
- timeout=timeout)
- if proc.returncode != 0:
- return None, self.mask(proc.err or proc.out)
- for line in proc.out.splitlines():
- parts = line.split()
- if len(parts) >= 2 and parts[1].rstrip("/").endswith("/" + branch):
- return parts[0], ""
- return "", ""
- def conflicted_files(self) -> list:
- return [x for x in self.out(["diff", "--name-only", "--diff-filter=U"]).splitlines()
- if x.strip()]
- # ---- 写操作(dry-run 只打印)----
- def _write(self, args, what: str, timeout=None, check=True):
- printable = " ".join(self.mask(a) for a in args)
- if self.dry:
- self.ui.dim(" [dry-run] 将执行:git %s" % printable)
- return None
- self.ui.dim(" $ git %s" % printable)
- proc = self.run(args, timeout=timeout)
- if check and proc.returncode != 0:
- raise PushFail("%s 失败:%s" % (what, self.mask(proc.err or proc.out)))
- return proc
- def add_all(self):
- return self._write(["add", "-A"], "git add")
- def commit(self, message: str):
- return self._write(["commit", "-m", message], "git commit")
- def merge(self, ref: str, strategy=None, timeout=None, allow_unrelated=False):
- args = ["merge", "--no-edit"]
- # 两边各自 git init 出来的历史没有共同祖先,git 默认拒绝合并。
- # 新一代 git 还会把「拒绝合并不相关历史」写成一堆注释塞进 MERGE_MSG,
- # 看起来像冲突但其实不是,所以这个开关必须能显式打开。
- if allow_unrelated:
- args.append("--allow-unrelated-histories")
- if strategy:
- args += ["-s", strategy]
- args.append(ref)
- return self._write(args, "git merge", timeout=timeout, check=False)
- def merge_abort(self):
- return self._write(["merge", "--abort"], "git merge --abort", check=False)
- def push(self, url: str, branch: str, timeout=None):
- # 显式 URL 推送:token 不落进 .git/config
- return self._write(["push", url, "refs/heads/%s:refs/heads/%s" % (branch, branch)],
- "git push", timeout=timeout, check=False)
- def fetch_branch(self, remote: str, branch: str, timeout=None) -> bool:
- """把远端分支抓成 refs/remotes/<remote>/<branch>。只动 refs,不碰工作区。"""
- refspec = "+refs/heads/%s:refs/remotes/%s/%s" % (branch, remote, branch)
- if self.dry:
- self.ui.dim(" [dry-run] 将执行:git fetch %s %s" % (remote, refspec))
- return True
- proc = self.run(["fetch", "--no-tags", remote, refspec], timeout=timeout)
- if proc.returncode != 0:
- self.ui.dim(" fetch 输出:%s" % self.mask(proc.err or proc.out))
- return False
- return True
- def find_git() -> str:
- """PATH -> 常见安装位置,逐个实测能跑起来才算数。"""
- candidates = []
- for name in ("git", "git.exe"):
- found = shutil.which(name)
- if found:
- candidates.append(found)
- for guess in (r"D:\software\git\cmd\git.exe",
- r"C:\Program Files\Git\cmd\git.exe",
- r"C:\Program Files (x86)\Git\cmd\git.exe"):
- if os.path.isfile(guess):
- candidates.append(guess)
- seen = set()
- for exe in candidates:
- key = os.path.normcase(os.path.abspath(exe))
- if key in seen:
- continue
- seen.add(key)
- try:
- proc = subprocess.run([exe, "--version"], stdin=subprocess.DEVNULL,
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
- if proc.returncode == 0:
- return exe
- except Exception:
- continue
- return ""
- # ---------------------------------------------------------------------- 上下文
- class Ctx:
- def __init__(self, args):
- self.args = args
- self.conf_path = Path(args.config).resolve() if args.config \
- else (SCRIPT_DIR / DEFAULT_CONFIG_NAME)
- self.conf = Conf(self.conf_path)
- self.ui = None
- self.git = None
- self.repo_dir = SCRIPT_DIR
- self.remote = "origin"
- self.branch = "master"
- self.url = ""
- self.token = ""
- self.username = ""
- self.authed_url = ""
- self.log_name = DEFAULT_LOG_NAME
- self.block_files = []
- self.block_secret = True
- self.timeout = 300
- # -------------------------------------------------------------------- .gitignore
- def merge_ignore_block(text: str, entries) -> str:
- """把 entries 并进 autogit 标记块(只增不减,保留用户手工加的其它规则)。"""
- kept, in_block, current = [], False, []
- for line in text.splitlines():
- stripped = line.strip()
- if stripped == GITIGNORE_BEGIN:
- in_block = True
- continue
- if stripped == GITIGNORE_END:
- in_block = False
- continue
- if in_block:
- # 以 ! 开头的是「取消忽略」,语义跟忽略正好相反,不能当成有效条目收进块里
- if stripped and not stripped.startswith("#") and not stripped.startswith("!"):
- current.append(stripped)
- continue
- kept.append(line)
- merged = sorted(set(current) | {str(e).replace("\\", "/") for e in entries},
- key=lambda x: x.lower())
- block = [GITIGNORE_BEGIN, GITIGNORE_NOTE] + merged + [GITIGNORE_END]
- while kept and not kept[-1].strip():
- kept.pop()
- return "\n".join(kept + ([""] if kept else []) + block) + "\n"
- def ignore_rules(text: str) -> set:
- """收集 .gitignore 里真正生效的忽略规则。
- 注意跳过以 ! 开头的行 —— 那是「不要忽略」,含义跟忽略相反。
- 要是把它也收进来,用户写了 !autogit.ini 反而会被判成「已经排除好了」,
- 结果令牌文件就这么进了仓库。
- """
- rules = set()
- for line in text.splitlines():
- stripped = line.strip()
- if not stripped or stripped.startswith("#") or stripped.startswith("!"):
- continue
- rules.add(stripped.replace("\\", "/").lower())
- return rules
- def check_gitignore(ctx: Ctx) -> None:
- """确保 .gitignore 覆盖了禁入文件。已被追踪的先拦住,否则自动补规则。"""
- ui, git = ctx.ui, ctx.git
- entries = ctx.block_files
- if not entries:
- return
- tracked = [name for name in entries
- if git.out(["ls-files", "--error-unmatch", name])]
- if tracked:
- ui.err("这些文件已经被 git 追踪,光写 .gitignore 拦不住:" + "、".join(tracked))
- for name in tracked:
- ui.bullet('git rm --cached "%s"' % name, tone="yellow")
- ui.bullet("token 就在这些文件里,先执行上面的命令再从暂存区提交", tone="yellow")
- raise ConfigFatal("禁入文件已被 git 追踪")
- ignore_path = ctx.repo_dir / ".gitignore"
- text = read_text_any(ignore_path) if ignore_path.is_file() else ""
- missing = [name for name in entries
- if name.replace("\\", "/").lower() not in ignore_rules(text)]
- if not missing:
- ui.ok(".gitignore 已排除 %s" % "、".join(entries))
- return
- new_text = merge_ignore_block(text, missing)
- if git.dry:
- ui.dim(" [dry-run] 将往 .gitignore 追加:" + "、".join(missing))
- return
- try:
- write_text_atomic(ignore_path, new_text)
- except OSError as exc:
- raise ConfigFatal("写入 .gitignore 失败:%s" % exc)
- ui.warn(".gitignore 缺少排除项,已自动补上:" + "、".join(missing))
- def resolve_remote_url(ctx: Ctx) -> None:
- """决定往哪儿推。
- 优先级:配置里的 repo.url > 仓库现有的 remote > 都没有就报错。
- 无论走哪条路,脚本都不会中途停下来问你 —— 需要你决定的东西一律
- 写在 autogit.json 里,运行过程只负责读它、报告读了什么。
- """
- ui, git = ctx.ui, ctx.git
- from_conf = ctx.conf.s("repo.url")
- if from_conf:
- ctx.url = from_conf
- ui.ok("远端地址 %s(来自 %s)" % (mask_text(ctx.url), ctx.conf_path.name))
- return
- existing = git.config_get("remote.%s.url" % ctx.remote).strip()
- if existing:
- ctx.url = existing
- ui.ok("远端地址 %s(取自仓库现有的 remote %s)" % (mask_text(ctx.url), ctx.remote))
- return
- ui.warn("还不知道往哪个仓库推")
- ui.bullet("在 %s 里把 url 填上就行:" % ctx.conf_path.name, tone="yellow")
- ui.bullet(' "url": "https://gitee.com/你的用户名/仓库名.git"', tone="yellow")
- ui.bullet("(或者先执行 git remote add %s <地址>)" % ctx.remote)
- if ctx.args.check:
- return
- raise ConfigFatal("没有可用的远端地址")
- def resolve_branch(ctx: Ctx) -> None:
- """决定推哪条分支。
- 优先级:autogit.ini 里写的 branch > 仓库当前分支 > master。
- 空仓库里 HEAD 也已经指向某个分支名(git init 时定的,你机器上是 master),
- 所以「你在哪条分支上就推哪条」对空仓库同样成立 —— 通常完全不用操心。
- """
- ui, git = ctx.ui, ctx.git
- from_conf = ctx.conf.s("repo.branch")
- if from_conf:
- ctx.branch = from_conf
- ui.ok("目标分支:%s(来自 %s)" % (ctx.branch, ctx.conf_path.name))
- return
- current = git.current_branch()
- if current:
- ctx.branch = current
- ui.ok("目标分支:%s(跟着仓库当前分支走)" % ctx.branch)
- return
- ctx.branch = "master"
- ui.ok("目标分支:master(默认值)")
- def build_authed_url(ctx: Ctx) -> str:
- """裸 URL + username + token 拼成带凭据的 URL。只在内存里存在。"""
- if is_blank(ctx.token):
- return ctx.url
- split = urlsplit(ctx.url)
- if split.scheme.lower() not in ("http", "https"):
- ctx.ui.warn("url 不是 http(s),token 只对 http(s) 仓库生效,本次忽略 token")
- return ctx.url
- host = split.hostname or ""
- if split.port:
- host += ":%d" % split.port
- netloc = "%s:%s@%s" % (quote(ctx.username or "oauth2", safe=""),
- quote(ctx.token, safe=""), host)
- return split._replace(netloc=netloc).geturl()
- def guard_staged(ctx: Ctx) -> None:
- """最后一道闸门:提交前确认配置文件和 token 明文没混进暂存区。"""
- ui, git = ctx.ui, ctx.git
- if ctx.args.dry_run:
- rows = git.dirty_entries()
- else:
- rows = git.staged_entries()
- staged_names = {Path(name).name.lower() for _status, name in rows}
- hit = [name for name in ctx.block_files if name.lower() in staged_names]
- if hit:
- ui.err("暂存区里有不该提交的文件:" + "、".join(hit))
- ui.bullet("这些文件含本机路径和访问令牌,提交出去等于把钥匙贴公告栏", tone="yellow")
- ui.bullet("真要提交,就把它们从 [guard] block_files 里去掉", tone="yellow")
- raise ConfigFatal("禁入文件进了暂存区")
- if not ctx.block_secret or is_blank(ctx.token) or ctx.args.dry_run:
- return
- # 在 index 里直接搜 token 明文,比 dump 整个 diff 快得多。
- # 末尾的 -- 是防止 token 本身以 - 开头时被 git 当成选项。
- proc = git.run(["grep", "--cached", "-F", "-I", "-e", ctx.token, "--"], timeout=120)
- if proc.returncode == 0 and proc.out.strip():
- ui.err("暂存区的内容里出现了 token 明文,已中止提交")
- for line in proc.out.splitlines()[:5]:
- ui.bullet(mask_text(line, [ctx.token]), tone="yellow")
- ui.bullet("把 token 从该文件里删掉;确实需要就设 [guard] block_secret = false",
- tone="yellow")
- raise ConfigFatal("token 明文进了暂存区")
- # --------------------------------------------------------------------- 主流程
- def render_message(template: str, ctx: Ctx, count: int, now: dt.datetime) -> str:
- mapping = {
- "{date}": now.strftime("%Y-%m-%d"),
- "{time}": now.strftime("%H:%M:%S"),
- "{datetime}": now.strftime("%Y-%m-%d %H:%M:%S"),
- "{branch}": ctx.branch,
- "{remote}": ctx.remote,
- "{count}": str(count),
- "{dir}": ctx.repo_dir.name,
- }
- out = template
- for key, value in mapping.items():
- out = out.replace(key, value)
- return out
- def do_commit_if_needed(ctx: Ctx) -> int:
- """有变更就提交,返回涉及的变更文件数(0 = 没有变更)。"""
- ui, git = ctx.ui, ctx.git
- if git.dry:
- rows = git.dirty_entries()
- else:
- git.add_all()
- rows = git.staged_entries()
- if not rows:
- ui.ok("没有文件变更")
- return 0
- guard_staged(ctx)
- label = {"A": "新增", "M": "修改", "D": "删除", "R": "重命名", "C": "复制",
- "T": "类型变更", "??": "未跟踪"}
- counts = {}
- for status, _name in rows:
- counts[status[:1] if status in label else status] = \
- counts.get(status[:1] if status in label else status, 0) + 1
- detail = "、".join("%s %d" % (label.get(key, key), value)
- for key, value in sorted(counts.items()))
- ui.info(" 本次变更 %d 个文件(%s)" % (len(rows), detail))
- for status, name in rows[:12]:
- ui.bullet("%s %s" % (status.ljust(2), name))
- if len(rows) > 12:
- ui.bullet("… 其余 %d 个" % (len(rows) - 12))
- if git.dry:
- ui.dim(" [dry-run] 跳过 commit(否则提交信息会是:%s)"
- % render_message(ctx.conf.s("commit.message", "sync: {datetime}"),
- ctx, len(rows), dt.datetime.now()))
- return len(rows)
- name = ctx.conf.s("commit.name")
- email = ctx.conf.s("commit.email")
- if name and not git.config_get("user.name"):
- git.run(["config", "user.name", name])
- if email and not git.config_get("user.email"):
- git.run(["config", "user.email", email])
- message = render_message(ctx.conf.s("commit.message", "sync: {datetime}"),
- ctx, len(rows), dt.datetime.now())
- git.commit(message)
- ui.ok("已提交:%s" % message)
- return len(rows)
- def check_remote_default_branch(ctx: Ctx, url: str, branch: str) -> None:
- """首次推送后看一眼远端默认分支的指向。
- 托管平台新建仓库时可能已经把默认分支定成 main。我们把内容推到了
- master,如果远端 HEAD 还指着 main,别人(或你换台机器)克隆下来会得到
- 一个空目录,看着就像推送没成功。
- 实测两种形态:
- HEAD 指向存在的分支 -> `ref: refs/heads/xxx\tHEAD`
- HEAD 指向不存在的分支 -> 输出为空(退出码仍是 0)
- 所以「拿到空的 ref: 行」本身就是信号。这个检查只在首次推送后跑一次,
- 属于锦上添花,任何异常都静默略过。
- """
- ui, git = ctx.ui, ctx.git
- proc = git.run(["ls-remote", "--symref", url, "HEAD"], timeout=ctx.timeout)
- if proc.returncode != 0:
- return
- target = ""
- for line in proc.out.splitlines():
- parts = line.split()
- if len(parts) >= 2 and parts[0] == "ref:":
- target = parts[1].replace("refs/heads/", "").strip()
- break
- if not target:
- # 刚推成功,分支肯定在,HEAD 却是悬空的
- ui.warn("远端的默认分支没有指向任何一个存在的分支(HEAD 悬空)")
- ui.bullet("换台机器克隆下来会是个空目录,看着像推送没成功", tone="yellow")
- ui.bullet("去仓库的「设置 → 默认分支」改成 %s 就好了" % branch, tone="yellow")
- return
- if target == branch:
- return
- ui.warn("远端默认分支指向 %s,而我们推的是 %s" % (target, branch))
- ui.bullet("换台机器克隆下来默认会检出 %s,看着像是空的" % target, tone="yellow")
- ui.bullet("去仓库的「设置 → 默认分支」改成 %s 就好了" % branch, tone="yellow")
- def sync_with_remote(ctx: Ctx, auto_yes: bool) -> None:
- """fetch -> 按需合并 -> push -> 用远端 SHA 验证。"""
- ui, git = ctx.ui, ctx.git
- remote, branch, timeout = ctx.remote, ctx.branch, ctx.timeout
- tracking = "refs/remotes/%s/%s" % (remote, branch)
- query_url = ctx.authed_url or ctx.url
- # ---- 1. 连通性 + 远端分支是否存在 + 远端 SHA,一次问清楚 ----
- ui.step(5, 6, "检查远端仓库")
- remote_head, error = git.ls_remote_head(query_url, branch, timeout=timeout)
- if remote_head is None:
- ui.err("连不上远端仓库,或者认证没通过")
- ui.bullet("地址:%s" % mask_text(ctx.url))
- ui.bullet("检查网络、仓库地址、token 是否过期", tone="yellow")
- if error:
- ui.dim(" git 返回:%s" % error.splitlines()[0])
- raise PushFail("ls-remote 失败")
- if remote_head:
- first_push = False
- ui.ok("远端 %s/%s 存在,SHA %s" % (remote, branch, remote_head[:8]))
- # fetch 必须成功。曾经这里失败会退化成「把 ls-remote 的 SHA 直接塞进
- # refs/remotes/<remote>/<branch>」,可那个对象本地根本没有,紧接着
- # rev-list 会失败、差数被算成 0 —— 于是分叉被读成「已是最新」,
- # 该合并的直接跳过。状态不明就不允许做合并/推送的决定。
- if not git.fetch_branch(remote, branch, timeout=timeout) and not git.dry:
- ui.dim(" fetch 失败,重试一次…")
- if not git.fetch_branch(remote, branch, timeout=timeout):
- ui.err("拉取远端状态失败,现在说不准远端是什么情况")
- ui.bullet("状态不明的时候合并或推送都可能出错,这次先停", tone="yellow")
- ui.bullet("确认网络后直接重跑一次就行,本地提交不会丢", tone="yellow")
- raise PushFail("fetch 远端失败")
- else:
- first_push = True
- ui.info(" 远端还没有 %s 分支,本次将是首次推送" % branch)
- head = git.head_sha()
- if not head:
- raise ConfigFatal("HEAD 读不出来,仓库是空的而且没有可提交的内容")
- # ---- 2. 算两边的差 ----
- if not remote_head:
- # 远端没有这个分支:本地所有提交都要推上去。
- # 这里绝不能去看 refs/remotes/<remote>/<branch> —— 远端要是被清空重建过,
- # 本地还留着上一次的陈旧引用,照它算会算出「待推送 0 个」然后什么都不做。
- local_ahead = git.count_commits("HEAD")
- remote_ahead = 0
- else:
- local_ahead = git.count_commits("%s..HEAD" % tracking)
- remote_ahead = git.count_commits("HEAD..%s" % tracking)
- if local_ahead is None or remote_ahead is None:
- ui.err("算不清本地和远端的提交差,状态不明,不敢继续")
- ui.bullet("先手动看一眼:git status 和 git ls-remote %s" % remote, tone="yellow")
- raise ConfigFatal("提交差算不出来")
- ui.info(" 本地待推送 %d 个提交,远端多出 %d 个提交" % (local_ahead, remote_ahead))
- # ---- 3. 分叉 -> 按配置决定合并 ----
- if local_ahead > 0 and remote_ahead > 0:
- ui.warn("本地与远端已经分叉:本地 %d 个待推,远端 %d 个你没拉过"
- % (local_ahead, remote_ahead))
- mode = ctx.conf.s("sync.onRemoteAhead", "ask")
- if mode == "merge":
- ui.info(" [sync] on_remote_ahead = merge,按配置直接合并")
- do_merge = True
- elif mode == "abort":
- ui.info(" [sync] on_remote_ahead = abort,按配置放弃本次推送")
- do_merge = False
- else:
- do_merge = ui.ask_yn("是否先把远端的 %d 个提交合并进来?" % remote_ahead,
- default=True, auto_yes=auto_yes)
- if not do_merge:
- ui.warn("已放弃推送。本地提交保留着,下次双击会自动重试。")
- ui.bullet("想手动处理:git fetch %s && git merge %s/%s" % (remote, remote, branch))
- raise UserAbort("用户放弃推送")
- ui.step(6, 6, "合并远端提交")
- # 本地是自己 git init 出来的、远端是平台新建时自带了一个初始提交
- # (常见的「新建仓库顺手勾了初始化 README」),这种两边没有共同祖先,
- # git 会直接拒绝合并。它不是冲突,加个开关就能正常合。
- allow_unrelated = False
- proc = git.merge("%s/%s" % (remote, branch), timeout=timeout)
- if proc is not None and proc.returncode != 0:
- blob = (proc.err or "") + (proc.out or "")
- if "unrelated histories" in blob or "refusing to merge" in blob:
- ui.warn("本地和远端是两条互不相关的历史(远端仓库带了个初始提交)")
- ui.info(" 加上 --allow-unrelated-histories 重新合并")
- allow_unrelated = True
- proc = git.merge("%s/%s" % (remote, branch), timeout=timeout,
- allow_unrelated=True)
- if proc is not None and proc.returncode != 0:
- conflicts = git.conflicted_files()
- if not conflicts:
- ui.err("合并失败,而且没识别出冲突文件")
- ui.dim(" %s" % mask_text(proc.err or proc.out)[:400])
- git.merge_abort()
- raise ConflictFatal("合并失败")
- ui.err("有 %d 个文件合并冲突:" % len(conflicts))
- for name in conflicts[:15]:
- ui.bullet(name, tone="yellow")
- if len(conflicts) > 15:
- ui.bullet("… 其余 %d 个" % (len(conflicts) - 15))
- mode = ctx.conf.s("sync.onConflict", "ask")
- if mode == "ours":
- ui.info(" [sync] on_conflict = ours,按配置用本地版本覆盖")
- use_ours = True
- elif mode == "abort":
- ui.info(" [sync] on_conflict = abort,按配置中止")
- use_ours = False
- else:
- use_ours = ui.ask_yn("是否用你本地的文件覆盖这些冲突(保留远端历史)?",
- default=None, auto_yes=auto_yes)
- if not use_ours:
- ui.warn("已中止合并,工作区恢复到合并前,本地提交保留。")
- git.merge_abort()
- raise UserAbort("用户放弃合并")
- # -s ours:结果树 100% 等于本地树,远端那几个提交仍作为第二父保留
- git.merge_abort()
- ui.info(" 改用「内容以本地为准」的方式重新合并…")
- proc = git.merge("%s/%s" % (remote, branch), strategy="ours", timeout=timeout,
- allow_unrelated=allow_unrelated)
- if proc is not None and proc.returncode != 0:
- ui.err("以本地为准的合并也失败了")
- ui.dim(" %s" % mask_text(proc.err or proc.out)[:400])
- git.merge_abort()
- raise ConflictFatal("merge -s ours 失败")
- ui.ok("已合并:内容取本地版本,远端提交保留在历史里")
- if not git.dry:
- local_ahead = git.count_commits("%s..HEAD" % tracking)
- if local_ahead is None:
- raise ConfigFatal("合并后算不出待推送提交数,状态不明,先停")
- elif remote_ahead > 0:
- ui.warn("本地落后远端 %d 个提交,而本地没有待推送的内容" % remote_ahead)
- ui.bullet("文件是旧的,要不要拉一下你自己定", tone="yellow")
- # ---- 4. 推送 ----
- if local_ahead <= 0:
- if remote_ahead > 0:
- ui.ok("本地没有要推的东西(远端比你新)")
- else:
- ui.ok("已经是最新,无需推送")
- return
- ui.step(6, 6, "推送到远端")
- proc = git.push(query_url, branch, timeout=timeout)
- if proc is not None and proc.returncode != 0:
- ui.err("推送失败")
- ui.dim(" %s" % mask_text(proc.err or proc.out)[:600])
- ui.bullet("本地提交保留着,下次双击会自动重试", tone="yellow")
- raise PushFail("push 失败")
- # ---- 5. 验证:不信返回码,重新问远端 ----
- if git.dry or not ctx.conf.b("sync.verifyAfterPush", True):
- return
- after, err = git.ls_remote_head(query_url, branch, timeout=timeout)
- head = git.head_sha()
- if after is None:
- # 复核时连不上 ≠ 推送失败。这里必须分开说,笼统报「对不上」就是撒谎。
- ui.warn("推送命令返回成功,但复核时连不上远端,暂时无法确认")
- if err:
- ui.dim(" git 返回:%s" % err.splitlines()[0])
- ui.bullet("稍后自己确认一次:git ls-remote %s %s" % (remote, branch), tone="yellow")
- elif after and head and after.startswith(head[:8]):
- ui.ok("远端已确认更新到 %s" % head[:8])
- else:
- ui.warn("推送命令返回成功,但远端 SHA 和本地对不上")
- ui.bullet("本地 %s / 远端 %s" % (head[:8] or "?", (after or "无")[:8]))
- ui.bullet("请手动 git ls-remote 复核一次", tone="yellow")
- # 首次推送额外确认远端默认分支的指向
- if first_push:
- check_remote_default_branch(ctx, query_url, branch)
- # ------------------------------------------------------------------ 启动与编排
- def banner(ui: UI, subtitle: str) -> None:
- ui.raw("")
- ui.raw(ui.c("bold", "=" * 64))
- ui.raw(ui.c("bold", " autogit v%s · %s" % (__version__, subtitle)))
- ui.raw(ui.c("bold", "=" * 64))
- def ensure_example_exists() -> None:
- """旁边没有参考模板就补一份。
- 纯参考用 —— 生成配置的逻辑早就改成读内置常量了,这个文件在不在
- 都不影响运行。丢了就静默补回来,不打扰任何人。
- """
- example = SCRIPT_DIR / EXAMPLE_CONFIG_NAME
- if example.is_file():
- return
- try:
- write_text_atomic(example, CONFIG_TEMPLATE)
- except OSError:
- pass
- def should_pause(conf, args) -> bool:
- """「结束时等回车」由谁负责。
- 被 .bat 包着的时候(AUTOGIT_WRAPPED=1)一律交给 bat —— 它在所有路径上
- 都会 pause,包括 python 根本没启动起来的情况。这样做的好处是双击时
- 只会停一次,而 python 崩在启动阶段也不会一闪而过。
- 独立跑 python 时才看配置和 --no-pause。
- """
- if not is_blank(os.environ.get("AUTOGIT_WRAPPED")):
- return False
- if args.no_pause:
- return False
- return conf.b("ui.pauseOnExit", False) if conf else False
- def run(args) -> int:
- ctx = Ctx(args)
- # 配置文件不存在已经不算错误了 —— Conf.load 会安静地把 exists 置 False,
- # 后面 url / branch 各自从仓库现状推断。只有语法坏了才在这里拦下。
- try:
- ctx.conf.load()
- except ConfigFatal as exc:
- boot = UI(color="never" if args.no_color else "auto")
- boot.err(str(exc))
- boot.pause(should_pause(None, args))
- return RC_CONFIG
- # 顺手补一份参考模板。纯粹给人抄,不参与运行,失败也不出声。
- ensure_example_exists()
- # ---- 日志路径 ----
- ctx.log_name = ctx.conf.s("ui.logFile", DEFAULT_LOG_NAME)
- if args.no_log:
- log_path = None
- elif os.path.isabs(ctx.log_name):
- log_path = Path(ctx.log_name)
- else:
- log_path = SCRIPT_DIR / ctx.log_name
- ui = UI(color="never" if args.no_color else ctx.conf.s("ui.color", "auto"),
- log_path=log_path,
- log_size_kb=ctx.conf.i("ui.logSizeKb", 1024))
- ctx.ui = ui
- banner(ui, "配置自检 → 提交 → 推送")
- ui.info("配置文件:%s" % ctx.conf_path)
- ui.info("运行时间:%s" % dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
- if args.dry_run:
- ui.warn("dry-run:只打印将要执行的操作,不真正落盘")
- if args.check:
- ui.warn("check:只做自检,不提交不推送")
- try:
- code = flow(ctx)
- except AutogitError as exc:
- ui.info("")
- ui.err(str(exc))
- code = exc.rc
- except KeyboardInterrupt:
- ui.info("")
- ui.err("被中断")
- code = RC_ABORT
- except Exception:
- ui.info("")
- ui.err("脚本内部异常,下面是堆栈:")
- ui.info(traceback.format_exc())
- code = RC_INTERNAL
- ui.info("")
- ui.raw(ui.c("bold", "─" * 64))
- if code == RC_OK:
- ui.raw(ui.c("green", " 完成 ") + "(警告 %d 条)" % ui.warn_count)
- else:
- ui.raw(ui.c("red", " 未完成 ") + "退出码 %d" % code)
- ui.pause(should_pause(ctx.conf, args))
- return code
- def flow(ctx: Ctx) -> int:
- ui = ctx.ui
- # ============================================ 1. 配置自检
- ui.step(1, 6, "读配置")
- if not ctx.conf.exists:
- ui.ok("没有 %s —— 全部按默认值来,下面会告诉你最终用了什么"
- % ctx.conf_path.name)
- else:
- ui.ok("读到 %s" % ctx.conf_path.name)
- fatals, warns = ctx.conf.check()
- for item in warns:
- ui.warn(item)
- if fatals:
- for item in fatals:
- ui.err(item)
- ui.info("")
- raise ConfigFatal("配置文件有问题,已停止。修好上面这些再运行。")
- ctx.remote = ctx.conf.s("repo.remote", "origin")
- ctx.url = ctx.conf.s("repo.url") # 允许为空:后面 resolve_ 会去推断
- ctx.token = ctx.conf.s("repo.token")
- ctx.username = ctx.conf.s("repo.username")
- ctx.timeout = ctx.conf.i("sync.timeoutSec", 300) or 300
- ctx.block_secret = ctx.conf.b("guard.blockSecret", True)
- ctx.block_files = ctx.conf.list_of("guard.blockFiles", [ctx.conf_path.name, ctx.log_name])
- repo_setting = ctx.conf.s("repo.path")
- ctx.repo_dir = Path(repo_setting).expanduser().resolve() if repo_setting else SCRIPT_DIR
- # ============================================ 2. 环境自检
- ui.step(2, 6, "自检运行环境")
- git_exe = find_git()
- if not git_exe:
- ui.bullet("PATH 和常见安装位置里都没找到能用的 git", tone="yellow")
- raise ConfigFatal("找不到 git")
- ctx.git = Git(git_exe, ctx.repo_dir, ui,
- dry_run=(ctx.args.dry_run or ctx.args.check))
- ctx.git.secrets = [s for s in (ctx.token, ctx.username) if not is_blank(s)]
- git = ctx.git
- ui.ok("git %s" % git.version())
- ui.bullet(str(git_exe))
- if not ctx.repo_dir.is_dir():
- raise ConfigFatal("仓库目录不存在:%s" % ctx.repo_dir)
- ui.ok("仓库目录 %s" % ctx.repo_dir)
- if not git.is_repo():
- if not ctx.conf.b("repo.autoInit", True):
- ui.bullet("目录还不是 git 仓库,而 [repo] auto_init = false", tone="yellow")
- raise ConfigFatal("目录不是 git 仓库")
- ui.warn("目录还不是 git 仓库" + ("(正式运行时会自动初始化)" if git.dry else ",正在初始化…"))
- if git._write(["init"], "git init") is not None:
- ui.ok("已初始化,分支将设为 %s" % ctx.branch)
- author_name = git.config_get("user.name")
- author_email = git.config_get("user.email")
- if author_name and author_email:
- ui.ok("提交者 %s <%s>" % (author_name, author_email))
- else:
- fallback_name = ctx.conf.s("commit.name")
- fallback_email = ctx.conf.s("commit.email")
- if not fallback_name or not fallback_email:
- ui.bullet('git config --global user.name "你的名字"', tone="yellow")
- ui.bullet('git config --global user.email "你的邮箱"', tone="yellow")
- ui.bullet("或者在 [commit] 里填 name / email", tone="yellow")
- raise ConfigFatal("没有提交者身份,commit 会被 git 拒绝")
- git.run(["config", "user.name", fallback_name])
- git.run(["config", "user.email", fallback_email])
- ui.ok("提交者取自配置文件:%s <%s>" % (fallback_name, fallback_email))
- if git.is_repo():
- pending = git.in_progress_operation()
- if pending:
- ui.bullet("先手动看一眼 git status,再 git merge --abort / git rebase --abort",
- tone="yellow")
- raise ConfigFatal("仓库里有个没做完的%s操作" % pending)
- ui.ok("没有卡在半截的 merge / rebase")
- else:
- ui.dim(" 仓库还没初始化,merge / rebase 检查留到正式运行时")
- if git.is_repo() and git.is_detached():
- ui.bullet("先切回分支:git checkout %s" % ctx.branch, tone="yellow")
- raise ConfigFatal("当前处于分离头指针(detached HEAD)状态")
- current = git.current_branch()
- if git.config_get("core.autocrlf").lower() == "true":
- ui.warn("core.autocrlf = true,纯 LF 文件提交时会被改写成 CRLF")
- ui.bullet("不想被改就在仓库里放 .gitattributes,写一行:* -text")
- credential = git.config_get("credential.helper")
- if is_blank(ctx.token):
- if is_blank(credential):
- ui.warn("没填 token,系统也没有 credential.helper,推送时可能没人问你要密码")
- ui.bullet("建议在 [repo] 里填 url_token", tone="yellow")
- else:
- ui.ok("认证:系统凭据助手 %s" % credential)
- else:
- ui.ok("认证:配置文件里的 token(不会写进 .git/config)")
- # token 就在配置文件里,这道闸门是硬性的
- check_gitignore(ctx)
- # ---- 远端地址:配置里有就用,没有就用现成 remote,都没有就报错 ----
- resolve_remote_url(ctx)
- if ctx.url and ctx.conf.b("repo.syncRemoteUrl", True):
- existing = git.config_get("remote.%s.url" % ctx.remote).strip()
- if not existing:
- if git._write(["remote", "add", ctx.remote, ctx.url],
- "git remote add") is not None:
- ui.ok("已写入 remote %s → %s" % (ctx.remote, mask_text(ctx.url)))
- elif existing != ctx.url.strip():
- # 只有「配置文件里显式写了 url 且和现有 remote 不一致」才会走到这里
- ui.warn("remote %s 现在是 %s,跟 %s 里写的不一样"
- % (ctx.remote, mask_text(existing), ctx.conf_path.name))
- if ctx.args.auto_yes or ui.ask_yn("改成配置文件里的地址?", default=True):
- if git._write(["remote", "set-url", ctx.remote, ctx.url],
- "git remote set-url") is not None:
- ui.ok("已更新远程地址")
- else:
- ui.warn("保留原地址,本次按原地址推送")
- ctx.url = existing
- ctx.authed_url = build_authed_url(ctx)
- # ---- 目标分支:配置文件里没写就跟着仓库走 ----
- resolve_branch(ctx)
- if ctx.authed_url != ctx.url:
- ui.dim(" 推送地址 %s" % mask_text(ctx.authed_url))
- # ============================================ check 模式出口
- if ctx.args.check:
- ui.step(3, 6, "自检完成(check 模式)")
- ui.info("")
- ui.ok("可以正式运行了。要跑的话,把 --check 去掉就行")
- ui.info(" 警告 %d 条,错误 %d 条" % (ui.warn_count, ui.err_count))
- return RC_OK
- # ============================================ 3. 分支
- ui.step(3, 6, "确认分支")
- if not git.head_sha():
- # 空仓库:HEAD 只是个还没落地的符号引用,直接指到目标分支就行。
- # 这里不要用 checkout —— 没有提交时 checkout 一个不存在的分支必然失败。
- if current != ctx.branch:
- ui.info(" 仓库还没有提交,把 HEAD 指向 %s" % ctx.branch)
- if git.dry:
- ui.dim(" [dry-run] 将执行:git symbolic-ref HEAD refs/heads/%s"
- % ctx.branch)
- else:
- git.run(["symbolic-ref", "HEAD", "refs/heads/%s" % ctx.branch])
- elif current != ctx.branch:
- ui.warn("当前在 %s,切到 %s" % (current, ctx.branch))
- git.wait(["checkout", ctx.branch], "git checkout %s" % ctx.branch)
- ui.ok("分支 %s" % ctx.branch)
- # ============================================ 4. 提交
- ui.step(4, 6, "提交本地变更")
- do_commit_if_needed(ctx)
- # ============================================ 5/6. 同步
- sync_with_remote(ctx, auto_yes=ctx.args.auto_yes)
- ui.ok("全部完成")
- ui.info(" %s → %s" % (ctx.branch, mask_text(ctx.url)))
- if ui.warn_count:
- ui.info(" 本次有 %d 条警告,往上看一眼" % ui.warn_count)
- return RC_OK
- # ------------------------------------------------------------------------ CLI
- def parse_args(argv):
- parser = argparse.ArgumentParser(
- prog=PROG,
- description="一键提交当前目录并推送到远端分支(双击 bat 时不需要任何参数)",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog=("退出码:\n"
- " 0 成功(含「已是最新」)\n"
- " 1 你选择了放弃 / 中止\n"
- " 2 配置或环境自检不通过\n"
- " 3 合并冲突且未处理\n"
- " 4 网络或推送失败\n"
- " 5 脚本内部异常\n"),
- )
- parser.add_argument("-c", "--config", help="配置文件路径,默认脚本旁边的 autogit.ini")
- parser.add_argument("--check", action="store_true", help="只做自检,不提交不推送")
- parser.add_argument("--dry-run", action="store_true", help="打印将要执行的操作,不真正执行")
- parser.add_argument("-y", "--auto-yes", action="store_true",
- help="所有提问一律回答 y(无人值守用,慎用)")
- parser.add_argument("--no-pause", action="store_true", help="结束时不等回车")
- parser.add_argument("--no-log", action="store_true", help="本次不写日志文件")
- parser.add_argument("--no-color", action="store_true", help="关闭彩色输出")
- parser.add_argument("-V", "--version", action="version", version="%(prog)s " + __version__)
- return parser.parse_args(argv)
- def main(argv=None) -> int:
- for stream in (sys.stdout, sys.stderr):
- try:
- stream.reconfigure(encoding="utf-8", errors="replace")
- except Exception:
- pass
- args = parse_args(sys.argv[1:] if argv is None else argv)
- try:
- return run(args)
- except AutogitError as exc:
- print("[FAIL] %s" % exc)
- return exc.rc
- except KeyboardInterrupt:
- print("[ABORT] 被用户中断")
- return RC_ABORT
- except Exception:
- print("[FAIL] 脚本内部异常:")
- traceback.print_exc()
- return RC_INTERNAL
- if __name__ == "__main__":
- sys.exit(main())
|