mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-18 18:04:17 +00:00
* fix(projects): save new projects in config.yaml again v0.29.0 wrote every project add, edit and remove to a machine-local registry, so a project added on one machine never reached config.yaml or the other machines that share it (#792). Most people share one config.yaml and expect a new project to follow it. config.yaml is the default again. Machine-local storage stays as an explicit choice: --machine-local on add, or projects_storage: machine-local for every new project, with --shared to override it. The new share command moves a local project into config.yaml, and localize still copies one to this machine. Edits and removals stay in the layer that owns the project; removing a local copy of a config.yaml project keeps config.yaml's version unless --shared asks to remove both, so one machine cannot silently drop a project for the others. Exclusions written by v0.29.0 are left as they are. The dashboard picks storage once, in the Add project dialog, and offers the two removal choices only where both copies exist. Moving a project between layers stays a CLI command, so the detail page keeps one job. Closes #792 * fix(projects): recheck both layers after a confirmation, sync the saved key remove and share ask before taking the config lock, then compared only the merged entry after locking. A share or localize from another terminal moves a project between layers without changing that entry, so a remove confirmed for this machine's copy could then delete config.yaml's declaration for every machine, and a confirmed share could overwrite config.yaml settings changed meanwhile. The recheck now compares the owning layer and config.yaml's declaration too (ProjectLayerState). Re-adding a project that v0.29.0 hid restores config.yaml's own key, which can be spelled differently from the folder given to add (~/app versus an absolute path). add --sync looked the project up by the given spelling and failed with "project not found" after saving it; it now syncs the key that was saved. * test(projects): make the layer tests hold on Windows The mutation-sequence test looked the shared project up by filepath.Join, but the fixture spells config.yaml's key $ROOT/app; on Windows the two spellings differ, so the lookup found nothing. It now asks the config for the key it uses. The remove save-failure test blocked the local registry, but removing a config.yaml project now writes config.yaml. On Linux the registry check still failed with ENOTDIR first, which hid the mismatch; on Windows that reads as a missing file and the save went through. The test now blocks config.yaml, as the edit save-failure test does, and its hook no longer shadows the config path with the target path. --------- Co-authored-by: sim <sim@example.invalid>
301 lines
10 KiB
Go
301 lines
10 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"net/http"
|
|
"os"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"skillshare/internal/config"
|
|
"skillshare/internal/projects"
|
|
ssync "skillshare/internal/sync"
|
|
)
|
|
|
|
type projectResource projects.Resource
|
|
type projectItem = projects.Item
|
|
|
|
type projectBody struct {
|
|
Root string `json:"root"`
|
|
Name string `json:"name"`
|
|
Targets []string `json:"targets"`
|
|
Skills *projectResource `json:"skills"`
|
|
Agents *projectResource `json:"agents"`
|
|
// Create refuses a root that is already declared.
|
|
Create bool `json:"create"`
|
|
// Storage is "shared" or "local" for a new project; empty follows
|
|
// projects_storage. Edits stay where the project is saved.
|
|
Storage string `json:"storage"`
|
|
}
|
|
|
|
func (r *projectResource) config() *config.ResourceTargetConfig {
|
|
if r == nil {
|
|
return nil
|
|
}
|
|
return &config.ResourceTargetConfig{Mode: r.Mode, TargetNaming: r.TargetNaming, Include: r.Include, Exclude: r.Exclude}
|
|
}
|
|
|
|
func (s *Server) requireGlobalProjects(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if s.IsProjectMode() {
|
|
writeError(w, http.StatusBadRequest, "projects belong in the global config")
|
|
return
|
|
}
|
|
next(w, r)
|
|
}
|
|
}
|
|
|
|
func (s *Server) handleListProjects(w http.ResponseWriter, r *http.Request) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if err := s.reloadProjectsReadOnly(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
items, err := s.projectService().List()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
type convertible struct {
|
|
Root string `json:"root"`
|
|
Targets []string `json:"targets"`
|
|
Tools []string `json:"tools"`
|
|
Agents bool `json:"agents"`
|
|
}
|
|
offers := []convertible{}
|
|
for _, found := range s.cfg.ConvertibleProjects() {
|
|
offers = append(offers, convertible{Root: found.Root, Targets: found.Targets, Tools: found.Project.Targets, Agents: found.Project.Agents != nil})
|
|
}
|
|
|
|
type tool struct {
|
|
Name string `json:"name"`
|
|
SkillsPath string `json:"skillsPath"`
|
|
AgentsPath string `json:"agentsPath"`
|
|
}
|
|
tools := []tool{}
|
|
agentPaths := config.ProjectAgentTargets()
|
|
for name, target := range config.ProjectTargets() {
|
|
tools = append(tools, tool{Name: name, SkillsPath: target.Path, AgentsPath: agentPaths[name].Path})
|
|
}
|
|
sort.Slice(tools, func(i, j int) bool { return tools[i].Name < tools[j].Name })
|
|
|
|
localPath, err := config.LocalProjectsPath(s.configPath())
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
// storagePaths names the file each storage choice writes, so the add
|
|
// dialog can say where a new project is saved.
|
|
storagePaths := map[string]string{projects.OriginShared: s.configPath(), projects.OriginLocal: localPath}
|
|
writeJSON(w, map[string]any{"projects": items, "convertible": offers, "tools": tools, "storage": s.cfg.NewProjectOrigin(), "storagePaths": storagePaths})
|
|
}
|
|
|
|
// handleSaveProject adds a project or replaces the one declared under the same root.
|
|
func (s *Server) handleSaveProject(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
var body projectBody
|
|
if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil {
|
|
if !errors.Is(err, errBodyTooLarge) {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
|
}
|
|
return
|
|
}
|
|
if body.Root == "" {
|
|
writeError(w, http.StatusBadRequest, "root is required")
|
|
return
|
|
}
|
|
for _, rc := range []*projectResource{body.Skills, body.Agents} {
|
|
if rc == nil {
|
|
continue
|
|
}
|
|
if _, err := ssync.FilterSkills(nil, rc.Include, rc.Exclude); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid include/exclude pattern: "+err.Error())
|
|
return
|
|
}
|
|
}
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
release, err := projects.LockConfig(r.Context(), s.configPath())
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
defer release()
|
|
if err := s.reloadProjectsReadOnly(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
root, lookupErr := lookupProjectRoot(s.cfg.Projects, body.Root)
|
|
if lookupErr != nil {
|
|
if !errors.Is(lookupErr, projects.ErrNotFound) {
|
|
writeError(w, http.StatusBadRequest, lookupErr.Error())
|
|
return
|
|
}
|
|
root = body.Root
|
|
}
|
|
result, err := s.projectService().Put(root, config.ManagedProject{Name: body.Name, Targets: body.Targets, Skills: body.Skills.config(), Agents: body.Agents.config()}, projects.PutOptions{Create: body.Create, Storage: body.Storage})
|
|
if err != nil {
|
|
status := http.StatusBadRequest
|
|
switch {
|
|
case errors.Is(err, projects.ErrSave), errors.Is(err, projects.ErrDetach):
|
|
status = http.StatusInternalServerError
|
|
case errors.Is(err, projects.ErrExists):
|
|
status = http.StatusConflict
|
|
case errors.Is(err, projects.ErrNotFound):
|
|
status = http.StatusNotFound
|
|
}
|
|
|
|
s.writeProjectFailure(w, status, result, err, start, "update", root)
|
|
return
|
|
}
|
|
s.installGlobalConfig(result.Expanded)
|
|
action := "update"
|
|
if body.Create {
|
|
action = "add"
|
|
}
|
|
s.writeOpsLog("project", "ok", start, map[string]any{"action": action, "root": root, "scope": "ui"}, "")
|
|
writeJSON(w, map[string]any{"success": true, "root": root, "origin": result.Item.Origin, "originPath": result.Item.OriginPath})
|
|
}
|
|
|
|
func (s *Server) handleRemoveProject(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
release, err := projects.LockConfig(r.Context(), s.configPath())
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
defer release()
|
|
if err := s.reloadProjectsReadOnly(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
root, lookupErr := lookupProjectRoot(s.cfg.Projects, r.URL.Query().Get("root"))
|
|
if lookupErr != nil {
|
|
if !errors.Is(lookupErr, projects.ErrNotFound) {
|
|
writeError(w, http.StatusBadRequest, lookupErr.Error())
|
|
return
|
|
}
|
|
root = r.URL.Query().Get("root")
|
|
}
|
|
if _, exists := s.cfg.Projects[root]; !exists {
|
|
writeError(w, http.StatusNotFound, "project not found: "+root)
|
|
return
|
|
}
|
|
shared := r.URL.Query().Get("shared") == "true"
|
|
result, err := s.projectService().Remove(root, projects.RemoveOptions{Shared: shared})
|
|
if err != nil {
|
|
s.writeProjectFailure(w, http.StatusInternalServerError, result, err, start, "remove", root)
|
|
return
|
|
}
|
|
s.installGlobalConfig(result.Expanded)
|
|
s.writeOpsLog("project", "ok", start, map[string]any{"action": "remove", "root": root, "shared": shared, "scope": "ui"}, "")
|
|
writeJSON(w, map[string]any{"success": true, "root": root, "origin": result.Item.Origin, "originPath": result.Item.OriginPath, "remaining": result.Remaining != nil})
|
|
}
|
|
|
|
// handleConvertProject moves the targets that write into one folder under projects.
|
|
// They keep their folders, mode and filters, so the next sync changes nothing.
|
|
func (s *Server) handleConvertProject(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
var body struct {
|
|
Root string `json:"root"`
|
|
}
|
|
if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil {
|
|
if !errors.Is(err, errBodyTooLarge) {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
|
}
|
|
return
|
|
}
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
release, err := projects.LockConfig(r.Context(), s.configPath())
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
defer release()
|
|
if err := s.reloadProjectsReadOnly(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
for _, found := range s.cfg.ConvertibleProjects() {
|
|
if found.Root != body.Root {
|
|
continue
|
|
}
|
|
next := *s.cfg
|
|
next.Targets = maps.Clone(s.cfg.Targets)
|
|
for _, name := range found.Targets {
|
|
delete(next.Targets, name)
|
|
}
|
|
candidate, err := projects.PrepareProjects(s.configPath(), &next, func(entries map[string]config.ManagedProject) error { entries[found.Root] = found.Project; return nil })
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
if err := candidate.Save.Write(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
s.installGlobalConfig(candidate.Save.Expanded)
|
|
s.writeOpsLog("project", "ok", start, map[string]any{"action": "convert", "root": found.Root, "targets": found.Targets, "scope": "ui"}, "")
|
|
origin, originPath := candidate.Save.Expanded.ProjectOrigin(found.Root)
|
|
writeJSON(w, map[string]any{"success": true, "root": found.Root, "origin": origin, "originPath": originPath})
|
|
return
|
|
}
|
|
writeError(w, http.StatusNotFound, "no targets to convert for "+body.Root)
|
|
}
|
|
|
|
func lookupProjectRoot(entries map[string]config.ManagedProject, root string) (string, error) {
|
|
cwd, err := os.Getwd()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return projects.FindRoot(entries, root, cwd, home)
|
|
}
|
|
|
|
// projectService is used while the caller holds s.mu.
|
|
func (s *Server) projectService() *projects.Service {
|
|
svc := projects.NewService(s.configPath(), func() (*config.Config, error) { return s.cfg, nil })
|
|
svc.DetachSkillsTarget = detachSkillsTarget
|
|
return svc
|
|
}
|
|
|
|
// reloadProjectsReadOnly is called under s.mu, and under the project file lock
|
|
// for mutations. Unlike the ordinary dashboard reload it never migrates on disk.
|
|
func (s *Server) reloadProjectsReadOnly() error {
|
|
cfg, err := config.LoadReadOnlyPath(s.configPath())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.installGlobalConfig(cfg)
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) writeProjectFailure(w http.ResponseWriter, status int, result projects.Result, err error, start time.Time, action, root string) {
|
|
if result.Detach == nil || (len(result.Detach.Removed) == 0 && len(result.Detach.CopiedBack) == 0) {
|
|
writeError(w, status, err.Error())
|
|
return
|
|
}
|
|
message := fmt.Sprintf("%s; registration %s; completed detach: removed [%s], copied back [%s]", err, result.Registration, strings.Join(result.Detach.Removed, ", "), strings.Join(result.Detach.CopiedBack, ", "))
|
|
s.writeOpsLog("project", "partial", start, map[string]any{"action": action, "root": root, "scope": "ui"}, message)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
writeJSON(w, map[string]any{"error": message, "detach": result.Detach, "registration": result.Registration})
|
|
}
|