diff --git a/internal/app/app.go b/internal/app/app.go index ba73d42c..04188e62 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -642,7 +642,8 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st }) updateHandler := handler.NewUpdateHandler(configDir, log.Logger, auditSvc, - app.updateRestart(configDir), updateActivation, configHandler.UpdateSource, configHandler.SetUpdateSource) + app.updateRestart(configDir), updateActivation, configHandler.UpdateSource, configHandler.SetUpdateSource). + WithUpdateConfig(configHandler.GetUpdateConfig, configHandler.SetUpdateConfig) // 设置路由(使用 App 实例以便动态获取 handler) setupRoutes( @@ -1255,6 +1256,7 @@ func setupRoutes( // 系统更新(保持本安装自身源码最新:查看、检查、应用、进度、回滚、接入、更新源) protected.GET("/system/update", updateHandler.GetStatus) + protected.GET("/system/update/branches", updateHandler.Branches) protected.GET("/system/update/job", updateHandler.Job) protected.POST("/system/update/check", updateHandler.Check) protected.POST("/system/update/apply", updateHandler.Apply) diff --git a/internal/config/config.go b/internal/config/config.go index 04bb7ec7..3f3bc031 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -57,11 +57,13 @@ type Config struct { Update UpdateConfig `yaml:"update,omitempty" json:"update,omitempty"` } -// UpdateConfig 一键更新的更新源(可选):一个仓库地址,更新跟随该仓库的默认分支。 -// 留空即官方仓库(internal/update.DefaultRepoURL),跟随镜像或自己的二开只需改这一处。 +// UpdateConfig 一键更新的更新源(可选):仓库地址与目标分支。 +// 仓库留空即官方仓库(internal/update.DefaultRepoURL);分支留空即跟随该仓库的默认分支。 type UpdateConfig struct { // Repo 更新源仓库地址(https/http/ssh/git/file:// 或本机绝对路径);留空 = 官方仓库。 Repo string `yaml:"repo,omitempty" json:"repo,omitempty"` + // Branch 目标分支名(如 main、feat/plugin-capability-platform);留空 = 跟随仓库默认分支。 + Branch string `yaml:"branch,omitempty" json:"branch,omitempty"` } type EnsureLocalConfigResult struct { diff --git a/internal/handler/config.go b/internal/handler/config.go index e1ea88dd..e2209505 100644 --- a/internal/handler/config.go +++ b/internal/handler/config.go @@ -2254,10 +2254,18 @@ func (h *ConfigHandler) ApplyConfig(c *gin.Context) { // SetUpdateSource 记录一键更新的更新源(单个仓库地址;空 = 回到官方仓库)。 // 走与其他设置相同的写入路径:备份旧文件、按 YAML 文档只改 update 段、原子落盘。 func (h *ConfigHandler) SetUpdateSource(repo string) error { + return h.SetUpdateConfig(config.UpdateConfig{Repo: repo}) +} + +// SetUpdateConfig 记录一键更新的仓库地址和目标分支(留空分别回到官方仓库/默认分支)。 +func (h *ConfigHandler) SetUpdateConfig(cfg config.UpdateConfig) error { h.mu.Lock() defer h.mu.Unlock() previous := h.config.Update - h.config.Update = config.UpdateConfig{Repo: strings.TrimSpace(repo)} + h.config.Update = config.UpdateConfig{ + Repo: strings.TrimSpace(cfg.Repo), + Branch: strings.TrimSpace(cfg.Branch), + } if err := h.saveConfig(); err != nil { h.config.Update = previous return err @@ -2272,6 +2280,13 @@ func (h *ConfigHandler) UpdateSource() string { return h.config.Update.Repo } +// GetUpdateConfig 读当前配置的更新源仓库和目标分支。 +func (h *ConfigHandler) GetUpdateConfig() config.UpdateConfig { + h.mu.RLock() + defer h.mu.RUnlock() + return h.config.Update +} + // saveConfig 保存配置到文件 func (h *ConfigHandler) saveConfig() error { configFileMu.Lock() @@ -2430,18 +2445,27 @@ func updateMCPConfig(doc *yaml.Node, cfg config.MCPConfig) { setIntInMap(mcpNode, "port", cfg.Port) } -// updateUpdateSourceConfig 写入一键更新的更新源(update 段的单个 repo 字段)。 -// 留空时把整段删掉,而不是留下一个空的 update: 块——"没有配置"应当就是文件里没有这一段, -// 运行时按官方仓库处理。 +// updateUpdateSourceConfig 写入一键更新的更新源(update 段的 repo 与可选 branch 字段)。 +// 两项均留空时把整段删掉,运行时按官方仓库默认分支处理。 func updateUpdateSourceConfig(doc *yaml.Node, cfg config.UpdateConfig) { root := doc.Content[0] repo := strings.TrimSpace(cfg.Repo) - if repo == "" { + branch := strings.TrimSpace(cfg.Branch) + if repo == "" && branch == "" { removeKeyFromMap(root, "update") return } node := ensureMap(root, "update") - setStringInMap(node, "repo", repo) + if repo != "" { + setStringInMap(node, "repo", repo) + } else { + removeKeyFromMap(node, "repo") + } + if branch != "" { + setStringInMap(node, "branch", branch) + } else { + removeKeyFromMap(node, "branch") + } } func updateVisionConfig(doc *yaml.Node, cfg config.VisionConfig) { diff --git a/internal/handler/update.go b/internal/handler/update.go index 4e15f8e5..ed6d9d5c 100644 --- a/internal/handler/update.go +++ b/internal/handler/update.go @@ -3,6 +3,7 @@ package handler import ( "context" "cyberstrike-ai/internal/audit" + "cyberstrike-ai/internal/config" "cyberstrike-ai/internal/update" "fmt" "net/http" @@ -43,10 +44,11 @@ type UpdateHandler struct { // operator last saved it; an empty string means "not configured" and the official // repository is used. A function rather than a value because the config can change // while the process runs. - source func() string - // saveSource persists a new source through the config layer; nil means this start - // has no config to write to. + source func() string saveSource func(repo string) error + // Optional full update config hooks supporting repo + branch. + updateCfg func() config.UpdateConfig + saveUpdateCfg func(cfg config.UpdateConfig) error // baseline is the binary this process is actually running: the file on disk at // construction time. An update, a rollback or a CLI run that replaces it leaves a // different file behind, and that difference is what "restart to activate" means. @@ -133,26 +135,44 @@ func restartSupervised() bool { strings.TrimSpace(os.Getenv("JOURNAL_STREAM")) != "" } -func (h *UpdateHandler) options() update.Options { - opts := update.Options{Root: h.root} - if h.source != nil { - opts.Repo = h.source() +// WithUpdateConfig attaches repo+branch persistence callbacks. +func (h *UpdateHandler) WithUpdateConfig(get func() config.UpdateConfig, save func(config.UpdateConfig) error) *UpdateHandler { + h.updateCfg = get + h.saveUpdateCfg = save + return h +} + +func (h *UpdateHandler) currentConfig() config.UpdateConfig { + if h.updateCfg != nil { + return h.updateCfg() + } + if h.source != nil { + return config.UpdateConfig{Repo: h.source()} + } + return config.UpdateConfig{} +} + +func (h *UpdateHandler) options() update.Options { + cfg := h.currentConfig() + return update.Options{ + Root: h.root, + Repo: cfg.Repo, + Branch: cfg.Branch, } - return opts } // sourceView is the configured source as the page edits it: the address (empty = the -// official repository) plus the default, so the page never hardcodes a URL the server -// would disagree with. +// official repository), optional branch (empty = repository default branch), plus the default. func (h *UpdateHandler) sourceView() gin.H { - repo := "" - if h.source != nil { - repo = strings.TrimSpace(h.source()) - } + cfg := h.currentConfig() + repo := strings.TrimSpace(cfg.Repo) + branch := strings.TrimSpace(cfg.Branch) return gin.H{ - "repo": repo, - "configured": repo != "", - "defaultRepo": update.DefaultRepoURL, + "repo": repo, + "branch": branch, + "configured": repo != "", + "branchConfigured": branch != "", + "defaultRepo": update.DefaultRepoURL, } } @@ -209,24 +229,54 @@ func (h *UpdateHandler) Check(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": snap}) } +// Branches answers GET /api/system/update/branches: lists remote branches of the +// configured (or previewed via ?repo=...) update source repository via git ls-remote. +func (h *UpdateHandler) Branches(c *gin.Context) { + opts := h.options() + if repoParam := strings.TrimSpace(c.Query("repo")); repoParam != "" { + if !update.ValidRemoteURL(repoParam) { + c.JSON(http.StatusBadRequest, gin.H{"error": "仓库地址不合法(只允许 https/http/ssh/git/file:// 或本机绝对路径)"}) + return + } + opts.Repo = repoParam + } + defaultBranch, branches, err := update.ListBranches(c.Request.Context(), opts) + if err != nil { + c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()}) + return + } + if branches == nil { + branches = []string{} + } + c.JSON(http.StatusOK, gin.H{ + "repo": opts.Repo, + "defaultBranch": defaultBranch, + "branches": branches, + }) +} + // SaveSource answers POST /api/system/update/source: the operator picks which repository -// this installation updates from - the official one, a mirror, or their own fork - and -// the choice lands in the update section of config.yaml. An empty address clears the -// setting, which means the official repository again. +// and optional target branch this installation updates from. func (h *UpdateHandler) SaveSource(c *gin.Context) { var body struct { - Repo string `json:"repo"` + Repo string `json:"repo"` + Branch string `json:"branch"` } if err := c.ShouldBindJSON(&body); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "请求体不是合法 JSON"}) return } body.Repo = strings.TrimSpace(body.Repo) + body.Branch = strings.TrimSpace(body.Branch) if body.Repo != "" && !update.ValidRemoteURL(body.Repo) { c.JSON(http.StatusBadRequest, gin.H{"error": "仓库地址不合法(只允许 https/http/ssh/git/file:// 或本机绝对路径)"}) return } - if h.saveSource == nil { + if body.Branch != "" && !update.ValidName(body.Branch) { + c.JSON(http.StatusBadRequest, gin.H{"error": "目标分支名不合法"}) + return + } + if h.saveUpdateCfg == nil && h.saveSource == nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "本次启动没有接入配置保存,更新源改不了"}) return } @@ -240,16 +290,28 @@ func (h *UpdateHandler) SaveSource(c *gin.Context) { c.JSON(http.StatusConflict, gin.H{"error": "更新进行中,不能切换更新源", "job": busy}) return } - if err := h.saveSource(body.Repo); err != nil { + if h.saveUpdateCfg != nil { + err = h.saveUpdateCfg(config.UpdateConfig{Repo: body.Repo, Branch: body.Branch}) + } else { + err = h.saveSource(body.Repo) + } + if err != nil { h.record(c, "update.source", "failure", "保存更新源失败: "+err.Error(), map[string]interface{}{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": "保存失败:" + err.Error()}) return } - message := "更新源已保存:" + body.Repo - if body.Repo == "" { - message = "已恢复默认更新源(官方仓库)" + message := "更新源已保存" + if body.Repo != "" { + message += ":" + body.Repo + } else { + message += "(官方仓库)" } - h.record(c, "update.source", "success", message, map[string]interface{}{"repo": body.Repo}) + if body.Branch != "" { + message += " / 分支 " + body.Branch + } else { + message += " / 默认分支" + } + h.record(c, "update.source", "success", message, map[string]interface{}{"repo": body.Repo, "branch": body.Branch}) c.JSON(http.StatusOK, gin.H{"source": h.sourceView()}) } diff --git a/internal/update/adopt.go b/internal/update/adopt.go index 11488521..1d71ac09 100644 --- a/internal/update/adopt.go +++ b/internal/update/adopt.go @@ -120,7 +120,7 @@ func Preview(ctx context.Context, opts Options) (*AdoptPlan, error) { if _, err := gitCmd(ctx, tmp, "init", "--quiet", "--bare"); err != nil { return nil, err } - branch, commit, subject, err := fetchSource(ctx, tmp, source) + branch, commit, subject, err := fetchSourceBranch(ctx, tmp, source, opts.Branch) if err != nil { return nil, err } @@ -166,7 +166,7 @@ func Adopt(ctx context.Context, opts Options, onStep func(Step)) (*Result, error return nil, &Error{Reason: "init_failed", Message: "添加远端失败:" + err.Error()} } - branch, commit, subject, err := fetchSource(ctx, root, source) + branch, commit, subject, err := fetchSourceBranch(ctx, root, source, opts.Branch) if err != nil { return nil, err } @@ -317,13 +317,22 @@ func adoptPreflight(ctx context.Context, opts Options) (root, source string, err // that ended up being, its short commit and its subject. Both callers fetch into a // repository of their own. func fetchSource(ctx context.Context, repo, source string) (string, string, string, error) { - out, err := gitCmd(ctx, repo, "ls-remote", "--symref", source, "HEAD") - if err != nil { - return "", "", "", &Error{Reason: "fetch_failed", Message: "读取远端默认分支失败:" + err.Error()} - } - branch := parseDefaultBranch(out) + return fetchSourceBranch(ctx, repo, source, "") +} + +func fetchSourceBranch(ctx context.Context, repo, source, configuredBranch string) (string, string, string, error) { + branch := strings.TrimSpace(configuredBranch) if branch == "" { - return "", "", "", &Error{Reason: "no_branch", Message: "无法确定远端默认分支:" + source} + out, err := gitCmd(ctx, repo, "ls-remote", "--symref", source, "HEAD") + if err != nil { + return "", "", "", &Error{Reason: "fetch_failed", Message: "读取远端默认分支失败:" + err.Error()} + } + branch = parseDefaultBranch(out) + if branch == "" { + return "", "", "", &Error{Reason: "no_branch", Message: "无法确定远端默认分支:" + source} + } + } else if !ValidName(branch) { + return "", "", "", &Error{Reason: "bad_branch", Message: "配置的目标分支名不合法:" + branch} } if _, err := gitCmd(ctx, repo, "fetch", "--quiet", "--no-tags", "--recurse-submodules=no", source, "+refs/heads/"+branch+":refs/remotes/origin/"+branch); err != nil { diff --git a/internal/update/apply.go b/internal/update/apply.go index 8d30f52e..3717a92f 100644 --- a/internal/update/apply.go +++ b/internal/update/apply.go @@ -261,7 +261,11 @@ func Apply(ctx context.Context, opts Options, onStep func(Step)) (*Result, error return res, nil } - step("fetch", fmt.Sprintf("%s(默认分支 %s)有 %d 个新提交:%s → %s", snap.sourceLabel(), snap.TargetBranch, snap.Behind, snap.Commit, snap.RemoteCommit)) + if snap.BranchSwitch { + step("fetch", fmt.Sprintf("准备切换分支 %s → %s(%s → %s)", snap.Branch, snap.TargetBranch, snap.Commit, snap.RemoteCommit)) + } else { + step("fetch", fmt.Sprintf("%s(分支 %s)有 %d 个新提交:%s → %s", snap.sourceLabel(), snap.TargetBranch, snap.Behind, snap.Commit, snap.RemoteCommit)) + } // Put operator-owned content aside, and clear the paths the incoming change would // write to, so the fast-forward cannot be refused by "your local changes would be @@ -314,12 +318,19 @@ func Apply(ctx context.Context, opts Options, onStep func(Step)) (*Result, error return nil, err } - if out, err := gitCmd(ctx, root, "merge", "--ff-only", "--no-verify", ref); err != nil { + var moveOut string + var moveErr error + if snap.BranchSwitch { + moveOut, moveErr = gitCmd(ctx, root, "checkout", "-B", snap.TargetBranch, ref) + } else { + moveOut, moveErr = gitCmd(ctx, root, "merge", "--ff-only", "--no-verify", ref) + } + if moveErr != nil { if restoreErr := restoreProtected(backupDir, kept); restoreErr != nil { - return nil, &Error{Reason: "backup_failed", Message: fmt.Sprintf("快进合并失败,恢复本地内容又失败:%v", restoreErr)} + return nil, &Error{Reason: "backup_failed", Message: fmt.Sprintf("更新工作树失败,恢复本地内容又失败:%v", restoreErr)} } _ = clearBuildPending(root) - return nil, &Error{Reason: "merge_failed", Message: fmt.Sprintf("快进合并失败:%v\n%s", err, strings.TrimSpace(out))} + return nil, &Error{Reason: "merge_failed", Message: fmt.Sprintf("更新工作树失败:%v\n%s", moveErr, strings.TrimSpace(moveOut))} } // The merge wrote upstream's version of the content paths; the operator's copies win // them back, which is what "update the code, keep my work" means. diff --git a/internal/update/branch_switch_test.go b/internal/update/branch_switch_test.go new file mode 100644 index 00000000..6772c384 --- /dev/null +++ b/internal/update/branch_switch_test.go @@ -0,0 +1,94 @@ +package update + +import ( + "context" + "os" + "path/filepath" + "slices" + "testing" +) + +func TestBranchSwitchForwardAndBackPreservesProtectedFiles(t *testing.T) { + ctx := context.Background() + upstream := t.TempDir() + mustGit(t, upstream, "init", "--initial-branch=main") + mustGit(t, upstream, "config", "user.name", "Test") + mustGit(t, upstream, "config", "user.email", "test@example.com") + writeFile(t, filepath.Join(upstream, "app.txt"), "main-v1\n") + writeFile(t, filepath.Join(upstream, "roles", "default.yaml"), "upstream-v1\n") + mustGit(t, upstream, "add", ".") + mustGit(t, upstream, "commit", "-m", "main v1") + + // Create feature branch with new commit. + mustGit(t, upstream, "checkout", "-b", "feat/plugin-capability-platform") + writeFile(t, filepath.Join(upstream, "app.txt"), "feat-v1\n") + writeFile(t, filepath.Join(upstream, "plugin.txt"), "plugin-ready\n") + mustGit(t, upstream, "add", ".") + mustGit(t, upstream, "commit", "-m", "feat plugin") + + // Advance main independently so main and feat diverge! + mustGit(t, upstream, "checkout", "main") + writeFile(t, filepath.Join(upstream, "app.txt"), "main-v2\n") + mustGit(t, upstream, "add", ".") + mustGit(t, upstream, "commit", "-m", "main v2") + + // Clone main at v1 as install tree. + install := t.TempDir() + mustGit(t, install, "clone", "--branch", "main", upstream, ".") + mustGit(t, install, "reset", "--hard", "HEAD~1") + writeFile(t, filepath.Join(install, "config.yaml"), "custom: true\n") + writeFile(t, filepath.Join(install, "roles", "default.yaml"), "operator-edited\n") + + // 1. ListBranches lists default main first + feature branch. + def, branches, err := ListBranches(ctx, Options{Root: install, Repo: upstream}) + if err != nil { + t.Fatalf("ListBranches failed: %v", err) + } + if def != "main" || len(branches) < 2 || branches[0] != "main" || !slices.Contains(branches, "feat/plugin-capability-platform") { + t.Fatalf("unexpected branches: default=%q list=%v", def, branches) + } + + // 2. Switch main -> feat/plugin-capability-platform. + optsFeat := Options{Root: install, Repo: upstream, Branch: "feat/plugin-capability-platform", BinaryName: "none"} + snap, err := Check(ctx, optsFeat) + if err != nil { + t.Fatal(err) + } + if !snap.BranchSwitch || !snap.UpdateAvailable || snap.Diverged || snap.TargetBranch != "feat/plugin-capability-platform" { + t.Fatalf("unexpected check snapshot for branch switch: %+v", snap) + } + if _, err := Apply(ctx, optsFeat, nil); err != nil { + t.Fatalf("Apply branch switch failed: %v", err) + } + if got := mustGit(t, install, "rev-parse", "--abbrev-ref", "HEAD"); got != "feat/plugin-capability-platform" { + t.Fatalf("expected feat branch, got %q", got) + } + if data, err := os.ReadFile(filepath.Join(install, "plugin.txt")); err != nil || string(data) != "plugin-ready\n" { + t.Fatalf("expected plugin.txt on feat branch: %q %v", string(data), err) + } + if data, err := os.ReadFile(filepath.Join(install, "roles", "default.yaml")); err != nil || string(data) != "operator-edited\n" { + t.Fatalf("operator protected file was not preserved: %q %v", string(data), err) + } + + // 3. Switch back feat/plugin-capability-platform -> main (diverged history!). + optsMain := Options{Root: install, Repo: upstream, Branch: "", BinaryName: "none"} + backSnap, err := Check(ctx, optsMain) + if err != nil { + t.Fatal(err) + } + if !backSnap.BranchSwitch || !backSnap.UpdateAvailable || backSnap.Diverged || backSnap.TargetBranch != "main" { + t.Fatalf("unexpected check snapshot switching back to main: %+v", backSnap) + } + if _, err := Apply(ctx, optsMain, nil); err != nil { + t.Fatalf("Apply switch back to main failed: %v", err) + } + if got := mustGit(t, install, "rev-parse", "--abbrev-ref", "HEAD"); got != "main" { + t.Fatalf("expected main branch, got %q", got) + } + if data, err := os.ReadFile(filepath.Join(install, "app.txt")); err != nil || string(data) != "main-v2\n" { + t.Fatalf("expected main-v2 after switching back: %q %v", string(data), err) + } + if _, err := os.Stat(filepath.Join(install, "plugin.txt")); !os.IsNotExist(err) { + t.Fatalf("plugin.txt should be removed after switching back to main") + } +} diff --git a/internal/update/update.go b/internal/update/update.go index 22efc1aa..4beef2c8 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -119,8 +119,9 @@ func Protected(rel string) bool { // Empty means the official repository, so an installation with no configuration at all // still has exactly one answer to "where does an update come from". type Options struct { - Root string - Repo string + Root string + Repo string + Branch string // BinaryName overrides the executable swapped after a successful update. Empty // means "cyberstrike-ai" in Root; "none" means leave the binary alone. BinaryName string @@ -180,10 +181,11 @@ type Snapshot struct { // came from config.yaml or is the built-in official repository. Repo string `json:"repo"` RepoConfigured bool `json:"repoConfigured"` - // TargetBranch is the update source's own default branch, learned from the source - // itself when the network answer arrives (empty until then). - TargetBranch string `json:"targetBranch,omitempty"` - Commit string `json:"commit"` + // TargetBranch is the configured target branch or the update source's default branch. + TargetBranch string `json:"targetBranch,omitempty"` + BranchConfigured bool `json:"branchConfigured,omitempty"` + BranchSwitch bool `json:"branchSwitch,omitempty"` + Commit string `json:"commit"` Subject string `json:"subject"` CommittedAt string `json:"committedAt"` @@ -260,7 +262,65 @@ func nulList(blob string) []string { } // ValidName reports whether s can safely reach git's argv as a branch name. -func ValidName(s string) bool { return namePattern.MatchString(s) } +func ValidName(s string) bool { + if !namePattern.MatchString(s) || len(s) > 180 { + return false + } + if strings.Contains(s, "..") || strings.Contains(s, "//") || strings.HasSuffix(s, "/") || strings.HasSuffix(s, ".") || strings.HasSuffix(s, ".lock") { + return false + } + for _, part := range strings.Split(s, "/") { + if part == "" || strings.HasPrefix(part, ".") || strings.HasSuffix(part, ".lock") { + return false + } + } + return true +} + +// ListBranches queries the update source via git ls-remote without modifying the working tree. +func ListBranches(ctx context.Context, opts Options) (string, []string, error) { + root, err := opts.installRoot() + if err != nil { + return "", nil, err + } + repo := opts.repoURL() + if !ValidRemoteURL(repo) { + return "", nil, fmt.Errorf("配置的更新源仓库地址不合法") + } + out, err := gitCmd(ctx, root, "ls-remote", "--symref", repo, "HEAD", "refs/heads/*") + if err != nil { + return "", nil, fmt.Errorf("无法读取远端分支 %s:%s", repo, strings.TrimSpace(err.Error())) + } + defaultBranch := parseDefaultBranch(out) + seen := map[string]bool{} + var branches []string + for _, line := range strings.Split(out, "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "ref:") { + continue + } + fields := strings.Fields(line) + if len(fields) < 2 { + continue + } + name, ok := strings.CutPrefix(fields[1], "refs/heads/") + if !ok || !ValidName(name) || seen[name] { + continue + } + seen[name] = true + branches = append(branches, name) + } + sort.Slice(branches, func(i, j int) bool { + if branches[i] == defaultBranch { + return true + } + if branches[j] == defaultBranch { + return false + } + return branches[i] < branches[j] + }) + return defaultBranch, branches, nil +} // Status reads the install tree without touching the network. func Status(ctx context.Context, opts Options) (*Snapshot, error) { @@ -268,18 +328,25 @@ func Status(ctx context.Context, opts Options) (*Snapshot, error) { if err != nil { return nil, err } + configuredBranch := strings.TrimSpace(opts.Branch) snap := &Snapshot{ - Root: root, - Repo: opts.repoURL(), - RepoConfigured: strings.TrimSpace(opts.Repo) != "", - Incoming: []Commit{}, - LocalChanges: []Change{}, - BlockingChanges: []Change{}, + Root: root, + Repo: opts.repoURL(), + RepoConfigured: strings.TrimSpace(opts.Repo) != "", + TargetBranch: configuredBranch, + BranchConfigured: configuredBranch != "", + Incoming: []Commit{}, + LocalChanges: []Change{}, + BlockingChanges: []Change{}, } if !ValidRemoteURL(snap.Repo) { snap.CheckError = "配置的更新源仓库地址不合法(只允许 https/http/ssh/git/file:// 或本机绝对路径)" return snap, nil } + if configuredBranch != "" && !ValidName(configuredBranch) { + snap.CheckError = "配置的目标分支名不合法" + return snap, nil + } if _, err := gitCmd(ctx, root, "rev-parse", "--is-inside-work-tree"); err != nil { // Not a git tree: the page still has to say something useful, so this is a @@ -400,14 +467,20 @@ func check(ctx context.Context, opts Options) (*Snapshot, error) { } root := snap.Root - // The branch to follow is the source repository's own default branch, so the - // operator never names one and a fork whose default differs from main still works. - target, err := resolveDefaultBranch(ctx, root, snap.Repo) - if err != nil { - snap.CheckError = err.Error() + target := strings.TrimSpace(opts.Branch) + if target == "" { + var resolveErr error + target, resolveErr = resolveDefaultBranch(ctx, root, snap.Repo) + if resolveErr != nil { + snap.CheckError = resolveErr.Error() + return snap, nil + } + } else if !ValidName(target) { + snap.CheckError = "配置的目标分支名不合法" return snap, nil } snap.TargetBranch = target + snap.BranchConfigured = strings.TrimSpace(opts.Branch) != "" // --recurse-submodules=no and --prune keep the fetch to this repository's own // history. A branch-scoped fetch means a source with many refs cannot turn the @@ -438,8 +511,14 @@ func check(ctx context.Context, opts Options) (*Snapshot, error) { return snap, nil } snap.Ahead, snap.Behind = ahead, behind - snap.Diverged = ahead > 0 && behind > 0 - snap.UpdateAvailable = snap.Behind > 0 + snap.BranchSwitch = snap.Branch != "" && snap.TargetBranch != "" && snap.Branch != snap.TargetBranch + if snap.BranchSwitch { + snap.Diverged = false + snap.UpdateAvailable = true + } else { + snap.Diverged = ahead > 0 && behind > 0 + snap.UpdateAvailable = snap.Behind > 0 + } snap.IncomingTotal = snap.Behind logs, err := gitCmd(ctx, root, "log", "--format=%h\x1f%s", "-n", fmt.Sprint(maxIncoming), "HEAD.."+ref) diff --git a/web/frontend/src/pages/settings/sections/UpdateSection.jsx b/web/frontend/src/pages/settings/sections/UpdateSection.jsx index 5210046c..1b2cd650 100644 --- a/web/frontend/src/pages/settings/sections/UpdateSection.jsx +++ b/web/frontend/src/pages/settings/sections/UpdateSection.jsx @@ -2,7 +2,7 @@ * 更新源配置、远端版本检查和更新进度。 */ import { useEffect, useState } from 'react'; -import { Banner, Button, Input, Space, Tag, Timeline, Typography } from '@douyinfe/semi-ui'; +import { Banner, Button, Input, Select, Space, Tag, Timeline, Typography } from '@douyinfe/semi-ui'; import { IconDownload, IconRefresh } from '@douyinfe/semi-icons'; import { api, errorMessage } from '../../../lib/http'; import { useAuth } from '../../../lib/auth'; @@ -61,6 +61,10 @@ export default function UpdateSection() { const [actionError, setActionError] = useState(null); const [activationBootID, setActivationBootID] = useState(null); const [sourceDraft, setSourceDraft] = useState(null); + const [branchDraft, setBranchDraft] = useState(null); + const [remoteBranches, setRemoteBranches] = useState([]); + const [remoteDefaultBranch, setRemoteDefaultBranch] = useState(''); + const [loadingBranches, setLoadingBranches] = useState(false); const [savingSource, setSavingSource] = useState(false); const [sourceError, setSourceError] = useState(null); @@ -77,8 +81,10 @@ export default function UpdateSection() { const needsRestart = consoleRes.data?.needsRestart; const source = consoleRes.data?.source; const sourceRepo = source?.repo || ''; + const sourceBranch = source?.branch || ''; const sourceValue = sourceDraft ?? sourceRepo; - const sourceChanged = sourceValue.trim() !== sourceRepo; + const branchValue = branchDraft ?? sourceBranch; + const sourceChanged = sourceValue.trim() !== sourceRepo || branchValue.trim() !== sourceBranch; const busy = Boolean(action || running || restarting); const sourceBusy = savingSource || busy || consoleRes.loading; @@ -170,18 +176,39 @@ export default function UpdateSection() { } }; + const fetchBranches = async () => { + setLoadingBranches(true); + setSourceError(null); + try { + const repoQuery = sourceValue.trim(); + const payload = await api.get('/system/update/branches', repoQuery ? { repo: repoQuery } : undefined); + const list = Array.isArray(payload?.branches) ? payload.branches : []; + setRemoteBranches(list); + setRemoteDefaultBranch(payload?.defaultBranch || ''); + toastSuccess(t('updateUi.branchesLoaded', { n: list.length }, `已获取 ${list.length} 个远端分支`)); + } catch (error) { + setSourceError(error); + } finally { + setLoadingBranches(false); + } + }; + const saveSource = async event => { event.preventDefault(); if (!source || !canManage || !sourceChanged || sourceBusy) return; setSavingSource(true); setSourceError(null); try { - const payload = await api.post('/system/update/source', { repo: sourceValue.trim() }); + const payload = await api.post('/system/update/source', { + repo: sourceValue.trim(), + branch: branchValue.trim() + }); if (!payload?.source || typeof payload.source.repo !== 'string') { throw new Error(t('updateUi.sourceResponseMissing', null, '服务端未返回更新源,刷新后可核对配置。')); } consoleRes.setData(previous => ({ ...previous, source: payload.source })); setSourceDraft(null); + setBranchDraft(null); setCheckResult(null); setActionError(null); toastSuccess(t('update.sourceSaveOk', null, '更新源已保存')); @@ -203,7 +230,13 @@ export default function UpdateSection() { const facts = [ { label: t('update.root', null, '安装目录'), value: {snapshot.root || '—'} }, { label: t('update.gitTree', null, 'Git 安装树'), value: yesNo(t, snapshot.installed) }, - { label: t('update.branch', null, '分支'), value: snapshot.branch || '—' }, + { label: t('update.branch', null, '当前分支'), value: snapshot.branch || '—' }, + { + label: t('updateUi.targetBranch', null, '目标分支'), + value: sourceBranch + ? {sourceBranch}{snapshot.branch && sourceBranch !== snapshot.branch && {t('updateUi.branchSwitchPending', null, '待切换')}} + : {t('updateUi.followDefaultBranch', null, '跟随仓库默认分支')} + }, { label: t('updateUi.repo', null, '更新源仓库'), value: {source?.repo || source?.defaultRepo || snapshot.repo || '—'} }, { label: t('update.commit', null, '当前提交'), value: {shortCommit(snapshot.commit)} }, { label: t('update.subject', null, '提交说明'), value: truncate(snapshot.subject || '—', 80) }, @@ -268,6 +301,7 @@ export default function UpdateSection() { value={sourceValue} onChange={value => { setSourceDraft(value); + setRemoteBranches([]); setSourceError(null); }} placeholder={source.defaultRepo} @@ -275,10 +309,48 @@ export default function UpdateSection() { disabled={savingSource} /> +
+ {t('updateUi.targetBranchLabel', null, '目标分支(留空 = 跟随仓库默认分支)')} + +