Files
skillshare/cmd/skillshare/pull.go
T
Willie 475b176914 fix(pull): keep the local config.yaml when a later pull brings a tracked copy (#362)
* fix(pull): keep the local config.yaml when a later pull brings a tracked copy

#357 refuses a root-scope first pull when the remote tracks config.yaml, but once upstream is set, a pull that merges in a remote-tracked copy still replaced this machine's config: Git treats the ignored file as expendable. Snapshot config.yaml around later pulls (CLI pull, push --pull, and the dashboard), restore it, and warn so the user can untrack it with push.

Refs #353

* fix(git): untrack config.yaml after push --pull and warn on identical copies

push --pull ran the root safety sweep before integrating the remote, so a
pull that brought in a remote-tracked config.yaml was pushed back as-is:
the remote kept tracking it and the next first pull elsewhere was refused.
Re-run EnsureConfigUntracked after the pull and commit the removal before
pushing.

The warning also depended on the pull changing the local bytes, so a
tracked copy identical to this machine's went unreported. KeepLocalConfig's
restore now reports whether the repo tracks config.yaml after the pull.

* fix(git): only restore config.yaml when the pull could have touched it

KeepLocalConfig wrote its snapshot back after every root-scope pull, so an
edit made to an untracked config.yaml while the pull ran was silently
replaced by the stale copy. Git only rewrites config.yaml when it is
tracked before or after the pull, so restore only in that case.

* fix(git): restore config.yaml only when the pull changed its index entry

Gating the restore on "tracked before or after" still overwrote edits made
during a pull when config.yaml was already tracked and the pull left it
alone. Compare config.yaml's index entry (mode, blob, stage) before and
after the pull instead; a merge, reset or conflict that touches the file
changes it, and anything else keeps the current file.

* fix(git): warn about a tracked config.yaml only when the upstream tracks it

The warning followed the local index, so a config.yaml tracked only by a
local, unpushed commit was reported as tracked by the remote, and the
suggested push would publish it in history. Check the upstream tree with
RemoteTracksConfig("@{u}") instead.

* fix(git): restore config.yaml after a pull that aborts its merge

A merge that brought in a tracked config.yaml and conflicted elsewhere was
aborted, which deleted the file again and returned the index entry to its
pre-pull state, so restore saw no change and the local config was lost.
Also restore when the snapshotted file is missing after the pull.

* fix(git): keep config.yaml ignored when a later rule negates it

EnsureConfigUntracked only checked that a "config.yaml" line existed, so a
pulled .gitignore with a later "!config.yaml" left the file unignored and
the following `git add -A` tracked this machine's copy again. Check the
effective ignore state and append an overriding entry when needed.

* fix: commit post-pull .gitignore repairs and keep config.yaml's mode

push --pull committed only when EnsureConfigUntracked removed an index
entry, so a pulled .gitignore that stopped ignoring config.yaml was
repaired locally but never pushed, leaving the tree dirty. Commit whenever
the safety step leaves changes.

KeepLocalConfig skipped the restore when the bytes matched, so a checkout
that rewrote config.yaml with the default mode dropped this machine's
restrictive permissions. Compare the mode too, and chmod after writing
since WriteFile's mode is masked by umask.

* fix(git): restore config.yaml over a tracked config.yaml directory

A pull that checks out a tracked config.yaml/ tree replaces the ignored
local file with a directory, which os.Remove cannot delete, so restore
failed and the local config stayed lost. Remove a directory there before
writing the snapshot back; its contents are in Git. EnsureConfigUntracked
now untracks recursively so push can remove that tree too.

* fix: keep post-checkout config edits and preview .gitignore repairs

Restore wrote the snapshot back whenever the pull changed config.yaml's
index entry, even when a newer copy had been written after Git checked it
out. Skip the restore when the file on disk no longer matches the blob the
pull checked out.

A dry-run push or commit only previewed untracking config.yaml, so when a
later "!config.yaml" rule un-ignored it the preview listed config.yaml to
commit while a real run repairs .gitignore instead. Preview that repair.

* fix: scope the post-pull safety commit and keep post-checkout symlinks

The post-pull safety step in push --pull ran `git add -A`, so an edit made
by another process while the pull ran was committed and pushed under the
config-safety message. Stage only .gitignore on top of the config.yaml
removal and commit the index as staged.

The post-checkout edit check skipped symlinks, so a dotfiles manager that
replaced config.yaml with a newer link after the checkout had it replaced
by the stale snapshot. Treat a link where Git checked out a file, or a
different link target, as a newer local edit.

* fix: preview explicit config.yaml entries and refuse other .gitignore edits

A dry run previewed the .gitignore repair only when config.yaml was not
ignored at all, but a real run also appends the explicit entry when a
broader rule such as *.yaml ignores it. Preview whenever the entry is
missing too.

The post-pull safety commit staged the whole .gitignore, so an edit made
by another process while the pull ran was pushed with it. Refuse unless
the file only gained config.yaml lines over its staged version.

* fix: report config.yaml restore failures instead of dropping them

integrateRemote declared the KeepLocalConfig result with :=, shadowing the
named err that the deferred restore joins its failure into, so a failed
restore was swallowed and pull or push --pull went on to sync targets with
another machine's config.yaml. The dashboard pull replaced the pull's own
error with a bare 500 on a restore failure, losing the conflict response
and the ops log entry; join the errors so both are reported.
2026-10-04 01:58:30 +08:00

229 lines
6.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"errors"
"fmt"
"os/exec"
"strings"
"time"
"skillshare/internal/config"
gitops "skillshare/internal/git"
"skillshare/internal/oplog"
"skillshare/internal/ui"
)
func cmdPull(args []string) error {
if wantsHelp(args) {
printPullHelp()
return nil
}
start := time.Now()
dryRun := false
force := false
for _, arg := range args {
switch arg {
case "--dry-run", "-n":
dryRun = true
case "--force", "-f":
force = true
}
}
cfg, err := config.Load()
if err != nil {
return err
}
err = pullFromRemote(cfg, dryRun, force)
if !dryRun {
e := oplog.NewEntry("pull", statusFromErr(err), time.Since(start))
if err != nil {
e.Message = err.Error()
}
oplog.WriteWithLimit(config.ConfigPath(), oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
}
return err
}
// pullFromRemote pulls from git remote and syncs to all targets
func pullFromRemote(cfg *config.Config, dryRun, force bool) error {
pullStart := time.Now()
spinner := ui.StartSpinner("Checking repository...")
source, err := resolveGitRoot(cfg, spinner)
if err != nil {
return err
}
// Check if source is a git repo with a configured remote
if err := checkGitRepo(source, spinner); err != nil {
return err
}
// Check for uncommitted changes
cmd := exec.Command("git", "status", "--porcelain")
cmd.Dir = source
output, err := cmd.Output()
if err != nil {
spinner.Fail("Failed to check git status")
return fmt.Errorf("failed to check git status: %w", err)
}
if len(strings.TrimSpace(string(output))) > 0 {
spinner.Fail("Local changes detected")
ui.Note("Run: skillshare push")
ui.Note(fmt.Sprintf("Or: cd %s && git stash -u", source))
return fmt.Errorf("local changes must be pushed or stashed before pulling")
}
width := ui.RowWidth("Pull", "Sync")
if dryRun {
spinner.Stop()
ui.Row(ui.MarkNone, "Pull", "would run git pull", width)
ui.Row(ui.MarkNone, "Sync", "would run skillshare sync", width)
fmt.Println()
ui.DryRun()
return nil
}
info, remoteEmpty, err := integrateRemote(source, force, cfg.GitRoot == "root", spinner)
if err != nil {
return err
}
spinner.Stop()
if remoteEmpty {
ui.Row(ui.MarkWarn, "Pull", "remote has no branches yet", width)
ui.Note("Push your skills first: skillshare push")
} else if info != nil {
ui.Row(ui.MarkOK, "Pull", pullSummary(info)+ui.Took(time.Since(pullStart)), width)
printCommitNotes(info.Commits)
}
return syncPulledScope(cfg)
}
// integrateRemote brings the remote's history into source. First pull (no
// upstream): fetch, then merge or reset onto the remote default branch and
// set upstream (see gitops.FirstPull). Subsequent pulls: normal git pull,
// which merges. remoteEmpty reports a remote with no branches yet.
// keepConfig (root scope) keeps this machine's config.yaml on later pulls even
// when the remote tracks one, and warns so the user can untrack it with push.
// FirstPull refuses that case instead (ErrRemoteTracksConfig).
func integrateRemote(source string, force, keepConfig bool, spinner *ui.Spinner) (info *gitops.UpdateInfo, remoteEmpty bool, err error) {
if !gitops.HasUpstream(source) {
spinner.Update("Fetching from remote...")
info, err = gitops.FirstPull(source, force)
if errors.Is(err, gitops.ErrNoRemoteBranches) {
return nil, true, nil
} else if errors.Is(err, gitops.ErrRemoteTracksConfig) {
spinner.Fail("Remote tracks config.yaml")
ui.Note("The remote repository tracks machine-specific config.yaml.")
ui.Note("Untrack it on the remote first via 'skillshare push' from the machine that committed it, then pull.")
return nil, false, err
} else if err != nil {
spinner.Fail("Pull failed")
if errors.Is(err, gitops.ErrMergeFailed) {
ui.Note(fmt.Sprintf("Resolve manually: cd %s && git merge --allow-unrelated-histories <remote branch>", source))
ui.Note("Or force-pull: skillshare pull --force (replaces local with remote)")
} else if !isAuthError(err.Error()) {
hintGitRemoteError(err.Error()) // auth guidance is already part of err
}
return nil, false, err
}
return info, false, nil
}
if keepConfig {
// Not :=, which would shadow the named err the deferred restore reports into.
restore, keepErr := gitops.KeepLocalConfig(source)
if keepErr != nil {
spinner.Fail("Pull failed")
return nil, false, keepErr
}
defer func() {
remoteTracks, restoreErr := restore()
if restoreErr != nil {
err = errors.Join(err, restoreErr)
} else if remoteTracks {
spinner.Warn("The remote tracks config.yaml; kept this machine's copy")
ui.Note("Remove it from the remote: skillshare push")
}
}()
}
spinner.Update("Running git pull...")
if info, err = gitops.PullWithEnv(source, gitops.AuthEnvForRepo(source)); err != nil {
spinner.Fail("git pull failed")
fmt.Println(err.Error())
hintGitRemoteError(err.Error())
return nil, false, fmt.Errorf("git pull failed: %w", err)
}
return info, false, nil
}
// syncPulledScope syncs what the git root scope holds (always global — pull
// operates on the global source). Sync opens with its own blank line, and
// extras are skipped when none are configured so sync does not print its
// setup guide. The config is read again because the pull may have changed it.
func syncPulledScope(cfg *config.Config) error {
if pulled, err := config.Load(); err == nil {
cfg.Extras = pulled.Extras
}
for _, args := range pulledScopeSyncArgs(cfg.GitRoot) {
if args[0] == "extras" && len(cfg.Extras) == 0 {
continue
}
if err := cmdSync(args); err != nil {
return err
}
}
return nil
}
// pulledScopeSyncArgs returns the `sync` invocations that cover a git root
// scope, in order. Retry hints print the same commands.
func pulledScopeSyncArgs(gitRoot string) [][]string {
switch gitRoot {
case "agents":
return [][]string{{"agents", "--global"}}
case "extras":
return [][]string{{"extras", "--global"}}
case "root":
return [][]string{{"--global"}, {"agents", "--global"}, {"extras", "--global"}}
}
return [][]string{{"--global"}}
}
// pullSummary says what a pull brought in, like update does for a tracked
// repository.
func pullSummary(info *gitops.UpdateInfo) string {
switch {
case info.UpToDate:
return "already up to date"
case len(info.Commits) == 0:
return "checked out the remote branch"
}
return fmt.Sprintf("%s, %s changed (+%d −%d)",
plural(len(info.Commits), "commit"), plural(info.Stats.FilesChanged, "file"),
info.Stats.Insertions, info.Stats.Deletions)
}
func printPullHelp() {
printHelp("skillshare pull [options]", "Pull from git remote and sync to all targets.",
helpGroup{title: "Options", rows: []helpRow{
{"-n, --dry-run", "Preview changes without applying"},
{"-f, --force", "Force-pull (reset local to remote on first pull)"},
}},
helpExamples(
helpRow{"skillshare pull", "Pull and sync"},
helpRow{"skillshare pull --dry-run", "Preview what would happen"},
helpRow{"skillshare pull --force", "Discard local, use remote"},
),
)
}