Files
skillshare/internal/server/handler_sync.go
T
Willie a570670a92 fix: registry cleanup after uninstall and sync, UI polish
- Fix UI batch uninstall not removing nested skill registry entries:
  handler used flat names (__) but registry stores path names (/),
  now tracks exact RelPath from discovered skills for matching

- Add stale entry pruning to ReconcileGlobalSkills and
  ReconcileProjectSkills using a live set built during disk walk,
  so skills deleted from source are removed from registry

- Trigger registry reconcile after sync in both UI handler (via defer
  for early-return safety) and CLI (global + project mode), writing
  warnings to stderr to avoid corrupting --json output

- UI: fix BatchUninstallPage search treating plain text as exact-match
  glob (now substring search when no * or ? present), display nested
  skill paths with / instead of __ in confirm and result dialogs

- UI: hide redundant 'X repo(s) and Y skill(s) already up to date'
  line on UpdatePage when everything is already current

- Fix test isolation: set XDG_CONFIG_HOME in server test helpers to
  prevent host agents dir leaking into test results, skip chmod-based
  oplog test when running as root

- Add README badge for Awesome Codex CLI
2026-04-01 22:30:39 +08:00

252 lines
6.9 KiB
Go

package server
import (
"encoding/json"
"log"
"maps"
"net/http"
"path/filepath"
"time"
"skillshare/internal/config"
"skillshare/internal/skillignore"
ssync "skillshare/internal/sync"
)
// ignorePayload builds the common ignored-skills fields for JSON responses.
func ignorePayload(stats *skillignore.IgnoreStats) map[string]any {
skills := []string{}
rootFile := ""
repoFiles := []string{}
if stats != nil {
if len(stats.IgnoredSkills) > 0 {
skills = stats.IgnoredSkills
}
rootFile = stats.RootFile
if stats.RepoFiles != nil {
repoFiles = stats.RepoFiles
}
}
return map[string]any{
"ignored_count": len(skills),
"ignored_skills": skills,
"ignore_root": rootFile,
"ignore_repos": repoFiles,
}
}
type syncTargetResult struct {
Target string `json:"target"`
Linked []string `json:"linked"`
Updated []string `json:"updated"`
Skipped []string `json:"skipped"`
Pruned []string `json:"pruned"`
DirCreated string `json:"dir_created,omitempty"`
}
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
start := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
var body struct {
DryRun bool `json:"dryRun"`
Force bool `json:"force"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
// Default to non-dry-run, non-force
}
globalMode := s.cfg.Mode
if globalMode == "" {
globalMode = "merge"
}
// Pre-check warnings via shared config validation
warnings, validErr := config.ValidateConfig(s.cfg)
if validErr != nil {
writeError(w, http.StatusBadRequest, validErr.Error())
return
}
// Discover skills once for all targets
allSkills, ignoreStats, err := ssync.DiscoverSourceSkillsWithStats(s.cfg.Source)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to discover skills: "+err.Error())
return
}
if len(allSkills) == 0 {
warnings = append(warnings, "source directory is empty (0 skills)")
}
// Prune stale registry entries using already-discovered skills (avoids second walk).
// Uses defer so early returns from target errors still trigger cleanup.
if !body.DryRun {
defer func() {
live := make(map[string]bool, len(allSkills))
for _, sk := range allSkills {
live[sk.RelPath] = true
}
// Ignored skills still exist on disk — don't prune their registry entries
if ignoreStats != nil {
for _, p := range ignoreStats.IgnoredSkills {
live[p] = true
}
}
skillsOnly := s.IsProjectMode() // project registries also store agent entries
var pruneChanged bool
s.registry.Skills, pruneChanged = config.PruneStaleSkills(s.registry.Skills, live, skillsOnly)
if pruneChanged {
regDir := s.cfg.RegistryDir
if s.IsProjectMode() {
regDir = filepath.Join(s.projectRoot, ".skillshare")
}
if err := s.registry.Save(regDir); err != nil {
log.Printf("warning: failed to save registry after prune: %v", err)
}
}
}()
}
results := make([]syncTargetResult, 0)
for name, target := range s.cfg.Targets {
sc := target.SkillsConfig()
mode := sc.Mode
if mode == "" {
mode = globalMode
}
res := syncTargetResult{
Target: name,
Linked: make([]string, 0),
Updated: make([]string, 0),
Skipped: make([]string, 0),
Pruned: make([]string, 0),
}
syncErrArgs := map[string]any{
"targets_total": len(s.cfg.Targets),
"targets_failed": 1,
"target": name,
"dry_run": body.DryRun,
"force": body.Force,
"scope": "ui",
}
switch mode {
case "merge":
mergeResult, err := ssync.SyncTargetMergeWithSkills(name, target, allSkills, s.cfg.Source, body.DryRun, body.Force)
if err != nil {
s.writeOpsLog("sync", "error", start, syncErrArgs, err.Error())
writeError(w, http.StatusInternalServerError, "sync failed for "+name+": "+err.Error())
return
}
res.Linked = mergeResult.Linked
res.Updated = mergeResult.Updated
res.Skipped = mergeResult.Skipped
res.DirCreated = mergeResult.DirCreated
pruneResult, err := ssync.PruneOrphanLinksWithSkills(ssync.PruneOptions{
TargetPath: sc.Path, SourcePath: s.cfg.Source, Skills: allSkills,
Include: sc.Include, Exclude: sc.Exclude, TargetNaming: sc.TargetNaming, TargetName: name,
DryRun: body.DryRun, Force: body.Force,
})
if err == nil {
res.Pruned = pruneResult.Removed
}
case "copy":
copyResult, err := ssync.SyncTargetCopyWithSkills(name, target, allSkills, s.cfg.Source, body.DryRun, body.Force, nil)
if err != nil {
s.writeOpsLog("sync", "error", start, syncErrArgs, err.Error())
writeError(w, http.StatusInternalServerError, "sync failed for "+name+": "+err.Error())
return
}
res.Linked = copyResult.Copied
res.Updated = copyResult.Updated
res.Skipped = copyResult.Skipped
res.DirCreated = copyResult.DirCreated
pruneResult, err := ssync.PruneOrphanCopiesWithSkills(sc.Path, allSkills, sc.Include, sc.Exclude, name, sc.TargetNaming, body.DryRun)
if err == nil {
res.Pruned = pruneResult.Removed
}
default:
err := ssync.SyncTarget(name, target, s.cfg.Source, body.DryRun)
if err != nil {
s.writeOpsLog("sync", "error", start, syncErrArgs, err.Error())
writeError(w, http.StatusInternalServerError, "sync failed for "+name+": "+err.Error())
return
}
res.Linked = []string{"(symlink mode)"}
}
results = append(results, res)
}
// Log the sync operation
s.writeOpsLog("sync", "ok", start, map[string]any{
"targets_total": len(results),
"targets_failed": 0,
"dry_run": body.DryRun,
"force": body.Force,
"scope": "ui",
}, "")
resp := map[string]any{
"results": results,
"warnings": warnings,
}
maps.Copy(resp, ignorePayload(ignoreStats))
writeJSON(w, resp)
}
type diffItem struct {
Skill string `json:"skill"`
Action string `json:"action"` // "link", "update", "skip", "prune", "local"
Reason string `json:"reason"` // human-readable description
}
type diffTarget struct {
Target string `json:"target"`
Items []diffItem `json:"items"`
SkippedCount int `json:"skippedCount,omitempty"`
CollisionCount int `json:"collisionCount,omitempty"`
}
func (s *Server) handleDiff(w http.ResponseWriter, r *http.Request) {
// Snapshot config under RLock, then release before slow I/O.
s.mu.RLock()
source := s.cfg.Source
globalMode := s.cfg.Mode
targets := s.cloneTargets()
s.mu.RUnlock()
if globalMode == "" {
globalMode = "merge"
}
filterTarget := r.URL.Query().Get("target")
discovered, ignoreStats, err := ssync.DiscoverSourceSkillsWithStats(source)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
diffs := make([]diffTarget, 0)
for name, target := range targets {
if filterTarget != "" && filterTarget != name {
continue
}
diffs = append(diffs, s.computeTargetDiff(name, target, discovered, globalMode, source))
}
resp := map[string]any{"diffs": diffs}
maps.Copy(resp, ignorePayload(ignoreStats))
writeJSON(w, resp)
}