fix: address review findings

This commit is contained in:
Willie
2026-07-30 01:34:52 +08:00
parent 262da080c0
commit 29bde9af3d
17 changed files with 423 additions and 104 deletions
+1 -1
View File
@@ -158,7 +158,7 @@ for p in "$(go env GOPATH)/bin/air" /go/bin/air /usr/local/go/bin/air; do
done
if [ -z "$AIR_BIN" ]; then
echo " air not found — installing..." >&2
go install github.com/air-verse/air@v1.67.0 # v1.67.3+ needs go >= 1.26
go install github.com/air-verse/air@v1.67.1 # v1.67.2+ needs go >= 1.26
AIR_BIN="$(go env GOPATH)/bin/air"
fi
+4 -2
View File
@@ -319,15 +319,17 @@ func planBackupCleanup(backups []backup.BackupInfo, cfg backup.CleanupConfig, no
}
size := backup.Size(backupInfo.Path)
totalSize += size
if cfg.MaxSizeMB > 0 && totalSize > cfg.MaxSizeMB*1024*1024 {
if !shouldRemove && cfg.MaxSizeMB > 0 && i > 0 &&
totalSize+size > cfg.MaxSizeMB*1024*1024 {
shouldRemove = true
}
if shouldRemove {
removed++
removedSize += size
continue
}
totalSize += size
}
return removed, removedSize
+63
View File
@@ -0,0 +1,63 @@
package main
import (
"os"
"path/filepath"
"testing"
"time"
"skillshare/internal/backup"
)
func TestPlanBackupCleanup_OverSizeCapKeepsNewestBackup(t *testing.T) {
backupPath := filepath.Join(t.TempDir(), "2026-07-30_00-00-00")
if err := os.MkdirAll(filepath.Join(backupPath, "claude"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(backupPath, "claude", "big.bin"), make([]byte, 2<<20), 0644); err != nil {
t.Fatal(err)
}
backups := []backup.BackupInfo{{
Timestamp: "2026-07-30_00-00-00",
Path: backupPath,
Date: time.Now(),
}}
removed, freed := planBackupCleanup(backups, backup.CleanupConfig{MaxSizeMB: 1}, time.Now())
if removed != 0 {
t.Errorf("removed = %d, want 0", removed)
}
if freed != 0 {
t.Errorf("freed = %d, want 0", freed)
}
}
func TestPlanBackupCleanup_SizeCapCountsOnlyRetainedBackups(t *testing.T) {
root := t.TempDir()
sizes := []int{400 << 10, 700 << 10, 400 << 10}
backups := make([]backup.BackupInfo, 0, len(sizes))
for i, size := range sizes {
path := filepath.Join(root, time.Now().Add(-time.Duration(i)*time.Hour).Format("2006-01-02_15-04-05"))
if err := os.MkdirAll(filepath.Join(path, "claude"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(path, "claude", "payload.bin"), make([]byte, size), 0644); err != nil {
t.Fatal(err)
}
backups = append(backups, backup.BackupInfo{
Timestamp: filepath.Base(path),
Path: path,
Date: time.Now().Add(-time.Duration(i) * time.Hour),
})
}
removed, freed := planBackupCleanup(backups, backup.CleanupConfig{MaxSizeMB: 1}, time.Now())
if removed != 1 {
t.Errorf("removed = %d, want 1", removed)
}
if freed != int64(sizes[1]) {
t.Errorf("freed = %d, want %d", freed, sizes[1])
}
}
+4 -4
View File
@@ -487,7 +487,7 @@ func checkTargets(cfg *config.Config, result *doctorResult, isProject bool) map[
result.addWarning()
}
targetIssues := checkTargetIssues(target, cfg.EffectiveSkillsSource())
targetIssues := checkTargetIssues(target, cfg.EffectiveSkillsSource(), mode)
// Target name header
fmt.Printf("%s%s%s\n", ui.Bold, name, ui.Reset)
@@ -519,7 +519,7 @@ func checkTargets(cfg *config.Config, result *doctorResult, isProject bool) map[
return cache
}
func checkTargetIssues(target config.TargetConfig, source string) []string {
func checkTargetIssues(target config.TargetConfig, source, mode string) []string {
sc := target.SkillsConfig()
var targetIssues []string
@@ -539,7 +539,7 @@ func checkTargetIssues(target config.TargetConfig, source string) []string {
// Check if it's a symlink. Relative links must resolve against the link's
// parent directory, not the current working directory.
if info.Mode()&os.ModeSymlink != 0 {
if mode == "symlink" && info.Mode()&os.ModeSymlink != 0 {
link, _ := os.Readlink(sc.Path)
absLink, err := utils.ResolveLinkTarget(sc.Path)
absSource, _ := filepath.Abs(source)
@@ -1017,7 +1017,7 @@ func checkDuplicateSkills(cfg *config.Config, result *doctorResult, discovered [
// The target dir is itself a link (symlink mode after sync), so its
// entries are the source itself, not target-local copies.
if utils.IsSymlinkOrJunction(sc.Path) {
if mode == "symlink" && utils.IsSymlinkOrJunction(sc.Path) {
continue
}
+22 -26
View File
@@ -28,7 +28,7 @@ type listOptions struct {
Pattern string // positional search pattern (case-insensitive)
TypeFilter string // --type: "tracked", "local", "github"
SortBy string // --sort: "name" (default), "newest", "oldest"
Status string // --status: "" (all), "enabled", "disabled"
Status listStatusFilter
}
// validTypeFilters lists accepted values for --type.
@@ -45,25 +45,21 @@ var validSortOptions = map[string]bool{
"oldest": true,
}
// validStatusFilters lists accepted values for --status.
var validStatusFilters = map[string]bool{
"all": true,
"enabled": true,
"disabled": true,
// validStatusFilters maps accepted --status values to their typed filter.
var validStatusFilters = map[string]listStatusFilter{
"all": statusFilterAll,
"enabled": statusFilterEnabled,
"disabled": statusFilterDisabled,
}
// parseStatusFilter validates a --status value and normalizes it.
// "all" normalizes to "" so it stays equivalent to omitting the flag —
// no filter applied, tracked-repo summary and footer unchanged.
func parseStatusFilter(raw string) (string, error) {
func parseStatusFilter(raw string) (listStatusFilter, error) {
v := strings.ToLower(raw)
if !validStatusFilters[v] {
return "", fmt.Errorf("invalid status %q: must be all, enabled, or disabled", raw)
status, ok := validStatusFilters[v]
if !ok {
return statusFilterAll, fmt.Errorf("invalid status %q: must be all, enabled, or disabled", raw)
}
if v == "all" {
return "", nil
}
return v, nil
return status, nil
}
// parseListArgs parses list command arguments into listOptions.
@@ -157,9 +153,9 @@ func parseListArgs(args []string) (listOptions, error) {
// filterSkillEntries filters skills by pattern, type, and status.
// Pattern matches case-insensitively against Name, RelPath, and Source.
// Status is "" (no filter), "enabled", or "disabled"; filters combine with AND.
func filterSkillEntries(skills []skillEntry, pattern, typeFilter, status string) []skillEntry {
if pattern == "" && typeFilter == "" && status == "" {
// Status uses statusFilterAll for no filter; filters combine with AND.
func filterSkillEntries(skills []skillEntry, pattern, typeFilter string, status listStatusFilter) []skillEntry {
if pattern == "" && typeFilter == "" && status == statusFilterAll {
return skills
}
@@ -167,7 +163,7 @@ func filterSkillEntries(skills []skillEntry, pattern, typeFilter, status string)
var result []skillEntry
for _, s := range skills {
// Status filter
if status != "" && s.Disabled != (status == "disabled") {
if status != statusFilterAll && s.Disabled != (status == statusFilterDisabled) {
continue
}
@@ -208,11 +204,11 @@ func filterSkillEntries(skills []skillEntry, pattern, typeFilter, status string)
// statusNote returns a " (status: enabled)" suffix for footers and messages,
// or "" when no status filter is active.
func statusNote(status string) string {
if status == "" {
func statusNote(status listStatusFilter) string {
if status == statusFilterAll {
return ""
}
return fmt.Sprintf(" (status: %s)", status)
return fmt.Sprintf(" (status: %s)", status.String())
}
// noMatchMessage builds the "no results" message for the active filter set.
@@ -225,7 +221,7 @@ func noMatchMessage(resourceLabel string, opts listOptions) string {
case opts.TypeFilter != "":
return fmt.Sprintf("No %s matching type %q%s", resourceLabel, opts.TypeFilter, statusNote(opts.Status))
default:
return fmt.Sprintf("No %s matching status %q", resourceLabel, opts.Status)
return fmt.Sprintf("No %s matching status %q", resourceLabel, opts.Status.String())
}
}
@@ -677,14 +673,14 @@ func cmdList(args []string) error {
total := len(allEntries)
// Status is NOT filtered here — the TUI needs both enabled and
// disabled entries loaded so the `s` key can restore them.
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, "")
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, statusFilterAll)
// Always sort: buildGroupedItems relies on contiguous top-group
// blocks, which the default sort guarantees (tracked → named
// locals → standalone).
sortSkillEntries(allEntries, opts.SortBy)
return listLoadResult{skills: toSkillItems(allEntries), totalCount: total}
}
action, skillName, skillKind, err := runListTUI(loadFn, "global", cfg.EffectiveSkillsSource(), cfg.EffectiveAgentsSource(), cfg.Targets, kind, statusFilterFrom(opts.Status))
action, skillName, skillKind, err := runListTUI(loadFn, "global", cfg.EffectiveSkillsSource(), cfg.EffectiveAgentsSource(), cfg.Targets, kind, opts.Status)
if err != nil {
return err
}
@@ -757,7 +753,7 @@ func cmdList(args []string) error {
sp.Success(fmt.Sprintf("Loaded %d %s", len(allEntries), resourceLabel))
}
totalCount := len(allEntries)
hasFilter := opts.Pattern != "" || opts.TypeFilter != "" || opts.Status != ""
hasFilter := opts.Pattern != "" || opts.TypeFilter != "" || opts.Status != statusFilterAll
// Apply filter and sort
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, opts.Status)
+3 -3
View File
@@ -54,11 +54,11 @@ func cmdListProject(root string, opts listOptions, kind resourceKindFilter) erro
total := len(allEntries)
// Status is NOT filtered here — the TUI needs both enabled and
// disabled entries loaded so the `s` key can restore them.
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, "")
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, statusFilterAll)
sortSkillEntries(allEntries, sortBy)
return listLoadResult{skills: toSkillItems(allEntries), totalCount: total}
}
action, skillName, skillKind, err := runListTUI(loadFn, "project", skillsSource, agentsSource, targets, kind, statusFilterFrom(opts.Status))
action, skillName, skillKind, err := runListTUI(loadFn, "project", skillsSource, agentsSource, targets, kind, opts.Status)
if err != nil {
return err
}
@@ -124,7 +124,7 @@ func cmdListProject(root string, opts listOptions, kind resourceKindFilter) erro
sp.Success(fmt.Sprintf("Loaded %d %s", len(allEntries), resourceLabel))
}
totalCount := len(allEntries)
hasFilter := opts.Pattern != "" || opts.TypeFilter != "" || opts.Status != ""
hasFilter := opts.Pattern != "" || opts.TypeFilter != "" || opts.Status != statusFilterAll
// Apply filter and sort
allEntries = filterSkillEntries(allEntries, opts.Pattern, opts.TypeFilter, opts.Status)
+24 -24
View File
@@ -6,14 +6,14 @@ func TestParseListArgs_Status(t *testing.T) {
tests := []struct {
name string
args []string
want string
want listStatusFilter
}{
{"space form", []string{"--status", "enabled"}, "enabled"},
{"equals form", []string{"--status=disabled"}, "disabled"},
{"case insensitive", []string{"--status", "DISABLED"}, "disabled"},
{"all normalizes to empty", []string{"--status", "all"}, ""},
{"all equals form", []string{"--status=ALL"}, ""},
{"absent", []string{}, ""},
{"space form", []string{"--status", "enabled"}, statusFilterEnabled},
{"equals form", []string{"--status=disabled"}, statusFilterDisabled},
{"case insensitive", []string{"--status", "DISABLED"}, statusFilterDisabled},
{"all", []string{"--status", "all"}, statusFilterAll},
{"all equals form", []string{"--status=ALL"}, statusFilterAll},
{"absent", []string{}, statusFilterAll},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
@@ -46,7 +46,7 @@ func TestParseListArgs_StatusCombinesWithOtherFilters(t *testing.T) {
if err != nil {
t.Fatalf("parseListArgs error = %v", err)
}
if opts.Pattern != "react" || opts.TypeFilter != "local" || opts.Status != "disabled" || opts.SortBy != "newest" {
if opts.Pattern != "react" || opts.TypeFilter != "local" || opts.Status != statusFilterDisabled || opts.SortBy != "newest" {
t.Errorf("got %+v, want pattern=react type=local status=disabled sort=newest", opts)
}
}
@@ -59,12 +59,12 @@ func TestFilterSkillEntries_Status(t *testing.T) {
}
tests := []struct {
status string
status listStatusFilter
want []string
}{
{"", []string{"on-a", "off-a", "on-b"}},
{"enabled", []string{"on-a", "on-b"}},
{"disabled", []string{"off-a"}},
{statusFilterAll, []string{"on-a", "off-a", "on-b"}},
{statusFilterEnabled, []string{"on-a", "on-b"}},
{statusFilterDisabled, []string{"off-a"}},
}
for _, tc := range tests {
got := filterSkillEntries(entries, "", "", tc.status)
@@ -86,14 +86,14 @@ func TestFilterSkillEntries_StatusAndPatternAreAND(t *testing.T) {
{Name: "vue-off", RelPath: "vue-off", Disabled: true},
}
got := filterSkillEntries(entries, "react", "", "disabled")
got := filterSkillEntries(entries, "react", "", statusFilterDisabled)
if len(got) != 1 || got[0].Name != "react-off" {
t.Fatalf("got %+v, want only react-off", got)
}
}
func TestNoMatchMessage_StatusOnly(t *testing.T) {
got := noMatchMessage("skills", listOptions{Status: "disabled"})
got := noMatchMessage("skills", listOptions{Status: statusFilterDisabled})
want := `No skills matching status "disabled"`
if got != want {
t.Errorf("got %q, want %q", got, want)
@@ -101,25 +101,25 @@ func TestNoMatchMessage_StatusOnly(t *testing.T) {
}
func TestNoMatchMessage_StatusWithOtherFilters(t *testing.T) {
got := noMatchMessage("agents", listOptions{Pattern: "react", Status: "enabled"})
got := noMatchMessage("agents", listOptions{Pattern: "react", Status: statusFilterEnabled})
want := `No agents matching "react" (status: enabled)`
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestStatusFilterFrom(t *testing.T) {
func TestListStatusFilterString(t *testing.T) {
tests := []struct {
status string
want listStatusFilter
status listStatusFilter
want string
}{
{"", statusFilterAll},
{"enabled", statusFilterEnabled},
{"disabled", statusFilterDisabled},
{statusFilterAll, "all"},
{statusFilterEnabled, "enabled"},
{statusFilterDisabled, "disabled"},
}
for _, tc := range tests {
if got := statusFilterFrom(tc.status); got != tc.want {
t.Errorf("statusFilterFrom(%q) = %v, want %v", tc.status, got, tc.want)
if got := tc.status.String(); got != tc.want {
t.Errorf("%v.String() = %q, want %q", tc.status, got, tc.want)
}
}
}
@@ -127,7 +127,7 @@ func TestStatusFilterFrom(t *testing.T) {
// The `s` key cycles All → Enabled → Disabled → All from whatever --status
// seeded, so an initial filter never traps the user.
func TestStatusFilterCyclesBackToAll(t *testing.T) {
s := statusFilterFrom("disabled")
s := statusFilterDisabled
if next := (s + 1) % 3; next != statusFilterAll {
t.Errorf("cycling from Disabled = %v, want All", next)
}
+8 -9
View File
@@ -43,16 +43,15 @@ const (
statusFilterDisabled // show only disabled
)
// statusFilterFrom maps a --status option value to the TUI's initial filter.
// An empty value (or "all") starts on statusFilterAll.
func statusFilterFrom(status string) listStatusFilter {
switch status {
case "enabled":
return statusFilterEnabled
case "disabled":
return statusFilterDisabled
// String returns the CLI representation of the status filter.
func (s listStatusFilter) String() string {
switch s {
case statusFilterEnabled:
return "enabled"
case statusFilterDisabled:
return "disabled"
default:
return statusFilterAll
return "all"
}
}
+10 -2
View File
@@ -449,7 +449,11 @@ func syncOutputJSON(results []syncTargetResult, dryRun bool, start time.Time, iS
func backupTargetsBeforeSync(cfg *config.Config) {
// Pre-sync backups are automatic, so retention must be too — otherwise
// every sync adds a snapshot that nothing ever removes.
defer backup.Cleanup(backup.DefaultCleanupConfig())
defer func() {
if _, err := backup.Cleanup(backup.DefaultCleanupConfig()); err != nil {
ui.Warning("Failed to clean up old backups: %v", err)
}
}()
backedUp := false
for name, target := range cfg.Targets {
@@ -467,7 +471,11 @@ func backupTargetsBeforeSync(cfg *config.Config) {
// Also backup agent targets if any exist.
backupDir, agentTargets, err := resolveGlobalAgentBackupContextFromCfg(cfg)
if err != nil || len(agentTargets) == 0 {
if err != nil {
ui.Warning("Failed to resolve agent backup targets: %v", err)
return
}
if len(agentTargets) == 0 {
return
}
for _, at := range agentTargets {
+16 -3
View File
@@ -55,8 +55,17 @@ func syncAgentsGlobal(cfg *config.Config, dryRun, force, jsonOutput bool, start
// Backup agent targets before sync (non-dry-run only).
if !dryRun && !jsonOutput {
backupDir, agentTargets, _ := resolveGlobalAgentBackupContextFromCfg(cfg)
defer backup.CleanupInDir(backupDir, backup.DefaultCleanupConfig())
backupDir, agentTargets, backupErr := resolveGlobalAgentBackupContextFromCfg(cfg)
if backupErr != nil {
ui.Warning("Failed to resolve agent backup targets: %v", backupErr)
agentTargets = nil
} else {
defer func() {
if _, err := backup.CleanupInDir(backupDir, backup.DefaultCleanupConfig()); err != nil {
ui.Warning("Failed to clean up old agent backups: %v", err)
}
}()
}
backedUp := false
for _, at := range agentTargets {
entryName := at.name + "-agents"
@@ -184,7 +193,11 @@ func syncAgentsProject(projectRoot string, dryRun, force, jsonOutput bool, start
// Backup agent targets before sync (non-dry-run only).
if !dryRun && !jsonOutput {
backupDir := filepath.Join(projectRoot, ".skillshare", "backups")
defer backup.CleanupInDir(backupDir, backup.DefaultCleanupConfig())
defer func() {
if _, err := backup.CleanupInDir(backupDir, backup.DefaultCleanupConfig()); err != nil {
ui.Warning("Failed to clean up old project agent backups: %v", err)
}
}()
backedUp := false
for _, entry := range projCfg.Targets {
agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot)
+2 -2
View File
@@ -26,8 +26,8 @@ RUN apt-get update \
&& rm -rf /var/lib/apt/lists/*
# Install Go development tools
# air pinned: v1.67.3+ requires go >= 1.26, image runs GO_VERSION with GOTOOLCHAIN=local
RUN go install github.com/air-verse/air@v1.67.0 \
# air pinned: v1.67.2+ requires go >= 1.26, image runs GO_VERSION with GOTOOLCHAIN=local
RUN go install github.com/air-verse/air@v1.67.1 \
&& go install github.com/go-delve/delve/cmd/dlv@latest
# Copy node runtime from ui-builder stage (for devcontainer / interactive use)
+83 -10
View File
@@ -1,16 +1,20 @@
package backup
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"
"skillshare/internal/config"
)
const stagingDirPrefix = ".snapshot-"
// BackupDir returns the global backup directory path.
func BackupDir() string {
return filepath.Join(config.DataDir(), "backups")
@@ -29,6 +33,10 @@ func Create(targetName, targetPath string) (string, error) {
// CreateInDir creates a backup of the target directory in the specified backup dir.
// Returns the backup path, or ("", nil) when there is nothing to back up.
func CreateInDir(backupDir, targetName, targetPath string) (string, error) {
return createInDir(backupDir, targetName, targetPath, copyDir)
}
func createInDir(backupDir, targetName, targetPath string, copyDirectory func(string, string) error) (backupPath string, retErr error) {
if backupDir == "" {
return "", fmt.Errorf("cannot determine backup directory: home directory not found")
}
@@ -49,17 +57,47 @@ func CreateInDir(backupDir, targetName, targetPath string) (string, error) {
// Check if directory has any content
entries, err := os.ReadDir(targetPath)
if err != nil || len(entries) == 0 {
if err != nil {
return "", fmt.Errorf("failed to inspect backup target: %w", err)
}
if len(entries) == 0 {
return "", nil // Empty, nothing to backup
}
// Create backup directory with timestamp
// Copy into a hidden staging directory so a failed copy can never be
// discovered or restored as a valid snapshot.
timestamp := time.Now().Format("2006-01-02_15-04-05")
backupPath := filepath.Join(backupDir, timestamp, targetName)
if err := os.MkdirAll(backupPath, 0755); err != nil {
timestampDir := filepath.Join(backupDir, timestamp)
if err := os.MkdirAll(backupDir, 0755); err != nil {
return "", fmt.Errorf("failed to create backup directory: %w", err)
}
stagingPath := ""
cleanupStaging := false
defer func() {
var cleanupErrs []error
if cleanupStaging {
if err := os.RemoveAll(stagingPath); err != nil {
cleanupErrs = append(cleanupErrs, fmt.Errorf("remove incomplete backup: %w", err))
}
}
if backupPath == "" {
if err := removeDirIfEmpty(timestampDir); err != nil {
cleanupErrs = append(cleanupErrs, fmt.Errorf("remove empty backup timestamp: %w", err))
}
}
if cleanupErr := errors.Join(cleanupErrs...); cleanupErr != nil {
retErr = errors.Join(retErr, cleanupErr)
}
}()
stagingPath, err = os.MkdirTemp(backupDir, stagingDirPrefix)
if err != nil {
return "", fmt.Errorf("failed to create backup staging directory: %w", err)
}
cleanupStaging = true
if err := os.Chmod(stagingPath, 0755); err != nil {
return "", fmt.Errorf("failed to set backup staging permissions: %w", err)
}
// Copy target contents to backup. copyDir skips symlinks: a merge-mode
// skill symlink points into the source, which is the single source of
@@ -67,22 +105,57 @@ func CreateInDir(backupDir, targetName, targetPath string) (string, error) {
// content (weights, .venv, browser profiles) into every snapshot.
// Only local, non-symlinked content is at risk from sync, so only that
// is worth backing up. Symlinks are recreated by `skillshare sync`.
if err := copyDir(targetPath, backupPath); err != nil {
if err := copyDirectory(targetPath, stagingPath); err != nil {
return "", fmt.Errorf("failed to backup: %w", err)
}
// A target holding nothing but symlinks yields an empty backup. Discard it:
// an empty restore point is useless and would consume a MaxCount slot,
// evicting older snapshots that do have content.
if copied, _ := os.ReadDir(backupPath); len(copied) == 0 {
os.Remove(backupPath)
os.Remove(filepath.Dir(backupPath)) // only succeeds if no other target wrote here
copied, err := os.ReadDir(stagingPath)
if err != nil {
return "", fmt.Errorf("failed to inspect staged backup: %w", err)
}
if len(copied) == 0 {
return "", nil
}
if err := os.MkdirAll(timestampDir, 0755); err != nil {
return "", fmt.Errorf("failed to create backup timestamp directory: %w", err)
}
backupPath = filepath.Join(timestampDir, targetName)
if _, err := os.Lstat(backupPath); err == nil {
// Timestamp precision is one second. If the same target is backed up
// twice within that window, preserve the already completed snapshot.
return backupPath, nil
} else if !os.IsNotExist(err) {
return "", fmt.Errorf("failed to inspect backup path: %w", err)
}
if err := os.Rename(stagingPath, backupPath); err != nil {
backupPath = ""
return "", fmt.Errorf("failed to finalize backup: %w", err)
}
cleanupStaging = false
return backupPath, nil
}
func removeDirIfEmpty(path string) error {
entries, err := os.ReadDir(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
if len(entries) != 0 {
return nil
}
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
// List returns all backups from the global backup dir, sorted by date (newest first).
func List() ([]BackupInfo, error) {
return ListInDir(BackupDir())
@@ -104,7 +177,7 @@ func ListInDir(backupDir string) ([]BackupInfo, error) {
var backups []BackupInfo
for _, entry := range entries {
if !entry.IsDir() {
if !entry.IsDir() || strings.HasPrefix(entry.Name(), stagingDirPrefix) {
continue
}
+105
View File
@@ -1,6 +1,7 @@
package backup
import (
"errors"
"os"
"path/filepath"
"testing"
@@ -168,6 +169,47 @@ func TestCopyDir_MergeMode_BacksUpOnlyLocalSkills(t *testing.T) {
}
}
func TestCreateInDir_CopyFailureRemovesIncompleteSnapshot(t *testing.T) {
backupDir := t.TempDir()
targetDir := t.TempDir()
if err := os.MkdirAll(filepath.Join(targetDir, "local-skill"), 0755); err != nil {
t.Fatal(err)
}
writeTestFile(t, filepath.Join(targetDir, "local-skill", "SKILL.md"), "# Local")
copyErr := errors.New("copy failed")
listedDuringCopy := false
backupPath, err := createInDir(backupDir, "claude", targetDir, func(_, dst string) error {
if err := os.MkdirAll(filepath.Join(dst, "local-skill"), 0755); err != nil {
t.Fatal(err)
}
writeTestFile(t, filepath.Join(dst, "local-skill", "partial.txt"), "partial")
backups, err := ListInDir(backupDir)
if err != nil {
t.Fatal(err)
}
listedDuringCopy = len(backups) != 0
return copyErr
})
if !errors.Is(err, copyErr) {
t.Fatalf("createInDir error = %v, want %v", err, copyErr)
}
if backupPath != "" {
t.Errorf("backupPath = %q, want empty", backupPath)
}
if listedDuringCopy {
t.Error("staging snapshot was listed as a completed backup")
}
backups, err := ListInDir(backupDir)
if err != nil {
t.Fatal(err)
}
if len(backups) != 0 {
t.Fatalf("incomplete snapshot was retained: %+v", backups)
}
}
func TestCleanupInDir_OverSizeCap_KeepsNewestBackup(t *testing.T) {
backupDir := t.TempDir()
payload := make([]byte, 2<<20) // 2 MB — each snapshot alone exceeds the 1 MB cap
@@ -203,6 +245,69 @@ func TestCleanupInDir_OverSizeCap_KeepsNewestBackup(t *testing.T) {
}
}
func TestCleanupInDir_SizeCapCountsOnlyRetainedBackups(t *testing.T) {
backupDir := t.TempDir()
base := time.Now().Add(-3 * time.Hour)
snapshots := []struct {
name string
size int
}{
{"2026-01-01_00-00-00", 400 << 10},
{"2026-01-02_00-00-00", 700 << 10},
{"2026-01-03_00-00-00", 400 << 10},
}
for i, snapshot := range snapshots {
dir := filepath.Join(backupDir, snapshot.name, "claude")
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "payload.bin"), make([]byte, snapshot.size), 0644); err != nil {
t.Fatal(err)
}
stamp := base.Add(time.Duration(i) * time.Hour)
if err := os.Chtimes(filepath.Join(backupDir, snapshot.name), stamp, stamp); err != nil {
t.Fatal(err)
}
}
removed, err := CleanupInDir(backupDir, CleanupConfig{MaxSizeMB: 1})
if err != nil {
t.Fatalf("CleanupInDir failed: %v", err)
}
if removed != 1 {
t.Fatalf("removed = %d, want 1", removed)
}
for _, name := range []string{"2026-01-01_00-00-00", "2026-01-03_00-00-00"} {
if _, err := os.Stat(filepath.Join(backupDir, name, "claude", "payload.bin")); err != nil {
t.Errorf("retained backup %s is missing: %v", name, err)
}
}
if _, err := os.Stat(filepath.Join(backupDir, "2026-01-02_00-00-00")); !os.IsNotExist(err) {
t.Errorf("over-cap backup should be removed, stat error = %v", err)
}
}
func TestCleanupInDir_IgnoresActiveStagingDirectory(t *testing.T) {
backupDir := t.TempDir()
stagingPath, err := os.MkdirTemp(backupDir, stagingDirPrefix)
if err != nil {
t.Fatal(err)
}
removed, err := CleanupInDir(backupDir, DefaultCleanupConfig())
if err != nil {
t.Fatalf("CleanupInDir failed: %v", err)
}
if removed != 0 {
t.Errorf("removed = %d, want 0", removed)
}
if _, err := os.Stat(stagingPath); err != nil {
t.Errorf("active staging directory was removed: %v", err)
}
}
func TestBackupDir_RespectsXDGDataHome(t *testing.T) {
t.Setenv("XDG_DATA_HOME", "/custom/data")
+34 -11
View File
@@ -1,8 +1,11 @@
package backup
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
@@ -43,6 +46,7 @@ func CleanupInDir(backupDir string, cfg CleanupConfig) (int, error) {
removed := 0
now := time.Now()
var totalSize int64
var cleanupErrs []error
// Backups are sorted by date (newest first)
for i, backup := range backups {
@@ -62,24 +66,29 @@ func CleanupInDir(backupDir string, cfg CleanupConfig) (int, error) {
// i > 0 always keeps the newest backup: a single snapshot larger than
// the cap must not leave the user with no restore point at all.
size := dirSize(backup.Path)
totalSize += size
if cfg.MaxSizeMB > 0 && i > 0 && totalSize > cfg.MaxSizeMB*1024*1024 {
if !shouldRemove && cfg.MaxSizeMB > 0 && i > 0 &&
totalSize+size > cfg.MaxSizeMB*1024*1024 {
shouldRemove = true
}
if shouldRemove {
if err := os.RemoveAll(backup.Path); err != nil {
// Log but continue with other backups
cleanupErrs = append(cleanupErrs, fmt.Errorf("remove backup %s: %w", backup.Timestamp, err))
totalSize += size
continue
}
removed++
continue
}
totalSize += size
}
// Clean up empty timestamp directories
cleanEmptyDirs(backupDir)
if err := cleanEmptyDirs(backupDir); err != nil {
cleanupErrs = append(cleanupErrs, err)
}
return removed, nil
return removed, errors.Join(cleanupErrs...)
}
// CleanupByAge removes backups older than the specified duration.
@@ -109,26 +118,40 @@ func dirSize(path string) int64 {
return size
}
// cleanEmptyDirs removes empty directories in the backup directory
func cleanEmptyDirs(path string) {
// cleanEmptyDirs removes empty directories in the backup directory.
func cleanEmptyDirs(path string) error {
if path == "" {
return
return nil
}
entries, err := os.ReadDir(path)
if err != nil {
return
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("read backup directory: %w", err)
}
var cleanupErrs []error
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), stagingDirPrefix) {
continue
}
if entry.IsDir() {
subPath := filepath.Join(path, entry.Name())
subEntries, _ := os.ReadDir(subPath)
subEntries, err := os.ReadDir(subPath)
if err != nil {
cleanupErrs = append(cleanupErrs, fmt.Errorf("read backup timestamp %s: %w", entry.Name(), err))
continue
}
if len(subEntries) == 0 {
os.Remove(subPath)
if err := os.Remove(subPath); err != nil && !os.IsNotExist(err) {
cleanupErrs = append(cleanupErrs, fmt.Errorf("remove empty backup timestamp %s: %w", entry.Name(), err))
}
}
}
}
return errors.Join(cleanupErrs...)
}
// Size returns the total size of a backup directory in bytes
+12 -6
View File
@@ -83,7 +83,7 @@ targets:
// protects. Synced agents are symlinks into the source and are recreated
// by `sync`, so they are deliberately not backed up (issue #252).
localPath := filepath.Join(claudeAgents, "local-helper.md")
os.WriteFile(localPath, []byte("# Local helper"), 0644)
sb.WriteFile(localPath, "# Local helper")
// Sync then backup
sb.RunCLI("sync", "agents")
@@ -96,7 +96,9 @@ targets:
}
// Delete the local agent from target
os.Remove(localPath)
if err := os.Remove(localPath); err != nil {
t.Fatalf("remove local agent: %v", err)
}
// Restore
result := sb.RunCLI("restore", "agents", "claude", "--force")
@@ -138,8 +140,10 @@ func TestBackup_Agents_ProjectMode_CreatesBackup(t *testing.T) {
// Local agent — synced agents are symlinks and are not backed up (#252),
// so without local content there is nothing to snapshot.
os.WriteFile(filepath.Join(projectDir, ".claude", "agents", "local-helper.md"),
[]byte("# Local helper"), 0644)
sb.WriteFile(
filepath.Join(projectDir, ".claude", "agents", "local-helper.md"),
"# Local helper",
)
// Sync agents first
result := sb.RunCLIInDir(projectDir, "sync", "-p", "agents")
@@ -190,7 +194,7 @@ func TestBackup_Agents_ProjectMode_RestoreRoundTrip(t *testing.T) {
// by `sync`, so they are deliberately not backed up (issue #252).
claudeAgents := filepath.Join(projectDir, ".claude", "agents")
localPath := filepath.Join(claudeAgents, "local-helper.md")
os.WriteFile(localPath, []byte("# Local helper"), 0644)
sb.WriteFile(localPath, "# Local helper")
// Sync → backup
sb.RunCLIInDir(projectDir, "sync", "-p", "agents")
@@ -203,7 +207,9 @@ func TestBackup_Agents_ProjectMode_RestoreRoundTrip(t *testing.T) {
}
// Delete the local agent from target
os.Remove(localPath)
if err := os.Remove(localPath); err != nil {
t.Fatalf("remove local agent: %v", err)
}
// Restore
result := sb.RunCLIInDir(projectDir, "restore", "-p", "agents", "claude", "--force")
+31
View File
@@ -933,3 +933,34 @@ func TestDoctorProject_RelativeSymlink_NoFalsePositives(t *testing.T) {
t.Errorf("doctor -p misreported valid relative symlinks:\n%s", out)
}
}
func TestDoctor_CopyModeExternalSymlink_ChecksDuplicateSkills(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
sb.CreateSkill("duplicate-skill", map[string]string{"SKILL.md": "# Source"})
realTarget := sb.CreateTarget("real-copy-target")
localSkill := filepath.Join(realTarget, "duplicate-skill")
if err := os.MkdirAll(localSkill, 0755); err != nil {
t.Fatal(err)
}
sb.WriteFile(filepath.Join(localSkill, "SKILL.md"), "# Local")
linkedTarget := filepath.Join(sb.Home, "linked-copy-target")
if err := os.Symlink(realTarget, linkedTarget); err != nil {
t.Skipf("symlink not supported: %v", err)
}
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
copilot:
path: ` + linkedTarget + `
mode: copy
`)
result := sb.RunCLI("doctor", "-g")
result.AssertSuccess(t)
result.AssertOutputContains(t, "Duplicate skills")
result.AssertOutputContains(t, "duplicate-skill")
}
+1 -1
View File
@@ -115,7 +115,7 @@ func TestListProject_FilterByStatus(t *testing.T) {
sb.CreateProjectSkill(projectRoot, "on-skill", map[string]string{"SKILL.md": "# On"})
sb.CreateProjectSkill(projectRoot, "off-skill", map[string]string{"SKILL.md": "# Off"})
skillsDir := filepath.Join(projectRoot, ".skillshare", "skills")
os.WriteFile(filepath.Join(skillsDir, ".skillignore"), []byte("off-skill\n"), 0644)
sb.WriteFile(filepath.Join(skillsDir, ".skillignore"), "off-skill\n")
enabled := sb.RunCLIInDir(projectRoot, "list", "-p", "--no-tui", "--status", "enabled")
enabled.AssertSuccess(t)