Files
skillshare/cmd/skillshare/sync_project.go
T
Willie 5dfd63d5e9 fix(sync): fail only the target whose config is invalid
Any per-target config problem, such as a skills path that is a file or
an unknown mode, made `skillshare sync`, `sync -p` and the dashboard
refuse to sync anything. That contradicts the policy that sync runs
every target and reports the ones that failed. Sync now validates the
config as a whole first and still stops on global problems (source,
global mode or naming, git_root, extras); a target whose own settings
are invalid is skipped for skills and agents and reported as failed
("invalid config" in CLI output and --json details, part "config" in
the dashboard's failed list). Config validation on save is unchanged.
2026-09-30 03:27:20 +08:00

179 lines
5.2 KiB
Go

package main
import (
"fmt"
"os"
"time"
"skillshare/internal/config"
"skillshare/internal/skillignore"
"skillshare/internal/sync"
"skillshare/internal/trash"
"skillshare/internal/ui"
)
// The returned map holds the targets skipped for invalid settings.
func cmdSyncProject(root string, dryRun, force, jsonOutput, quiet bool) (syncLogStats, []syncTargetResult, *skillignore.IgnoreStats, *contextCostJSON, map[string]error, error) {
start := time.Now()
stats := syncLogStats{
DryRun: dryRun,
Force: force,
ProjectScope: true,
}
if err := ensureProjectConfig(root); err != nil {
return stats, nil, nil, nil, nil, err
}
runtime, err := loadProjectRuntime(root)
if err != nil {
return stats, nil, nil, nil, nil, err
}
stats.Targets = len(runtime.config.Targets)
// Validate project config before sync. A target with invalid settings
// fails alone; the other targets still sync.
warnings, invalid, validErr := config.ValidateProjectConfigForSync(runtime.config, root)
if validErr != nil {
return stats, nil, nil, nil, nil, validErr
}
if !jsonOutput {
for _, w := range warnings {
ui.Warning("%s", w)
}
}
// ValidateProjectConfig warns on missing source (may not exist yet after init).
// Gate here as a hard error — sync cannot proceed without source skills.
if _, err := os.Stat(runtime.sourcePath); os.IsNotExist(err) {
return stats, nil, nil, nil, nil, fmt.Errorf("source directory does not exist: %s", runtime.sourcePath)
}
// Phase 1: Discovery
var spinner *ui.Spinner
if !jsonOutput {
spinner = ui.StartSpinner("Discovering skills")
}
discoveredSkills, ignoreStats, discoverErr := sync.DiscoverSourceSkillsWithStatsAndContext(runtime.sourcePath)
if discoverErr != nil {
if spinner != nil {
spinner.Fail("Discovery failed")
}
return stats, nil, nil, nil, nil, discoverErr
}
if spinner != nil {
spinner.Success(fmt.Sprintf("Discovered %d skills", len(discoveredSkills)))
reportCollisions(discoveredSkills, runtime.targets)
}
// Phase 2: Per-target sync
if !jsonOutput {
ui.Header("Syncing skills (project)")
if dryRun {
ui.Warning("Dry run mode - no changes will be made")
}
}
var entries []syncTargetEntry
var notFound []string
for _, entry := range runtime.config.Targets {
name := entry.Name
target, ok := runtime.targets[name]
if !ok {
if !jsonOutput {
ui.Error("%s: target not found", name)
}
notFound = append(notFound, name)
continue
}
mode := target.SkillsConfig().Mode
if mode == "" {
mode = "merge"
}
entries = append(entries, syncTargetEntry{name: name, target: target, mode: mode, configErr: invalid[name]})
}
var results []syncTargetResult
ignorePatterns := sync.EffectiveFileIgnorePatterns(runtime.config.Ignore)
if jsonOutput {
results, _ = runParallelSyncQuiet(entries, runtime.sourcePath, discoveredSkills, ignorePatterns, dryRun, force, root)
} else {
results, _ = runParallelSync(entries, runtime.sourcePath, discoveredSkills, ignorePatterns, dryRun, force, root)
}
movedTargets := sync.MovedProjectTargets(runtime.config, runtime.targets)
for _, msg := range sync.CleanMovedProjectDirs(root, runtime.sourcePath, movedTargets, dryRun) {
if !jsonOutput {
ui.Info("%s", msg)
}
}
var totals syncModeStats
for _, r := range results {
totals.linked += r.stats.linked
totals.local += r.stats.local
totals.updated += r.stats.updated
totals.pruned += r.stats.pruned
}
stats.FailedTargets = mergeFailedTargets(failedSkillTargets(results), notFound)
if !jsonOutput {
// Phase 3: Summary
ui.SyncSummary(ui.SyncStats{
Targets: len(runtime.config.Targets),
Linked: totals.linked,
Local: totals.local,
Updated: totals.updated,
Pruned: totals.pruned,
Duration: time.Since(start),
})
// Show ignored skills from .skillignore
printIgnoredSkills(ignoreStats)
// One-liner path-overlap hint — points users at `doctor` for details.
printSyncOverlapHint(runtime.targets, true, jsonOutput)
}
// Compute context cost once — used by both text summary and JSON output
analyzeEntries, analyzeErr := buildAnalyzeEntries(discoveredSkills, runtime.targets, "", runtime.sourcePath, "")
var ctxCost *contextCostJSON
if analyzeErr == nil && len(analyzeEntries) > 0 {
ctxCost = buildContextCostJSON(analyzeEntries, runtime.config.ContextBudget)
if !jsonOutput && !quiet {
printTokenSummary(analyzeEntries)
if violations := checkBudget(analyzeEntries, runtime.config.ContextBudget); len(violations) > 0 {
printBudgetWarning(violations, true)
}
}
}
// Reconcile registry and cleanup regardless of target failures.
// Registry cleanup only depends on source disk state, not target sync results.
if !dryRun {
if n, _ := trash.Cleanup(trash.ProjectTrashDir(root), 0); n > 0 {
if !jsonOutput {
ui.Info("Cleaned up %d expired trash item(s)", n)
}
}
}
if len(stats.FailedTargets) > 0 {
return stats, results, ignoreStats, ctxCost, invalid, fmt.Errorf("some targets failed to sync")
}
return stats, results, ignoreStats, ctxCost, invalid, nil
}
func projectTargetDisplayPath(entry config.ProjectTargetEntry) string {
if p := entry.SkillsConfig().Path; p != "" {
return p
}
if known, ok := config.LookupProjectTarget(entry.Name); ok {
return known.Path
}
return ""
}