mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
A root skill discovered through a followed source link occupies the link entry itself. Moving that entry to trash silently unlinks every nested skill instead of removing one skill. Share the root-skill guard across single and batch API handlers and CLI uninstall, report the unlink action clearly, and preserve explicit unlink and nested skill removal.
416 lines
11 KiB
Go
416 lines
11 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"skillshare/internal/git"
|
|
"skillshare/internal/install"
|
|
"skillshare/internal/sourcefs"
|
|
"skillshare/internal/sync"
|
|
"skillshare/internal/trash"
|
|
)
|
|
|
|
type batchUninstallRequest struct {
|
|
Names []string `json:"names"`
|
|
Kind string `json:"kind,omitempty"`
|
|
Force bool `json:"force"`
|
|
}
|
|
|
|
type batchUninstallItemResult struct {
|
|
Name string `json:"name"`
|
|
Kind string `json:"kind,omitempty"`
|
|
Success bool `json:"success"`
|
|
MovedToTrash bool `json:"movedToTrash,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
type batchUninstallSummary struct {
|
|
Succeeded int `json:"succeeded"`
|
|
Failed int `json:"failed"`
|
|
}
|
|
|
|
func (s *Server) handleBatchUninstall(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
var body batchUninstallRequest
|
|
if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil {
|
|
if !errors.Is(err, errBodyTooLarge) {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
|
}
|
|
return
|
|
}
|
|
if len(body.Names) == 0 {
|
|
writeError(w, http.StatusBadRequest, "names array is required and must not be empty")
|
|
return
|
|
}
|
|
if body.Kind != "" && body.Kind != "skill" && body.Kind != "agent" {
|
|
writeError(w, http.StatusBadRequest, "invalid kind: "+body.Kind)
|
|
return
|
|
}
|
|
|
|
// Agent-mode batch uninstall
|
|
if body.Kind == "agent" {
|
|
s.handleBatchUninstallAgents(w, body, start)
|
|
return
|
|
}
|
|
|
|
// Skill-mode (default) batch uninstall
|
|
s.handleBatchUninstallSkills(w, body, start)
|
|
}
|
|
|
|
func (s *Server) handleBatchUninstallAgents(w http.ResponseWriter, body batchUninstallRequest, start time.Time) {
|
|
agentsSource := s.agentsSource()
|
|
if agentsSource == "" {
|
|
writeError(w, http.StatusInternalServerError, "agents source not configured")
|
|
return
|
|
}
|
|
|
|
results := make([]batchUninstallItemResult, 0, len(body.Names))
|
|
var removedNames []string
|
|
succeeded, failed := 0, 0
|
|
var firstErr string
|
|
|
|
for _, name := range body.Names {
|
|
res := batchUninstallItemResult{Name: name, Kind: "agent"}
|
|
|
|
agent, err := resolveAgentResource(agentsSource, name)
|
|
if err != nil {
|
|
res.Success = false
|
|
res.Error = "agent not found: " + name
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
|
|
displayName := agentMetaKey(agent.RelPath)
|
|
legacySidecar := filepath.Join(filepath.Dir(agent.SourcePath), filepath.Base(displayName)+".skillshare-meta.json")
|
|
if _, err := trash.MoveAgentToTrash(agent.SourcePath, legacySidecar, displayName, s.agentTrashBase()); err != nil {
|
|
res.Success = false
|
|
res.Error = fmt.Sprintf("failed to trash agent: %v", err)
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
|
|
removedNames = append(removedNames, displayName)
|
|
res.Success = true
|
|
res.MovedToTrash = true
|
|
results = append(results, res)
|
|
succeeded++
|
|
}
|
|
|
|
if succeeded > 0 && s.agentsStore != nil {
|
|
for _, name := range removedNames {
|
|
s.agentsStore.Remove(name)
|
|
}
|
|
if err := s.agentsStore.Save(agentsSource); err != nil {
|
|
log.Printf("warning: failed to save agent metadata after batch uninstall: %v", err)
|
|
}
|
|
}
|
|
|
|
status := "ok"
|
|
if failed > 0 && succeeded > 0 {
|
|
status = "partial"
|
|
} else if failed > 0 {
|
|
status = "error"
|
|
}
|
|
|
|
s.writeOpsLog("uninstall", status, start, map[string]any{
|
|
"names": body.Names,
|
|
"kind": "agent",
|
|
"scope": "ui",
|
|
"count": succeeded,
|
|
}, firstErr)
|
|
|
|
writeJSON(w, map[string]any{
|
|
"results": results,
|
|
"summary": batchUninstallSummary{
|
|
Succeeded: succeeded,
|
|
Failed: failed,
|
|
},
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleBatchUninstallSkills(w http.ResponseWriter, body batchUninstallRequest, start time.Time) {
|
|
// Use DiscoverSourceSkillsAll (not DiscoverSourceSkills) so disabled skills
|
|
// — those listed in .skillignore — are also resolvable. The list handler
|
|
// shows disabled skills, so uninstall must be able to find them too (#190).
|
|
source := s.skillsSource()
|
|
walk := s.skillsWalk()
|
|
discovered, err := sync.DiscoverSourceSkillsAll(source, walk)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to discover skills: "+err.Error())
|
|
return
|
|
}
|
|
|
|
results := make([]batchUninstallItemResult, 0, len(body.Names))
|
|
removedPaths := make(map[string]bool) // exact RelPaths of successfully removed items
|
|
var repoEntriesToRemove []string
|
|
succeeded, failed := 0, 0
|
|
var firstErr string
|
|
|
|
for _, name := range body.Names {
|
|
res := batchUninstallItemResult{Name: name, Kind: "skill"}
|
|
|
|
if !validSourceName(name) {
|
|
res.Success = false
|
|
res.Error = "invalid skill name: " + name
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
|
|
repoPath := filepath.Join(source, name)
|
|
_, repoFollowed := walk.Follow.Resolve(repoPath)
|
|
managedRepo := strings.HasPrefix(name, "_") && filepath.Base(name) == name && !repoFollowed && install.IsGitRepo(repoPath)
|
|
var skill *sync.DiscoveredSkill
|
|
if !managedRepo {
|
|
skill, err = resolveUninstallSkill(discovered, name)
|
|
if err != nil {
|
|
res.Error = err.Error()
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
}
|
|
followed := false
|
|
if skill != nil {
|
|
_, followed = walk.Follow.Resolve(skill.SourcePath)
|
|
}
|
|
// An explicit managed repo takes precedence over a skill's basename.
|
|
if managedRepo || (strings.HasPrefix(name, "_") && !followed) {
|
|
if !install.IsGitRepo(repoPath) {
|
|
res.Success = false
|
|
res.Error = "not a tracked repository: " + name
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
|
|
if !body.Force {
|
|
dirty, err := git.IsDirty(repoPath)
|
|
if err != nil {
|
|
res.Error = fmt.Sprintf("failed to check git status: %v", err)
|
|
} else if dirty {
|
|
res.Error = "uncommitted changes (use force to override)"
|
|
}
|
|
}
|
|
if res.Error != "" {
|
|
res.Success = false
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
|
|
if err := sourcefs.CheckMoveOut(source, repoPath, walk.Follow); err != nil {
|
|
res.Success = false
|
|
res.Error = err.Error()
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
if _, err := trash.MoveToTrash(repoPath, name, s.trashBase()); err != nil {
|
|
res.Success = false
|
|
res.Error = fmt.Sprintf("failed to trash repo: %v", err)
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
|
|
repoEntriesToRemove = append(repoEntriesToRemove, name)
|
|
removedPaths[name] = true // repo dir name is already the registry path
|
|
res.Success = true
|
|
res.MovedToTrash = true
|
|
results = append(results, res)
|
|
succeeded++
|
|
continue
|
|
}
|
|
|
|
if skill == nil {
|
|
res.Success = false
|
|
res.Error = "skill not found: " + name
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
|
|
if skill.IsInRepo && !followed {
|
|
res.Success = false
|
|
res.Error = "skill is inside a tracked repo; uninstall the repo instead"
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
|
|
if err := sourcefs.CheckSkillMoveOut(source, skill.SourcePath, walk.Follow); err != nil {
|
|
res.Success = false
|
|
res.Error = err.Error()
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
trashName := filepath.Base(skill.SourcePath)
|
|
if followed {
|
|
trashName = skill.RelPath // Preserve the linked skill's logical restore path.
|
|
}
|
|
if _, err := trash.MoveToTrash(skill.SourcePath, trashName, s.trashBase()); err != nil {
|
|
res.Success = false
|
|
res.Error = fmt.Sprintf("failed to trash skill: %v", err)
|
|
results = append(results, res)
|
|
failed++
|
|
if firstErr == "" {
|
|
firstErr = res.Error
|
|
}
|
|
continue
|
|
}
|
|
|
|
removedPaths[skill.RelPath] = true // exact path for registry matching
|
|
res.Success = true
|
|
res.MovedToTrash = true
|
|
results = append(results, res)
|
|
succeeded++
|
|
}
|
|
|
|
if len(repoEntriesToRemove) > 0 {
|
|
gitDir := s.gitignoreDir()
|
|
if gitDir != "" {
|
|
entries := repoEntriesToRemove
|
|
if s.IsProjectMode() {
|
|
prefix := s.projectGitignorePrefix()
|
|
entries = make([]string, len(repoEntriesToRemove))
|
|
for i, e := range repoEntriesToRemove {
|
|
entries[i] = prefix + "/" + e
|
|
}
|
|
}
|
|
if _, err := install.RemoveFromGitIgnoreBatch(gitDir, entries); err != nil {
|
|
log.Printf("warning: failed to clean .gitignore: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
if succeeded > 0 {
|
|
// removedPaths contains exact RelPaths (e.g. "frontend/vue/vue-best-practices")
|
|
// and repo dir names (e.g. "_team-skills"), collected during the uninstall loop.
|
|
for _, name := range s.skillsStore.List() {
|
|
entry := s.skillsStore.Get(name)
|
|
if entry == nil {
|
|
continue
|
|
}
|
|
if removedPaths[name] {
|
|
s.skillsStore.Remove(name)
|
|
continue
|
|
}
|
|
// Tracked repos: store uses group without "_" prefix (e.g., group="team-skills"
|
|
// for repo dir "_team-skills"). Reconstruct the prefixed name to match removedPaths.
|
|
if entry.Group != "" && removedPaths["_"+entry.Group] {
|
|
s.skillsStore.Remove(name)
|
|
continue
|
|
}
|
|
// When a group directory is uninstalled, also remove its member skills
|
|
memberOfRemoved := false
|
|
for rp := range removedPaths {
|
|
if strings.HasPrefix(name, rp+"/") {
|
|
memberOfRemoved = true
|
|
break
|
|
}
|
|
}
|
|
if memberOfRemoved {
|
|
s.skillsStore.Remove(name)
|
|
}
|
|
}
|
|
for rp := range removedPaths {
|
|
s.skillsStore.RemoveTargetOverrides(rp)
|
|
}
|
|
|
|
if err := s.skillsStore.Save(s.cfg.EffectiveSkillsSource()); err != nil {
|
|
log.Printf("warning: failed to save metadata: %v", err)
|
|
}
|
|
|
|
s.reconcileSkillsConfig(s.cfg.EffectiveSkillsSource())
|
|
}
|
|
|
|
status := "ok"
|
|
if failed > 0 && succeeded > 0 {
|
|
status = "partial"
|
|
} else if failed > 0 {
|
|
status = "error"
|
|
}
|
|
|
|
s.writeOpsLog("uninstall", status, start, map[string]any{
|
|
"names": body.Names,
|
|
"force": body.Force,
|
|
"scope": "ui",
|
|
"count": succeeded,
|
|
}, firstErr)
|
|
|
|
writeJSON(w, map[string]any{
|
|
"results": results,
|
|
"summary": batchUninstallSummary{
|
|
Succeeded: succeeded,
|
|
Failed: failed,
|
|
},
|
|
})
|
|
}
|
|
|
|
// ponytail: scan per requested name; index discovery if large batches become slow.
|
|
func resolveUninstallSkill(discovered []sync.DiscoveredSkill, name string) (*sync.DiscoveredSkill, error) {
|
|
for i := range discovered {
|
|
if discovered[i].FlatName == name {
|
|
return &discovered[i], nil
|
|
}
|
|
}
|
|
var match *sync.DiscoveredSkill
|
|
var candidates []string
|
|
for i := range discovered {
|
|
if filepath.Base(discovered[i].SourcePath) == name {
|
|
match = &discovered[i]
|
|
candidates = append(candidates, match.FlatName)
|
|
}
|
|
}
|
|
if len(candidates) > 1 {
|
|
return nil, fmt.Errorf("ambiguous skill name %q: use one of %s", name, strings.Join(candidates, ", "))
|
|
}
|
|
return match, nil
|
|
}
|