From bcfed0fa006ebd7b0dc86a4aff1d93183ff21446 Mon Sep 17 00:00:00 2001 From: fullstackjam Date: Tue, 17 Nov 2026 22:46:00 +0800 Subject: [PATCH] fix: protect dotfiles sources and report install failures accurately Skip linked target directories during conflict backup, preserve full brew failure output and the latest retry error, and summarize actual step outcomes instead of planned package counts. Architecture baseline changes only track shifted existing subprocess call sites; no new exemption is introduced. --- internal/archtest/baseline/no-direct-exec.txt | 4 +-- internal/brew/brew_install.go | 25 ++++++++++++++---- internal/brew/brew_test.go | 21 +++++++++++++++ internal/brew/install_progress.go | 7 ++++- internal/dotfiles/dotfiles.go | 22 +++++++++++----- internal/dotfiles/dotfiles_test.go | 26 +++++++++++++++++++ internal/installer/installer.go | 26 ++++++++++++------- internal/installer/installer_extra_test.go | 19 ++++++++------ 8 files changed, 118 insertions(+), 32 deletions(-) diff --git a/internal/archtest/baseline/no-direct-exec.txt b/internal/archtest/baseline/no-direct-exec.txt index a6c53a0f..c0aa6323 100644 --- a/internal/archtest/baseline/no-direct-exec.txt +++ b/internal/archtest/baseline/no-direct-exec.txt @@ -2,7 +2,7 @@ # Each line is : of a known existing violation. # Regenerate: ARCHTEST_UPDATE_BASELINE=1 go test ./internal/archtest/... internal/auth/login.go:195 -internal/brew/brew_install.go:332 +internal/brew/brew_install.go:334 internal/cli/snapshot.go:22 internal/diff/compare.go:247 internal/diff/compare.go:253 @@ -10,7 +10,7 @@ internal/dotfiles/dotfiles.go:27 internal/dotfiles/dotfiles.go:41 internal/dotfiles/dotfiles.go:79 internal/dotfiles/dotfiles.go:376 -internal/dotfiles/dotfiles.go:474 +internal/dotfiles/dotfiles.go:484 internal/installer/step_system.go:126 internal/npm/npm.go:22 internal/permissions/screen_recording_cgo.go:21 diff --git a/internal/brew/brew_install.go b/internal/brew/brew_install.go index e163b44c..35cede3c 100644 --- a/internal/brew/brew_install.go +++ b/internal/brew/brew_install.go @@ -226,7 +226,8 @@ func retryFailedJobs(ctx context.Context, allFailed []failedJob, installedFormul ui.Printf("\nRetrying %d failed packages...\n", len(allFailed)) - for _, f := range allFailed { + for i := range allFailed { + f := &allFailed[i] var errMsg string if f.isCask { errMsg = installSmartCaskWithError(ctx, f.name) @@ -241,6 +242,7 @@ func retryFailedJobs(ctx context.Context, allFailed []failedJob, installedFormul *installedFormulae = append(*installedFormulae, aliasMap[f.name]) } } else { + f.errMsg = errMsg ui.Printf(" ✗ %s (still failed)\n", f.name) } } @@ -319,7 +321,7 @@ func installCaskWithProgress(ctx context.Context, pkg string) string { if err == nil { return "" } - return parseBrewError(output) + return brewFailureDetails(output, err) } // Runner-exempt: this helper sets HOMEBREW_NO_AUTO_UPDATE=1 and returns a raw @@ -361,7 +363,7 @@ func retryBrew(action func() (string, error)) string { sleepFunc(time.Duration(attempt) * 2 * time.Second) continue } - return errMsg + return brewFailureDetails(output, err) } return "max retries exceeded" } @@ -382,7 +384,7 @@ func installFormulaWithError(ctx context.Context, pkg string) string { if err2 == nil { return "" } - outputStr = caskOutput + outputStr, err = caskOutput, err2 } errMsg := parseBrewError(outputStr) @@ -391,7 +393,7 @@ func installFormulaWithError(ctx context.Context, pkg string) string { continue } - return errMsg + return brewFailureDetails(outputStr, err) } return "max retries exceeded" } @@ -421,6 +423,19 @@ func installSmartCaskWithError(ctx context.Context, pkg string) string { }) } +// Keep the concise classification for progress, but retain the complete +// subprocess output for diagnosis (including curl errors preceding Error:). +func brewFailureDetails(output string, err error) string { + summary := parseBrewError(output) + if summary == "" || summary == "unknown error" { + summary = fmt.Sprintf("brew failed: %v", err) + } + if details := strings.TrimSpace(output); details != "" && details != summary { + return summary + "\n" + details + } + return summary +} + func parseBrewError(output string) string { lowerOutput := strings.ToLower(output) diff --git a/internal/brew/brew_test.go b/internal/brew/brew_test.go index 7ab23bed..c375cf61 100644 --- a/internal/brew/brew_test.go +++ b/internal/brew/brew_test.go @@ -238,3 +238,24 @@ func TestHandleFailedJobs_WithFailures(t *testing.T) { } handleFailedJobs(failed) } + +func TestRetryFailedJobsRetainsLatestFullOutput(t *testing.T) { + original := brewCaskInstallFunc + t.Cleanup(func() { brewCaskInstallFunc = original }) + details := "curl: (35) TLS handshake failed\nError: Download failed: https://example.com/" + strings.Repeat("long-path/", 30) + brewCaskInstallFunc = func(context.Context, string) (string, error) { + return details, fmt.Errorf("exit status 1") + } + var formulae, casks []string + output := captureOutput(t, func() { + failed := retryFailedJobs(context.Background(), []failedJob{{installJob: installJob{name: "office", isCask: true}, errMsg: "old failure"}}, &formulae, &casks, nil) + assert.Len(t, failed, 1) + handleFailedJobs(failed) + }) + assert.Contains(t, output, details) + assert.NotContains(t, output, "old failure") +} + +func TestBrewFailureDetailsEmptyOutput(t *testing.T) { + assert.Contains(t, brewFailureDetails("", context.DeadlineExceeded), "context deadline exceeded") +} diff --git a/internal/brew/install_progress.go b/internal/brew/install_progress.go index f6fae61f..9e4fd8fa 100644 --- a/internal/brew/install_progress.go +++ b/internal/brew/install_progress.go @@ -1,12 +1,17 @@ package brew -import "github.com/openbootdotdev/openboot/internal/ui" +import ( + "strings" + + "github.com/openbootdotdev/openboot/internal/ui" +) func stepStart(bar *ui.StickyProgress, name string) { bar.SetCurrent(name) } func stepDone(bar *ui.StickyProgress, name string, ok bool, errMsg, duration string) { + errMsg, _, _ = strings.Cut(errMsg, "\n") bar.IncrementWithStatus(ok) if ok { bar.PrintLine(" %s %s", ui.Green("✔ "+name), ui.Cyan("("+duration+")")) diff --git a/internal/dotfiles/dotfiles.go b/internal/dotfiles/dotfiles.go index 76ae1d1c..f1d572f5 100644 --- a/internal/dotfiles/dotfiles.go +++ b/internal/dotfiles/dotfiles.go @@ -311,7 +311,7 @@ func linkWithMake(dotfilesPath string, dryRun bool) error { } for _, pair := range allBacked { - if rmErr := os.Remove(pair[0]); rmErr != nil { + if rmErr := os.Remove(pair[0]); rmErr != nil && !os.IsNotExist(rmErr) { ui.Warn(fmt.Sprintf("could not remove backup %s: %v", pair[0], rmErr)) } } @@ -395,16 +395,26 @@ func backupConflicts(pkgDir, targetDir string, dryRun bool) ([][2]string, error) if err != nil { return err } - if d.IsDir() { - return nil - } - rel, relErr := filepath.Rel(pkgDir, path) if relErr != nil { return relErr } target := filepath.Join(targetDir, rel) + if d.IsDir() { + // Lstat on a child follows symlinks in its parents. Prune linked + // target directories before visiting children, or backing up an + // already deployed directory would modify the source repository. + info, statErr := os.Lstat(target) + if statErr != nil && !os.IsNotExist(statErr) { + return fmt.Errorf("inspect target directory %s: %w", target, statErr) + } + if statErr == nil && info.Mode()&os.ModeSymlink != 0 { + return filepath.SkipDir + } + return nil + } + info, statErr := os.Lstat(target) if statErr != nil || info.Mode()&os.ModeSymlink != 0 { // Target doesn't exist or is already a symlink — no conflict. @@ -486,7 +496,7 @@ func linkWithStow(dotfilesPath string, dryRun bool) error { // Stow succeeded — clean up backups. for _, pair := range backed { - if rmErr := os.Remove(pair[0]); rmErr != nil { + if rmErr := os.Remove(pair[0]); rmErr != nil && !os.IsNotExist(rmErr) { ui.Warn(fmt.Sprintf("could not remove backup %s: %v", pair[0], rmErr)) } } diff --git a/internal/dotfiles/dotfiles_test.go b/internal/dotfiles/dotfiles_test.go index 40ad1a61..eec68d82 100644 --- a/internal/dotfiles/dotfiles_test.go +++ b/internal/dotfiles/dotfiles_test.go @@ -786,3 +786,29 @@ func TestClone_LocalChanges_CleanRepo(t *testing.T) { _, statErr := os.Stat(filepath.Join(dotfilesPath, ".vimrc")) assert.NoError(t, statErr, ".vimrc must appear after clean sync") } + +// A deployed directory link must not turn its source files into conflicts. +func TestBackupConflicts_DirectorySymlinksPreserveSources(t *testing.T) { + for _, linkedDir := range []string{".agents", ".agents/skills/how"} { + t.Run(linkedDir, func(t *testing.T) { + root := t.TempDir() + pkg := filepath.Join(root, "repo", "agents") + home := filepath.Join(root, "home") + rel := filepath.Join(".agents", "skills", "how", "SKILL.md") + source := filepath.Join(pkg, rel) + require.NoError(t, os.MkdirAll(filepath.Dir(source), 0755)) + require.NoError(t, os.WriteFile(source, []byte("original skill"), 0644)) + link := filepath.Join(home, linkedDir) + require.NoError(t, os.MkdirAll(filepath.Dir(link), 0755)) + require.NoError(t, os.Symlink(filepath.Join(pkg, linkedDir), link)) + backed, err := backupConflicts(pkg, home, false) + require.NoError(t, err) + assert.Empty(t, backed) + content, err := os.ReadFile(source) + require.NoError(t, err) + assert.Equal(t, "original skill", string(content)) + assert.NoFileExists(t, source+".openboot.bak") + assert.FileExists(t, filepath.Join(home, rel)) + }) + } +} diff --git a/internal/installer/installer.go b/internal/installer/installer.go index 3beb8c28..808858b1 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -118,6 +118,7 @@ func Apply(plan InstallPlan, r Reporter) error { func ApplyContext(ctx context.Context, plan InstallPlan, r Reporter) error { steps := plannedSteps(plan) var softErrs []error + var results []stepResult for i, s := range steps { // ctrl+c cancels ctx. brew/npm honour it (exec.CommandContext), but the @@ -131,6 +132,7 @@ func ApplyContext(ctx context.Context, plan InstallPlan, r Reporter) error { r.Header(sectionTitle(i, len(steps), s.name)) err := s.run(ctx, plan, r) + results = append(results, stepResult{name: s.name, failed: err != nil}) if err == nil { continue } @@ -148,7 +150,7 @@ func ApplyContext(ctx context.Context, plan InstallPlan, r Reporter) error { softErrs = append(softErrs, fmt.Errorf("%s: %w", strings.ToLower(s.name), err)) } - showCompletionFromPlan(plan, r, len(softErrs)) + showCompletionFromPlan(plan, r, len(softErrs), results...) if len(softErrs) > 0 { slog.Info("install_completed", "soft_errors", len(softErrs)) @@ -215,7 +217,12 @@ func abortWith(softErrs []error, cause error) error { return errors.Join(append(softErrs, cause)...) } -func showCompletionFromPlan(plan InstallPlan, r Reporter, errCount int) { +type stepResult struct { + name string + failed bool +} + +func showCompletionFromPlan(plan InstallPlan, r Reporter, errCount int, results ...stepResult) { if plan.DryRun { showDryRunCompletionFromPlan(plan, r, errCount) return @@ -234,14 +241,13 @@ func showCompletionFromPlan(plan InstallPlan, r Reporter, errCount int) { } ui.Println() - r.Info("What was installed:") - if !plan.PackagesOnly { - r.Info(" - Git configured with your identity") - } - r.Info(fmt.Sprintf(" - %d CLI packages", len(plan.Formulae))) - r.Info(fmt.Sprintf(" - %d GUI applications", len(plan.Casks))) - if len(plan.Npm) > 0 { - r.Info(fmt.Sprintf(" - %d npm global packages", len(plan.Npm))) + r.Info("Step results (package details above):") + for _, result := range results { + status := "completed" + if result.failed { + status = "failed" + } + r.Info(fmt.Sprintf(" - %s: %s", result.name, status)) } ui.Println() diff --git a/internal/installer/installer_extra_test.go b/internal/installer/installer_extra_test.go index 03fd875c..7dfddb9f 100644 --- a/internal/installer/installer_extra_test.go +++ b/internal/installer/installer_extra_test.go @@ -134,8 +134,7 @@ func TestShowCompletionFromPlan_WithNpm(t *testing.T) { }) } -// A real run's summary is pinned line for line, so making the dry-run summary -// honest can't quietly reword it. +// Real summaries report step outcomes, never planned package counts as installed. func TestShowCompletionFromPlan_RealRunOutput(t *testing.T) { tests := []struct { name string @@ -156,16 +155,20 @@ func TestShowCompletionFromPlan_RealRunOutput(t *testing.T) { Npm: []string{"typescript"}, } rr := &recordReporter{} - showCompletionFromPlan(plan, rr, tt.errCount) + showCompletionFromPlan(plan, rr, tt.errCount, + stepResult{name: "Packages", failed: tt.errCount > 0}, + stepResult{name: "npm globals"}) + packageStatus := "completed" + if tt.errCount > 0 { + packageStatus = "failed" + } assert.Equal(t, tt.wantHeaders, rr.headers) assert.Equal(t, []string{ tt.wantStatus, - "What was installed:", - " - Git configured with your identity", - " - 2 CLI packages", - " - 1 GUI applications", - " - 1 npm global packages", + "Step results (package details above):", + " - Packages: " + packageStatus, + " - npm globals: completed", "Next steps:", " - Restart your terminal to apply changes", " - Run 'brew doctor' to verify Homebrew health",