feat(server): git operations honor git_root scope + POST /git/root to switch scope

- extract shared git.InitScopeRepo/WriteScopeGitignore/EnsureLocalIdentity (UI-free)
- cmd init delegates to the shared helpers (no logic duplication)
- handler_git operations use EffectiveGitRoot; status exposes the scope
- new POST /api/git/root inits a repo at the target scope dir + persists git_root
This commit is contained in:
Willie
2026-05-30 19:23:12 +08:00
parent d6b6b929de
commit 16c6e8ec8d
5 changed files with 247 additions and 81 deletions
+13 -75
View File
@@ -1028,10 +1028,15 @@ func setupInitGit(cfg *config.Config, skillsSource string, opts *initOptions) st
}
// doGitInitIfAbsent initializes a repo at gitRoot (with a scope-aware .gitignore)
// unless one already exists there. dryRun only prints intentions.
// unless one already exists there. dryRun only prints intentions. The actual git
// work is shared with the web server via gitops.InitScopeRepo.
func doGitInitIfAbsent(gitRoot, scope string, dryRun bool) {
if hasGitDir(gitRoot) {
ui.Info("Git already initialized in %s", gitRoot)
// Still ensure the scope-aware .gitignore (e.g. config.yaml at root scope).
if err := gitops.WriteScopeGitignore(gitRoot, scope); err != nil {
ui.Warning("Failed to update .gitignore: %v", err)
}
return
}
if dryRun {
@@ -1039,86 +1044,19 @@ func doGitInitIfAbsent(gitRoot, scope string, dryRun bool) {
return
}
if err := os.MkdirAll(gitRoot, 0o755); err != nil {
ui.Warning("Failed to create git root %s: %v", gitRoot, err)
return
}
cmd := exec.Command("git", "init")
cmd.Dir = gitRoot
if err := cmd.Run(); err != nil {
identitySet, err := gitops.InitScopeRepo(gitRoot, scope)
if err != nil {
ui.Warning("Failed to initialize git: %v", err)
return
}
writeInitGitignore(gitRoot, scope)
ensureGitIdentity(gitRoot)
if identitySet {
ui.Info("Git identity not configured, using local default")
ui.Info(" Set yours: git config --global user.name \"Your Name\"")
ui.Info(" git config --global user.email \"you@example.com\"")
}
ui.Success("Git initialized in %s", gitRoot)
}
// writeInitGitignore writes a default .gitignore at gitRoot unless one exists.
// At "root" scope it also ignores config.yaml (machine-specific paths/tokens).
func writeInitGitignore(gitRoot, scope string) {
gitignore := filepath.Join(gitRoot, ".gitignore")
// If a .gitignore already exists, don't clobber it — but at root scope we
// MUST guarantee config.yaml (machine-specific paths + local target config)
// is excluded, so append the entry if it's missing (idempotent).
if existing, err := os.ReadFile(gitignore); err == nil {
if scope == "root" && !gitignoreHasEntry(string(existing), "config.yaml") {
content := string(existing)
if content != "" && !strings.HasSuffix(content, "\n") {
content += "\n"
}
content += "config.yaml\n"
if err := os.WriteFile(gitignore, []byte(content), 0o644); err != nil {
ui.Warning("Failed to add config.yaml to .gitignore: %v", err)
}
}
return
}
lines := []string{".DS_Store"}
if scope == "root" {
lines = append([]string{"config.yaml"}, lines...)
}
if err := os.WriteFile(gitignore, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
ui.Warning("Failed to write .gitignore: %v", err)
}
}
// gitignoreHasEntry reports whether content has a line exactly matching entry
// (ignoring surrounding whitespace), so we don't add a duplicate.
func gitignoreHasEntry(content, entry string) bool {
for _, line := range strings.Split(content, "\n") {
if strings.TrimSpace(line) == entry {
return true
}
}
return false
}
// ensureGitIdentity sets repo-local user.name/email if not configured globally.
func ensureGitIdentity(repoDir string) {
// Check if user.name is already set (global or local)
cmd := exec.Command("git", "config", "user.name")
cmd.Dir = repoDir
if out, err := cmd.Output(); err == nil && strings.TrimSpace(string(out)) != "" {
return // already configured
}
// Set repo-local fallback identity so git commit works
nameCmd := exec.Command("git", "config", "user.name", "skillshare")
nameCmd.Dir = repoDir
nameCmd.Run()
emailCmd := exec.Command("git", "config", "user.email", "skillshare@local")
emailCmd.Dir = repoDir
emailCmd.Run()
ui.Info("Git identity not configured, using local default")
ui.Info(" Set yours: git config --global user.name \"Your Name\"")
ui.Info(" git config --global user.email \"you@example.com\"")
}
// commitSourceFiles creates a single commit with all source files
// (.gitignore, copied skills, installed skills).
func commitSourceFiles(sourcePath string) error {
+92
View File
@@ -0,0 +1,92 @@
package git
import (
"os"
"os/exec"
"path/filepath"
"strings"
)
// WriteScopeGitignore ensures a .gitignore at dir. If none exists it writes a
// default; at "root" scope the default also excludes config.yaml. If a
// .gitignore already exists it is preserved, but at "root" scope config.yaml is
// appended when missing (idempotent) — this is the safety guarantee that a
// root-scope repo never tracks machine-specific config.yaml.
func WriteScopeGitignore(dir, scope string) error {
gitignore := filepath.Join(dir, ".gitignore")
if existing, err := os.ReadFile(gitignore); err == nil {
if scope == "root" && !gitignoreHasEntry(string(existing), "config.yaml") {
content := string(existing)
if content != "" && !strings.HasSuffix(content, "\n") {
content += "\n"
}
content += "config.yaml\n"
return os.WriteFile(gitignore, []byte(content), 0o644)
}
return nil
}
lines := []string{".DS_Store"}
if scope == "root" {
lines = append([]string{"config.yaml"}, lines...)
}
return os.WriteFile(gitignore, []byte(strings.Join(lines, "\n")+"\n"), 0o644)
}
// gitignoreHasEntry reports whether content has a line exactly matching entry
// (ignoring surrounding whitespace), so we don't add a duplicate.
func gitignoreHasEntry(content, entry string) bool {
for _, line := range strings.Split(content, "\n") {
if strings.TrimSpace(line) == entry {
return true
}
}
return false
}
// EnsureLocalIdentity sets a repo-local fallback user.name/email when no git
// identity is configured (global or local), so commits succeed in fresh
// environments. Returns true if the fallback was applied.
func EnsureLocalIdentity(dir string) (bool, error) {
cmd := exec.Command("git", "config", "user.name")
cmd.Dir = dir
if out, err := cmd.Output(); err == nil && strings.TrimSpace(string(out)) != "" {
return false, nil // already configured
}
nameCmd := exec.Command("git", "config", "user.name", "skillshare")
nameCmd.Dir = dir
if err := nameCmd.Run(); err != nil {
return false, err
}
emailCmd := exec.Command("git", "config", "user.email", "skillshare@local")
emailCmd.Dir = dir
if err := emailCmd.Run(); err != nil {
return false, err
}
return true, nil
}
// InitScopeRepo initializes a git repository at dir if one is not already
// present: it creates dir, runs `git init`, writes a scope-aware .gitignore,
// and ensures a local identity. If dir is already a repo it only ensures the
// scope-aware .gitignore (so an existing root repo gains config.yaml exclusion).
// identitySet reports whether a fallback git identity was applied.
func InitScopeRepo(dir, scope string) (identitySet bool, err error) {
if IsRepo(dir) {
return false, WriteScopeGitignore(dir, scope)
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return false, err
}
cmd := exec.Command("git", "init")
cmd.Dir = dir
if err := cmd.Run(); err != nil {
return false, err
}
if err := WriteScopeGitignore(dir, scope); err != nil {
return false, err
}
return EnsureLocalIdentity(dir)
}
+71
View File
@@ -0,0 +1,71 @@
package git
import (
"os"
"path/filepath"
"strings"
"testing"
)
func readGitignore(t *testing.T, dir string) string {
t.Helper()
b, err := os.ReadFile(filepath.Join(dir, ".gitignore"))
if err != nil {
t.Fatalf("read .gitignore: %v", err)
}
return string(b)
}
func TestWriteScopeGitignore_FreshRootExcludesConfig(t *testing.T) {
dir := t.TempDir()
if err := WriteScopeGitignore(dir, "root"); err != nil {
t.Fatal(err)
}
got := readGitignore(t, dir)
if !strings.Contains(got, "config.yaml") {
t.Errorf("root .gitignore must exclude config.yaml, got:\n%s", got)
}
}
func TestWriteScopeGitignore_FreshNonRootOmitsConfig(t *testing.T) {
dir := t.TempDir()
if err := WriteScopeGitignore(dir, "skills"); err != nil {
t.Fatal(err)
}
got := readGitignore(t, dir)
if strings.Contains(got, "config.yaml") {
t.Errorf("non-root .gitignore must not mention config.yaml, got:\n%s", got)
}
}
func TestWriteScopeGitignore_AppendsToExistingAtRoot(t *testing.T) {
dir := t.TempDir()
gi := filepath.Join(dir, ".gitignore")
if err := os.WriteFile(gi, []byte("node_modules/\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := WriteScopeGitignore(dir, "root"); err != nil {
t.Fatal(err)
}
got := readGitignore(t, dir)
if !strings.Contains(got, "config.yaml") {
t.Errorf("existing root .gitignore must gain config.yaml, got:\n%s", got)
}
if !strings.Contains(got, "node_modules/") {
t.Errorf("existing entries must be preserved, got:\n%s", got)
}
}
func TestWriteScopeGitignore_IdempotentAtRoot(t *testing.T) {
dir := t.TempDir()
if err := WriteScopeGitignore(dir, "root"); err != nil {
t.Fatal(err)
}
if err := WriteScopeGitignore(dir, "root"); err != nil {
t.Fatal(err)
}
got := readGitignore(t, dir)
if n := strings.Count(got, "config.yaml"); n != 1 {
t.Errorf("config.yaml must appear exactly once, got %d:\n%s", n, got)
}
}
+70 -6
View File
@@ -5,6 +5,7 @@ import (
"net/http"
"time"
"skillshare/internal/config"
"skillshare/internal/git"
ssync "skillshare/internal/sync"
)
@@ -16,6 +17,7 @@ type gitStatusResponse struct {
IsDirty bool `json:"isDirty"`
Files []string `json:"files"`
SourceDir string `json:"sourceDir"`
Scope string `json:"scope"`
RemoteURL string `json:"remoteURL,omitempty"`
HeadHash string `json:"headHash,omitempty"`
HeadMessage string `json:"headMessage,omitempty"`
@@ -26,10 +28,15 @@ type gitStatusResponse struct {
func (s *Server) handleGitStatus(w http.ResponseWriter, r *http.Request) {
// Snapshot config under RLock, then release before I/O.
s.mu.RLock()
src := s.cfg.EffectiveSkillsSource()
src := s.cfg.EffectiveGitRoot()
scope := s.cfg.GitRoot
s.mu.RUnlock()
if scope == "" {
scope = "skills"
}
resp := gitStatusResponse{
SourceDir: src,
Scope: scope,
Files: make([]string, 0),
}
@@ -72,6 +79,63 @@ func (s *Server) handleGitStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, resp)
}
type setGitRootRequest struct {
Scope string `json:"scope"`
}
// handleSetGitRoot changes the git_root scope: it initializes a git repo at the
// new scope directory if absent (with a scope-aware .gitignore), persists the
// scope to config, and returns the updated git status. It does NOT relocate an
// existing repo — switching scope creates/uses a repo at the target directory,
// mirroring the CLI's `skillshare init --git-root` behavior.
func (s *Server) handleSetGitRoot(w http.ResponseWriter, r *http.Request) {
start := time.Now()
if s.IsProjectMode() {
writeError(w, http.StatusBadRequest, "git_root is only available in global mode")
return
}
var body setGitRootRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
if !config.ValidGitRoot(body.Scope) || body.Scope == "" {
writeError(w, http.StatusBadRequest, "invalid scope (want: skills, agents, extras, or root)")
return
}
s.mu.Lock()
defer s.mu.Unlock()
dir := config.ScopeDir(s.cfg, body.Scope)
if _, err := git.InitScopeRepo(dir, body.Scope); err != nil {
writeError(w, http.StatusInternalServerError, "failed to initialize git at scope: "+err.Error())
return
}
// Persist the scope. "skills" is the default — store it as empty to keep
// config.yaml clean and consistent with the CLI.
if body.Scope == "skills" {
s.cfg.GitRoot = ""
} else {
s.cfg.GitRoot = body.Scope
}
if err := s.saveAndReloadConfig(); err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
s.writeOpsLog("git-root", "ok", start, map[string]any{"scope": body.Scope}, "")
writeJSON(w, map[string]any{
"success": true,
"scope": body.Scope,
"gitRoot": dir,
})
}
type gitBranchesResponse struct {
Current string `json:"current"`
Local []string `json:"local"`
@@ -85,7 +149,7 @@ type gitBranchesResponse struct {
func (s *Server) handleGitBranches(w http.ResponseWriter, r *http.Request) {
// Snapshot config under RLock, then release before I/O.
s.mu.RLock()
src := s.cfg.EffectiveSkillsSource()
src := s.cfg.EffectiveGitRoot()
s.mu.RUnlock()
if !git.IsRepo(src) {
@@ -155,7 +219,7 @@ func (s *Server) handleGitCheckout(w http.ResponseWriter, r *http.Request) {
return
}
src := s.cfg.EffectiveSkillsSource()
src := s.cfg.EffectiveGitRoot()
if !git.IsRepo(src) {
writeError(w, http.StatusBadRequest, "source directory is not a git repository")
@@ -231,7 +295,7 @@ func (s *Server) handleGitCommit(w http.ResponseWriter, r *http.Request) {
return
}
src := s.cfg.EffectiveSkillsSource()
src := s.cfg.EffectiveGitRoot()
if !git.IsRepo(src) {
writeError(w, http.StatusBadRequest, "source directory is not a git repository")
@@ -298,7 +362,7 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request) {
return
}
src := s.cfg.EffectiveSkillsSource()
src := s.cfg.EffectiveGitRoot()
if !git.IsRepo(src) {
writeError(w, http.StatusBadRequest, "source directory is not a git repository")
@@ -387,7 +451,7 @@ func (s *Server) handlePull(w http.ResponseWriter, r *http.Request) {
}
json.NewDecoder(r.Body).Decode(&body)
src := s.cfg.EffectiveSkillsSource()
src := s.cfg.EffectiveGitRoot()
if !git.IsRepo(src) {
writeError(w, http.StatusBadRequest, "source directory is not a git repository")
+1
View File
@@ -460,6 +460,7 @@ func (s *Server) registerRoutes() {
// Git
s.mux.HandleFunc("GET /api/git/status", s.handleGitStatus)
s.mux.HandleFunc("POST /api/git/root", s.handleSetGitRoot)
s.mux.HandleFunc("GET /api/git/branches", s.handleGitBranches)
s.mux.HandleFunc("POST /api/git/checkout", s.handleGitCheckout)
s.mux.HandleFunc("POST /api/git/commit", s.handleGitCommit)