14 Commits

Author SHA1 Message Date
Sameen Karim 4c05e58b83 cache selected remote (#128)
* Save selected remote to gh-stack.remote git config

Users with multiple git remotes are prompted to choose a remote on
every gh stack operation, which is tedious. This adds the ability to
persist that choice so it only needs to be made once.

When a user interactively selects a remote (because multiple remotes
exist and none is configured as a push default), they are now shown a
Y/n follow-up prompt offering to save that remote for all future gh
stack operations. If accepted, the choice is written to the local git
config key `gh-stack.remote`, and instructions for changing or clearing
it are printed.

The saved remote is checked in `ResolveRemote` after the standard git
push config keys (branch.<name>.pushRemote, remote.pushDefault,
branch.<name>.remote) but before falling back to listing all remotes.
This means per-branch git push configuration still takes precedence,
and the --remote flag on individual commands continues to override
everything.

All commands that resolve a remote (push, submit, sync, rebase,
checkout, link, modify, trunk) go through the shared `pickRemote`
helper, so they all benefit automatically.

Changes:

- Add GetSavedRemote, SaveRemote, ClearRemote to the git Ops interface,
  defaultOps implementation, public wrappers, and MockOps
- Check gh-stack.remote in ResolveRemote's priority chain
- Move pickRemote from push.go to utils.go as a shared helper
- Add save-remote confirmation prompt after interactive remote selection
- Add unit tests for pickRemote save/decline/skip/override flows
- Add integration tests for ResolveRemote with saved remote and
  precedence, and for the SaveRemote/GetSavedRemote/ClearRemote
  lifecycle

* add error message for save failure

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-15 13:54:20 -04:00
Sameen Karim 756002b4c9 ensure local trunk branch for required operations (#127)
* Ensure trunk branch exists locally before commands that need it

When a user starts a stack after renaming their initial branch
(e.g. `git branch -m newbranch`), the trunk branch (e.g. main) may
not exist as a local branch. Commands that pass the trunk name to git
operations like merge-base, rebase, or rev-parse then fail with:

  fatal: Not a valid object name main

Add an `ensureLocalTrunk` helper that checks whether the trunk branch
exists locally and, if not, fetches it from the remote and creates a
local tracking branch. This mirrors the pattern already used in the
checkout command for importing stacks.

Commands updated:
- modify: call ensureLocalTrunk before the linearity check in
  CheckStackLinearity, which uses IsAncestor(trunk, branch). This was
  the originally reported failure.
- rebase: call ensureLocalTrunk after fetch and before fastForwardTrunk
  and the cascade rebase. git rebase requires a locally resolvable ref;
  the remote tracking ref alone is not sufficient.
- trunk: call ensureLocalTrunk before CheckoutBranch so that
  `gh stack trunk` works even when trunk was never created locally.
- checkout: refactor the existing inline BranchExists + CreateBranch
  block to use the shared helper.

Also fix an incorrect comment in fastForwardTrunk that claimed "the
remote tracking ref is sufficient for rebasing" — verified empirically
that `git rebase main` fails when main has no local branch, even after
fetching origin/main.

Commands that were already safe and required no changes:
- sync: fetches trunk explicitly and fastForwardTrunk guards with
  BranchExists
- push, switch, navigate, unstack: do not reference trunk
- add, submit: do not require trunk as a local git ref
- view: handles IsAncestor errors gracefully (false positive is
  acceptable since rebase will fix it)

* add check to avoid unnecessary remote selection prompt
2026-06-15 13:54:20 -04:00
Sameen Karim 8c2d9e3da6 sync: skip trunk fast-forward silently when local branch doesn't exist (#125)
When the trunk branch (e.g. main) doesn't exist locally — only the
remote tracking ref (origin/main) exists — `fastForwardTrunk` called
`git rev-parse main origin/main` which failed, emitting:

  ⚠ Could not compare trunk main with remote — skipping trunk update

This also caused `stackNeedsRebase` to always return true (since
`IsAncestor("main", ...)` errors out), forcing an unnecessary rebase
and force-push on every sync.

Add a `BranchExists` check at the top of `fastForwardTrunk`. If the
local trunk doesn't exist, return silently — there's nothing to
fast-forward, and the remote tracking ref is sufficient for rebasing
via git's DWIM resolution.
2026-06-15 13:54:19 -04:00
Sameen Karim d235a21a9c alert for unsupported auth tokens (#113)
When users authenticate the GitHub CLI with a personal access token
(PAT) instead of OAuth (`gh auth login`), the `cli_internal` stacks
API endpoints return 404. The CLI previously interpreted this as
"Stacked PRs are not enabled for this repository," which is misleading
— the feature may be enabled, but the token type simply cannot access
the internal endpoints.

This is a recurring source of user confusion. The docs already note
that PATs are not supported, but users don't always read them before
hitting the error.

This change adds token-type detection by inspecting the `gh` auth
token prefix:

  - `gho_`        → OAuth (supported)
  - `ghs_`        → GitHub App installation token (supported)
  - `ghp_`        → Classic PAT (NOT supported)
  - `github_pat_` → Fine-grained PAT (NOT supported)

When a PAT is detected, the CLI now shows:

  ⚠ Personal access tokens are not supported by gh stack
    Run `gh auth login` to authenticate with OAuth instead.

Instead of the misleading:

  ⚠ Stacked PRs are not enabled for this repository

Changes:

- Add `internal/config/auth.go` with auth detection methods on Config:
  `IsPersonalAccessToken()`, `WarnIfPAT()`, and `RepoHost()`. Uses a
  `TokenForHostFn` field on Config for test overrides, following the
  same pattern as `GitHubClientOverride`.

- Add a pre-flight PAT check in `cmd/submit.go` before the
  `ListStacks` call. If a PAT is detected, the command aborts early
  with a clear error instead of making a doomed API call.

- Update all 404 handlers for `cli_internal` endpoints to check the
  token type and show the appropriate message:
  - `cmd/submit.go` (createNewStack)
  - `cmd/link.go` (listStacksSafe, createLink)
  - `cmd/checkout.go` (checkoutRemoteStack)

- Add `warnStacksUnavailableOrPAT()` helper in `cmd/utils.go` that
  shows the PAT-specific warning when applicable, falling back to the
  generic "not enabled" message for non-PAT tokens.

- Add unit tests in `internal/config/auth_test.go` for token prefix
  detection and warning output.

- Add integration tests in `cmd/submit_test.go` verifying that both
  classic PATs (`ghp_`) and fine-grained PATs (`github_pat_`) trigger
  the pre-flight check and abort before any API calls.

- Add `warnStacksUnavailableOrPAT` tests in `cmd/utils_test.go`
  verifying correct message selection based on token type.

- Update existing 404 tests to explicitly set an OAuth token so they
  continue exercising the ListStacks 404 path.
2026-06-15 13:54:17 -04:00
Sameen Karim 89643dc8db input prompter improvements (#98)
* include prefix in branch name input

* custom prompter with colored input text

* minor fix: arrow direction for initialized stack

* fix comment

* handle SetTermMode err
2026-05-26 17:39:37 -04:00
Sameen Karim b219e96fb5 rebase with preserve dates opt (#96)
* Add --committer-date-is-author-date flag to gh stack rebase

Introduce an opt-in `--committer-date-is-author-date` flag (with
`--preserve-dates` alias) for `gh stack rebase`. The flag is passed
through to every underlying `git rebase` invocation in the cascade,
keeping committer dates equal to author dates so that identical content
rebased onto an identical parent produces stable SHAs. This reduces
spurious force-push notifications and noisy review timelines, especially
in deep stacks where bottom branches get re-rebased on every merge.

Git layer changes:
- Add `RebaseOpts` struct with `CommitterDateIsAuthorDate` field to
  `internal/git/gitops.go`
- Update `Ops` interface, `defaultOps`, public wrappers, and
  `rebaseContinueOnce`/`tryAutoResolveRebase` helpers to accept and
  forward the flag
- Update `MockOps` to match the new signatures

Command layer changes:
- Register `--committer-date-is-author-date` and `--preserve-dates`
  flags on the cobra command in `cmd/rebase.go`
- Add `CommitterDateIsAuthorDate` to `cascadeRebaseOpts` and thread it
  to all `git.Rebase`/`git.RebaseOnto` calls in `cmd/utils.go`
- Persist the flag in `rebaseState` JSON so `--continue` resumes with
  the same behavior; pass it to `RebaseContinue` and subsequent cascade
  calls
- Update `internal/modify/apply.go` callers to pass zero-value
  `RebaseOpts{}`

Tests:
- Update all existing mock signatures in rebase, sync, and modify tests
- Add tests for flag passthrough, `--preserve-dates` alias, state
  round-trip, `--continue` flag restoration, and conflict state
  persistence

Docs:
- Update flag tables and examples in README.md and
  docs/src/content/docs/reference/cli.md

* clearer wording in docs and help text
2026-05-26 17:39:36 -04:00
Sameen Karim e7acfc1b16 fix for rebase in sync cmd (#95)
* fix: sync performs cascade rebase even when trunk is already up-to-date

Previously, `gh stack sync` gated the cascade rebase on whether trunk
or stack branches were fast-forwarded during the current run. This meant
that if the user had already updated trunk locally (e.g., `git pull`),
sync would skip the rebase entirely even though stack branches hadn't
been rebased onto the current trunk.

This change:
- Adds `stackNeedsRebase()` to detect stale branches regardless of
  whether trunk was updated in this run
- Extracts shared helpers (`fastForwardTrunk`, `cascadeRebase`,
  `resolveOriginalRefs`) from duplicated code in sync.go and rebase.go
  into utils.go, reducing ~450 lines of duplication
- Fixes rebase.go to skip queued branches (was only skipping merged),
  consistent with sync's behavior via `IsSkipped()`
- Refactors rebase --continue to reuse the shared cascade helper

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* address review feedback: error handling and index validation

- resolveOriginalRefs now returns (map, error) instead of silently
  swallowing RevParseMap failures; sync warns and skips rebase, rebase
  aborts with a clear error
- cascadeRebase uses a new Err field on the result struct to distinguish
  fatal errors (e.g. checkout failure) from recoverable conflicts;
  callers no longer enter conflict-recovery flow for non-conflict errors
- continueRebase validates that remaining branch indices are contiguous
  in stack order, erroring out if the stack was reordered between
  conflict and --continue

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-26 17:39:36 -04:00
Sameen Karim 8cddfd4e21 Optimize view/modify TUI load time with parallel fetching (#79)
- Deduplicate API calls: syncStackPRs now returns PRDetails for
  LoadBranchNodes to reuse, eliminating redundant FindPRDetailsForBranch calls
- Parallelize API calls in syncStackPRs (capped at 6 concurrent requests)
- Parallelize git operations in LoadBranchNodes (capped at 4 concurrent)
- Show "Loading stack..." indicator for interactive sessions

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-11 11:09:32 -04:00
Sameen Karim 7a268fc380 modify command (#72)
* git primitives for modify cmd

* extract reusable TUI parts

* modify cmd

* recreate stack after modify

* add checks to prevent other modifications while modify is applying

* modify continue for resuming after resolving conflicts

* fix bug with duplicate stack entries after modifying

* reuse conflict resolution help msg from rebase

* additional confirmation before overwriting stack on remote

* fix recreate order of operations

Co-authored-by: Copilot <copilot@github.com>

* move base commit instead of cherry picking for fold up

* check to ensure we aren't left with zero branches

* unify and dedupe across view and modify tui

* more detailed help instructions

Co-authored-by: Copilot <copilot@github.com>

* only recommend submit if stack exists on remote

Co-authored-by: Copilot <copilot@github.com>

* tests for modify tui, apply modifications, submit modifications

* refactor submit for regular and pending modifications

* rename recover to abort

Co-authored-by: Copilot <copilot@github.com>

* docs for modify cmd

* tui styling updates

* updated tui screenshot

* addressing review comments

* Fix 4 bugs from code review

Bug 1: Move RevParseMap error check before using originalRefs.
The error from git.RevParseMap() was deferred past iteration of
originalRefs, which could panic on a nil map.

Bug 2: Differentiate cherry-pick vs rebase conflicts in modify.
Cherry-pick conflicts don't save state as 'conflict' phase, so
--continue won't work. Now prints --abort-only instructions for
cherry-pick conflicts.

Bug 3: Unwind now cleans up branches created by renames.
After restoring snapshot branches, Unwind deletes renamed branch
names that don't belong to the original snapshot.

Bug 4: Simplify push message in submit command.
Changed from 'Pushing N branches to remote...' to 'Pushing to
remote...' since individual branches may fail.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix 7 nit issues from code review

11: Add named constants for phase strings (PhaseApplying, PhaseConflict,
PhasePendingSubmit) in state.go; replace remaining raw literals in
state.go CheckStateGuard.

14: Fix bottomLines comment mismatch — listed 3 items but value is 2.

15: Extract magic number 88 to MinWidthForArt constant in header.go.

16: Remove unused stackview import anchor in model.go — the import
is used via types.go where BranchNode is embedded.

17: Simplify CheckStackLinearity parent resolution — ActiveBaseBranch
already handles skipping merged branches.

18: Fix rename undo matching any rename — add NewName check so only
the specific rename being undone is matched.

20: Add TestUndoRename and TestUndoRename_DoesNotAffectOtherRenames
to validate rename undo behavior.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Make cherry-pick conflicts recoverable via --continue

Previously, cherry-pick conflicts during fold-down operations could only
be resolved with --abort. Now they save full conflict state (phase,
conflict type, fold branch/target, remaining branches) to the state file,
enabling recovery via 'gh stack modify --continue'.

Changes:
- Add ConflictType field to StateFile (rebase or cherry_pick)
- Add FoldBranch/FoldTarget fields for cherry-pick context
- Add CherryPickContinue to git package (cherry-pick --continue)
- Save cherry-pick conflict state in ApplyPlan with remaining branches
- ContinueApply handles both rebase and cherry-pick conflicts
- Unified conflict messaging in cmd/modify.go (both types show --continue)
- Updated test to verify cherry-pick conflict state is saved correctly

* Apply suggestions from code review

Co-authored-by: Luke Ghenco <lukeghenco@github.com>
Co-authored-by: Sameen Karim <skarim@github.com>

---------

Co-authored-by: Copilot <copilot@github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Luke Ghenco <lukeghenco@github.com>
2026-05-04 22:34:42 -04:00
Sameen Karim 42e43a47ae ignore stale merged/closed PRs for reused branch names (#49)
* ignore stale merged/closed PRs for reused branch names

* guard for edge case of deleted PR
2026-04-20 11:18:19 -04:00
Sameen Karim 8893d274f2 preflight check for stacked PR availability in submit (#44)
* preflight check for stacked prs before submit

* close pipe read end in test to avoid FD leak

* concise var reuse
2026-04-20 11:17:20 -04:00
Sameen Karim 766d0e2ab9 fast forward active branches where local is behind remote (#40)
* fast forward active branches where local is behind remote
2026-04-20 11:10:55 -04:00
Sameen Karim e06284ff5c skip pulling merged branches during remote checkout (#16)
* skip pulling merged branches during remote checkout

* show message if stack fully merged
2026-04-13 18:36:35 -04:00
Sameen Karim b01754e4a9 Initial release 2026-04-10 03:32:08 -04:00