Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -467,3 +467,4 @@ Compared to the typical workflow, there's no need to name branches, run `git add
| 5 | Invalid arguments or flags |
| 6 | Disambiguation required (branch belongs to multiple stacks) |
| 7 | Rebase already in progress |
| 8 | Stack is locked by another process |
3 changes: 1 addition & 2 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,7 @@ func runAdd(cfg *config.Config, opts *addOptions, args []string) error {
}

if err := stack.Save(gitDir, sf); err != nil {
cfg.Errorf("failed to save stack state: %s", err)
return ErrSilent
return handleSaveError(cfg, err)
}

// Print summary
Expand Down
2 changes: 1 addition & 1 deletion cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ func runInit(cfg *config.Config, opts *initOptions) error {
syncStackPRs(cfg, &sf.Stacks[len(sf.Stacks)-1])

if err := stack.Save(gitDir, sf); err != nil {
return err
return handleSaveError(cfg, err)
}

// Print result
Expand Down
3 changes: 1 addition & 2 deletions cmd/push.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,7 @@ func runPush(cfg *config.Config, opts *pushOptions) error {
syncStackPRs(cfg, s)

if err := stack.Save(gitDir, sf); err != nil {
cfg.Errorf("failed to save stack state: %s", err)
return ErrSilent
return handleSaveError(cfg, err)
}

cfg.Successf("Pushed and synced %d branches", len(s.ActiveBranches()))
Expand Down
3 changes: 1 addition & 2 deletions cmd/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,7 @@ func runSync(cfg *config.Config, opts *syncOptions) error {
updateBaseSHAs(s)

if err := stack.Save(gitDir, sf); err != nil {
cfg.Errorf("failed to save stack state: %s", err)
return ErrSilent
return handleSaveError(cfg, err)
}

cfg.Printf("")
Expand Down
3 changes: 1 addition & 2 deletions cmd/unstack.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ func runUnstack(cfg *config.Config, opts *unstackOptions) error {
// Remove from local tracking
sf.RemoveStackForBranch(target)
if err := stack.Save(gitDir, sf); err != nil {
cfg.Errorf("failed to save stack state: %s", err)
return ErrSilent
return handleSaveError(cfg, err)
}
cfg.Successf("Stack removed from local tracking")

Expand Down
17 changes: 17 additions & 0 deletions cmd/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ var (
ErrInvalidArgs = &ExitError{Code: 5} // invalid arguments or flags
ErrDisambiguate = &ExitError{Code: 6} // multiple stacks/remotes, can't auto-select
ErrRebaseActive = &ExitError{Code: 7} // rebase already in progress
ErrLockFailed = &ExitError{Code: 8} // could not acquire stack file lock
)

// ExitError is returned by commands to indicate a specific exit code.
Expand Down Expand Up @@ -77,6 +78,9 @@ type loadStackResult struct {
// branch, calls resolveStack (which may prompt for disambiguation), checks for
// a nil stack, and re-reads the current branch (in case disambiguation caused
// a checkout). Errors are printed via cfg and returned.
//
// loadStack does NOT acquire the stack file lock. The lock is acquired
// automatically by stack.Save() when writing.
func loadStack(cfg *config.Config, branch string) (*loadStackResult, error) {
gitDir, err := git.GitDir()
if err != nil {
Expand Down Expand Up @@ -133,6 +137,19 @@ func loadStack(cfg *config.Config, branch string) (*loadStackResult, error) {
}, nil
}

// handleSaveError translates a stack.Save error into the appropriate user
// message and exit error. Lock failures return ErrLockFailed (exit 8);
// other write failures return ErrSilent (exit 1).
func handleSaveError(cfg *config.Config, err error) error {
var lockErr *stack.LockError
if errors.As(err, &lockErr) {
cfg.Errorf("another process is currently editing the stack — try again later")
return ErrLockFailed
}
cfg.Errorf("failed to save stack state: %s", err)
return ErrSilent
Comment thread
skarim marked this conversation as resolved.
Resolved
}
Comment thread
skarim marked this conversation as resolved.
Resolved

// resolveStack finds the stack for the given branch, handling ambiguity when
// a branch (typically a trunk) belongs to multiple stacks. If exactly one
// stack matches, it is returned directly. If multiple stacks match, the user
Expand Down
2 changes: 1 addition & 1 deletion cmd/view.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func runView(cfg *config.Config, opts *viewOptions) error {
s := result.Stack
currentBranch := result.CurrentBranch

// Sync PR state
// Sync PR state and save (best-effort).
syncStackPRs(cfg, s)
_ = stack.Save(gitDir, sf)
Comment thread
skarim marked this conversation as resolved.
Resolved

Expand Down
73 changes: 73 additions & 0 deletions internal/stack/lock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package stack

import (
"fmt"
"os"
"path/filepath"
"time"
)

const lockFileName = "gh-stack.lock"

// LockError is returned when the stack file lock cannot be acquired.
// Callers can check for this with errors.As to distinguish lock failures
// from other errors.
type LockError struct {
Err error
}

func (e *LockError) Error() string { return e.Err.Error() }
func (e *LockError) Unwrap() error { return e.Err }
Comment thread
skarim marked this conversation as resolved.
Resolved

// LockTimeout is how long Lock() will wait for the exclusive lock before
// giving up. With the lock held only during file writes (milliseconds),
// this timeout primarily guards against stuck or orphaned lock files.
Comment thread
skarim marked this conversation as resolved.
Resolved
const LockTimeout = 5 * time.Second

// lockRetryInterval is the sleep between non-blocking lock attempts.
const lockRetryInterval = 100 * time.Millisecond

// FileLock provides an exclusive advisory lock on the stack file to prevent
// concurrent Load-Modify-Save races between multiple gh-stack processes.
type FileLock struct {
f *os.File
}

// Lock acquires an exclusive lock on the stack file in the given git directory.
// It retries with a non-blocking attempt every 100ms for up to LockTimeout.
//
// Most callers should not use Lock directly — stack.Save() acquires the lock
// automatically. Use Lock only when you need to hold the lock across multiple
// operations (e.g. Load-Modify-Save as an atomic unit).
Comment thread
skarim marked this conversation as resolved.
Resolved
func Lock(gitDir string) (*FileLock, error) {
path := filepath.Join(gitDir, lockFileName)
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return nil, fmt.Errorf("opening lock file: %w", err)
}

deadline := time.Now().Add(LockTimeout)
for {
err := tryLockFile(f)
if err == nil {
return &FileLock{f: f}, nil
}
if time.Now().After(deadline) {
f.Close()
return nil, fmt.Errorf("timed out waiting for stack lock after %s — another gh-stack process may be running", LockTimeout)
}
time.Sleep(lockRetryInterval)
}
Comment thread
skarim marked this conversation as resolved.
Resolved
}

// Unlock releases the lock. The lock file is intentionally left on disk to
// avoid a race where another process opens the same path, blocks on flock,
// then wakes up holding a lock on an unlinked inode while a third process
// creates a new file and locks a different inode.
func (l *FileLock) Unlock() {
if l == nil || l.f == nil {
return
}
unlockFile(l.f)
l.f.Close()
}
106 changes: 106 additions & 0 deletions internal/stack/lock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package stack

import (
"sync"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestLock_Basic(t *testing.T) {
dir := t.TempDir()

lock, err := Lock(dir)
require.NoError(t, err)
require.NotNil(t, lock)

lock.Unlock()
}

func TestLock_NilUnlockSafe(t *testing.T) {
// Unlock on nil should not panic.
var lock *FileLock
lock.Unlock()
}

func TestLock_BlocksUntilReleased(t *testing.T) {
dir := t.TempDir()

lock1, err := Lock(dir)
require.NoError(t, err)

acquired := make(chan struct{})
go func() {
lock2, err := Lock(dir)
require.NoError(t, err)
close(acquired)
lock2.Unlock()
}()
Comment thread
skarim marked this conversation as resolved.
Resolved

// lock2 should be blocked while lock1 is held.
select {
case <-acquired:
t.Fatal("lock2 acquired while lock1 was still held")
case <-time.After(300 * time.Millisecond):
// expected — lock2 is waiting
}

lock1.Unlock()

// After releasing lock1, lock2 should acquire promptly.
select {
case <-acquired:
// success
case <-time.After(5 * time.Second):
t.Fatal("lock2 did not acquire after lock1 was released")
}
}

func TestLock_SerializesConcurrentAccess(t *testing.T) {
dir := t.TempDir()

// Write an initial stack file with 0 stacks.
sf := &StackFile{SchemaVersion: 1, Stacks: []Stack{}}
require.NoError(t, Save(dir, sf))

// Run 10 concurrent goroutines, each adding a stack under lock.
// Uses Lock + Load + SaveLocked for atomic read-modify-write.
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()

lock, err := Lock(dir)
require.NoError(t, err)
defer lock.Unlock()

loaded, err := Load(dir)
require.NoError(t, err)

loaded.AddStack(makeStack("main", "branch"))
require.NoError(t, SaveLocked(dir, loaded))
}(i)
}
wg.Wait()
Comment thread
skarim marked this conversation as resolved.
Resolved

// All 10 stacks should be present — no lost updates.
final, err := Load(dir)
require.NoError(t, err)
assert.Len(t, final.Stacks, 10, "all concurrent writes should be preserved")
}

func TestLock_FileLeftOnDisk(t *testing.T) {
dir := t.TempDir()

lock, err := Lock(dir)
require.NoError(t, err)
lock.Unlock()

// Lock file should still exist after unlock (no os.Remove race).
lock2, err := Lock(dir)
require.NoError(t, err, "should be able to re-lock after unlock")
lock2.Unlock()
}
Comment thread
skarim marked this conversation as resolved.
Resolved
18 changes: 18 additions & 0 deletions internal/stack/lock_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//go:build !windows

package stack

import (
"os"
"syscall"
)

// tryLockFile attempts a non-blocking exclusive lock.
// Returns nil on success, or an error if the lock is held by another process.
func tryLockFile(f *os.File) error {
return syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
}

func unlockFile(f *os.File) {
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
}
31 changes: 31 additions & 0 deletions internal/stack/lock_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//go:build windows

package stack

import (
"os"

"golang.org/x/sys/windows"
)

// tryLockFile attempts a non-blocking exclusive lock.
// Returns nil on success, or an error if the lock is held by another process.
func tryLockFile(f *os.File) error {
ol := new(windows.Overlapped)
return windows.LockFileEx(
windows.Handle(f.Fd()),
windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,
0, // reserved
1, // lock 1 byte
0, // high word
ol,
)
}

func unlockFile(f *os.File) {
ol := new(windows.Overlapped)
_ = windows.UnlockFileEx(
windows.Handle(f.Fd()),
0, 1, 0, ol,
)
}
19 changes: 18 additions & 1 deletion internal/stack/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,25 @@ func Load(gitDir string) (*StackFile, error) {
return &sf, nil
}

// Save writes the stack file to the given git directory.
// Save acquires an exclusive lock on the stack file, writes sf as JSON, and
// releases the lock. The lock is held only for the duration of the write.
func Save(gitDir string, sf *StackFile) error {
lock, err := Lock(gitDir)
if err != nil {
return &LockError{Err: err}
Comment thread
skarim marked this conversation as resolved.
Resolved
}
defer lock.Unlock()
return writeStackFile(gitDir, sf)
Comment thread
skarim marked this conversation as resolved.
Resolved
}

// SaveLocked writes the stack file without acquiring the lock. The caller
// must already hold the lock (via Lock) to protect the write. Use this when
// you need an atomic Load-Modify-Save sequence.
func SaveLocked(gitDir string, sf *StackFile) error {
return writeStackFile(gitDir, sf)
}

func writeStackFile(gitDir string, sf *StackFile) error {
sf.SchemaVersion = schemaVersion
if sf.Stacks == nil {
sf.Stacks = []Stack{}
Expand Down
1 change: 1 addition & 0 deletions skills/gh-stack/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,7 @@ gh stack unstack feature-auth --local
| 5 | Invalid arguments | Fix the command invocation (check flags and arguments) |
| 6 | Disambiguation required | A branch belongs to multiple stacks. Run `gh stack checkout <specific-branch>` to switch to a non-shared branch first |
| 7 | Rebase already in progress | Run `gh stack rebase --continue` (after resolving conflicts) or `gh stack rebase --abort` to start over |
| 8 | Stack is locked | Another `gh stack` process is writing the stack file. Wait and retry — the lock times out after 5 seconds |

## Known limitations

Expand Down
Loading