Files
skillshare/internal/server/handler_instructions_setup.go
T
Willie 87e6cc9538 fix(extras): guard shared-file ownership and keep user files on restore
Exploratory CLI, dashboard and real-Windows testing of single-file extras
found paths that corrupted another shared file, lost user content, or
reported the wrong state.

- One shared file per link/copy target is now enforced in config
  validation, so the CLI, sync and API all refuse it; an import is never
  written through a link into another shared file (409
  instructions_target_held in the API).
- Restore recreates an original Windows junction as a junction, which
  needs no privilege, and remove restores before saving config so a
  failed restore no longer orphans the record.
- Imports into dotfiles links, damaged managed blocks, repointed links
  and CRLF files keep the user's content; project imports use paths
  relative to the file so a moved repo keeps working.
- Mode and assign responses carry sync warnings; dry-run says when an
  edit would be backed up; invalid modes no longer show as healthy.
- An edited copy reports modified, identical unowned copies count as
  synced without being owned, and relative project links no longer show
  drift.
- sync extras --json exits non-zero on errors; extras <name> --help
  works; --add-target gains --as; detach messages match behavior.

Refs #299
2026-09-28 15:27:02 +08:00

140 lines
4.6 KiB
Go

package server
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"skillshare/internal/config"
"skillshare/internal/instructions"
)
// errInstructionsInUse is the error code for moving or removing a target's
// instruction file while shared instruction files are attached to it.
const errInstructionsInUse = "instructions_in_use"
// setTargetInstructionsConfig sets (ic != nil) or clears the user-set
// instruction file of a target in the config of the current mode. Callers
// must hold s.mu and save the config afterwards.
func (s *Server) setTargetInstructionsConfig(name string, ic *config.TargetInstructionsConfig) {
tc := s.cfg.Targets[name]
tc.Instructions = ic
s.cfg.Targets[name] = tc
if !s.IsProjectMode() {
return
}
for i := range s.projectCfg.Targets {
if s.projectCfg.Targets[i].Name == name {
s.projectCfg.Targets[i].Instructions = ic
return
}
}
}
// attachedShared returns the shared instruction files attached to the
// target's current instruction file. Callers must hold s.mu.
func (s *Server) attachedShared(name string) []instructions.Assignment {
it, _, ok := s.targetInstructions(name)
if !ok {
return nil
}
return instructions.Assignments(s.extrasConfig(), it.Path, s.instructionsResolver())
}
func writeInstructionsInUse(w http.ResponseWriter, name string) {
writeCodedError(w, http.StatusConflict, errInstructionsInUse,
name+" uses shared instruction files; switch it back to its own file first",
map[string]string{"target": name})
}
// handlePutTargetInstructionsSetup — PUT /api/targets/{name}/instructions/setup
// Tells skillshare which instruction file the target reads.
func (s *Server) handlePutTargetInstructionsSetup(w http.ResponseWriter, r *http.Request) {
start := time.Now()
name := r.PathValue("name")
var body struct {
Path string `json:"path"`
Import bool `json:"import"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
ic := &config.TargetInstructionsConfig{Path: strings.TrimSpace(body.Path), Import: body.Import}
if err := config.ValidateTargetInstructions(ic, s.IsProjectMode()); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
s.mu.Lock()
defer s.mu.Unlock()
tc, found := s.cfg.Targets[name]
if !found {
writeError(w, http.StatusNotFound, "target not found: "+name)
return
}
if tc.ProjectRoot() != "" {
writeError(w, http.StatusBadRequest, name+" belongs to a project; edit the project instead")
return
}
// Shared files are attached to the current path; moving it would strand them.
old, _, hadFile := s.targetInstructions(name)
shared := s.attachedShared(name)
tc.Instructions = ic
next, _ := config.TargetInstructions(name, tc, s.IsProjectMode())
if info, err := os.Stat(instructions.Resolve(next, s.projectRoot).Path); err == nil && info.IsDir() {
writeError(w, http.StatusBadRequest, fmt.Sprintf("instructions.path %q must name a file, not a directory", ic.Path))
return
}
if hadFile && len(shared) > 0 && filepath.Clean(old.Path) != filepath.Clean(instructions.Resolve(next, s.projectRoot).Path) {
writeInstructionsInUse(w, name)
return
}
s.setTargetInstructionsConfig(name, ic)
args := map[string]any{"target": name, "path": ic.Path, "import": ic.Import, "scope": "ui"}
if err := s.saveAndReloadConfig(); err != nil {
s.writeOpsLog("instructions-setup", "error", start, args, err.Error())
writeError(w, http.StatusInternalServerError, err.Error())
return
}
s.writeOpsLog("instructions-setup", "ok", start, args, "")
writeJSON(w, map[string]any{"success": true})
}
// handleDeleteTargetInstructionsSetup — DELETE /api/targets/{name}/instructions/setup
// Forgets the user-set instruction file; the built-in one, if any, applies again.
func (s *Server) handleDeleteTargetInstructionsSetup(w http.ResponseWriter, r *http.Request) {
start := time.Now()
name := r.PathValue("name")
s.mu.Lock()
defer s.mu.Unlock()
tc, found := s.cfg.Targets[name]
if !found {
writeError(w, http.StatusNotFound, "target not found: "+name)
return
}
if tc.Instructions == nil {
writeJSON(w, map[string]any{"success": true})
return
}
if len(s.attachedShared(name)) > 0 {
writeInstructionsInUse(w, name)
return
}
s.setTargetInstructionsConfig(name, nil)
args := map[string]any{"target": name, "scope": "ui"}
if err := s.saveAndReloadConfig(); err != nil {
s.writeOpsLog("instructions-setup-remove", "error", start, args, err.Error())
writeError(w, http.StatusInternalServerError, err.Error())
return
}
s.writeOpsLog("instructions-setup-remove", "ok", start, args, "")
writeJSON(w, map[string]any{"success": true})
}