mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-20 12:23:22 +00:00
* fix(sync): never delete or re-point entries skillshare did not create On Windows, a plain `init` followed by `sync` deleted things in ~/.claude/skills that skillshare never created, with no backup and no prompt. It also re-pointed another tool's junction. Seen in a sandbox run of v0.30.7: - prune removed real folders whose names only look like skillshare's flat naming (team__shared, _drafts), via the name heuristic - prune removed a broken link that another tool or the user made - merge sync deleted and re-created a same-name link that pointed into another manager's store - init's import deleted original folders that matched the source byte for byte The manifest already records what skillshare made, so use it: - prune keeps a look-alike folder that is not in the manifest and warns once per sync; --force still removes it - prune removes a broken external link only if the manifest records it (e.g. after the source moved); otherwise it keeps the link and warns - merge sync re-points a link only if the manifest records it or it already points into the source; otherwise it reports the entry as kept local, as it already does for a real folder; --force replaces it - init's import moves identical copies to the trash under replaced-by-init/<target>/ instead of deleting them Tests: ownership_test.go adds regression tests that use createLink, so they run on Windows without Developer Mode (junctions). The 4 keep tests fail without this change. TestSyncTargetMerge_FixesBrokenLink now records the link in the manifest first, since a same-name link that skillshare did not make is no longer re-pointed. Existing tests in internal/sync, internal/trash and cmd/skillshare show the same failures on a Windows host with and without the change (symlink privilege). The devcontainer suite has not been run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: say what sync and init keep when skillshare did not create it The previous commit makes sync and init leave alone entries skillshare did not create. Update the pages that describe that behaviour: - sync-modes: merge mode keeps a same-name link from another tool and reports it as local; orphan cleanup keeps folders that only look like skillshare's flat names, and broken links outside the source that the manifest does not record. sync --force still removes them. - init: identical folders replaced with links during the first sync go to the trash first (replaced-by-init/<tool>/, cleaned after 7 days). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(sourcefs): drop the raw-write allowance replaceIdenticalCopies no longer needs replaceIdenticalCopies now moves an identical copy to the trash instead of calling os.RemoveAll, so TestRawWriteRatchet reports its allowance as stale. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(sync): apply the ownership rule at every consumer Review of the first commit found places that still did, or predicted, the old behaviour. One rule now decides whether a link is skillshare's: Manifest.OwnsLink (the manifest records a link there, or it points into the source). It compares canonical paths, so a source reached through an alias and a relative project link still count as skillshare's. - copy mode kept re-pointing: it removed any same-name link and wrote a copy. It now keeps a link it does not own, like merge mode. - the dashboard diff predicted a prune for a folder that is only named like skillshare's, and an update for another tool's link. It now reports them as local and kept. The orphan-link prediction uses the same rule as prune. - `diff` reported a target as in sync while sync printed "kept local" for another tool's link. It lists the link as a local override. - doctor reported a broken link skillshare did not create as an error and suggested `skillshare sync`, which now keeps it. It is a warning with its own row, and `broken_symlinks` is `warning` in --json. - `trash restore` put a folder init had replaced into the source as a new nested skill. Restore refuses entries under replaced-by-init/ and names the trash folder to copy from. - init reported a folder it could not move to the trash as one that differs from the source, and dropped the error. It is reported separately, with the error. - the PruneOptions.ManagedOnly comment still said broken external links are skipped; manifest-recorded ones are removed. Tests cover the states the review listed: a source behind an alias, a relative project link, ManagedOnly, standard naming, dry run with --force, and a recorded copy the user replaced with a link. TestSync_Pruning_RemovesBrokenExternalSymlinks passed without testing anything, because FileExists follows links; it is now two tests that use Lstat, one per owner. Agent merge is unchanged: agents have no link manifest. * fix(diff): list another tool's link as kept in copy mode too Copy mode now keeps a same-name link skillshare did not create, but both diffs read the entry with os.Stat. A broken link showed as a skill to add on every run, and a live one as a plain local copy, while sync kept both and said "kept local". `diff` and the dashboard diff check the link first and report it the way merge mode does: a local override, kept until --force. * test(sync): make the aliased-source link while its folder exists TestSyncMergeRepointsUnrecordedLinkIntoAliasedSource failed on Windows: it linked straight to a missing folder, and a junction cannot be made to one. It now links first and removes the folder after, like the other broken-link tests in this file. * fix(sync): compare a broken link by where it would point linksIntoSource resolved both paths with EvalSymlinks, which gives up on a path that does not exist. A broken link is exactly that, so a link into a source reached through an alias (a symlinked config folder, or a short 8.3 path on Windows) compared an unresolved path with a resolved one and was taken for another tool's link. Sync then kept it instead of repairing or pruning it. It now uses sourcewalk.Canonical, which resolves the nearest folder that exists and keeps the missing tail. The test covers both spellings: the alias in the link, and the alias in the configured source. * fix(init): report what the first sync kept, and match prune in the diff Two previews said less, or more, than sync does. init ran its first sync quietly and printed only "Synced". Sync now keeps a link another tool put on a skill's name, a folder that is only named like skillshare's, and a broken link it did not create, so the skill was reported as synced while the tool still loaded the other copy. firstSync returns the warnings a plain sync prints, and init shows them. They already name the folders that differ from the source, so the separate list of those is gone. The dashboard diff counted an orphan link as a removal whenever the manifest recorded it. Prune keeps a recorded link that still resolves outside the source (the source moved and the old checkout stayed), so the Sync page showed a removal that never happened. The diff now uses prune's own rule: a link into the source goes when broken or recorded; any other link only when broken and recorded. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Willie <egg358358@gmail.com>
690 lines
20 KiB
Go
690 lines
20 KiB
Go
package trash
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"skillshare/internal/config"
|
|
"skillshare/internal/projectdir"
|
|
"skillshare/internal/sourcefs"
|
|
"skillshare/internal/sourcewalk"
|
|
"skillshare/internal/utils"
|
|
)
|
|
|
|
const defaultMaxAge = 7 * 24 * time.Hour // 7 days
|
|
|
|
const reservedAgentTrashDir = "agents"
|
|
|
|
// ReplacedByInitDir is the skills trash subfolder, one folder per tool, for
|
|
// target folders that init replaced with links. They came from a tool, not the
|
|
// source, so restore refuses them: the trash copy is for copying back by hand.
|
|
const ReplacedByInitDir = "replaced-by-init"
|
|
|
|
// validateTrashName rejects names that could cause path traversal when joined
|
|
// with a base directory. Allowed: plain names ("skill"), nested names
|
|
// ("org/team-skill"). Rejected: empty, absolute, ".", "..", any segment
|
|
// containing NUL, or any segment equal to "..".
|
|
func validateTrashName(name string) error {
|
|
if name == "" {
|
|
return fmt.Errorf("trash name must not be empty")
|
|
}
|
|
if strings.ContainsRune(name, 0) {
|
|
return fmt.Errorf("trash name must not contain NUL")
|
|
}
|
|
// filepath.IsAbs is platform-dependent: on Windows "/absolute/path" carries
|
|
// no volume, so it reads as relative there. A leading separator is never a
|
|
// valid trash name on any platform, so reject it explicitly.
|
|
if filepath.IsAbs(name) || strings.HasPrefix(name, "/") {
|
|
return fmt.Errorf("trash name must not be absolute: %s", name)
|
|
}
|
|
for _, part := range strings.Split(name, "/") {
|
|
if part == "" {
|
|
continue
|
|
}
|
|
if part == "." || part == ".." {
|
|
return fmt.Errorf("trash name must not contain path traversal segment %q in %q", part, name)
|
|
}
|
|
}
|
|
// Trash names use logical slash-separated paths. Backslash is rejected
|
|
// even on Unix to unconditionally block Windows-style traversal syntax.
|
|
if strings.Contains(name, `\`) {
|
|
return fmt.Errorf("trash name must not contain backslash: %s", name)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// trashLogicalName builds a slash-separated logical name for a trash entry.
|
|
// It normalizes OS path separators to '/' so that List() returns names
|
|
// compatible with validateTrashName() (which rejects backslashes).
|
|
func trashLogicalName(parentRel, name string) string {
|
|
if parentRel == "." {
|
|
return name
|
|
}
|
|
|
|
// filepath.ToSlash converts the current OS path separator to slash.
|
|
// Do not translate literal backslashes on Unix; they are filename
|
|
// characters, not path separators, and should remain invalid input.
|
|
parentRel = filepath.ToSlash(parentRel)
|
|
return path.Join(parentRel, name)
|
|
}
|
|
|
|
// ensureUnderBase asserts that candidate resolves to a path under base.
|
|
// Both are resolved to absolute paths before comparison.
|
|
// candidate == base is allowed (used by RestoreAgent where targetDir may
|
|
// equal destDir).
|
|
func ensureUnderBase(base, candidate string) error {
|
|
return ensureUnderBaseRel(base, candidate, true)
|
|
}
|
|
|
|
// ensureStrictlyUnderBase is like ensureUnderBase but rejects candidate == base.
|
|
// Used by destructive sinks (e.g. Cleanup) that must never target the base
|
|
// directory itself.
|
|
func ensureStrictlyUnderBase(base, candidate string) error {
|
|
return ensureUnderBaseRel(base, candidate, false)
|
|
}
|
|
|
|
func ensureUnderBaseRel(base, candidate string, allowEqual bool) error {
|
|
baseAbs, err := filepath.Abs(base)
|
|
if err != nil {
|
|
return fmt.Errorf("resolve base %q: %w", base, err)
|
|
}
|
|
|
|
candidateAbs, err := filepath.Abs(candidate)
|
|
if err != nil {
|
|
return fmt.Errorf("resolve candidate %q: %w", candidate, err)
|
|
}
|
|
|
|
baseAbs = filepath.Clean(baseAbs)
|
|
candidateAbs = filepath.Clean(candidateAbs)
|
|
|
|
rel, err := filepath.Rel(baseAbs, candidateAbs)
|
|
if err != nil {
|
|
return fmt.Errorf("path %q escapes base %q: %w", candidate, base, err)
|
|
}
|
|
|
|
if rel == "." {
|
|
if allowEqual {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("path %q equals base %q — refusing to operate on base", candidate, base)
|
|
}
|
|
|
|
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
|
|
return fmt.Errorf("path %q escapes base %q", candidate, base)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// TrashDir returns the global trash directory path.
|
|
func TrashDir() string {
|
|
return filepath.Join(config.DataDir(), "trash")
|
|
}
|
|
|
|
// ProjectTrashDir returns the project-level trash directory path.
|
|
func ProjectTrashDir(root string) string {
|
|
return filepath.Join(projectdir.Resolve(root), "trash")
|
|
}
|
|
|
|
// AgentTrashDir returns the global trash directory for agents.
|
|
func AgentTrashDir() string {
|
|
return filepath.Join(config.DataDir(), "trash", "agents")
|
|
}
|
|
|
|
// ProjectAgentTrashDir returns the project-level trash directory for agents.
|
|
func ProjectAgentTrashDir(root string) string {
|
|
return filepath.Join(projectdir.Resolve(root), "trash", "agents")
|
|
}
|
|
|
|
// MoveAgentToTrash moves an agent file (and its metadata) to the trash directory.
|
|
func MoveAgentToTrash(agentFile, metaFile, name, trashBase string) (string, error) {
|
|
if err := validateTrashName(name); err != nil {
|
|
return "", fmt.Errorf("invalid trash name: %w", err)
|
|
}
|
|
|
|
timestamp := time.Now().Format("2006-01-02_15-04-05")
|
|
trashDir := filepath.Join(trashBase, name+"_"+timestamp)
|
|
|
|
if err := ensureUnderBase(trashBase, trashDir); err != nil {
|
|
return "", fmt.Errorf("trash path unsafe: %w", err)
|
|
}
|
|
|
|
if err := os.MkdirAll(trashDir, 0755); err != nil {
|
|
return "", fmt.Errorf("failed to create agent trash dir: %w", err)
|
|
}
|
|
|
|
// Move agent .md file
|
|
destFile := filepath.Join(trashDir, filepath.Base(agentFile))
|
|
if err := os.Rename(agentFile, destFile); err != nil {
|
|
// Fallback: copy then delete
|
|
data, readErr := os.ReadFile(agentFile)
|
|
if readErr != nil {
|
|
return "", fmt.Errorf("failed to read agent for trash: %w", readErr)
|
|
}
|
|
if writeErr := os.WriteFile(destFile, data, 0644); writeErr != nil {
|
|
return "", fmt.Errorf("failed to write agent to trash: %w", writeErr)
|
|
}
|
|
os.Remove(agentFile)
|
|
}
|
|
|
|
// Move metadata if exists
|
|
if metaFile != "" {
|
|
if _, err := os.Stat(metaFile); err == nil {
|
|
destMeta := filepath.Join(trashDir, filepath.Base(metaFile))
|
|
if err := os.Rename(metaFile, destMeta); err != nil {
|
|
data, _ := os.ReadFile(metaFile)
|
|
os.WriteFile(destMeta, data, 0644)
|
|
os.Remove(metaFile)
|
|
}
|
|
}
|
|
}
|
|
|
|
return trashDir, nil
|
|
}
|
|
|
|
// TrashEntry holds information about a trashed item.
|
|
type TrashEntry struct {
|
|
Name string // Original skill name
|
|
Timestamp string // Timestamp portion of dir name
|
|
Path string // Full path to trashed directory
|
|
Date time.Time // Parsed or stat-based date
|
|
Size int64 // Total size in bytes
|
|
Kind string // "skill" or "agent" — set by caller
|
|
LinkTarget string // Non-empty for a trashed link; never inventory its target
|
|
}
|
|
|
|
// MoveToTrash moves a skill directory or link entry to the trash.
|
|
// Links keep their target intact; relative link text becomes absolute so it
|
|
// still points to the same location after moving to trash and restoring.
|
|
func MoveToTrash(srcPath, name, trashBase string) (string, error) {
|
|
return moveToTrash(srcPath, name, trashBase, os.Rename)
|
|
}
|
|
|
|
func moveToTrash(srcPath, name, trashBase string, rename func(string, string) error) (string, error) {
|
|
if err := validateTrashName(name); err != nil {
|
|
return "", fmt.Errorf("invalid trash name: %w", err)
|
|
}
|
|
|
|
timestamp := time.Now().Format("2006-01-02_15-04-05")
|
|
trashName := name + "_" + timestamp
|
|
trashPath := filepath.Join(trashBase, trashName)
|
|
|
|
if err := ensureUnderBase(trashBase, trashPath); err != nil {
|
|
return "", fmt.Errorf("trash path unsafe: %w", err)
|
|
}
|
|
|
|
if err := os.MkdirAll(filepath.Dir(trashPath), 0755); err != nil {
|
|
return "", fmt.Errorf("failed to create trash directory: %w", err)
|
|
}
|
|
|
|
if utils.IsSymlinkOrJunction(srcPath) {
|
|
if err := moveLink(srcPath, trashPath, rename); err != nil {
|
|
return "", fmt.Errorf("failed to move link to trash: %w", err)
|
|
}
|
|
return trashPath, nil
|
|
}
|
|
|
|
// Try atomic rename first (same device)
|
|
if err := rename(srcPath, trashPath); err == nil {
|
|
return trashPath, nil
|
|
}
|
|
|
|
// Fallback: copy then delete (cross-device)
|
|
if err := copyDir(srcPath, trashPath); err != nil {
|
|
return "", fmt.Errorf("failed to move to trash: %w", err)
|
|
}
|
|
|
|
if err := os.RemoveAll(srcPath); err != nil {
|
|
return trashPath, fmt.Errorf("copied to trash but failed to remove original: %w", err)
|
|
}
|
|
|
|
return trashPath, nil
|
|
}
|
|
|
|
// List returns all trashed items sorted by date (newest first).
|
|
// Walks recursively to find nested entries (e.g., "org/_team-skills_<ts>").
|
|
func List(trashBase string) []TrashEntry {
|
|
var items []TrashEntry
|
|
base := filepath.Clean(trashBase)
|
|
|
|
filepath.WalkDir(trashBase, func(path string, d fs.DirEntry, err error) error {
|
|
if shouldSkipReservedAgentTrashSubtree(base, path, d) {
|
|
return fs.SkipDir
|
|
}
|
|
if err != nil || path == base {
|
|
return nil
|
|
}
|
|
isLink := utils.IsLinkMode(path, d.Type())
|
|
if !d.IsDir() && !isLink {
|
|
return nil
|
|
}
|
|
|
|
name, ts := parseTrashName(d.Name())
|
|
if name == "" {
|
|
return nil // intermediate directory — keep walking
|
|
}
|
|
|
|
// Compute full nested name from relative path
|
|
parentRel, _ := filepath.Rel(trashBase, filepath.Dir(path))
|
|
fullName := trashLogicalName(parentRel, name)
|
|
|
|
date, parseErr := time.Parse("2006-01-02_15-04-05", ts)
|
|
if parseErr != nil {
|
|
if info, serr := d.Info(); serr == nil {
|
|
date = info.ModTime()
|
|
}
|
|
}
|
|
|
|
linkTarget := ""
|
|
if isLink {
|
|
linkTarget, _ = utils.ResolveLinkTarget(path)
|
|
}
|
|
items = append(items, TrashEntry{
|
|
LinkTarget: linkTarget,
|
|
Name: fullName,
|
|
Timestamp: ts,
|
|
Path: path,
|
|
Date: date,
|
|
Size: dirSize(path),
|
|
})
|
|
|
|
if d.IsDir() {
|
|
return fs.SkipDir // don't descend into trashed content
|
|
}
|
|
return nil // SkipDir on a link would skip its remaining siblings
|
|
})
|
|
|
|
sort.Slice(items, func(i, j int) bool {
|
|
return items[i].Date.After(items[j].Date)
|
|
})
|
|
|
|
return items
|
|
}
|
|
|
|
// shouldSkipReservedAgentTrashSubtree prevents the skills trash root from
|
|
// recursively listing agent trash entries under the reserved "trash/agents" path.
|
|
// Agent trash is listed separately from AgentTrashDir()/ProjectAgentTrashDir().
|
|
func shouldSkipReservedAgentTrashSubtree(base, path string, d fs.DirEntry) bool {
|
|
if d == nil || !d.IsDir() {
|
|
return false
|
|
}
|
|
if filepath.Base(base) != "trash" {
|
|
return false
|
|
}
|
|
return filepath.Clean(path) == filepath.Join(base, reservedAgentTrashDir)
|
|
}
|
|
|
|
// Cleanup removes trashed items older than maxAge.
|
|
// Returns the number of items removed.
|
|
func Cleanup(trashBase string, maxAge time.Duration) (int, error) {
|
|
if maxAge == 0 {
|
|
maxAge = defaultMaxAge
|
|
}
|
|
|
|
items := List(trashBase)
|
|
cutoff := time.Now().Add(-maxAge)
|
|
removed := 0
|
|
|
|
for _, item := range items {
|
|
if item.Date.Before(cutoff) {
|
|
if err := ensureStrictlyUnderBase(trashBase, item.Path); err != nil {
|
|
return removed, fmt.Errorf("skip unsafe item %s: %w", item.Name, err)
|
|
}
|
|
if err := Delete(item.Path); err != nil {
|
|
return removed, fmt.Errorf("failed to clean up %s: %w", item.Name, err)
|
|
}
|
|
cleanEmptyParents(item.Path, trashBase)
|
|
removed++
|
|
}
|
|
}
|
|
|
|
return removed, nil
|
|
}
|
|
|
|
// MetadataFile returns where the metadata uninstall saved for the trash entry
|
|
// at entryPath is kept. It sits beside the entry, which may be a link.
|
|
func MetadataFile(entryPath string) string {
|
|
return entryPath + ".metadata.json"
|
|
}
|
|
|
|
// Delete permanently removes a trash entry and its saved metadata.
|
|
func Delete(entryPath string) error {
|
|
if err := os.RemoveAll(entryPath); err != nil {
|
|
return err
|
|
}
|
|
if err := os.Remove(MetadataFile(entryPath)); err != nil && !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// cleanEmptyParents removes empty parent directories between path and stopAt.
|
|
func cleanEmptyParents(path, stopAt string) {
|
|
stopAt = filepath.Clean(stopAt)
|
|
dir := filepath.Dir(filepath.Clean(path))
|
|
for dir != stopAt && dir != "." && dir != "/" {
|
|
entries, err := os.ReadDir(dir)
|
|
if err != nil || len(entries) > 0 {
|
|
break
|
|
}
|
|
os.Remove(dir)
|
|
dir = filepath.Dir(dir)
|
|
}
|
|
}
|
|
|
|
// TotalSize returns the total size of all trashed items in bytes.
|
|
func TotalSize(trashBase string) int64 {
|
|
items := List(trashBase)
|
|
var total int64
|
|
for _, item := range items {
|
|
total += item.Size
|
|
}
|
|
return total
|
|
}
|
|
|
|
// FindByName returns the most recent trashed item matching the given skill name.
|
|
// Returns nil if not found.
|
|
func FindByName(trashBase, name string) *TrashEntry {
|
|
items := List(trashBase)
|
|
for i := range items {
|
|
if items[i].Name == name {
|
|
return &items[i] // List is sorted newest-first
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Restore moves a trashed skill or link entry back to the destination directory.
|
|
// Returns an error if the destination already exists, including a broken link.
|
|
func Restore(entry *TrashEntry, destDir string, follow ...*sourcewalk.Follow) error {
|
|
return restore(entry, destDir, os.Rename, follow...)
|
|
}
|
|
|
|
func restore(entry *TrashEntry, destDir string, rename func(string, string) error, follow ...*sourcewalk.Follow) error {
|
|
if err := validateTrashName(entry.Name); err != nil {
|
|
return fmt.Errorf("invalid trash entry name: %w", err)
|
|
}
|
|
if strings.HasPrefix(entry.Name, ReplacedByInitDir+"/") {
|
|
return fmt.Errorf("%s is a tool's folder that init replaced with a link, and the source already holds the same skill; copy it back by hand from %s if you need it", entry.Name, entry.Path)
|
|
}
|
|
|
|
destPath := filepath.Join(destDir, entry.Name)
|
|
|
|
if err := ensureUnderBase(destDir, destPath); err != nil {
|
|
return fmt.Errorf("restore path unsafe: %w", err)
|
|
}
|
|
|
|
src, err := sourcefs.Create(destDir, follow...)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to open destination directory: %w", err)
|
|
}
|
|
defer src.Close()
|
|
name := filepath.FromSlash(entry.Name)
|
|
if err := src.CheckParent(name); err != nil {
|
|
return fmt.Errorf("restore path unsafe: %w", err)
|
|
}
|
|
// Check before creating parents so a refused restore keeps its trash copy.
|
|
if err := src.MkdirAll(filepath.Dir(name), 0755); err != nil {
|
|
return fmt.Errorf("failed to create destination directory: %w", err)
|
|
}
|
|
|
|
if _, err := src.Lstat(name); err == nil {
|
|
return fmt.Errorf("'%s' already exists in %s (use --force on uninstall to replace)", entry.Name, destDir)
|
|
} else if !os.IsNotExist(err) {
|
|
return fmt.Errorf("cannot access destination: %w", err)
|
|
}
|
|
|
|
if utils.IsSymlinkOrJunction(entry.Path) {
|
|
if err := moveLink(entry.Path, destPath, rename); err != nil {
|
|
return fmt.Errorf("failed to restore link: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Try atomic rename first
|
|
if err := src.MoveIn(entry.Path, name); err == nil {
|
|
return nil
|
|
} else if !sourcefs.IsCrossDevice(err) {
|
|
return fmt.Errorf("failed to restore: %w", err)
|
|
}
|
|
|
|
// Fallback: copy then delete
|
|
if err := src.CopyIn(entry.Path, name); err != nil {
|
|
return fmt.Errorf("failed to restore: %w", err)
|
|
}
|
|
|
|
if err := os.RemoveAll(entry.Path); err != nil {
|
|
return fmt.Errorf("restored but failed to remove trash entry: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// moveLink moves only the link entry, never copying or removing target contents.
|
|
// Recreate relative links before removing the source so relocation preserves
|
|
// their meaning without leaving a broken link when creation fails.
|
|
func moveLink(src, dst string, rename func(string, string) error) error {
|
|
text, readErr := os.Readlink(src)
|
|
var target string
|
|
if readErr == nil {
|
|
target = text
|
|
if filepath.IsAbs(text) {
|
|
if err := rename(src, dst); err == nil {
|
|
return nil
|
|
}
|
|
} else {
|
|
parent, err := filepath.Abs(filepath.Dir(src))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Cleaning the link text would change traversal through alias/../target.
|
|
target = parent + string(filepath.Separator) + text
|
|
}
|
|
} else {
|
|
var err error
|
|
target, err = utils.ResolveLinkTarget(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := recreateLink(src, target, dst); err != nil {
|
|
return err
|
|
}
|
|
if err := os.Remove(src); err != nil {
|
|
// Roll back the newly created entry; neither removal follows the link.
|
|
os.Remove(dst)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// recreateLink creates at dst a link to target of the same kind as the one at
|
|
// src. A junction stays a junction: a symlink would need Developer Mode or
|
|
// elevation on Windows, which the junction was chosen to avoid.
|
|
func recreateLink(src, target, dst string) error {
|
|
if utils.IsJunction(src) {
|
|
return utils.CreateJunction(dst, target)
|
|
}
|
|
return os.Symlink(target, dst)
|
|
}
|
|
|
|
// RestoreAgent restores agent files from a trashed directory back to the agent source.
|
|
// Unlike Restore (which moves the whole directory), this copies individual files
|
|
// from the trashed directory to destDir (since agents are file-based, not directory-based).
|
|
func RestoreAgent(entry *TrashEntry, destDir string) error {
|
|
if err := validateTrashName(entry.Name); err != nil {
|
|
return fmt.Errorf("invalid trash entry name: %w", err)
|
|
}
|
|
|
|
// Reconstruct subdirectory for nested agents (e.g., "demo/my-agent" → destDir/demo/)
|
|
targetDir := destDir
|
|
if subDir := filepath.Dir(entry.Name); subDir != "." {
|
|
targetDir = filepath.Join(destDir, subDir)
|
|
}
|
|
|
|
if err := ensureUnderBase(destDir, targetDir); err != nil {
|
|
return fmt.Errorf("restore path unsafe: %w", err)
|
|
}
|
|
|
|
if err := os.MkdirAll(targetDir, 0755); err != nil {
|
|
return fmt.Errorf("failed to create agent destination: %w", err)
|
|
}
|
|
|
|
// Read files from the trashed directory
|
|
entries, err := os.ReadDir(entry.Path)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read trashed agent: %w", err)
|
|
}
|
|
|
|
for _, e := range entries {
|
|
if e.IsDir() {
|
|
continue
|
|
}
|
|
srcPath := filepath.Join(entry.Path, e.Name())
|
|
destPath := filepath.Join(targetDir, e.Name())
|
|
|
|
if _, statErr := os.Stat(destPath); statErr == nil {
|
|
return fmt.Errorf("'%s' already exists in %s", e.Name(), targetDir)
|
|
}
|
|
|
|
// Try rename, fallback to copy
|
|
if renameErr := os.Rename(srcPath, destPath); renameErr != nil {
|
|
data, readErr := os.ReadFile(srcPath)
|
|
if readErr != nil {
|
|
return fmt.Errorf("failed to read %s: %w", e.Name(), readErr)
|
|
}
|
|
if writeErr := os.WriteFile(destPath, data, 0644); writeErr != nil {
|
|
return fmt.Errorf("failed to write %s: %w", e.Name(), writeErr)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Remove the trashed directory
|
|
if removeErr := os.RemoveAll(entry.Path); removeErr != nil {
|
|
return fmt.Errorf("restored but failed to remove trash entry: %w", removeErr)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// parseTrashName splits "skillname_YYYY-MM-DD_HH-MM-SS" into name and timestamp.
|
|
func parseTrashName(dirName string) (string, string) {
|
|
// Timestamp format: YYYY-MM-DD_HH-MM-SS (19 chars)
|
|
const tsLen = 19 // "2006-01-02_15-04-05"
|
|
// Need at least "x_" + timestamp
|
|
if len(dirName) < tsLen+2 {
|
|
return "", ""
|
|
}
|
|
|
|
// The timestamp is always the last 19 characters, preceded by "_"
|
|
sep := len(dirName) - tsLen - 1
|
|
if dirName[sep] != '_' {
|
|
return "", ""
|
|
}
|
|
|
|
name := dirName[:sep]
|
|
ts := dirName[sep+1:]
|
|
|
|
// Validate timestamp format
|
|
if _, err := time.Parse("2006-01-02_15-04-05", ts); err != nil {
|
|
return "", ""
|
|
}
|
|
|
|
return name, ts
|
|
}
|
|
|
|
// dirSize calculates total size of a directory.
|
|
func dirSize(path string) int64 {
|
|
var size int64
|
|
filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if !info.IsDir() {
|
|
size += info.Size()
|
|
}
|
|
return nil
|
|
})
|
|
return size
|
|
}
|
|
|
|
// copyDir copies a directory recursively.
|
|
func copyDir(src, dst string) error {
|
|
if err := os.MkdirAll(dst, 0755); err != nil {
|
|
return err
|
|
}
|
|
|
|
entries, err := os.ReadDir(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, entry := range entries {
|
|
srcPath := filepath.Join(src, entry.Name())
|
|
dstPath := filepath.Join(dst, entry.Name())
|
|
|
|
info, err := os.Lstat(srcPath)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
// Preserve link text without copying the target. Junctions may need
|
|
// ResolveLinkTarget, as in moveLink, and are recreated as junctions.
|
|
if utils.IsLinkMode(srcPath, info.Mode()) {
|
|
target, err := os.Readlink(srcPath)
|
|
if err != nil {
|
|
target, err = utils.ResolveLinkTarget(srcPath)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := recreateLink(srcPath, target, dstPath); err != nil {
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
|
|
if info.IsDir() {
|
|
if err := copyDir(srcPath, dstPath); err != nil {
|
|
return err
|
|
}
|
|
} else if info.Mode().IsRegular() {
|
|
if err := copyFile(srcPath, dstPath); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// copyFile copies a single file.
|
|
func copyFile(src, dst string) error {
|
|
srcFile, err := os.Open(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer srcFile.Close()
|
|
|
|
srcInfo, err := srcFile.Stat()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
dstFile, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, srcInfo.Mode())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer dstFile.Close()
|
|
|
|
_, err = io.Copy(dstFile, srcFile)
|
|
return err
|
|
}
|