Compare commits

...
12 Commits
16 changed files with 4352 additions and 3889 deletions
+4
View File
@@ -101,8 +101,12 @@ $RECYCLE.BIN/
#logs
logs/*
*.log
# 运行时生成的统计/日志(避免自动提交把运行产物入库)
stats/
#configs
configs/*
# End of https://www.toptal.com/developers/gitignore/api/code,go,linux,macos,windows
+9
View File
@@ -0,0 +1,9 @@
BINARY := git-auto.exe
# 关闭 VCS 标记:绕过本地 .git 对象库不持久导致的 build 报错
.PHONY: build run
build:
go build -buildvcs=false -o $(BINARY) .
run: build
./$(BINARY) -dir .. -addr 127.0.0.1:5757
+123
View File
@@ -0,0 +1,123 @@
# Git 自动同步 · 网页控制台(git-sync-web)
将 `git-auto-sync`(原 Bash 脚本版定时同步工具)的能力搬上网页:用浏览器即可监控、手动触发、查看差异、在线编辑文件、就地解决冲突,无需登录服务器敲命令行。
单二进制、纯标准库实现(Go 1.25+),前端资源通过 `go:embed` 内嵌,**零外部依赖、零运行时下载**,拷贝一个 exe 即可运行。
---
## 核心功能
### 1. 仓库总览(Dashboard)
- 每个被监控仓库一张卡片:同步状态灯、领先/落后提交数、本地改动文件数。
- 运行中的仓库实时显示;关闭「自动同步」的仓库标注「手动模式」徽标,仅响应手动触发。
- 顶部按钮「全部启动 / 全部暂停」一键管控。
### 2. 实时活动(SSE 日志)
- 右侧实时日志面板通过 Server-Sent Events 推送每个仓库的同步过程、提交、冲突等事件,并带错误/警告高亮。
- 支持按关键字过滤、一键清空。
### 3. 手动同步
- 每个仓库提供「获取 / 拉取 / 推送」按钮,随时手动触发,不必等待定时调度。
### 4. 差异查看(Diff)
- 支持「工作区 / 已暂存 / 某次提交」三种范围;统一视图与**并排(split)视图**切换。
- 可选的**词级差异**(`git --word-diff=plain`),改动以行内增删高亮呈现。
- 一键**复制**差异内容、下载 `.patch` 文件;编辑器内「对比此文件」可只看当前文件的改动。
### 5. 网页端文件编辑
- 文件树列出仓库内可跟踪 / 未跟踪文件,并标注改动状态(M/A/D/?)。
- 点击文件即可**在线读取与编辑**,保存可「仅写盘」或「保存并提交」。
- 内置 **CodeMirror** 语法高亮;编辑过程中自动缓存草稿到浏览器 `localStorage`,刷新不丢稿,可「放弃草稿」回滚。
- 二进制文件自动识别并只读提示。
### 6. 冲突解决
- **拉取冲突**:选择「放弃合并」或「我已在本地解决,继续」。
- **推送冲突**(non-fast-forward):提供「强制推送(--force-with-lease)」或「放弃」。
- **冲突文件内联编辑**:直接在网页展开冲突文件、编辑解决、保存并标记已解决;所有冲突处理完毕时自动结束合并/变基。
### 7. 自动同步 / 自动提交 / Cron
- 每个仓库可设固定间隔(秒)或 **Cron 表达式**自动拉取推送(Cron 非空时优先于固定间隔)。
- 「自动提交」开启后,检测到工作区脏文件会自动 `add -A` + `commit` 再推送。
- 「自动同步」开关可单独关闭——关闭后该仓库不再自动运行,仅响应手动同步。
### 8. 提交历史
- 浏览仓库提交记录,点击展开单条提交的详细 diff。提交哈希经正则白名单校验,防止命令注入。
### 9. 统计
- 每次同步写入 CSV 统计(领先/落后/改动等),网页端以图表呈现近 30 天趋势。
### 10. 访问密码(可选)
- 启动时加 `-password` 参数启用鉴权:生成 30 天会话 cookie,除静态资源外的 API 均受保护。
---
## 编译与运行
```bash
# 编译(会重新内嵌 static 目录下的前端资源,改前端后必须重新 build)
go build -o git-auto.exe .
# Windows下可能需要执行如下命令编译:
go build -buildvcs=false -o git-auto.exe .
# 运行
./git-auto.exe -dir "C:/OtherFiles/Github/git-auto-sync" -addr 127.0.0.1:5757
```
| 参数 | 说明 | 默认值 |
| --- | --- | --- |
| `-dir` | 项目根目录,需包含 `configs/`、`logs/`、`stats/` | `.` |
| `-addr` | 监听地址 | `127.0.0.1:5757` |
| `-password` | 访问密码(为空则不启用鉴权) | 空 |
启动后浏览器打开 `http://127.0.0.1:5757` 即可。
---
## 配置文件格式
监控目标以 `.conf` 文件存放在 `-dir` 指定的 `configs/` 目录下,兼容原 Bash 脚本的配置字段:
```ini
# Git 自动同步配置 - 示例
REPO_PATH="/c/OtherFiles/Github/your-repo" # 支持 Git Bash 风格 /c/... 路径,会自动转为 Windows 路径
REMOTE_NAME="origin"
REMOTE_URL="https://example.com/you/repo.git"
# 多远程写法:REMOTES="origin=https://a.git,fork=https://b.git"
BRANCH="main"
MODE="both" # both / push / pull
INTERVAL="60" # 固定间隔(秒)
CRON="" # 可选,cron 表达式优先于 INTERVAL
LOG_FILE="/c/.../sync.log"
AUTH_METHOD="ssh" # ssh / https
AUTO_COMMIT="0" # 1 开启自动提交
AUTO_SYNC="1" # 0 关闭自动同步(仅手动)
CONFLICT_STRATEGY="merge" # merge / rebase
PUSH_STRATEGY="manual" # manual / auto
```
> 说明:路径既支持 `C:/...` 也支持 Git Bash 的 `/c/...`,后者会在加载时自动规范化;`.git` 内部目录被禁止通过网页访问。
---
## 目录结构
```
git-sync-web/
├── main.go # 入口:-dir / -addr / -password,内嵌 static
├── config.go # .conf 解析与写回、Windows 路径规范化
├── git.go # git 执行器、领先/落后、冲突检测
├── engine.go # 每仓库调度循环、SSE 事件总线、文件树/读写
├── cron.go # 纯标准库 5 段 cron 解析(含单测)
├── server.go # REST API 与静态资源服务
└── static/ # 前端:index.html / app.js / style.css / cm-boot.js / vendor/cm/
```
---
## 设计要点
- **单二进制 + 内嵌前端**:部署只需一个可执行文件,不依赖任何外部 CDN 或运行时。
- **安全边界**:仓库内路径经 `safeRepoPath` 严格校验,禁止 `..` 越界与访问 `.git`;提交哈希白名单防注入;网页编辑单文件 ≤1MB 且拒绝二进制写入。
- **优雅降级**:CodeMirror 资源缺失或初始化失败时,编辑器自动回退原生 `<textarea>`,核心功能不受影响。
+9 -4
View File
@@ -28,13 +28,13 @@ type RepoConfig struct {
ConflictStrategy string `json:"conflict_strategy"`
PushStrategy string `json:"push_strategy"`
AutoCommit bool `json:"auto_commit"`
AutoSync bool `json:"auto_sync"`
Cron string `json:"cron"`
}
var nameRe = regexp.MustCompile(`^[A-Za-z0-9_\-]+$`)
// normalizeWinPath 把 Git Bash 风格路径 /c/foo/bar 转成 Windows 的 C:/foo/bar,
// 兼容旧脚本配置里存放的 bash 风格路径
func normalizeWinPath(p string) string {
p = strings.ReplaceAll(strings.TrimSpace(p), "\\", "/")
if len(p) >= 3 && p[0] == '/' && p[2] == '/' {
@@ -109,6 +109,7 @@ func loadRepoConfig(dir, name string) (*RepoConfig, error) {
c.ConflictStrategy = orDefault(m["CONFLICT_STRATEGY"], "merge")
c.PushStrategy = orDefault(m["PUSH_STRATEGY"], "manual")
c.AutoCommit = strings.EqualFold(m["AUTO_COMMIT"], "1") || strings.EqualFold(m["AUTO_COMMIT"], "true")
c.AutoSync = !(strings.EqualFold(m["AUTO_SYNC"], "0") || strings.EqualFold(m["AUTO_SYNC"], "false"))
c.Cron = strings.TrimSpace(m["CRON"])
if remotes := strings.TrimSpace(m["REMOTES"]); remotes != "" {
for _, pair := range strings.Split(remotes, ",") {
@@ -123,7 +124,6 @@ func loadRepoConfig(dir, name string) (*RepoConfig, error) {
c.Remotes = append(c.Remotes, Remote{Name: strings.TrimSpace(n), URL: strings.TrimSpace(u)})
}
}
// 兼容旧版单远程格式:REMOTE_NAME + REMOTE_URL
if len(c.Remotes) == 0 && m["REMOTE_NAME"] != "" && m["REMOTE_URL"] != "" {
c.Remotes = append(c.Remotes, Remote{Name: m["REMOTE_NAME"], URL: m["REMOTE_URL"]})
}
@@ -154,8 +154,13 @@ func saveRepoConfig(dir string, c *RepoConfig) error {
if c.AutoCommit {
ac = "1"
}
fmt.Fprintf(&b, "AUTO_COMMIT=%s\n", q(ac))
fmt.Fprintf(&b, "CRON=%s\n", q(c.Cron))
fmt.Fprintf(&b, "AUTO_COMMIT=%s\n", q(ac))
as := "0"
if c.AutoSync {
as = "1"
}
fmt.Fprintf(&b, "AUTO_SYNC=%s\n", q(as))
fmt.Fprintf(&b, "CRON=%s\n", q(c.Cron))
return os.WriteFile(filepath.Join(dir, c.Name+".conf"), []byte(b.String()), 0o644)
}
+3 -1
View File
@@ -9,5 +9,7 @@ AUTH_METHOD="https"
RETRY_COUNT="0"
RETRY_INTERVAL="0"
CONFLICT_STRATEGY="merge"
AUTO_COMMIT="1"
PUSH_STRATEGY="manual"
AUTO_COMMIT="0"
AUTO_SYNC="0"
CRON=""
-4
View File
@@ -7,8 +7,6 @@ import (
"time"
)
// 5 段 cron:分 时 日 月 周。支持 * 、数字、范围 a-b、步长 */n 与 a-b/n、逗号列表。
// 日(day-of-month) 与 周(day-of-week) 均受限时采用标准 cron 的「或」语义。
type cronSpec struct {
min, hour, dom, mon, dow map[int]bool
@@ -92,7 +90,6 @@ func parseCronField(f string, min, max int) (map[int]bool, error) {
return set, nil
}
// cronNextString 返回 cron 表达式相对当前时间的下次触发时间(供配置表单实时预览)
func cronNextString(expr string) (string, error) {
spec, err := parseCron(expr)
if err != nil {
@@ -101,7 +98,6 @@ func cronNextString(expr string) (string, error) {
return cronNext(spec, time.Now()).Format("2006-01-02 15:04"), nil
}
// cronNext 返回 spec 在 after 之后的下一次触发时间(分钟精度,最多向前搜索一年)
func cronNext(spec *cronSpec, after time.Time) time.Time {
t := after.Truncate(time.Minute).Add(time.Minute)
limit := t.AddDate(1, 0, 0)
-4
View File
@@ -19,7 +19,6 @@ func TestParseCron(t *testing.T) {
}
func TestCronNext(t *testing.T) {
// 每日 09:30:从当天 10:00 出发应得到次日 09:30
spec, _ := parseCron("30 9 * * *")
next := cronNext(spec, time.Date(2026, 9, 8, 10, 0, 0, 0, time.Local))
want := time.Date(2026, 9, 9, 9, 30, 0, 0, time.Local)
@@ -27,7 +26,6 @@ func TestCronNext(t *testing.T) {
t.Fatalf("每日 09:30:期望 %v,得到 %v", want, next)
}
// 每 15 分钟
spec2, _ := parseCron("*/15 * * * *")
next2 := cronNext(spec2, time.Date(2026, 9, 8, 10, 7, 0, 0, time.Local))
want2 := time.Date(2026, 9, 8, 10, 15, 0, 0, time.Local)
@@ -35,7 +33,6 @@ func TestCronNext(t *testing.T) {
t.Fatalf("*/15:期望 %v,得到 %v", want2, next2)
}
// 仅周五 12:00:2026-09-08 是周二,应得到 2026-09-11(周五)
spec3, _ := parseCron("0 12 * * 5")
next3 := cronNext(spec3, time.Date(2026, 9, 8, 12, 0, 0, 0, time.Local))
want3 := time.Date(2026, 9, 11, 12, 0, 0, 0, time.Local)
@@ -43,7 +40,6 @@ func TestCronNext(t *testing.T) {
t.Fatalf("仅周五:期望 %v,得到 %v", want3, next3)
}
// 7 表示周日:2026-09-13 是周日
spec4, _ := parseCron("0 0 * * 7")
next4 := cronNext(spec4, time.Date(2026, 9, 12, 0, 0, 0, 0, time.Local)) // 周六
want4 := time.Date(2026, 9, 13, 0, 0, 0, 0, time.Local)
+301 -56
View File
@@ -17,7 +17,6 @@ import (
"time"
)
// ---------- 事件总线 ----------
type EventBus struct {
mu sync.Mutex
next int
@@ -55,7 +54,6 @@ func (b *EventBus) Publish(data []byte) {
}
}
// ---------- 状态 ----------
type SyncResult struct {
Time string `json:"time"`
Result string `json:"result"` // ok | error | conflict | push_conflict
@@ -75,6 +73,7 @@ type RepoSnapshot struct {
PushStrategy string `json:"push_strategy"`
LogFile string `json:"log_file"`
AutoCommit bool `json:"auto_commit"`
AutoSync bool `json:"auto_sync"`
Cron string `json:"cron"`
Remotes []Remote `json:"remotes"`
Running bool `json:"running"`
@@ -85,7 +84,6 @@ type RepoSnapshot struct {
Conflicts []string `json:"conflicts"`
LastError string `json:"last_error"`
LastSync *SyncResult `json:"last_sync"`
// 新增:推送冲突信息
PushConflict bool `json:"push_conflict"`
PushConflictRemote string `json:"push_conflict_remote"`
PushConflictBranch string `json:"push_conflict_branch"`
@@ -104,7 +102,6 @@ type repoState struct {
lastError string
lastSync *SyncResult
stopCh chan struct{}
// 推送冲突信息
pushConflict bool
pushConflictRemote string
pushConflictBranch string
@@ -134,9 +131,119 @@ func NewEngine(base string) (*Engine, error) {
return nil, err
}
}
_ = e.ensureSummariesDir()
return e, nil
}
func (e *Engine) summariesDir() string {
return filepath.Join(e.baseDir, "summaries")
}
// ensureSummariesDir 创建本地变更摘要目录(gitignored,不同步到远程)。
func (e *Engine) ensureSummariesDir() error {
dir := e.summariesDir()
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
gi := filepath.Join(dir, ".gitignore")
if _, err := os.Stat(gi); err != nil {
_ = os.WriteFile(gi, []byte("*\n"), 0o644)
}
return nil
}
func (e *Engine) summaryPath(name string) string {
return filepath.Join(e.summariesDir(), name+".md")
}
func (e *Engine) pendingPath(name string) string {
return filepath.Join(e.summariesDir(), name+".pending")
}
func (e *Engine) GetPendingSummary(name string) string {
b, err := os.ReadFile(e.pendingPath(name))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
func (e *Engine) SavePendingSummary(name, text string) error {
if err := e.ensureSummariesDir(); err != nil {
return err
}
t := strings.TrimSpace(text)
if t == "" {
return os.Remove(e.pendingPath(name))
}
return os.WriteFile(e.pendingPath(name), []byte(t+"\n"), 0o644)
}
// statusFiles 返回工作区相对改动文件列表(用于自动摘要;须在 git add 之前调用)。
func (e *Engine) statusFiles(repoPath string) []string {
out, err := gitRun(repoPath, 15*time.Second, "status", "--porcelain")
if err != nil {
return nil
}
var files []string
for _, ln := range strings.Split(strings.TrimSpace(out), "\n") {
ln = strings.TrimSpace(ln)
if ln == "" {
continue
}
p := strings.TrimSpace(ln[3:])
if i := strings.Index(p, "->"); i >= 0 {
p = strings.TrimSpace(p[i+2:])
}
p = strings.Trim(p, `"`)
if p != "" {
files = append(files, p)
}
}
return files
}
// autoSummary 在没有任何人工摘要时,依据本次改动自动生成一句话摘要(仅本地记录用)。
// files 须为提交前的改动文件列表(见 statusFiles)。
func (e *Engine) autoSummary(files []string) string {
if len(files) == 0 {
return "自动提交(无改动文件)"
}
const max = 6
shown := files
if len(shown) > max {
shown = files[:max]
}
more := ""
if len(files) > max {
more = fmt.Sprintf(" 等%d个", len(files))
}
return fmt.Sprintf("改动 %d 个文件:%s%s", len(files), strings.Join(shown, ", "), more)
}
// RecordCommit 把一次提交(commit id + 摘要)追加写入本地按项目分开的摘要文件(不上传)。
func (e *Engine) RecordCommit(name, sha, summary string) {
if err := e.ensureSummariesDir(); err != nil {
return
}
ts := time.Now().Format("2006-01-02 15:04:05")
entry := fmt.Sprintf("## %s · %s\n%s\n\n", strings.TrimSpace(sha), ts, strings.TrimSpace(summary))
f, err := os.OpenFile(e.summaryPath(name), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return
}
defer f.Close()
_, _ = f.WriteString(entry)
}
func (e *Engine) GetSummaryLog(name string) string {
b, err := os.ReadFile(e.summaryPath(name))
if err != nil {
return ""
}
return string(b)
}
func (e *Engine) Bus() *EventBus { return e.bus }
func (e *Engine) configNames() []string {
@@ -184,6 +291,7 @@ func (e *Engine) LoadAll() {
continue
}
e.states[name] = &repoState{cfg: cfg, status: "idle"}
e.restoreLastSync(e.states[name])
}
}
@@ -205,7 +313,6 @@ func (e *Engine) logf(s *repoState, level, format string, args ...any) {
if logPath != "" {
_ = os.MkdirAll(filepath.Dir(logPath), 0o755)
if f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
// 落盘格式:[时间] [级别] 消息,便于网页端按级别过滤
fmt.Fprintln(f, "["+ts+"] ["+level+"] "+msg)
_ = f.Close()
}
@@ -213,7 +320,6 @@ func (e *Engine) logf(s *repoState, level, format string, args ...any) {
e.publish(map[string]any{"type": "log", "repo": s.cfg.Name, "level": level, "msg": msg, "time": ts})
}
// statMaxLines 控制单个仓库统计 CSV 的最大行数(含表头),超过则滚动保留最近 N 行
const statMaxLines = 2000
func (e *Engine) stat(s *repoState, action, result string, commits int) {
@@ -221,7 +327,6 @@ func (e *Engine) stat(s *repoState, action, result string, commits int) {
if _, err := os.Stat(path); os.IsNotExist(err) {
_ = os.WriteFile(path, []byte("timestamp,action,result,commits\n"), 0o644)
}
// 文件过大时滚动截断,避免长期运行无限膨胀(统计频率低,重写成本可接受)
if rotateStatIfNeeded(path, statMaxLines) {
e.logf(s, "info", "统计文件已滚动截断至最近 %d 行", statMaxLines)
}
@@ -233,7 +338,6 @@ func (e *Engine) stat(s *repoState, action, result string, commits int) {
fmt.Fprintf(f, "%s,%s,%s,%d\n", time.Now().Format("2006-01-02 15:04:05"), action, result, commits)
}
// rotateStatIfNeeded 当 CSV 行数超过 maxLines 时,保留表头 + 最近 (maxLines-1) 条数据行并重写
func rotateStatIfNeeded(path string, maxLines int) bool {
data, err := os.ReadFile(path)
if err != nil {
@@ -250,6 +354,44 @@ func rotateStatIfNeeded(path string, maxLines int) bool {
return true
}
// restoreLastSync 从统计 CSV 的最后一条记录恢复 lastSync,使重启后界面不再显示「从未同步」。
func (e *Engine) restoreLastSync(s *repoState) {
path := filepath.Join(e.statsDir, s.cfg.Name+".csv")
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
recs, err := csv.NewReader(f).ReadAll()
if err != nil || len(recs) < 2 {
return
}
var ts, raw string
for _, rec := range recs[1:] {
if len(rec) < 3 {
continue
}
ts, raw = rec[0], rec[2]
}
if ts == "" {
return
}
result := raw
switch raw {
case "success":
result = "ok"
case "failed":
result = "error"
}
detail := map[string]string{"ok": "同步完成", "error": "同步失败", "conflict": "存在冲突"}[result]
if detail == "" {
detail = "上次同步"
}
s.mu.Lock()
s.lastSync = &SyncResult{Time: ts, Result: result, Detail: detail}
s.mu.Unlock()
}
func firstRemoteName(cfg *RepoConfig) string {
if len(cfg.Remotes) > 0 {
return cfg.Remotes[0].Name
@@ -273,6 +415,7 @@ func (s *repoState) snapshot(live bool) RepoSnapshot {
PushStrategy: cfg.PushStrategy,
LogFile: cfg.LogFile,
AutoCommit: cfg.AutoCommit,
AutoSync: cfg.AutoSync,
Cron: cfg.Cron,
Remotes: cfg.Remotes,
Running: s.running,
@@ -320,7 +463,6 @@ func (e *Engine) pushStatus(s *repoState) {
e.publish(map[string]any{"type": "status", "repo": s.cfg.Name, "data": s.snapshot(false)})
}
// ---------- 启动 / 停止 ----------
func (e *Engine) Start(name string) error {
s := e.get(name)
if s == nil {
@@ -350,7 +492,14 @@ func (e *Engine) loop(s *repoState, stopCh chan struct{}) {
s.mu.Lock()
interval := s.cfg.Interval
cronStr := s.cfg.Cron
autoSync := s.cfg.AutoSync
s.mu.Unlock()
if !autoSync {
e.logf(s, "info", "已关闭自动同步,仅响应手动同步")
e.pushStatus(s)
<-stopCh
return
}
if interval < 5 {
interval = 5
}
@@ -434,7 +583,6 @@ func (e *Engine) SyncNow(name string) error {
return nil
}
// ---------- 同步核心 ----------
func (e *Engine) withRetry(s *repoState, label string, fn func() (string, error)) (string, error) {
maxAttempts, sleep, retryCount := 1, 0, 0
s.mu.Lock()
@@ -467,6 +615,7 @@ func (e *Engine) setFail(s *repoState, msg string) {
s.lastError = msg
s.lastSync = &SyncResult{Time: now, Result: "error", Detail: msg}
s.mu.Unlock()
e.stat(s, "sync", "error", 0)
e.logf(s, "error", "%s", msg)
e.pushStatus(s)
}
@@ -478,10 +627,10 @@ func (e *Engine) setOK(s *repoState, detail string) {
s.lastError = ""
s.lastSync = &SyncResult{Time: now, Result: "ok", Detail: detail}
s.mu.Unlock()
e.stat(s, "sync", "ok", 0)
e.pushStatus(s)
}
// ensureRemotes 把配置中的远程同步到仓库
func (e *Engine) ensureRemotes(s *repoState, cfg *RepoConfig) {
for _, r := range cfg.Remotes {
out, err := gitRun(cfg.RepoPath, 15*time.Second, "remote", "get-url", r.Name)
@@ -528,7 +677,6 @@ func (e *Engine) safeSync(s *repoState, trigger string) {
e.syncOnce(s, trigger)
}
// syncOnce 核心同步逻辑(已调整顺序,并增加 push_conflict 处理)
func (e *Engine) syncOnce(s *repoState, trigger string) {
s.mu.Lock()
if s.syncing {
@@ -544,7 +692,6 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
s.mu.Unlock()
}()
// 自动 stash 恢复(B4):若本次同步前暂存了改动,结束时尝试恢复
stashed := false
defer func() {
if !stashed {
@@ -577,7 +724,6 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
return
}
// 自动 stash(B4):未开启自动提交且有未提交改动时先暂存,避免分支切换/推送被脏工作区阻断
if !cfg.AutoCommit && dirtyCount(cfg.RepoPath) > 0 {
if _, serr := gitRun(cfg.RepoPath, 60*time.Second, "stash", "push", "-u", "-m", "git-sync-web auto-stash"); serr == nil {
stashed = true
@@ -615,7 +761,6 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
}
}
// 自动提交
dirty := dirtyCount(cfg.RepoPath)
if dirty > 0 {
if cfg.AutoCommit {
@@ -625,10 +770,26 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
return
}
cmsg := "git-sync-web 自动提交 " + time.Now().Format("2006-01-02 15:04:05")
pend := e.GetPendingSummary(s.cfg.Name)
if pend != "" {
cmsg = pend
}
var autoFiles []string
if pend == "" {
autoFiles = e.statusFiles(cfg.RepoPath)
}
if _, cerr := gitRun(cfg.RepoPath, 120*time.Second, "commit", "-m", cmsg); cerr != nil {
e.setFail(s, "自动提交失败: "+cerr.Error())
return
}
if sha, serr := gitRun(cfg.RepoPath, 10*time.Second, "rev-parse", "--short", "HEAD"); serr == nil {
sum := cmsg
if pend == "" {
sum = e.autoSummary(autoFiles)
}
e.RecordCommit(s.cfg.Name, sha, sum)
}
_ = os.Remove(e.pendingPath(s.cfg.Name))
e.logf(s, "info", "自动提交完成,将随本轮同步推送")
dirty = 0
} else {
@@ -636,7 +797,6 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
}
}
// 计算 ahead/behind
var ahead, behind int
var err error
tip, remoteHasBranch := remoteTip(cfg.RepoPath, remote, cfg.Branch)
@@ -657,7 +817,6 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
s.mu.Unlock()
e.pushStatus(s)
// ---- 先拉取 ----
if behind > 0 && (cfg.Mode == "pull" || cfg.Mode == "both") {
if !e.pullRemote(s, cfg, remote, behind) {
return
@@ -669,11 +828,9 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
e.pushStatus(s)
}
// ---- 再推送 ----
if ahead > 0 && (cfg.Mode == "push" || cfg.Mode == "both") {
pushOK, pushErr := e.pushAll(s, cfg, ahead)
if !pushOK {
// 检查是否是 non-fast-forward 错误,按推送策略处理(B3)
if pushErr != nil && strings.Contains(strings.ToLower(pushErr.Error()), "non-fast-forward") {
switch cfg.PushStrategy {
case "force":
@@ -705,7 +862,6 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
s.lastError = ""
s.mu.Unlock()
default:
// manual:保持 push_conflict 状态,等待用户在控制台决策(强制推送 / 放弃)
e.logf(s, "warn", "推送被拒绝(non-fast-forward),等待用户决策")
return
}
@@ -716,7 +872,6 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
}
}
// 最终刷新
ahead, behind, _ = aheadBehind(cfg.RepoPath, remote, cfg.Branch)
now := time.Now().Format("2006-01-02 15:04:05")
s.mu.Lock()
@@ -724,7 +879,6 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
s.status = "ok"
s.lastError = ""
s.lastSync = &SyncResult{Time: now, Result: "ok", Detail: "同步完成"}
// 清除可能遗留的推送冲突状态
s.pushConflict = false
s.pushConflictRemote = ""
s.pushConflictBranch = ""
@@ -733,8 +887,6 @@ func (e *Engine) syncOnce(s *repoState, trigger string) {
e.pushStatus(s)
}
// pushAll 返回 (是否全部成功, 错误信息)
// 如果遇到 non-fast-forward,会设置 pushConflict 状态并返回 false,错误包含 "non-fast-forward"
func (e *Engine) pushAll(s *repoState, cfg *RepoConfig, n int) (bool, error) {
allOK := true
var firstErr error
@@ -748,7 +900,6 @@ func (e *Engine) pushAll(s *repoState, cfg *RepoConfig, n int) (bool, error) {
if firstErr == nil {
firstErr = err
}
// 检测到 non-fast-forward,记录状态并继续尝试其他远程
if strings.Contains(strings.ToLower(err.Error()), "non-fast-forward") {
s.mu.Lock()
s.status = "push_conflict"
@@ -776,7 +927,6 @@ func (e *Engine) pushAll(s *repoState, cfg *RepoConfig, n int) (bool, error) {
return false, firstErr
}
// pullRemote 已使用重试
func (e *Engine) pullRemote(s *repoState, cfg *RepoConfig, remote string, n int) bool {
args := []string{"pull"}
if cfg.ConflictStrategy == "rebase" {
@@ -806,6 +956,7 @@ func (e *Engine) pullRemote(s *repoState, cfg *RepoConfig, remote string, n int)
s.lastError = "拉取产生冲突,等待在冲突处理台解决"
s.lastSync = &SyncResult{Time: now, Result: "conflict", Detail: s.lastError}
s.mu.Unlock()
e.stat(s, "sync", "conflict", 0)
e.stat(s, "pull", "conflict", n)
e.logf(s, "error", "拉取产生冲突:%s(请在详情 → 冲突中处理)", strings.Join(files, ", "))
e.pushStatus(s)
@@ -816,8 +967,6 @@ func (e *Engine) pullRemote(s *repoState, cfg *RepoConfig, remote string, n int)
return false
}
// ---------- 推送冲突处理 ----------
// ForcePush 强制推送(--force-with-lease)到冲突的远程
func (e *Engine) ForcePush(name string) error {
s := e.get(name)
if s == nil {
@@ -848,11 +997,11 @@ func (e *Engine) ForcePush(name string) error {
s.lastError = ""
s.lastSync = &SyncResult{Time: time.Now().Format("2006-01-02 15:04:05"), Result: "ok", Detail: "强制推送完成"}
s.mu.Unlock()
e.stat(s, "sync", "ok", 0)
e.pushStatus(s)
return nil
}
// AbortPush 放弃强制推送,清除冲突状态
func (e *Engine) AbortPush(name string) error {
s := e.get(name)
if s == nil {
@@ -869,12 +1018,12 @@ func (e *Engine) AbortPush(name string) error {
s.status = "ok"
s.lastError = "用户放弃强制推送"
s.lastSync = &SyncResult{Time: time.Now().Format("2006-01-02 15:04:05"), Result: "ok", Detail: "放弃强制推送,状态已清除"}
e.stat(s, "sync", "ok", 0)
e.logf(s, "warn", "放弃强制推送")
e.pushStatus(s)
return nil
}
// ---------- 手动操作 ----------
func (e *Engine) ManualGit(name, action string) error {
s := e.get(name)
if s == nil {
@@ -954,7 +1103,6 @@ func (e *Engine) ManualGit(name, action string) error {
return fmt.Errorf("未知操作: %s", action)
}
// ---------- 冲突处理 ----------
func (e *Engine) ConflictAbort(name string) error {
s := e.get(name)
if s == nil {
@@ -1007,8 +1155,14 @@ func (e *Engine) ConflictResolve(name string) error {
return nil
}
// ---------- 配置 CRUD ----------
func (e *Engine) Create(c *RepoConfig) error {
branch := c.Branch
if branch == "" {
branch = "main"
}
if err := ensureRepo(c.RepoPath, branch); err != nil {
return fmt.Errorf("初始化仓库失败: %w", err)
}
if err := validateRepoConfig(e.cfgDir, c, true); err != nil {
return err
}
@@ -1029,6 +1183,13 @@ func (e *Engine) Update(c *RepoConfig) error {
if s == nil {
return fmt.Errorf("配置不存在: %s", c.Name)
}
branch := c.Branch
if branch == "" {
branch = "main"
}
if err := ensureRepo(c.RepoPath, branch); err != nil {
return fmt.Errorf("初始化仓库失败: %w", err)
}
if err := validateRepoConfig(e.cfgDir, c, false); err != nil {
return err
}
@@ -1048,7 +1209,6 @@ func (e *Engine) Update(c *RepoConfig) error {
s.lastError = ""
s.ahead, s.behind, s.dirty = 0, 0, 0
s.lastSync = nil
// 清除推送冲突
s.pushConflict = false
s.pushConflictRemote = ""
s.pushConflictBranch = ""
@@ -1078,7 +1238,6 @@ func (e *Engine) Delete(name string) error {
return nil
}
// ---------- 日志 / 统计 / 冲突 diff ----------
type StatRow struct {
Time string `json:"time"`
Action string `json:"action"`
@@ -1158,7 +1317,6 @@ func (e *Engine) ConflictDiffs(name string) []ConflictFile {
return out
}
// ---------- 提交历史 ----------
var hashRe = regexp.MustCompile(`^[0-9a-fA-F]{6,40}$`)
type Commit struct {
@@ -1212,7 +1370,6 @@ func (e *Engine) ReadCommitDiff(name, hash string) (string, error) {
return out, nil
}
// ---------- 差异与文件编辑(网页端) ----------
const fileEditMaxBytes = 1 << 20 // 1MB,网页编辑单文件上限
@@ -1240,13 +1397,11 @@ func (e *Engine) safeRepoPath(s *repoState, rel string) (string, error) {
return full, nil
}
// FileNode 文件树节点(网页端)
type FileNode struct {
Path string `json:"path"`
Status string `json:"status"` // M 已修改 / A 新增 / D 删除 / ? 未跟踪 / 空 未改动
}
// FileTree 列出仓库内可编辑文件(已跟踪 + 未跟踪且未被忽略),天然避开 .git 内部
func (e *Engine) FileTree(name string) []FileNode {
s := e.get(name)
if s == nil {
@@ -1270,7 +1425,6 @@ func (e *Engine) FileTree(name string) []FileNode {
paths = append(paths, p)
}
sort.Strings(paths)
// 附带每个文件的改动状态(M/A/D/?),便于网页端一眼看出哪些文件被动过
status := changedFiles(s.cfg.RepoPath)
nodes := make([]FileNode, 0, len(paths))
for _, p := range paths {
@@ -1279,15 +1433,14 @@ func (e *Engine) FileTree(name string) []FileNode {
return nodes
}
// FileContent 文件内容读取结果
type FileContent struct {
Path string `json:"path"`
Content string `json:"content"`
Binary bool `json:"binary"`
Size int `json:"size"`
Path string `json:"path"`
Content string `json:"content"`
Binary bool `json:"binary"`
Size int `json:"size"`
Changed []int `json:"changed,omitempty"`
}
// ReadFileContent 读取仓库内文件内容(带大小上限与二进制检测)
func (e *Engine) ReadFileContent(name, rel string) (*FileContent, error) {
s := e.get(name)
if s == nil {
@@ -1314,10 +1467,108 @@ func (e *Engine) ReadFileContent(name, rel string) (*FileContent, error) {
if bytes.Contains(data, []byte{0}) {
return &FileContent{Path: rel, Binary: true, Size: int(info.Size())}, nil
}
return &FileContent{Path: rel, Content: string(data), Size: int(info.Size())}, nil
content := string(data)
changed, _ := fileChangeLines(s.cfg.RepoPath, rel, content)
return &FileContent{Path: rel, Content: content, Size: int(info.Size()), Changed: changed}, nil
}
func isUntracked(repoPath, rel string) bool {
out, err := gitRun(repoPath, 10*time.Second, "status", "--porcelain", "--", rel)
if err != nil {
return false
}
for _, line := range strings.Split(out, "\n") {
if strings.HasPrefix(strings.TrimSpace(line), "??") {
return true
}
}
return false
}
func fileChangeLines(repoPath, rel, content string) ([]int, error) {
if _, err := gitRun(repoPath, 10*time.Second, "rev-parse", "--verify", "HEAD"); err != nil {
return nil, nil
}
if isUntracked(repoPath, rel) {
return allLineNumbers(content), nil
}
out, err := gitRun(repoPath, 30*time.Second, "diff", "--no-color", "HEAD", "--", rel)
if err != nil {
return nil, nil
}
return parseDiffAddedLines(out), nil
}
func allLineNumbers(content string) []int {
n := strings.Count(content, "\n")
if content == "" {
return nil
}
n++
lines := make([]int, 0, n)
for i := 1; i <= n; i++ {
lines = append(lines, i)
}
return lines
}
func parseDiffAddedLines(diff string) []int {
set := map[int]struct{}{}
newLine := 0
for _, raw := range strings.Split(diff, "\n") {
line := raw
if strings.HasPrefix(line, "@@") {
if i := strings.Index(line, " +"); i >= 0 {
rest := line[i+2:]
if c, ok := parseHunkNewStart(rest); ok {
newLine = c
}
}
continue
}
if newLine == 0 {
continue
}
switch {
case strings.HasPrefix(line, "+"):
if strings.HasPrefix(line, "+++") {
continue
}
set[newLine] = struct{}{}
newLine++
case strings.HasPrefix(line, " "):
newLine++
case strings.HasPrefix(line, "-"):
default:
}
}
out := make([]int, 0, len(set))
for k := range set {
out = append(out, k)
}
sort.Ints(out)
return out
}
func parseHunkNewStart(rest string) (int, bool) {
end := strings.IndexAny(rest, " @")
if end >= 0 {
rest = rest[:end]
}
if i := strings.Index(rest, ","); i >= 0 {
rest = rest[:i]
}
n := strings.TrimSpace(rest)
if n == "" {
return 0, false
}
v, err := strconv.Atoi(n)
if err != nil {
return 0, false
}
return v, true
}
// WriteFileContent 将内容写回仓库内文件(路径校验 + 大小上限 + 二进制拒绝)
func (e *Engine) WriteFileContent(name, rel, content string) error {
s := e.get(name)
if s == nil {
@@ -1339,7 +1590,6 @@ func (e *Engine) WriteFileContent(name, rel, content string) error {
return os.WriteFile(full, []byte(content), 0o644)
}
// CommitFile 仅提交单个被网页端编辑的文件
func (e *Engine) CommitFile(name, rel, message string) error {
s := e.get(name)
if s == nil {
@@ -1357,12 +1607,13 @@ func (e *Engine) CommitFile(name, rel, message string) error {
if _, err := gitRun(s.cfg.RepoPath, 60*time.Second, "commit", "-m", message, "--", rel); err != nil {
return fmt.Errorf("git commit 失败: %w", err)
}
if sha, serr := gitRun(s.cfg.RepoPath, 10*time.Second, "rev-parse", "--short", "HEAD"); serr == nil {
e.RecordCommit(name, sha, message)
}
e.logf(s, "info", "网页端提交 %s 成功", rel)
return nil
}
// ResolveConflictFile 网页端解决冲突:写入内容 → 暂存 → (可选)结束合并/变基
// finish=true 且已无其它冲突文件时才真正结束,避免把带冲突标记的内容提交进去
func (e *Engine) ResolveConflictFile(name, rel, content string, finish bool) error {
s := e.get(name)
if s == nil {
@@ -1386,14 +1637,12 @@ func (e *Engine) ResolveConflictFile(name, rel, content string, finish bool) err
return e.ConflictResolve(name)
}
// DiffFile 单文件增删统计
type DiffFile struct {
Path string `json:"path"`
Add int `json:"add"`
Del int `json:"del"`
}
// DiffResult 差异结果(网页端「差异」tab)
type DiffResult struct {
Scope string `json:"scope"`
Stat string `json:"stat"`
@@ -1403,7 +1652,6 @@ type DiffResult struct {
Word bool `json:"word"`
}
// WorkingDiff 返回工作区/暂存/全部/与远程的差异
// rel 非空时只对比单个文件(已做路径安全校验)
// mode = "word" 时改用 --word-diff=plain,便于词级定位改动
func (e *Engine) WorkingDiff(name, scope, rel, mode string) (*DiffResult, error) {
@@ -1431,7 +1679,6 @@ func (e *Engine) WorkingDiff(name, scope, rel, mode string) (*DiffResult, error)
args = []string{"diff", "--no-color"}
}
// 词级差异:--word-diff=plain 用 [-x-] / {+x+} 标记行内改动
// 注意:该模式下 git 输出的上下文行不带前导空格,前端解析需兼容(见 parseUnifiedDiff)
if mode == "word" {
args = append(args, "--word-diff=plain")
res.Word = true
@@ -1466,7 +1713,6 @@ func (e *Engine) WorkingDiff(name, scope, rel, mode string) (*DiffResult, error)
return res, nil
}
// stripWarnings 去掉 git 在 stderr 输出的环境告警(如 autocrlf 提示),避免污染差异展示
func stripWarnings(s string) string {
lines := strings.Split(s, "\n")
out := make([]string, 0, len(lines))
@@ -1479,7 +1725,6 @@ func stripWarnings(s string) string {
return strings.Join(out, "\n")
}
// parseStatFiles 解析 `git diff --stat` 输出为单文件增删统计
func parseStatFiles(stat string) []DiffFile {
var files []DiffFile
for _, line := range strings.Split(stat, "\n") {
+41 -23
View File
@@ -13,11 +13,6 @@ import (
"time"
)
// gitRun 在指定仓库目录执行 git 命令,返回合并后的输出。
// 非交互环境:GIT_TERMINAL_PROMPT=0 只能挡住终端提示,挡不住 Windows 凭据管理器(GCM)弹窗,
// 因此额外禁用 GCM 交互、askpass 和 ssh 交互,避免后台同步被凭据弹窗永久卡死。
// WaitDelay 保证超时 Kill 后即使 git 的子进程仍占用管道,Wait() 也能强制返回(Windows 上
// CommandContext 只杀主进程,不杀 git-remote-https / 凭据 helper 等子进程)。
func gitRun(repoPath string, timeout time.Duration, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
@@ -30,16 +25,10 @@ func gitRun(repoPath string, timeout time.Duration, args ...string) (string, err
"GIT_SSH_COMMAND=ssh -oBatchMode=yes -oStrictHostKeyChecking=accept-new",
)
cmd.WaitDelay = 10 * time.Second
// stdout 与 stderr 分开收集:成功时只返回干净的 stdout 供解析,
// 避免 git 的环境告警(如 autocrlf、进度信息)污染解析结果;
// 失败时优先用 stderr 作为错误信息,保证诊断信息不丢失。
var outBuf, errBuf bytes.Buffer
cmd.Stdout = &outBuf
cmd.Stderr = &errBuf
err := cmd.Run()
// 只裁剪尾部空白,不要用 TrimSpace 裁整体:
// git 输出首行的前导空格具有语义(status --porcelain 的暂存位、diff 的上下文行),
// 整体 TrimSpace 会把它吃掉,导致按固定偏移解析路径时错位。
out := strings.TrimRight(outBuf.String(), "\r\n\t ")
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
@@ -65,11 +54,33 @@ func isRepo(path string) bool {
return err == nil
}
func ensureRepo(path, branch string) error {
if path == "" {
return fmt.Errorf("仓库路径为空")
}
path = normalizeWinPath(path)
if err := os.MkdirAll(path, 0o755); err != nil {
return err
}
if isRepo(path) {
return nil
}
if branch == "" {
branch = "main"
}
if _, err := gitRun(path, 30*time.Second, "init", "-b", branch); err != nil {
if _, e2 := gitRun(path, 30*time.Second, "init"); e2 != nil {
return e2
}
_, _ = gitRun(path, 15*time.Second, "checkout", "-b", branch)
}
return nil
}
func currentBranch(path string) (string, error) {
return gitRun(path, 15*time.Second, "rev-parse", "--abbrev-ref", "HEAD")
}
// aheadBehind 返回 (领先, 落后) 远程跟踪分支的提交数(需先 fetch 才准确)
func aheadBehind(path, remote, branch string) (int, int, error) {
out, err := gitRun(path, 30*time.Second, "rev-list", "--left-right", "--count", "HEAD..."+remote+"/"+branch)
if err != nil {
@@ -84,21 +95,16 @@ func aheadBehind(path, remote, branch string) (int, int, error) {
return a, b, nil
}
// remoteRefExists 检查远程跟踪引用是否存在(远程仓库为空或分支名不一致时为 false)
func remoteRefExists(path, remote, branch string) bool {
_, err := gitRun(path, 15*time.Second, "rev-parse", "--verify", "-q", remote+"/"+branch)
return err == nil
}
// branchExists 检查本地分支是否存在
func branchExists(path, branch string) bool {
_, err := gitRun(path, 15*time.Second, "show-ref", "--verify", "-q", "refs/heads/"+branch)
return err == nil
}
// remoteTip 返回远程分支当前指向的 SHA。
// 优先读本地远程跟踪引用(refs/remotes/<remote>/<branch>,快);
// 若本地跟踪引用不可用(个别环境下 ref 存储读写异常),回退用 ls-remote 直查远程。
func remoteTip(path, remote, branch string) (sha string, exists bool) {
if remoteRefExists(path, remote, branch) {
out, err := gitRun(path, 15*time.Second, "rev-parse", remote+"/"+branch)
@@ -117,7 +123,6 @@ func remoteTip(path, remote, branch string) (sha string, exists bool) {
return fields[0], true
}
// aheadBehindSha 基于远程分支的具体 SHA 计算 (领先, 落后),不依赖本地跟踪引用
func aheadBehindSha(path, tip string) (int, int, error) {
out, err := gitRun(path, 30*time.Second, "rev-list", "--left-right", "--count", "HEAD..."+tip)
if err != nil {
@@ -183,7 +188,6 @@ func abortMerge(path string) (string, error) {
return gitRun(path, 30*time.Second, "merge", "--abort")
}
// resolveDone 在用户网页上标记"已解决"后调用:暂存全部 → 继续 merge/rebase 流程
func resolveDone(path string, rebase bool) error {
if _, err := gitRun(path, 30*time.Second, "add", "-A"); err != nil {
return err
@@ -199,8 +203,6 @@ func resolveDone(path string, rebase bool) error {
return nil
}
// changedFiles 解析 git status --porcelain,返回 路径 -> 状态标记(M/A/D/?),
// 供网页端文件树展示每个文件的改动状态。
func changedFiles(path string) map[string]string {
out, err := gitRun(path, 30*time.Second, "status", "--porcelain")
m := map[string]string{}
@@ -213,11 +215,9 @@ func changedFiles(path string) map[string]string {
}
code := line[:2]
p := strings.TrimSpace(line[3:])
// 重命名/复制:取目标路径
if i := strings.Index(p, "->"); i >= 0 {
p = strings.TrimSpace(p[i+2:])
}
// git 对含特殊字符的路径会加引号
p = strings.Trim(p, `"`)
if p == "" {
continue
@@ -233,5 +233,23 @@ func changedFiles(path string) map[string]string {
m[p] = "M" // 含 UU/AU 冲突状态,统一显示为已修改
}
}
for p, st := range m {
if st == "?" && strings.HasSuffix(p, "/") {
expandUntracked(path, p, m)
}
}
return m
}
func expandUntracked(repoPath, dir string, m map[string]string) {
out, err := gitRun(repoPath, 15*time.Second, "ls-files", "--others", "--exclude-standard", "--", dir)
if err != nil {
return
}
for _, ln := range strings.Split(out, "\n") {
ln = strings.TrimSpace(ln)
if ln != "" {
m[ln] = "?"
}
}
}
+1
View File
@@ -0,0 +1 @@
2026/09/09 15:59:43 Git Sync Web 已启动: http://127.0.0.1:5799(鉴权:false)
+24 -5
View File
@@ -53,6 +53,8 @@ func NewServer(e *Engine, static fs.FS, password string) *Server {
mux.HandleFunc("GET /api/repos/{name}/tree", s.wrapRepo(s.treeRepo))
mux.HandleFunc("GET /api/repos/{name}/file", s.wrapRepo(s.fileRepo))
mux.HandleFunc("PUT /api/repos/{name}/file", s.wrapRepo(s.fileWriteRepo))
mux.HandleFunc("GET /api/repos/{name}/summary", s.wrapRepo(s.summaryGetRepo))
mux.HandleFunc("POST /api/repos/{name}/summary", s.wrapRepo(s.summarySaveRepo))
mux.HandleFunc("POST /api/repos/{name}/resolve-file", s.wrapRepo(s.resolveFileRepo))
mux.HandleFunc("POST /api/repos/{name}/commit", s.wrapRepo(s.commitFileRepo))
mux.HandleFunc("GET /api/repos/{name}/diff", s.wrapRepo(s.diffRepo))
@@ -63,7 +65,6 @@ func NewServer(e *Engine, static fs.FS, password string) *Server {
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 访问密码保护:静态资源开放,/api/* 需要会话(登录接口除外)
if s.password != "" && strings.HasPrefix(r.URL.Path, "/api/") &&
r.URL.Path != "/api/login" && !s.validToken(r) {
writeErr(w, 401, "需要登录")
@@ -338,7 +339,6 @@ func (s *Server) abortPushRepo(w http.ResponseWriter, r *http.Request, name stri
writeJSON(w, 200, map[string]any{"ok": true})
}
// ---------- 差异与文件编辑(网页端) ----------
func (s *Server) treeRepo(w http.ResponseWriter, r *http.Request, name string) {
writeJSON(w, 200, map[string]any{"files": s.engine.FileTree(name)})
@@ -378,7 +378,28 @@ func (s *Server) fileWriteRepo(w http.ResponseWriter, r *http.Request, name stri
writeJSON(w, 200, map[string]any{"ok": true})
}
// resolveFileRepo 网页端解决单个冲突文件:写入 + 暂存,finish=true 时尝试结束合并/变基
func (s *Server) summaryGetRepo(w http.ResponseWriter, r *http.Request, name string) {
writeJSON(w, 200, map[string]any{
"pending": s.engine.GetPendingSummary(name),
"log": s.engine.GetSummaryLog(name),
})
}
func (s *Server) summarySaveRepo(w http.ResponseWriter, r *http.Request, name string) {
var req struct {
Summary string `json:"summary"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, 400, "请求体格式错误")
return
}
if err := s.engine.SavePendingSummary(name, req.Summary); err != nil {
writeErr(w, 500, err.Error())
return
}
writeJSON(w, 200, map[string]any{"ok": true, "pending": s.engine.GetPendingSummary(name)})
}
func (s *Server) resolveFileRepo(w http.ResponseWriter, r *http.Request, name string) {
var req struct {
Path string `json:"path"`
@@ -425,7 +446,6 @@ func (s *Server) diffRepo(w http.ResponseWriter, r *http.Request, name string) {
if scope == "" {
scope = "working"
}
// path 可选:传入时只对比该文件(用于编辑器「对比此文件」)
// mode = word 时返回 --word-diff=plain 结果(词级差异)
res, err := s.engine.WorkingDiff(name, scope, r.URL.Query().Get("path"), r.URL.Query().Get("mode"))
if err != nil {
@@ -435,7 +455,6 @@ func (s *Server) diffRepo(w http.ResponseWriter, r *http.Request, name string) {
writeJSON(w, 200, res)
}
// handleCronNext 返回 cron 表达式的下次执行时间,供配置表单实时预览
func (s *Server) handleCronNext(w http.ResponseWriter, r *http.Request) {
expr := r.URL.Query().Get("expr")
if expr == "" {
+92 -77
View File
@@ -9,11 +9,9 @@ const STATUS = {
};
const RESULT_TEXT = { ok: '成功', error: '失败', conflict: '冲突' };
// ---------- 相对时间(卡片「上次同步」) ----------
const STALE_HOURS = 24; // 超过该小时数且仍在运行 → 标记「久未同步」
function parseTs(s) {
if (!s) return null;
// 后端时间格式 "2006-01-02 15:04:05",补齐为 ISO 本地时间
const t = new Date(String(s).replace(' ', 'T'));
return isNaN(t.getTime()) ? null : t;
}
@@ -39,7 +37,6 @@ let current = null;
let creating = false;
let chart = null;
// ---------- 基础 ----------
function esc(s) {
return String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
@@ -56,10 +53,8 @@ async function api(url, opts) {
}
const post = (url) => api(url, { method: 'POST' });
// ---------- Toast 轻提示(替代原生 alert,避免打断操作) ----------
function toast(msg, type) {
const box = $('#toasts');
// 兜底:容器缺失时不能递归调用自身
if (!box) { console.warn('toast 容器缺失:', msg); return; }
const el = document.createElement('div');
el.className = 'toast t-' + (type || 'info');
@@ -75,9 +70,6 @@ function toast(msg, type) {
}, life);
}
// ---------- 编辑器抽象:统一原生 textarea 与 CodeMirror 的读写 ----------
// CodeMirror 由 cm-boot.js 在脚本加载后接管并写入 Editor.cm;
// 库缺失 / 初始化失败时 Editor.cm 保持 null,自动回退原生 textarea,功能不受影响。
const Editor = {
cm: null,
get el() { return $('#file-editor'); },
@@ -98,7 +90,6 @@ const Editor = {
if (this.cm) this.cm.setOption('readOnly', b ? 'nocursor' : false);
if (this.el) this.el.disabled = !!b;
},
// 按扩展名选择语法高亮模式
setMode(path) {
if (!this.cm) return;
const ext = String(path || '').split('.').pop().toLowerCase();
@@ -121,15 +112,23 @@ const Editor = {
setTheme(dark) {
if (this.cm) this.cm.setOption('theme', dark ? 'material-darker' : 'eclipse');
},
// 弹窗 / tab 切换后需要重算尺寸,否则 CodeMirror 可能不显示内容
refresh() { if (this.cm) setTimeout(() => this.cm.refresh(), 30); },
setChangedLines(lines) {
this._changed = lines && lines.length ? lines : null;
if (!this.cm) return;
const n = this.cm.lineCount();
for (let i = 0; i < n; i++) this.cm.removeLineClass(i, 'background', 'cm-chg');
if (!this._changed) return;
for (const ln of this._changed) {
const idx = ln - 1;
if (idx >= 0 && idx < n) this.cm.addLineClass(idx, 'background', 'cm-chg');
}
},
onSave: null, // 由 cm-boot.js 的快捷键触发
onChange: null, // 由 cm-boot.js 的 change 事件触发(草稿缓存)
};
// 顶层 const 不会挂到 window,显式暴露给 cm-boot.js 使用
window.Editor = Editor;
// ---------- 渲染 ----------
function render() {
const grid = $('#grid');
grid.innerHTML = '';
@@ -161,6 +160,7 @@ function card(r) {
${r.cron ? `<span class="badge" title="${esc(r.cron)}">cron</span>` : ''}
${r.conflicts && r.conflicts.length ? `<span class="badge b-conflict">冲突 ${r.conflicts.length}</span>` : ''}
${r.push_conflict ? `<span class="badge b-conflict">推送冲突</span>` : ''}
${r.running && r.auto_sync === false ? `<span class="badge b-paused">手动模式</span>` : ''}
${r.running && r.last_sync && isStale(r.last_sync.time) ? '<span class="badge b-stale">久未同步</span>' : ''}
</div>
<div class="last" title="${r.last_sync ? esc(r.last_sync.time) : ''}">上次同步:${esc(last)}</div>
@@ -191,7 +191,6 @@ $('#grid').addEventListener('click', async (e) => {
} catch (err) { toast(err.message, 'error'); }
});
// ---------- SSE 实时事件 ----------
function connect() {
const es = new EventSource('/api/events');
es.onopen = () => setConn(true);
@@ -226,7 +225,6 @@ function setConn(ok) {
}
}
// ---------- 全局实时活动面板 ----------
const LIVE_MAX = 400;
function appendLiveLine(msg) {
const box = $('#live-log');
@@ -247,7 +245,6 @@ function clearLive() {
if (box) box.innerHTML = '';
}
// 载入各仓库最近日志作为初始上下文,避免面板一开始空白(仅启动播种一次)
let liveSeeded = false;
async function seedLive() {
if (liveSeeded) return;
@@ -258,7 +255,6 @@ async function seedLive() {
const d = await api(`/api/repos/${name}/log?lines=8`);
if (d.lines && d.lines.length) {
d.lines.forEach(t => {
// 兼容新格式 [时间] [级别] 消息 与历史格式 [时间] 消息
const m = t.match(/^\[(.+?)\]\s*(?:\[(info|warn|error)\]\s*)?(.*)$/i);
appendLiveLine({
time: m ? m[1] : '',
@@ -275,7 +271,6 @@ async function seedLive() {
$('#btn-live-clear').addEventListener('click', clearLive);
// ---------- 登录 ----------
function showLogin() {
const el = $('#login');
if (el.hidden) {
@@ -307,7 +302,6 @@ async function doLogin() {
$('#btn-login').addEventListener('click', doLogin);
$('#login-password').addEventListener('keydown', (e) => { if (e.key === 'Enter') doLogin(); });
// ---------- 详情弹窗 ----------
function showTab(t) {
document.querySelectorAll('#m-tabs .tab').forEach(b => b.classList.toggle('active', b.dataset.tab === t));
document.querySelectorAll('.tab-pane').forEach(p => { p.hidden = p.id !== 'tab-' + t; });
@@ -333,6 +327,8 @@ function openDetail(name) {
$('#btn-delete').hidden = false;
$('#btn-clone').hidden = false;
fillForm(r);
$('#summary-box').hidden = false;
loadSummary(name);
showTab('log');
$('#modal').hidden = false;
}
@@ -345,10 +341,22 @@ function openCreate() {
$('#btn-delete').hidden = true;
$('#btn-clone').hidden = true;
fillForm(null);
$('#summary-box').hidden = true;
showTab('config');
$('#modal').hidden = false;
}
async function loadSummary(name) {
if (!name) return;
try {
const d = await api(`/api/repos/${name}/summary`);
$('#f-summary').value = d.pending || '';
$('#summary-log').textContent = d.log ? d.log.trim() : '(暂无本地变更摘要记录)';
} catch (err) {
$('#summary-log').textContent = '读取摘要失败:' + err.message;
}
}
function closeModal() {
$('#modal').hidden = true;
current = null;
@@ -358,12 +366,10 @@ $('#m-close').addEventListener('click', closeModal);
$('#modal').addEventListener('click', (e) => { if (e.target === $('#modal')) closeModal(); });
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeModal(); });
// ---------- 日志(级别过滤 + 关键词搜索) ----------
let logLines = [];
let logLevel = 'all';
let logQuery = '';
// 落盘格式:[时间] [级别] 消息;历史日志无级别前缀时按 info 处理
function logLevelOf(line) {
const m = /^\[[^\]]+\]\s*\[(info|warn|error)\]/i.exec(line);
return m ? m[1].toLowerCase() : 'info';
@@ -404,7 +410,6 @@ $('#btn-log-clear').addEventListener('click', () => {
renderLog();
});
// ---------- 提交历史 ----------
function loadHistory(name) {
const list = $('#commit-list');
list.textContent = '加载中…';
@@ -441,7 +446,6 @@ $('#commit-list').addEventListener('click', async (e) => {
}
});
// ---------- 冲突 ----------
function loadConflicts(name) {
api(`/api/repos/${name}/conflicts`).then(files => {
const list = $('#conflict-list');
@@ -470,7 +474,6 @@ function loadConflicts(name) {
}).catch(err => { $('#conflict-list').innerHTML = `<p style="color:var(--red)">${esc(err.message)}</p>`; });
}
// 冲突文件内联编辑:展开编辑区 → 读取原文 → 保存 / 保存并标记已解决
$('#conflict-list').addEventListener('click', async (e) => {
const btn = e.target.closest('button[data-cf]');
if (!btn || !current) return;
@@ -510,7 +513,6 @@ $('#conflict-list').addEventListener('click', async (e) => {
return;
}
// save / resolve
if (ta.disabled) { toast('该文件当前不可编辑', 'error'); return; }
try {
await api(`/api/repos/${current}/resolve-file`, {
@@ -545,12 +547,10 @@ $('#btn-abort').addEventListener('click', () => {
});
$('#btn-resolved').addEventListener('click', () => doAction('resolve', '冲突处理流程完成'));
// 手动拉取 / 推送 / 获取(B1:后端 ManualGit 已支持)
$('#btn-fetch').addEventListener('click', () => doAction('fetch', '获取完成'));
$('#btn-pull').addEventListener('click', () => doAction('pull', '拉取完成'));
$('#btn-push').addEventListener('click', () => doAction('push', '推送完成'));
// 推送冲突(non-fast-forward)的解决入口(B3)
$('#btn-force-push').addEventListener('click', async () => {
if (!current) return;
try {
@@ -568,7 +568,6 @@ $('#btn-abort-push').addEventListener('click', async () => {
} catch (err) { toast(err.message, 'error'); }
});
// 根据当前仓库快照切换推送冲突操作区显隐(B3)
function updateConflictActions() {
const r = repos.find(x => x.name === current);
const box = $('#push-conflict-actions');
@@ -582,10 +581,7 @@ function updateConflictActions() {
}
}
// ---------- 差异显示(网页端) ----------
// diffPath 非空时只显示单个文件的差异(编辑器「对比此文件」进入)
let diffPath = '';
// diffText 保存当前差异原文,供「复制 / 下载 .patch」使用
let diffText = '';
function updateDiffFilterNote() {
@@ -625,13 +621,12 @@ function loadDiff(name) {
}).catch(err => { box.textContent = '差异加载失败:' + err.message; });
}
// ---------- 差异渲染:统一 / 并排 / 词级 ----------
// 把 unified diff 解析成「文件 → 行记录」,统一与并排两种视图共用同一份结构
function parseUnifiedDiff(text) {
const lines = String(text).split('\n');
const files = [];
let cur = null;
let oldNo = 0, newNo = 0;
let inHunk = false; // 词级模式(--word-diff=plain)下 git 的上下文行不带前导空格,需据此兜底
const push = (header) => { cur = { header, rows: [] }; files.push(cur); return cur; };
for (const line of lines) {
if (line.startsWith('diff --git') || line.startsWith('Index: ')) { push(line); continue; }
@@ -655,7 +650,6 @@ function parseUnifiedDiff(text) {
if (line.startsWith(' ')) { cur.rows.push({ type: 'ctx', text: line.slice(1), no: oldNo++, nNo: newNo++ }); continue; }
if (line === '') { cur.rows.push({ type: 'ctx', text: '', no: oldNo++, nNo: newNo++ }); continue; }
// 词级模式(--word-diff=plain)下 git 的上下文行不带前导空格,
// 因此 hunk 内未识别的行一律按上下文处理;hunk 外的(如 "\ No newline")按元信息处理。
if (inHunk && !line.startsWith('\\')) {
cur.rows.push({ type: 'ctx', text: line, no: oldNo++, nNo: newNo++ });
continue;
@@ -665,7 +659,6 @@ function parseUnifiedDiff(text) {
return files;
}
// 词级:把 [-删除-] / {+新增+} 渲染成高亮片段(textContent 拼接,天然防 XSS)
function fillWord(el, text) {
const re = /\[-([\s\S]*?)-\]|\{\+([\s\S]*?)\+\}/g;
let last = 0, m;
@@ -683,7 +676,6 @@ function fillWord(el, text) {
if (!el.childNodes.length) el.appendChild(document.createTextNode(text));
}
// 并排:把连续的 del/add 段配对成行,多余的一侧留空
function buildSplitRows(rows) {
const out = [];
let i = 0;
@@ -691,7 +683,6 @@ function buildSplitRows(rows) {
const r = rows[i];
if (r.type === 'hunk' || r.type === 'meta') { out.push({ kind: r.type, text: r.text }); i++; continue; }
if (r.type === 'ctx') {
// 左右列行号分别取旧/新行号,故右侧用副本
out.push({ kind: 'ctx', left: r, right: { text: r.text, no: r.nNo == null ? r.no : r.nNo } });
i++;
continue;
@@ -791,7 +782,6 @@ function renderDiff(box, text) {
box.appendChild(frag);
}
// ---------- 文件编辑(网页端) ----------
let fileCurrent = null;
const STATUS_LABEL = { M: '已修改', A: '已新增', D: '已删除', '?': '未跟踪' };
function loadTree(name) {
@@ -811,7 +801,6 @@ function loadTree(name) {
}).catch(err => { list.textContent = '文件列表加载失败:' + err.message; });
}
// ---------- 草稿缓存(localStorage,防刷新丢稿) ----------
const draftKey = (name, path) => `gitautosync:draft:${name}:${path}`;
let draftServer = ''; // 当前文件在磁盘上的原文,用于「放弃草稿」回滚
let draftTimer = null;
@@ -826,12 +815,11 @@ function showDraftNote(on) {
if (a) a.addEventListener('click', (e) => {
e.preventDefault();
localStorage.removeItem(draftKey(current, fileCurrent));
$('#file-editor').value = draftServer;
Editor.value = draftServer;
showDraftNote(false);
});
}
// 编辑时防抖缓存草稿;内容与磁盘一致时自动清除
function scheduleDraft() {
if (!current || !fileCurrent) return;
if (draftTimer) clearTimeout(draftTimer);
@@ -844,35 +832,56 @@ function scheduleDraft() {
}
async function loadFile(name, path) {
const editor = $('#file-editor');
editor.value = '加载中…';
editor.disabled = false;
$('#file-current').textContent = path;
fileCurrent = path;
showDraftNote(false);
Editor._suspend = true;
try {
Editor.value = '加载中…';
Editor.disabled = false;
Editor.setMode(path);
$('#file-current').textContent = path;
fileCurrent = path;
showDraftNote(false);
const d = await api(`/api/repos/${name}/file?path=${encodeURIComponent(path)}`);
if (d.binary) {
editor.value = `(二进制文件,大小 ${d.size} 字节,无法在网页编辑)`;
editor.disabled = true;
Editor.setChangedLines(null);
const bh = $('#file-chg-hint'); if (bh) bh.hidden = true;
Editor.value = `(二进制文件,大小 ${d.size} 字节,无法在网页编辑)`;
Editor.disabled = true;
draftServer = '';
return;
}
draftServer = d.content || '';
const saved = localStorage.getItem(draftKey(name, path));
if (saved !== null && saved !== draftServer) {
editor.value = saved;
Editor.value = saved;
showDraftNote(true);
} else {
editor.value = draftServer;
Editor.value = draftServer;
}
editor.disabled = false;
Editor.setChangedLines(d.changed);
const hint = $('#file-chg-hint');
if (hint) hint.hidden = !(d.changed && d.changed.length);
Editor.disabled = false;
} catch (err) {
editor.value = '读取失败:' + err.message;
editor.disabled = true;
Editor.setChangedLines(null);
const eh = $('#file-chg-hint'); if (eh) eh.hidden = true;
Editor.value = '读取失败:' + err.message;
Editor.disabled = true;
} finally {
Editor._suspend = false;
}
}
async function commitCurrentFile() {
const name = current;
const path = fileCurrent;
if (!name || !path) throw new Error('请先在左侧选择一个文件');
await api(`/api/repos/${name}/commit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path, message: $('#file-msg').value })
});
}
async function saveFile(commit) {
const name = current;
const path = fileCurrent;
@@ -880,39 +889,30 @@ async function saveFile(commit) {
if (Editor.disabled) { toast('当前文件不可编辑(二进制或读取失败)'); return; }
const content = Editor.value;
try {
// 先写盘
await api(`/api/repos/${name}/file`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path, content })
});
// 写盘成功 → 草稿作废
localStorage.removeItem(draftKey(name, path));
showDraftNote(false);
draftServer = content;
if (commit) {
await api(`/api/repos/${name}/commit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path, message: $('#file-msg').value })
});
toast('已保存并提交');
await commitCurrentFile();
toast('已保存并提交:' + path);
} else {
// 保存后自动切到差异预览
$('#f-diff-scope').value = 'working';
showTab('diff');
toast('已保存到磁盘(未提交)。可在「差异」tab 查看改动,或稍后由自动同步提交。');
toast('已保存到磁盘(未提交)。可在「差异」tab 查看改动;提交请用「提交」或「保存并提交」。');
}
} catch (err) { toast('保存失败:' + err.message); }
}
$('#f-diff-scope').addEventListener('change', () => { if (current && !$('#tab-diff').hidden) loadDiff(current); });
// 并排/统一纯前端重渲染(同一份 diff 原文);词级需后端重新生成,故重新拉取
$('#f-diff-view').addEventListener('change', () => { renderDiff($('#diffbox'), diffText || '(无差异)'); });
$('#f-diff-word').addEventListener('change', () => { if (current && !$('#tab-diff').hidden) loadDiff(current); });
$('#btn-diff-refresh').addEventListener('click', () => { if (current) loadDiff(current); });
// 差异:复制 / 下载 .patch
$('#btn-diff-copy').addEventListener('click', async () => {
if (!diffText) { toast('当前没有可复制的差异内容'); return; }
try {
@@ -937,7 +937,6 @@ $('#btn-diff-download').addEventListener('click', () => {
$('#btn-file-refresh').addEventListener('click', () => { if (current) loadTree(current); });
// 编辑器「对比此文件」→ 跳到差异 tab 并只看该文件
$('#btn-file-diff').addEventListener('click', () => {
if (!current || !fileCurrent) { toast('请先在左侧选择一个文件'); return; }
diffPath = fileCurrent;
@@ -952,8 +951,16 @@ $('#file-list').addEventListener('click', (e) => {
});
$('#btn-file-save').addEventListener('click', () => saveFile(false));
$('#btn-file-commit').addEventListener('click', () => saveFile(true));
$('#btn-file-commit-only').addEventListener('click', async () => {
if (!current || !fileCurrent) { toast('请先在左侧选择一个文件'); return; }
try {
await commitCurrentFile();
toast('已提交:' + fileCurrent);
if (Editor.value === draftServer) await loadFile(current, fileCurrent);
refresh();
} catch (err) { toast('提交失败:' + err.message, 'error'); }
});
// 编辑器:输入时缓存草稿,Ctrl/Cmd + S 直接保存
$('#file-editor').addEventListener('input', scheduleDraft);
$('#file-editor').addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && (e.key === 's' || e.key === 'S')) {
@@ -961,21 +968,22 @@ $('#file-editor').addEventListener('keydown', (e) => {
saveFile(false);
}
});
Editor.onChange = scheduleDraft;
Editor.onSave = () => saveFile(false);
// ---------- 统计 ----------
function dateStr(d) {
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
function loadStats(name) {
api(`/api/repos/${name}/stats`).then(rows => {
rows = rows.filter(r => r.action !== 'sync');
const days = [];
for (let i = 29; i >= 0; i--) {
const d = new Date();
d.setDate(d.getDate() - i);
days.push(dateStr(d));
}
// 后端写入的 result 词汇是 success/failed/conflict,这里归一化到 ok/error/conflict 再统计
const normResult = r => r.result === 'success' ? 'ok' : r.result === 'failed' ? 'error' : r.result;
const mk = (key) => days.map(d => rows.filter(r => normResult(r) === key && r.time.slice(0, 10) === d).length);
const total = { ok: 0, error: 0, conflict: 0 };
@@ -1009,7 +1017,6 @@ function loadStats(name) {
}).catch(err => { $('#stat-summary').textContent = '统计加载失败:' + err.message; });
}
// ---------- 配置表单 ----------
function fillForm(r) {
$('#f-name').value = r ? r.name : '';
$('#f-path').value = r ? r.repo_path : '';
@@ -1023,6 +1030,7 @@ function fillForm(r) {
$('#f-retry').value = r ? r.retry_count : 3;
$('#f-retry-interval').value = r ? r.retry_interval : 5;
$('#f-autocommit').checked = r ? !!r.auto_commit : false;
$('#f-autosync').checked = r ? (r.auto_sync !== false) : true;
$('#f-cron').value = r ? (r.cron || '') : '';
$('#f-log').value = r ? (r.log_file || '') : '';
previewCron();
@@ -1049,6 +1057,7 @@ function readForm() {
conflict_strategy: $('#f-conflict').value,
push_strategy: $('#f-push').value,
auto_commit: $('#f-autocommit').checked,
auto_sync: $('#f-autosync').checked,
cron: $('#f-cron').value.trim(),
log_file: $('#f-log').value.trim(),
};
@@ -1086,8 +1095,6 @@ $('#btn-delete').addEventListener('click', async () => {
} catch (err) { toast(err.message, 'error'); }
});
// ---------- 配置「克隆」按钮(多仓库同构时省得重填) ----------
// 复用 readForm 取当前表单值 → 切到新建态:名称自动加 -copy(去重),仓库路径清空
$('#btn-clone').addEventListener('click', () => {
if (!current) return;
const base = readForm();
@@ -1111,7 +1118,19 @@ $('#btn-clone').addEventListener('click', () => {
$('#f-name').focus();
});
// ---------- 顶部按钮 ----------
$('#btn-summary-save').addEventListener('click', async () => {
if (!current) return;
try {
const res = await api(`/api/repos/${current}/summary`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ summary: $('#f-summary').value })
});
toast(res.ok ? '摘要已保存(本地,下次自动提交将使用此信息)' : '摘要保存失败', res.ok ? 'info' : 'error');
await loadSummary(current);
} catch (err) { toast('摘要保存失败:' + err.message, 'error'); }
});
$('#btn-new').addEventListener('click', openCreate);
$('#btn-empty-new').addEventListener('click', openCreate);
$('#btn-sync-all').addEventListener('click', () => {
@@ -1119,7 +1138,6 @@ $('#btn-sync-all').addEventListener('click', () => {
toast(`已向 ${repos.filter(r => r.running).length} 个运行中的仓库发起同步`);
});
// 批量启停:并发调用,汇总成功/失败
async function batchToggle(act) {
const isStart = act === 'start';
const targets = repos.filter(r => isStart ? !r.running : r.running);
@@ -1138,7 +1156,6 @@ async function batchToggle(act) {
$('#btn-start-all').addEventListener('click', () => batchToggle('start'));
$('#btn-stop-all').addEventListener('click', () => batchToggle('stop'));
// ---------- 暗色模式 ----------
const THEME_KEY = 'gitautosync:theme';
function applyTheme(dark) {
document.documentElement.classList.toggle('dark', !!dark);
@@ -1155,7 +1172,6 @@ $('#btn-theme').addEventListener('click', () => {
applyTheme(dark);
});
// ---------- Cron 下次执行预览 ----------
let cronTimer = null;
async function previewCron() {
const el = $('#cron-next');
@@ -1176,7 +1192,6 @@ $('#f-cron').addEventListener('input', () => {
cronTimer = setTimeout(previewCron, 400);
});
// ---------- 初始化 ----------
async function refresh() {
try {
const d = await api('/api/status');
+1 -5
View File
@@ -1,5 +1,3 @@
// CodeMirror 引导:在 codemirror.min.js 及其 mode 加载完成后接管 #file-editor。
// 若库未加载或初始化失败,window.Editor.cm 保持 null,自动回退原生 textarea,功能不受影响。
(function () {
if (typeof window.CodeMirror === 'undefined' || typeof window.Editor === 'undefined') return;
var ta = document.getElementById('file-editor');
@@ -19,9 +17,7 @@
}
});
window.Editor.cm = cm;
// CodeMirror 的 change 事件桥接到草稿缓存
cm.on('change', function () { if (window.Editor.onChange) window.Editor.onChange(); });
// 模式跟随打开文件时的 setMode
cm.on('change', function () { if (window.Editor._suspend) return; if (window.Editor.onChange) window.Editor.onChange(); });
var cur = window.Editor.value;
} catch (e) {
if (window.console) console.warn('CodeMirror 初始化失败,已回退原生编辑器:', e);
+30 -16
View File
@@ -111,12 +111,14 @@
</div>
<div class="file-body" data-page-node-id="RXmkN5Ep4iegYWG3iWBiON">
<div id="file-list" class="file-list" data-page-node-id="F75SFyDQShim9rZFPnjuJC">加载中…</div>
<div class="file-edit-col" data-page-node-id="xh1qou2SVboDfvKTLcXFEA">
<textarea id="file-editor" class="file-editor" placeholder="选择左侧文件进行编辑(Ctrl/Cmd + S 保存)" spellcheck="false"></textarea>
<div class="file-edit-col" data-page-node-id="xh1qou2SVboDfvKTLcXFEA">
<div class="file-chg-hint" id="file-chg-hint" hidden>● 黄色高亮 = 相对最近一次提交仍未提交的修改行</div>
<textarea id="file-editor" class="file-editor" placeholder="选择左侧文件进行编辑(Ctrl/Cmd + S 保存)" spellcheck="false"></textarea>
<div class="file-actions" data-page-node-id="GAMAnkYKeMi93EVEx8eYOn">
<input id="file-msg" class="file-msg" placeholder="提交说明(可选)" data-page-node-id="aS2jRAr1kAkqElk1T4Cldz">
<button class="btn btn-sm" id="btn-file-save" data-page-node-id="gaVGyD6YkFFElkXJFBtLk5">保存</button>
<button class="btn btn-sm btn-primary" id="btn-file-commit" data-page-node-id="1VDju8pdiboyM0zBgwff21">保存并提交</button>
<button class="btn btn-sm" id="btn-file-save" data-page-node-id="gaVGyD6YkFFElkXJFBtLk5">保存</button>
<button class="btn btn-sm" id="btn-file-commit-only" title="提交当前文件在磁盘上的改动(不含编辑器里尚未保存的修改)">提交</button>
<button class="btn btn-sm btn-primary" id="btn-file-commit" data-page-node-id="1VDju8pdiboyM0zBgwff21">保存并提交</button>
</div>
</div>
</div>
@@ -127,15 +129,15 @@
<button class="btn btn-sm" id="btn-pull" data-page-node-id="D3F7c7ZkTj2GaQqrBtshfW">拉取</button>
<button class="btn btn-sm" id="btn-push" data-page-node-id="qTA9vsiTSuWz4dwilu7Prf">推送</button>
</div>
<div class="conflict-actions" id="pull-conflict-actions" data-page-node-id="u1mYEBVApFghZDqR2RFg7V">
<button class="btn btn-danger" id="btn-abort" data-page-node-id="iFRU44FOA3NXieww4PmbAR">放弃合并</button>
<button class="btn btn-primary" id="btn-resolved" data-page-node-id="C4SMNurpXaOJ8jByGjS2zg">我已在本地解决,继续</button>
</div>
<div class="conflict-actions" id="push-conflict-actions" hidden data-page-node-id="C2kukXRbyT5HAgGznQBEOF">
<span class="hint" id="push-conflict-hint" data-page-node-id="meqqutN8Y8BlHoIUOsDuc3"></span>
<button class="btn btn-danger" id="btn-force-push" data-page-node-id="20FtTVRLlB3HrObTPUgS7I">强制推送(--force-with-lease)</button>
<button class="btn" id="btn-abort-push" data-page-node-id="kr5vGtshzwTYewuRpjenau">放弃强制推送</button>
</div>
<div class="conflict-actions" id="pull-conflict-actions" data-page-node-id="u1mYEBVApFghZDqR2RFg7V">
<button class="btn btn-sm btn-danger" id="btn-abort" data-page-node-id="iFRU44FOA3NXieww4PmbAR">放弃合并</button>
<button class="btn btn-sm btn-primary" id="btn-resolved" data-page-node-id="C4SMNurpXaOJ8jByGjS2zg">我已在本地解决,继续</button>
</div>
<div class="conflict-actions" id="push-conflict-actions" hidden data-page-node-id="C2kukXRbyT5HAgGznQBEOF">
<span class="hint" id="push-conflict-hint" data-page-node-id="meqqutN8Y8BlHoIUOsDuc3"></span>
<button class="btn btn-sm btn-danger" id="btn-force-push" data-page-node-id="20FtTVRLlB3HrObTPUgS7I">强制推送(--force-with-lease)</button>
<button class="btn btn-sm" id="btn-abort-push" data-page-node-id="kr5vGtshzwTYewuRpjenau">放弃强制推送</button>
</div>
<div id="conflict-list" data-page-node-id="5cossjGefHTRs2BQmv7ZiE"></div>
</div>
<div id="tab-stats" class="tab-pane" hidden data-page-node-id="AmEsRLuCU7oz0ILjoFOSan">
@@ -197,14 +199,26 @@
<input type="checkbox" id="f-autocommit" data-page-node-id="5ADMjJXNR5EGPDmhwiCBlm">
<span data-page-node-id="z0tpoI6jpAbJCEwUJ4cSxO">自动提交模式:检测到未提交改动时自动 commit,并随同步推送到远程</span>
</label>
<label class="full check-row">
<input type="checkbox" id="f-autosync">
<span>自动同步:按间隔 / Cron 自动拉取推送。关闭后仅响应「立即同步」手动触发,不再自动运行</span>
</label>
<label class="full" data-page-node-id="tei066TFL8N9sqInjysFvD">Cron 表达式(可选,5 段:分 时 日 月 周;填写后优先于固定间隔)
<input name="cron" id="f-cron" placeholder="*/30 * * * * 表示每 30 分钟,留空使用固定间隔" data-page-node-id="6W3Ua8pPoGLuaNh7rGcDOw">
<span id="cron-next" class="cron-next" data-page-node-id="WgXuBnZPqGWvOBGRxzIVCn"></span>
</label>
<label class="full" data-page-node-id="fsjZ6wLid5NUBV0yAHKdII">日志文件路径(留空使用默认 logs/配置名.log)
<input name="log_file" id="f-log" data-page-node-id="KJpv7jEWYnOQZ1PtQMetfP">
</label>
<label class="full" data-page-node-id="fsjZ6wLid5NUBV0yAHKdII">日志文件路径(留空使用默认 logs/配置名.log)
<input name="log_file" id="f-log" data-page-node-id="KJpv7jEWYnOQZ1PtQMetfP">
</label>
<div class="summary-box" id="summary-box" hidden>
<div class="summary-head">
<span>变更摘要(本地,不同步)</span>
<button type="button" class="btn btn-sm" id="btn-summary-save">保存摘要</button>
</div>
<textarea id="f-summary" class="file-editor" style="min-height:84px" placeholder="填写后将作为【自动提交】的下一次 commit 信息;留空则由工具自动生成一句话并在本地记录。此摘要与映射仅存于本地 summaries/,不会上传。"></textarea>
<div class="summary-log" id="summary-log"></div>
</div>
</div>
<div class="form-actions" data-page-node-id="1GfIJLKdxSyPwBqpqCCMb9">
<button type="submit" class="btn btn-primary" data-page-node-id="E2123htNE6lmoNzZTg7AwV">保存</button>
<button type="button" class="btn" id="btn-clone" hidden data-page-node-id="H6BdDiraff2cjD9EWjF8Eh">克隆此配置</button>
+28 -8
View File
@@ -23,21 +23,21 @@ header { display: flex; justify-content: space-between; align-items: center; pad
.btn-danger:hover { background: var(--red-bg); }
.btn-icon { border: none; background: none; font-size: 18px; cursor: pointer; color: var(--muted); }
main { max-width: 1320px; margin: 24px auto; padding: 0 24px; }
.layout { display: flex; gap: 20px; align-items: flex-start; }
main { max-width: 1320px; margin: 18px auto; padding: 0 18px; }
.layout { display: flex; gap: 16px; align-items: flex-start; }
.main-col { flex: 1; min-width: 0; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 12px; }
.empty { text-align: center; color: var(--muted); padding: 80px 0; }
/* 全局实时活动面板 */
.live { width: 360px; flex: none; position: sticky; top: 80px; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); display: flex; flex-direction: column; max-height: calc(100vh - 104px); }
.live { width: 460px; flex: none; position: sticky; top: 78px; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); display: flex; flex-direction: column; max-height: calc(100vh - 100px); }
.live-head { display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-bottom: 1px solid var(--border); }
.live-head h2 { margin: 0; font-size: 15px; font-weight: 500; flex: 1; }
.live-head .conn { margin: 0; }
.btn-sm { border: 1px solid var(--border); background: #fff; border-radius: 7px; padding: 3px 10px; font-size: 12px; cursor: pointer; color: var(--muted); }
.btn-sm:hover { border-color: #b6bcc4; background: #f3f4f6; }
.live-hint { font-size: 11px; color: var(--muted); padding: 8px 14px; border-bottom: 1px solid var(--border); }
.live-log { flex: 1; overflow-y: auto; padding: 8px 10px; font-family: Consolas, "Cascadia Code", monospace; font-size: 11.5px; line-height: 1.5; }
.live-log { flex: 1; overflow-y: auto; padding: 8px 10px; font-family: Consolas, "Cascadia Code", monospace; font-size: 12px; line-height: 1.45; }
.live-line { display: flex; gap: 6px; padding: 2px 0; border-bottom: 1px solid #f2f2f2; }
.live-line .ll-time { color: #9aa0a6; flex: none; }
.live-line .ll-repo { color: var(--blue); flex: none; font-weight: 600; max-width: 96px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -53,7 +53,7 @@ main { max-width: 1320px; margin: 24px auto; padding: 0 24px; }
.live { width: 100%; position: static; max-height: 360px; }
}
.card { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px; display: flex; flex-direction: column; gap: 8px; }
.card { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px; display: flex; flex-direction: column; gap: 6px; }
.card.st-conflict { border-color: #e8c98a; background: #fffdf6; }
.card.st-error { border-color: #eec9c9; }
.card-head { display: flex; align-items: center; gap: 8px; }
@@ -89,7 +89,8 @@ main { max-width: 1320px; margin: 24px auto; padding: 0 24px; }
.tab-pane[hidden] { display: none; }
.logbox { margin: 0; background: #f6f7f9; border: 1px solid var(--border); padding: 12px; border-radius: 8px; font: 12px/1.5 Consolas, monospace; white-space: pre-wrap; word-break: break-all; max-height: 55vh; overflow: auto; }
.conflict-actions { display: flex; gap: 8px; margin-bottom: 12px; }
.conflict-actions { display: flex; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; }
.manual-actions { display: flex; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; }
.conflict-file { margin-bottom: 14px; }
.conflict-file h4 { margin: 0 0 6px; font-size: 13px; font-family: Consolas, monospace; }
.conflict-file pre { margin: 0; background: #f6f7f9; border: 1px solid var(--border); border-radius: 8px; padding: 10px; font: 12px/1.5 Consolas, monospace; white-space: pre-wrap; word-break: break-all; max-height: 300px; overflow: auto; }
@@ -144,11 +145,19 @@ textarea { font-family: Consolas, monospace; resize: vertical; }
.file-item { padding: 4px 8px; border-radius: 6px; font-size: 12.5px; font-family: Consolas, monospace; cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.file-item:hover { background: #f0f3f6; }
.file-edit-col { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8px; }
.file-chg-hint { font-size: 12px; color: #9a6b00; background: rgba(255, 196, 0, 0.12); border: 1px solid rgba(224, 160, 32, 0.4); border-radius: 6px; padding: 4px 8px; }
html.dark .file-chg-hint { color: #d9a93a; background: rgba(255, 196, 0, 0.1); border-color: rgba(201, 143, 28, 0.4); }
.file-editor { flex: 1; min-height: 360px; width: 100%; border: 1px solid var(--border); border-radius: 8px; padding: 10px; font: 12.5px/1.55 Consolas, monospace; color: var(--text); background: #fff; white-space: pre; overflow: auto; }
.file-editor:disabled { background: #f6f7f9; color: var(--muted); }
.file-actions { display: flex; gap: 8px; align-items: center; }
.file-msg { flex: 1; }
.summary-box { margin-top: 16px; padding: 12px 14px; border: 1px solid var(--border); border-radius: 10px; background: var(--card); }
.summary-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; font-size: 13px; color: var(--muted); }
.summary-head .btn-sm { padding: 4px 10px; font-size: 12px; }
.summary-log { margin-top: 10px; padding: 10px 12px; border: 1px dashed var(--border); border-radius: 8px; background: #fafbfc; font: 12px/1.6 Consolas, "Microsoft YaHei", monospace; color: var(--text); white-space: pre-wrap; max-height: 220px; overflow: auto; }
html.dark .summary-log { background: #12151a; }
@media (max-width: 760px) {
.file-body { flex-direction: column; }
.file-list { width: 100%; max-height: 200px; }
@@ -201,6 +210,7 @@ html.dark .file-editor { background: #12151a; }
/* ---------- 卡片:久未同步 ---------- */
.badge.b-stale { background: var(--amber-bg); color: var(--amber); }
.badge.b-paused { background: var(--gray-bg); color: var(--muted); }
/* ---------- 配置:cron 下次执行预览 ---------- */
.cron-next { font-size: 12px; color: var(--muted); min-height: 16px; }
@@ -239,12 +249,22 @@ html.dark .file-editor { background: #12151a; }
.CodeMirror { height: 420px; border: 1px solid var(--border); border-radius: 8px; font: 12.5px/1.55 Consolas, monospace; }
.CodeMirror-scroll { min-height: 380px; }
/* 未提交修改行高亮 */
.CodeMirror-linebackground.cm-chg {
background-color: rgba(255, 196, 0, 0.16);
box-shadow: inset 3px 0 0 0 #e0a020;
}
html.dark .CodeMirror-linebackground.cm-chg {
background-color: rgba(255, 196, 0, 0.13);
box-shadow: inset 3px 0 0 0 #c98f1c;
}
/* ---------- 冲突文件内联编辑 ---------- */
.cf-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap; }
.cf-head h4 { margin: 0; flex: 1; }
.cf-ta { width: 100%; min-height: 260px; border: 1px solid var(--border); border-radius: 8px; padding: 10px; font: 12.5px/1.55 Consolas, monospace; color: var(--text); background: #fff; white-space: pre; overflow: auto; }
html.dark .cf-ta { background: #12151a; }
.cf-actions { display: flex; gap: 8px; margin-top: 6px; }
.cf-actions { display: flex; gap: 8px; margin-top: 6px; flex-wrap: wrap; }
.cf-hint { font-size: 12px; color: var(--muted); margin-top: 6px; line-height: 1.5; }
.cf-edit { margin-bottom: 10px; }
.conflict-file { border: 1px solid var(--border); border-radius: 8px; padding: 10px; margin-bottom: 10px; }