| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/sylvinus/agent-vm/internal/gitguard" |
| 10 | "github.com/sylvinus/agent-vm/internal/gitx" |
| 11 | ) |
| 12 | |
| 13 | type hostGitState struct { |
| 14 | State string `json:"state"` |
| 15 | Ready bool `json:"ready"` |
| 16 | CanEnable bool `json:"can_enable"` |
| 17 | Message string `json:"message"` |
| 18 | } |
| 19 | |
| 20 | func inspectHostGit(ctx context.Context) hostGitState { |
| 21 | state := gitguard.BareState(ctx) |
| 22 | view := hostGitState{State: state} |
| 23 | switch state { |
| 24 | case gitguard.BareOK: |
| 25 | view.Ready = true |
| 26 | view.Message = "本机 Git 安全保护已启用。" |
| 27 | case gitguard.BareNoGit: |
| 28 | view.Ready = true |
| 29 | view.Message = "本机未安装可用的 Git,无需修改;以后启动环境时会重新检查。" |
| 30 | case gitguard.BareUnset: |
| 31 | view.CanEnable = true |
| 32 | view.Message = "启动前需要启用本机 Git 安全保护。" |
| 33 | case gitguard.BareOld: |
| 34 | view.Message = "本机 Git 版本过旧,请升级到 2.38 或更新版本后重新检查。" |
| 35 | default: |
| 36 | view.Message = "暂时无法检查本机 Git。请确认 Git 安装完整,再重新检查;Cage 不会自动打开安装器。" |
| 37 | } |
| 38 | return view |
| 39 | } |
| 40 | |
| 41 | func (s *Server) hostGit(w http.ResponseWriter, r *http.Request) { |
| 42 | jsonReply(w, inspectHostGit(r.Context())) |
| 43 | } |
| 44 | |
| 45 | func (s *Server) enableHostGit(w http.ResponseWriter, r *http.Request) { |
| 46 | var input struct { |
| 47 | Confirm bool `json:"confirm"` |
| 48 | } |
| 49 | if !readJSON(w, r, &input) { |
| 50 | return |
| 51 | } |
| 52 | if !input.Confirm { |
| 53 | http.Error(w, "请先确认启用本机 Git 安全保护。", http.StatusBadRequest) |
| 54 | return |
| 55 | } |
| 56 | if !s.op.TryLock() { |
| 57 | http.Error(w, "正在处理环境操作,请完成后重试。", http.StatusConflict) |
| 58 | return |
| 59 | } |
| 60 | defer s.op.Unlock() |
| 61 | ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) |
| 62 | defer cancel() |
| 63 | before := inspectHostGit(ctx) |
| 64 | if before.Ready { |
| 65 | jsonReply(w, before) |
| 66 | return |
| 67 | } |
| 68 | if !before.CanEnable { |
| 69 | http.Error(w, before.Message, http.StatusConflict) |
| 70 | return |
| 71 | } |
| 72 | cmd := gitx.Untrusted(ctx, "config", "--global", "--replace-all", "safe.bareRepository", "explicit") |
| 73 | cmd.Dir = s.profile |
| 74 | if err := cmd.Run(); err != nil { |
| 75 | http.Error(w, "未能保存 Git 安全设置。请检查全局 Git 配置的写入权限,关闭其他 Git 设置操作后重试。", http.StatusInternalServerError) |
| 76 | return |
| 77 | } |
| 78 | after := inspectHostGit(ctx) |
| 79 | if !after.Ready { |
| 80 | http.Error(w, "Git 设置已写入,但检查尚未通过。请检查全局 Git 配置后重新检测。", http.StatusConflict) |
| 81 | return |
| 82 | } |
| 83 | jsonReply(w, after) |
| 84 | } |
| 85 | |
| 86 | func requireHostGit(ctx context.Context) error { |
| 87 | state := inspectHostGit(ctx) |
| 88 | if !state.Ready { |
| 89 | return errors.New(state.Message + " 请从工作台点击启动,按提示完成检查。") |
| 90 | } |
| 91 | return nil |
| 92 | } |