mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-20 20:34:19 +00:00
fix(cli): ensure --json mode outputs pure JSON to stdout
Address code review feedback from PR #67: - Move all dry-run diagnostic messages (internal/sync) from stdout to stderr so they don't pollute JSON output - Suppress UI output (spinners, headers, warnings) in uninstall --json mode by adding jsonOutput guards across all phases - Return nil after writeJSONError to prevent dual output (JSON + plain text error) in install and sync commands - Handle json.MarshalIndent error in writeJSONError with stderr fallback - Merge duplicated discovery logic (JSON vs non-JSON branches) in sync, sync_project, diff, and collect using nullable spinner pattern - Remove checkRepoDirty alias in status.go, call isRepoDirty directly - Remove extractJSON test workaround — tests now assert stdout is valid JSON directly, enforcing the clean-stdout contract
This commit is contained in:
+50
-45
@@ -121,63 +121,68 @@ func cmdCollect(args []string) error {
|
||||
}
|
||||
|
||||
// Collect all local skills
|
||||
var sp *ui.Spinner
|
||||
if !jsonOutput {
|
||||
ui.Header(ui.WithModeLabel("Collect"))
|
||||
sp := ui.StartSpinner("Scanning for local skills...")
|
||||
allLocalSkills := collectLocalSkills(targets, cfg.Source)
|
||||
if len(allLocalSkills) == 0 {
|
||||
sp.Success("No local skills found")
|
||||
return nil
|
||||
}
|
||||
sp.Success(fmt.Sprintf("Found %d local skill(s)", len(allLocalSkills)))
|
||||
|
||||
// Display found skills
|
||||
displayLocalSkills(allLocalSkills)
|
||||
|
||||
if dryRun {
|
||||
ui.Info("Dry run - no changes made")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Confirm unless --force
|
||||
if !force {
|
||||
if !confirmCollect() {
|
||||
ui.Info("Cancelled")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Execute collect
|
||||
err = executeCollect(allLocalSkills, cfg.Source, dryRun, force)
|
||||
logCollectOp(config.ConfigPath(), start, err)
|
||||
return err
|
||||
sp = ui.StartSpinner("Scanning for local skills...")
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Scanning for local skills...\n")
|
||||
}
|
||||
|
||||
// JSON mode: suppress UI output
|
||||
fmt.Fprintf(os.Stderr, "Scanning for local skills...\n")
|
||||
allLocalSkills := collectLocalSkills(targets, cfg.Source)
|
||||
|
||||
if len(allLocalSkills) == 0 {
|
||||
fmt.Fprintf(os.Stderr, "No local skills found\n")
|
||||
return collectOutputJSON(nil, dryRun, start, nil)
|
||||
if sp != nil {
|
||||
sp.Success("No local skills found")
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "No local skills found\n")
|
||||
}
|
||||
if jsonOutput {
|
||||
return collectOutputJSON(nil, dryRun, start, nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if sp != nil {
|
||||
sp.Success(fmt.Sprintf("Found %d local skill(s)", len(allLocalSkills)))
|
||||
displayLocalSkills(allLocalSkills)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Found %d local skill(s)\n", len(allLocalSkills))
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Found %d local skill(s)\n", len(allLocalSkills))
|
||||
|
||||
if dryRun {
|
||||
names := make([]string, len(allLocalSkills))
|
||||
for i, s := range allLocalSkills {
|
||||
names[i] = s.Name
|
||||
if jsonOutput {
|
||||
names := make([]string, len(allLocalSkills))
|
||||
for i, s := range allLocalSkills {
|
||||
names[i] = s.Name
|
||||
}
|
||||
logCollectOp(config.ConfigPath(), start, nil)
|
||||
return collectOutputJSON(&sync.PullResult{Pulled: names}, true, start, nil)
|
||||
}
|
||||
logCollectOp(config.ConfigPath(), start, nil)
|
||||
return collectOutputJSON(&sync.PullResult{Pulled: names}, true, start, nil)
|
||||
ui.Info("Dry run - no changes made")
|
||||
return nil
|
||||
}
|
||||
|
||||
// --json implies --force, so no confirmation needed
|
||||
result, collectErr := sync.PullSkills(allLocalSkills, cfg.Source, sync.PullOptions{
|
||||
DryRun: dryRun,
|
||||
Force: force,
|
||||
})
|
||||
logCollectOp(config.ConfigPath(), start, collectErr)
|
||||
return collectOutputJSON(result, dryRun, start, collectErr)
|
||||
// Confirm unless --force (JSON implies force)
|
||||
if !force {
|
||||
if !confirmCollect() {
|
||||
ui.Info("Cancelled")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
result, collectErr := sync.PullSkills(allLocalSkills, cfg.Source, sync.PullOptions{
|
||||
DryRun: dryRun,
|
||||
Force: force,
|
||||
})
|
||||
logCollectOp(config.ConfigPath(), start, collectErr)
|
||||
return collectOutputJSON(result, dryRun, start, collectErr)
|
||||
}
|
||||
|
||||
err = executeCollect(allLocalSkills, cfg.Source, dryRun, force)
|
||||
logCollectOp(config.ConfigPath(), start, err)
|
||||
return err
|
||||
}
|
||||
|
||||
func logCollectOp(cfgPath string, start time.Time, cmdErr error) {
|
||||
|
||||
+10
-13
@@ -375,21 +375,18 @@ func cmdDiffGlobal(targetName string, opts diffRenderOpts, start time.Time) erro
|
||||
return err
|
||||
}
|
||||
|
||||
var discovered []sync.DiscoveredSkill
|
||||
if opts.jsonOutput {
|
||||
var discoverErr error
|
||||
discovered, discoverErr = sync.DiscoverSourceSkills(cfg.Source)
|
||||
if discoverErr != nil {
|
||||
return fmt.Errorf("failed to discover skills: %w", discoverErr)
|
||||
}
|
||||
} else {
|
||||
spinner := ui.StartSpinner("Discovering skills")
|
||||
var discoverErr error
|
||||
discovered, discoverErr = sync.DiscoverSourceSkills(cfg.Source)
|
||||
if discoverErr != nil {
|
||||
var spinner *ui.Spinner
|
||||
if !opts.jsonOutput {
|
||||
spinner = ui.StartSpinner("Discovering skills")
|
||||
}
|
||||
discovered, discoverErr := sync.DiscoverSourceSkills(cfg.Source)
|
||||
if discoverErr != nil {
|
||||
if spinner != nil {
|
||||
spinner.Fail("Discovery failed")
|
||||
return fmt.Errorf("failed to discover skills: %w", discoverErr)
|
||||
}
|
||||
return fmt.Errorf("failed to discover skills: %w", discoverErr)
|
||||
}
|
||||
if spinner != nil {
|
||||
spinner.Success(fmt.Sprintf("Discovered %d skills", len(discovered)))
|
||||
}
|
||||
|
||||
|
||||
@@ -307,6 +307,7 @@ func cmdInstall(args []string) error {
|
||||
if err != nil {
|
||||
if parsed.jsonOutput {
|
||||
writeJSONError(err)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("failed to load config: %w", err)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,12 @@ func writeJSON(v any) error {
|
||||
// writeJSONError writes a JSON error object to stdout.
|
||||
// Used when a command fails but we still need parseable JSON output.
|
||||
func writeJSONError(err error) {
|
||||
out, _ := json.MarshalIndent(map[string]string{"error": err.Error()}, "", " ")
|
||||
out, merr := json.MarshalIndent(map[string]string{"error": err.Error()}, "", " ")
|
||||
if merr != nil {
|
||||
fmt.Fprintf(os.Stderr, "json marshal error: %v\n", merr)
|
||||
fmt.Printf("{\"error\": %q}\n", err.Error())
|
||||
return
|
||||
}
|
||||
fmt.Println(string(out))
|
||||
}
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ func cmdStatus(args []string) error {
|
||||
skillCount++
|
||||
}
|
||||
}
|
||||
dirty, _ := checkRepoDirty(repoPath)
|
||||
dirty, _ := isRepoDirty(repoPath)
|
||||
output.TrackedRepos = append(output.TrackedRepos, statusJSONRepo{
|
||||
Name: repoName,
|
||||
SkillCount: skillCount,
|
||||
@@ -204,7 +204,7 @@ func printTrackedReposStatus(cfg *config.Config, discovered []sync.DiscoveredSki
|
||||
|
||||
statusStr := "up-to-date"
|
||||
statusIcon := "✓"
|
||||
if isDirty, _ := checkRepoDirty(repoPath); isDirty {
|
||||
if isDirty, _ := isRepoDirty(repoPath); isDirty {
|
||||
statusStr = "has uncommitted changes"
|
||||
statusIcon = "!"
|
||||
}
|
||||
@@ -237,12 +237,6 @@ func extractTrackedRepos(discovered []sync.DiscoveredSkill) []string {
|
||||
return repos
|
||||
}
|
||||
|
||||
// checkRepoDirty checks if a git repository has uncommitted changes.
|
||||
// Alias for isRepoDirty (defined in uninstall.go) for backward compatibility.
|
||||
func checkRepoDirty(repoPath string) (bool, error) {
|
||||
return isRepoDirty(repoPath)
|
||||
}
|
||||
|
||||
// targetStatusResult bundles status detail with synced count to avoid
|
||||
// duplicate CheckStatusMerge/Copy calls.
|
||||
type targetStatusResult struct {
|
||||
|
||||
@@ -69,7 +69,7 @@ func printProjectTrackedReposStatus(sourcePath string, discovered []sync.Discove
|
||||
|
||||
statusStr := "up-to-date"
|
||||
statusIcon := "✓"
|
||||
if isDirty, _ := checkRepoDirty(repoPath); isDirty {
|
||||
if isDirty, _ := isRepoDirty(repoPath); isDirty {
|
||||
statusStr = "has uncommitted changes"
|
||||
statusIcon = "!"
|
||||
}
|
||||
|
||||
+58
-64
@@ -109,7 +109,7 @@ func cmdSync(args []string) error {
|
||||
if err != nil {
|
||||
if jsonOutput {
|
||||
writeJSONError(err)
|
||||
return err
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -119,40 +119,72 @@ func cmdSync(args []string) error {
|
||||
sourceErr := fmt.Errorf("source directory does not exist: %s", cfg.Source)
|
||||
if jsonOutput {
|
||||
writeJSONError(sourceErr)
|
||||
return nil
|
||||
}
|
||||
return sourceErr
|
||||
}
|
||||
|
||||
// Phase 1: Discovery
|
||||
var spinner *ui.Spinner
|
||||
if !jsonOutput {
|
||||
spinner := ui.StartSpinner("Discovering skills")
|
||||
discoveredSkills, discoverErr := sync.DiscoverSourceSkills(cfg.Source)
|
||||
if discoverErr != nil {
|
||||
spinner = ui.StartSpinner("Discovering skills")
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Discovering skills...\n")
|
||||
}
|
||||
discoveredSkills, discoverErr := sync.DiscoverSourceSkills(cfg.Source)
|
||||
if discoverErr != nil {
|
||||
if spinner != nil {
|
||||
spinner.Fail("Discovery failed")
|
||||
return discoverErr
|
||||
}
|
||||
if jsonOutput {
|
||||
writeJSONError(discoverErr)
|
||||
return nil
|
||||
}
|
||||
return discoverErr
|
||||
}
|
||||
if spinner != nil {
|
||||
spinner.Success(fmt.Sprintf("Discovered %d skills", len(discoveredSkills)))
|
||||
reportCollisions(discoveredSkills, cfg.Targets)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Discovered %d skills\n", len(discoveredSkills))
|
||||
}
|
||||
|
||||
// Backup targets before sync (only if not dry-run and there are skills)
|
||||
if !dryRun && len(discoveredSkills) > 0 {
|
||||
// Backup targets before sync (only if not dry-run and there are skills)
|
||||
if !dryRun && len(discoveredSkills) > 0 {
|
||||
if !jsonOutput {
|
||||
fmt.Println()
|
||||
backupTargetsBeforeSync(cfg)
|
||||
}
|
||||
backupTargetsBeforeSync(cfg)
|
||||
}
|
||||
|
||||
// Phase 2: Per-target sync (parallel)
|
||||
// Phase 2: Per-target sync (parallel)
|
||||
if !jsonOutput {
|
||||
ui.Header("Syncing skills")
|
||||
if dryRun {
|
||||
ui.Warning("Dry run mode - no changes will be made")
|
||||
}
|
||||
}
|
||||
|
||||
var entries []syncTargetEntry
|
||||
for name, target := range cfg.Targets {
|
||||
entries = append(entries, syncTargetEntry{name: name, target: target, mode: getTargetMode(target.Mode, cfg.Mode)})
|
||||
}
|
||||
var entries []syncTargetEntry
|
||||
for name, target := range cfg.Targets {
|
||||
entries = append(entries, syncTargetEntry{name: name, target: target, mode: getTargetMode(target.Mode, cfg.Mode)})
|
||||
}
|
||||
|
||||
results, failedTargets := runParallelSync(entries, cfg.Source, discoveredSkills, dryRun, force)
|
||||
var results []syncTargetResult
|
||||
var failedTargets int
|
||||
if jsonOutput {
|
||||
results, failedTargets = runParallelSyncQuiet(entries, cfg.Source, discoveredSkills, dryRun, force)
|
||||
} else {
|
||||
results, failedTargets = runParallelSync(entries, cfg.Source, discoveredSkills, dryRun, force)
|
||||
}
|
||||
|
||||
var syncErr error
|
||||
if failedTargets > 0 {
|
||||
syncErr = fmt.Errorf("some targets failed to sync")
|
||||
}
|
||||
|
||||
if !jsonOutput {
|
||||
// Phase 3: Summary
|
||||
var totals syncModeStats
|
||||
for _, r := range results {
|
||||
totals.linked += r.stats.linked
|
||||
@@ -160,13 +192,6 @@ func cmdSync(args []string) error {
|
||||
totals.updated += r.stats.updated
|
||||
totals.pruned += r.stats.pruned
|
||||
}
|
||||
|
||||
var syncErr error
|
||||
if failedTargets > 0 {
|
||||
syncErr = fmt.Errorf("some targets failed to sync")
|
||||
}
|
||||
|
||||
// Phase 3: Summary
|
||||
ui.SyncSummary(ui.SyncStats{
|
||||
Targets: len(cfg.Targets),
|
||||
Linked: totals.linked,
|
||||
@@ -182,48 +207,6 @@ func cmdSync(args []string) error {
|
||||
ui.Info("Cleaned up %d expired trash item(s)", n)
|
||||
}
|
||||
}
|
||||
|
||||
logSyncOp(config.ConfigPath(), syncLogStats{
|
||||
Targets: len(cfg.Targets),
|
||||
Failed: failedTargets,
|
||||
DryRun: dryRun,
|
||||
Force: force,
|
||||
}, start, syncErr)
|
||||
|
||||
if hasAll {
|
||||
fmt.Println()
|
||||
if extrasErr := cmdSyncExtras(rest); extrasErr != nil {
|
||||
ui.Warning("Extras sync: %v", extrasErr)
|
||||
}
|
||||
}
|
||||
|
||||
return syncErr
|
||||
}
|
||||
|
||||
// JSON mode: suppress all UI output
|
||||
fmt.Fprintf(os.Stderr, "Discovering skills...\n")
|
||||
discoveredSkills, discoverErr := sync.DiscoverSourceSkills(cfg.Source)
|
||||
if discoverErr != nil {
|
||||
writeJSONError(discoverErr)
|
||||
return discoverErr
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Discovered %d skills\n", len(discoveredSkills))
|
||||
|
||||
// Backup targets before sync (same as non-JSON path)
|
||||
if !dryRun && len(discoveredSkills) > 0 {
|
||||
backupTargetsBeforeSync(cfg)
|
||||
}
|
||||
|
||||
var entries []syncTargetEntry
|
||||
for name, target := range cfg.Targets {
|
||||
entries = append(entries, syncTargetEntry{name: name, target: target, mode: getTargetMode(target.Mode, cfg.Mode)})
|
||||
}
|
||||
|
||||
results, failedTargets := runParallelSyncQuiet(entries, cfg.Source, discoveredSkills, dryRun, force)
|
||||
|
||||
var syncErr error
|
||||
if failedTargets > 0 {
|
||||
syncErr = fmt.Errorf("some targets failed to sync")
|
||||
}
|
||||
|
||||
logSyncOp(config.ConfigPath(), syncLogStats{
|
||||
@@ -233,7 +216,18 @@ func cmdSync(args []string) error {
|
||||
Force: force,
|
||||
}, start, syncErr)
|
||||
|
||||
return syncOutputJSON(results, dryRun, start, syncErr)
|
||||
if jsonOutput {
|
||||
return syncOutputJSON(results, dryRun, start, syncErr)
|
||||
}
|
||||
|
||||
if hasAll {
|
||||
fmt.Println()
|
||||
if extrasErr := cmdSyncExtras(rest); extrasErr != nil {
|
||||
ui.Warning("Extras sync: %v", extrasErr)
|
||||
}
|
||||
}
|
||||
|
||||
return syncErr
|
||||
}
|
||||
|
||||
func parseSyncFlags(args []string) (dryRun, force, jsonOutput bool) {
|
||||
|
||||
@@ -36,25 +36,24 @@ func cmdSyncProject(root string, dryRun, force, jsonOutput bool) (syncLogStats,
|
||||
}
|
||||
|
||||
// Phase 1: Discovery
|
||||
var discoveredSkills []sync.DiscoveredSkill
|
||||
if jsonOutput {
|
||||
fmt.Fprintf(os.Stderr, "Discovering skills...\n")
|
||||
var discoverErr error
|
||||
discoveredSkills, discoverErr = sync.DiscoverSourceSkills(runtime.sourcePath)
|
||||
if discoverErr != nil {
|
||||
return stats, nil, discoverErr
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Discovered %d skills\n", len(discoveredSkills))
|
||||
var spinner *ui.Spinner
|
||||
if !jsonOutput {
|
||||
spinner = ui.StartSpinner("Discovering skills")
|
||||
} else {
|
||||
spinner := ui.StartSpinner("Discovering skills")
|
||||
var discoverErr error
|
||||
discoveredSkills, discoverErr = sync.DiscoverSourceSkills(runtime.sourcePath)
|
||||
if discoverErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "Discovering skills...\n")
|
||||
}
|
||||
discoveredSkills, discoverErr := sync.DiscoverSourceSkills(runtime.sourcePath)
|
||||
if discoverErr != nil {
|
||||
if spinner != nil {
|
||||
spinner.Fail("Discovery failed")
|
||||
return stats, nil, discoverErr
|
||||
}
|
||||
return stats, nil, discoverErr
|
||||
}
|
||||
if spinner != nil {
|
||||
spinner.Success(fmt.Sprintf("Discovered %d skills", len(discoveredSkills)))
|
||||
reportCollisions(discoveredSkills, runtime.targets)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Discovered %d skills\n", len(discoveredSkills))
|
||||
}
|
||||
|
||||
// Phase 2: Per-target sync
|
||||
|
||||
+49
-10
@@ -580,13 +580,20 @@ func cmdUninstall(args []string) error {
|
||||
var resolveWarnings []string
|
||||
|
||||
if opts.all {
|
||||
sp := ui.StartSpinner("Discovering skills...")
|
||||
var sp *ui.Spinner
|
||||
if !opts.jsonOutput {
|
||||
sp = ui.StartSpinner("Discovering skills...")
|
||||
}
|
||||
discovered, _, err := sync.DiscoverSourceSkillsLite(cfg.Source)
|
||||
if err != nil {
|
||||
sp.Fail("Discovery failed")
|
||||
if sp != nil {
|
||||
sp.Fail("Discovery failed")
|
||||
}
|
||||
return fmt.Errorf("failed to discover skills: %w", err)
|
||||
}
|
||||
sp.Success(fmt.Sprintf("Found %d skills", len(discovered)))
|
||||
if sp != nil {
|
||||
sp.Success(fmt.Sprintf("Found %d skills", len(discovered)))
|
||||
}
|
||||
if len(discovered) == 0 {
|
||||
return fmt.Errorf("no skills found in source")
|
||||
}
|
||||
@@ -618,7 +625,9 @@ func cmdUninstall(args []string) error {
|
||||
resolveWarnings = append(resolveWarnings, fmt.Sprintf("%s: no skills match pattern", name))
|
||||
continue
|
||||
}
|
||||
if !opts.jsonOutput {
|
||||
ui.Info("Pattern '%s' matched %d item(s)", name, len(globMatches))
|
||||
}
|
||||
for _, t := range globMatches {
|
||||
if !seen[t.path] {
|
||||
seen[t.path] = true
|
||||
@@ -653,8 +662,10 @@ func cmdUninstall(args []string) error {
|
||||
}
|
||||
}
|
||||
|
||||
for _, w := range resolveWarnings {
|
||||
ui.Warning("%s", w)
|
||||
if !opts.jsonOutput {
|
||||
for _, w := range resolveWarnings {
|
||||
ui.Warning("%s", w)
|
||||
}
|
||||
}
|
||||
|
||||
// Shell glob detection: if positional args look like shell-expanded filenames,
|
||||
@@ -676,7 +687,9 @@ func cmdUninstall(args []string) error {
|
||||
// --- Phase 3: DISPLAY ---
|
||||
single := len(targets) == 1
|
||||
summary := summarizeUninstallTargets(targets)
|
||||
if single {
|
||||
if opts.jsonOutput {
|
||||
// Skip display in JSON mode
|
||||
} else if single {
|
||||
displayUninstallInfo(targets[0])
|
||||
} else {
|
||||
ui.Header(fmt.Sprintf("Uninstalling %d %s", len(targets), summary.noun()))
|
||||
@@ -761,7 +774,9 @@ func cmdUninstall(args []string) error {
|
||||
}
|
||||
dr := dirtyResults[i]
|
||||
if dr.err != nil {
|
||||
ui.Warning("Could not check git status for %s: %v", t.name, dr.err)
|
||||
if !opts.jsonOutput {
|
||||
ui.Warning("Could not check git status for %s: %v", t.name, dr.err)
|
||||
}
|
||||
preflight = append(preflight, t)
|
||||
continue
|
||||
}
|
||||
@@ -779,14 +794,16 @@ func cmdUninstall(args []string) error {
|
||||
ui.StepSkip(t.name, "uncommitted changes, use --force")
|
||||
continue
|
||||
}
|
||||
ui.Warning("Repository %s has uncommitted changes (proceeding with --force)", t.name)
|
||||
if !opts.jsonOutput {
|
||||
ui.Warning("Repository %s has uncommitted changes (proceeding with --force)", t.name)
|
||||
}
|
||||
preflight = append(preflight, t)
|
||||
}
|
||||
preflightSkipped = len(targets) - len(preflight)
|
||||
targets = preflight
|
||||
summary = summarizeUninstallTargets(targets)
|
||||
|
||||
if preflightSkipped > 0 {
|
||||
if preflightSkipped > 0 && !opts.jsonOutput {
|
||||
ui.Info("%d tracked repo%s skipped, %d remaining", preflightSkipped, pluralS(preflightSkipped), len(targets))
|
||||
fmt.Println()
|
||||
}
|
||||
@@ -855,7 +872,29 @@ func cmdUninstall(args []string) error {
|
||||
var succeeded []*uninstallTarget
|
||||
var failed []string
|
||||
|
||||
if batch {
|
||||
if opts.jsonOutput {
|
||||
// JSON mode: quiet execution, no UI output
|
||||
for _, t := range targets {
|
||||
if _, err := performUninstallQuiet(t); err != nil {
|
||||
failed = append(failed, fmt.Sprintf("%s: %v", t.name, err))
|
||||
} else {
|
||||
succeeded = append(succeeded, t)
|
||||
}
|
||||
}
|
||||
|
||||
// Batch-remove .gitignore entries for tracked repos
|
||||
if len(succeeded) > 0 {
|
||||
var gitignoreEntries []string
|
||||
for _, t := range succeeded {
|
||||
if t.isTrackedRepo {
|
||||
gitignoreEntries = append(gitignoreEntries, t.name)
|
||||
}
|
||||
}
|
||||
if len(gitignoreEntries) > 0 {
|
||||
install.RemoveFromGitIgnoreBatch(cfg.Source, gitignoreEntries) //nolint:errcheck
|
||||
}
|
||||
}
|
||||
} else if batch {
|
||||
sp := ui.StartSpinner(fmt.Sprintf("Uninstalling %d %s", len(targets), summary.noun()))
|
||||
var results []batchResult
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ func SyncTargetCopyWithSkills(name string, target config.TargetConfig, allSkills
|
||||
if err == nil && info != nil && utils.IsSymlinkOrJunction(target.Path) {
|
||||
if isSymlinkToSource(target.Path, sourcePath) {
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would convert from symlink mode to copy mode: %s\n", target.Path)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would convert from symlink mode to copy mode: %s\n", target.Path)
|
||||
} else {
|
||||
if err := os.Remove(target.Path); err != nil {
|
||||
return nil, fmt.Errorf("failed to remove symlink for copy conversion: %w", err)
|
||||
@@ -108,7 +108,7 @@ func SyncTargetCopyWithSkills(name string, target config.TargetConfig, allSkills
|
||||
// If it's a symlink (leftover from merge mode), remove it
|
||||
if utils.IsSymlinkOrJunction(targetSkillPath) {
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would replace symlink with copy: %s\n", skill.FlatName)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would replace symlink with copy: %s\n", skill.FlatName)
|
||||
} else {
|
||||
os.Remove(targetSkillPath)
|
||||
}
|
||||
@@ -119,7 +119,7 @@ func SyncTargetCopyWithSkills(name string, target config.TargetConfig, allSkills
|
||||
if !targetInfo.IsDir() {
|
||||
if isManaged || force {
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would replace non-directory entry with copy: %s\n", skill.FlatName)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would replace non-directory entry with copy: %s\n", skill.FlatName)
|
||||
} else {
|
||||
if err := os.RemoveAll(targetSkillPath); err != nil {
|
||||
return nil, fmt.Errorf("failed to remove invalid entry %s: %w", skill.FlatName, err)
|
||||
@@ -153,7 +153,7 @@ func SyncTargetCopyWithSkills(name string, target config.TargetConfig, allSkills
|
||||
if isManaged || force {
|
||||
// Managed or forced — overwrite
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would update copy: %s\n", skill.FlatName)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would update copy: %s\n", skill.FlatName)
|
||||
} else {
|
||||
if err := os.RemoveAll(targetSkillPath); err != nil {
|
||||
return nil, fmt.Errorf("failed to remove old copy %s: %w", skill.FlatName, err)
|
||||
@@ -180,7 +180,7 @@ func SyncTargetCopyWithSkills(name string, target config.TargetConfig, allSkills
|
||||
|
||||
// Copy skill to target
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would copy: %s -> %s\n", skill.SourcePath, targetSkillPath)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would copy: %s -> %s\n", skill.SourcePath, targetSkillPath)
|
||||
} else {
|
||||
if err := copyDirectory(skill.SourcePath, targetSkillPath); err != nil {
|
||||
return nil, fmt.Errorf("failed to copy skill %s: %w", skill.FlatName, err)
|
||||
@@ -241,7 +241,7 @@ func PruneOrphanCopiesWithSkills(targetPath string, allSourceSkills []Discovered
|
||||
|
||||
entryPath := filepath.Join(targetPath, flatName)
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would remove orphan copy: %s\n", entryPath)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would remove orphan copy: %s\n", entryPath)
|
||||
} else {
|
||||
if err := os.RemoveAll(entryPath); err != nil {
|
||||
result.Warnings = append(result.Warnings,
|
||||
|
||||
+11
-11
@@ -299,14 +299,14 @@ func SyncTarget(name string, target config.TargetConfig, sourcePath string, dryR
|
||||
|
||||
case StatusNotExist:
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would create symlink: %s -> %s\n", target.Path, sourcePath)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would create symlink: %s -> %s\n", target.Path, sourcePath)
|
||||
return nil
|
||||
}
|
||||
return CreateSymlink(target.Path, sourcePath)
|
||||
|
||||
case StatusHasFiles:
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would migrate files from %s to %s, then create symlink\n", target.Path, sourcePath)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would migrate files from %s to %s, then create symlink\n", target.Path, sourcePath)
|
||||
return nil
|
||||
}
|
||||
if err := MigrateToSource(target.Path, sourcePath); err != nil {
|
||||
@@ -323,7 +323,7 @@ func SyncTarget(name string, target config.TargetConfig, sourcePath string, dryR
|
||||
|
||||
case StatusBroken:
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would remove broken symlink and recreate: %s\n", target.Path)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would remove broken symlink and recreate: %s\n", target.Path)
|
||||
return nil
|
||||
}
|
||||
os.Remove(target.Path)
|
||||
@@ -350,7 +350,7 @@ func mergeDirectories(src, dst string) error {
|
||||
|
||||
// Skip if destination exists
|
||||
if _, err := os.Stat(dstPath); err == nil {
|
||||
fmt.Printf(" skip (exists): %s\n", relPath)
|
||||
fmt.Fprintf(os.Stderr, " skip (exists): %s\n", relPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -484,7 +484,7 @@ func SyncTargetMergeWithSkills(name string, target config.TargetConfig, allSkill
|
||||
if err == nil && info != nil && utils.IsSymlinkOrJunction(target.Path) {
|
||||
if isSymlinkToSource(target.Path, sourcePath) {
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would convert from symlink mode to merge mode: %s\n", target.Path)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would convert from symlink mode to merge mode: %s\n", target.Path)
|
||||
} else {
|
||||
if err := os.Remove(target.Path); err != nil {
|
||||
return nil, fmt.Errorf("failed to remove symlink for merge conversion: %w", err)
|
||||
@@ -532,7 +532,7 @@ func SyncTargetMergeWithSkills(name string, target config.TargetConfig, allSkill
|
||||
|
||||
// Symlink points elsewhere - broken or wrong
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would fix symlink: %s\n", skill.FlatName)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would fix symlink: %s\n", skill.FlatName)
|
||||
} else {
|
||||
os.Remove(targetSkillPath)
|
||||
if err := createLink(targetSkillPath, skill.SourcePath); err != nil {
|
||||
@@ -545,7 +545,7 @@ func SyncTargetMergeWithSkills(name string, target config.TargetConfig, allSkill
|
||||
if force {
|
||||
// Force: replace local copy with symlink
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would replace local copy: %s\n", skill.FlatName)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would replace local copy: %s\n", skill.FlatName)
|
||||
} else {
|
||||
if err := os.RemoveAll(targetSkillPath); err != nil {
|
||||
return nil, fmt.Errorf("failed to remove local copy %s: %w", skill.FlatName, err)
|
||||
@@ -563,7 +563,7 @@ func SyncTargetMergeWithSkills(name string, target config.TargetConfig, allSkill
|
||||
} else if os.IsNotExist(err) {
|
||||
// Doesn't exist - create link
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would create link: %s -> %s\n", targetSkillPath, skill.SourcePath)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would create link: %s -> %s\n", targetSkillPath, skill.SourcePath)
|
||||
} else {
|
||||
if err := createLink(targetSkillPath, skill.SourcePath); err != nil {
|
||||
return nil, fmt.Errorf("failed to create link for %s: %w", skill.FlatName, err)
|
||||
@@ -719,7 +719,7 @@ func PruneOrphanLinksWithSkills(opts PruneOptions) (*PruneResult, error) {
|
||||
}
|
||||
if utils.PathHasPrefix(absLink, absSource+string(filepath.Separator)) {
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would remove excluded symlink: %s\n", entryPath)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would remove excluded symlink: %s\n", entryPath)
|
||||
} else if err := os.RemoveAll(entryPath); err != nil {
|
||||
result.Warnings = append(result.Warnings,
|
||||
fmt.Sprintf("%s: failed to remove excluded symlink: %v", name, err))
|
||||
@@ -730,7 +730,7 @@ func PruneOrphanLinksWithSkills(opts PruneOptions) (*PruneResult, error) {
|
||||
} else if inManifest && info.IsDir() {
|
||||
// Real directory previously managed by skillshare, now excluded by filter — remove it
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would remove excluded managed directory: %s\n", entryPath)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would remove excluded managed directory: %s\n", entryPath)
|
||||
} else if err := os.RemoveAll(entryPath); err != nil {
|
||||
result.Warnings = append(result.Warnings,
|
||||
fmt.Sprintf("%s: failed to remove excluded managed directory: %v", name, err))
|
||||
@@ -795,7 +795,7 @@ func PruneOrphanLinksWithSkills(opts PruneOptions) (*PruneResult, error) {
|
||||
|
||||
if shouldRemove {
|
||||
if dryRun {
|
||||
fmt.Printf("[dry-run] Would remove %s: %s\n", reason, entryPath)
|
||||
fmt.Fprintf(os.Stderr, "[dry-run] Would remove %s: %s\n", reason, entryPath)
|
||||
} else {
|
||||
if err := os.RemoveAll(entryPath); err != nil {
|
||||
result.Warnings = append(result.Warnings,
|
||||
|
||||
@@ -2,35 +2,11 @@ package integration
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/testutil"
|
||||
)
|
||||
|
||||
// extractJSON finds the first complete JSON object in a string that may
|
||||
// contain non-JSON text (e.g. dry-run messages from internal sync).
|
||||
func extractJSON(s string) string {
|
||||
start := strings.Index(s, "{")
|
||||
if start < 0 {
|
||||
return s
|
||||
}
|
||||
// Find matching closing brace
|
||||
depth := 0
|
||||
for i := start; i < len(s); i++ {
|
||||
switch s[i] {
|
||||
case '{':
|
||||
depth++
|
||||
case '}':
|
||||
depth--
|
||||
if depth == 0 {
|
||||
return s[start : i+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
return s[start:]
|
||||
}
|
||||
|
||||
// --- sync --json ---
|
||||
|
||||
func TestSync_JSON_OutputsValidJSON(t *testing.T) {
|
||||
@@ -77,11 +53,9 @@ func TestSync_JSON_DryRun(t *testing.T) {
|
||||
result := sb.RunCLI("sync", "--json", "--dry-run")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
// Dry-run may include "[dry-run] Would create link..." from internal sync
|
||||
// before the JSON object, so we extract the JSON portion
|
||||
jsonStr := extractJSON(result.Stdout)
|
||||
// stdout should be pure JSON — dry-run messages go to stderr now
|
||||
var output map[string]any
|
||||
if err := json.Unmarshal([]byte(jsonStr), &output); err != nil {
|
||||
if err := json.Unmarshal([]byte(result.Stdout), &output); err != nil {
|
||||
t.Fatalf("invalid JSON output: %v\nStdout: %q", err, result.Stdout)
|
||||
}
|
||||
if output["dry_run"] != true {
|
||||
@@ -125,10 +99,9 @@ func TestUninstall_JSON_OutputsValidJSON(t *testing.T) {
|
||||
result := sb.RunCLI("uninstall", "to-remove", "--json")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
// uninstall --json still prints UI output before JSON; extract JSON
|
||||
jsonStr := extractJSON(result.Stdout)
|
||||
// stdout should be pure JSON — UI output is suppressed in JSON mode
|
||||
var output map[string]any
|
||||
if err := json.Unmarshal([]byte(jsonStr), &output); err != nil {
|
||||
if err := json.Unmarshal([]byte(result.Stdout), &output); err != nil {
|
||||
t.Fatalf("invalid JSON output: %v\nStdout: %s", err, result.Stdout)
|
||||
}
|
||||
|
||||
@@ -161,9 +134,8 @@ func TestUninstall_JSON_DryRun(t *testing.T) {
|
||||
result := sb.RunCLI("uninstall", "keep-me", "--json", "--dry-run")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
jsonStr := extractJSON(result.Stdout)
|
||||
var output map[string]any
|
||||
if err := json.Unmarshal([]byte(jsonStr), &output); err != nil {
|
||||
if err := json.Unmarshal([]byte(result.Stdout), &output); err != nil {
|
||||
t.Fatalf("invalid JSON output: %v\nStdout: %q", err, result.Stdout)
|
||||
}
|
||||
if output["dry_run"] != true {
|
||||
@@ -182,9 +154,8 @@ func TestUninstall_JSON_ImpliesForce(t *testing.T) {
|
||||
result := sb.RunCLI("uninstall", "auto-force", "--json")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
jsonStr := extractJSON(result.Stdout)
|
||||
var output map[string]any
|
||||
if err := json.Unmarshal([]byte(jsonStr), &output); err != nil {
|
||||
if err := json.Unmarshal([]byte(result.Stdout), &output); err != nil {
|
||||
t.Fatalf("invalid JSON output: %v\nStdout: %s", err, result.Stdout)
|
||||
}
|
||||
|
||||
@@ -296,9 +267,8 @@ func TestCollect_JSON_NoLocalSkills(t *testing.T) {
|
||||
result := sb.RunCLI("collect", "--json", "--all")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
jsonStr := extractJSON(result.Stdout)
|
||||
var output map[string]any
|
||||
if err := json.Unmarshal([]byte(jsonStr), &output); err != nil {
|
||||
if err := json.Unmarshal([]byte(result.Stdout), &output); err != nil {
|
||||
t.Fatalf("invalid JSON output: %v\nStdout: %s", err, result.Stdout)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user