Something went wrong. Try again.
A code review TUI that tries to reduce how many red and green squiggles you have to squint at
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605package git
import ( "context" "crypto/sha256" "errors" "fmt" "io" "os" "path/filepath" "strconv" "strings" "time")
const worktreeCaptureAttemptsMax = 3
// ErrNoChanges reports that a selection has no comparison to review.var ErrNoChanges = errors.New("git: no changes to review")
type mutableCaptureKind uint8
const ( mutableCaptureStaged mutableCaptureKind = iota + 1 mutableCaptureUnstaged)
// MutableCaptureInstabilityError reports that a Git selection changed during// every bounded coherence attempt.type MutableCaptureInstabilityError struct { kind mutableCaptureKind attempts int}
// Error implements error.func (captureError MutableCaptureInstabilityError) Error() string { switch captureError.kind { case mutableCaptureStaged: return fmt.Sprintf( "git: HEAD or index changed while Thresh was capturing staged changes after %d attempts", captureError.attempts, ) case mutableCaptureUnstaged: return fmt.Sprintf( "git: worktree changed while Thresh was capturing it after %d attempts", captureError.attempts, ) default: return fmt.Sprintf( "git: mutable capture kind %d was unstable after %d attempts", captureError.kind, captureError.attempts, ) }}
// CaptureAttempts returns the exhausted coherence-attempt count.func (captureError MutableCaptureInstabilityError) CaptureAttempts() int { return captureError.attempts}
// MutableCapture owns one private object database containing an immutable// staged or tracked-worktree comparison.type MutableCapture struct { repository Repository unit ResolvedUnit directory string}
// Repository returns the repository view that can read the private endpoints.func (capture *MutableCapture) Repository() Repository { return capture.repository }
// Unit returns the exact immutable comparison.func (capture *MutableCapture) Unit() ResolvedUnit { return capture.unit }
// Close removes the private index and object database.func (capture *MutableCapture) Close() error { if capture == nil || capture.directory == "" { return errors.New("git: mutable capture is already closed") } directory := capture.directory if err := os.RemoveAll(directory); err != nil { return fmt.Errorf("git: removing private capture: %w", err) } capture.directory = "" capture.repository = Repository{} capture.unit = ResolvedUnit{} return nil}
// CaptureStaged captures one immutable HEAD-tree to index-tree unit.func (repository Repository) CaptureStaged(ctx context.Context) (*MutableCapture, error) { return repository.captureStaged(ctx, nil)}
func (repository Repository) captureStaged( ctx context.Context, beforeValidation func(int) error,) (*MutableCapture, error) { if ctx == nil { return nil, errors.New("git: context is required") } if err := repository.validate(); err != nil { return nil, err } for attempt := 1; attempt <= worktreeCaptureAttemptsMax; attempt++ { capture, coherent, err := repository.captureStagedAttempt(ctx, attempt, beforeValidation) if err != nil { return nil, err } if coherent { unit := capture.Unit() if unit.BaseCommit == unit.HeadCommit { closeErr := capture.Close() return nil, errors.Join( fmt.Errorf("%w: staged index is unchanged", ErrNoChanges), closeErr, ) } return capture, nil } } return nil, MutableCaptureInstabilityError{ kind: mutableCaptureStaged, attempts: worktreeCaptureAttemptsMax, }}
func (repository Repository) captureStagedAttempt( ctx context.Context, attempt int, beforeValidation func(int) error,) (result *MutableCapture, coherent bool, resultErr error) { head, err := repository.resolveCommit(ctx, "HEAD") if err != nil { if ctxErr := ctx.Err(); ctxErr != nil { return nil, false, ctxErr } return nil, false, errors.New("git: staged review requires an existing HEAD commit") } base, err := repository.resolveTree(ctx, head) if err != nil { return nil, false, err } index, err := repository.copyIndex(ctx) if err != nil { return nil, false, fmt.Errorf("git: capturing index tree: %w", err) } cleanupDirectory := index.directory defer func() { resultErr = errors.Join(resultErr, removeGitDirectoryIfSet(cleanupDirectory)) }() if err := repository.materializeFullIndex(ctx, index); err != nil { return nil, false, err } indexTree, err := repository.writeTree(ctx, index) if err != nil { return nil, false, err } if beforeValidation != nil { if err := beforeValidation(attempt); err != nil { return nil, false, fmt.Errorf("git: preparing staged capture validation: %w", err) } } headAfter, err := repository.resolveCommit(ctx, "HEAD") if err != nil { return nil, false, err } unchanged, err := index.sourceUnchanged() if err != nil { return nil, false, err } if headAfter != head || !unchanged { return nil, false, nil } result = index.capture(repository, ResolvedUnit{ CommitID: "git-staged", BaseCommit: base, HeadCommit: indexTree, Description: "staged changes", }) cleanupDirectory = "" return result, true, nil}
// CaptureUnstaged captures one coherent index-tree to tracked-worktree-tree// unit. Unknown and ignored files are not added to the synthetic tree.func (repository Repository) CaptureUnstaged(ctx context.Context) (*MutableCapture, error) { return repository.captureUnstaged(ctx, nil)}
func (repository Repository) captureUnstaged( ctx context.Context, beforeValidation func(int) error,) (*MutableCapture, error) { if ctx == nil { return nil, errors.New("git: context is required") } if err := repository.validate(); err != nil { return nil, err } if _, err := repository.resolveCommit(ctx, "HEAD"); err != nil { if ctxErr := ctx.Err(); ctxErr != nil { return nil, ctxErr } return nil, errors.New("git: unstaged review requires an existing HEAD commit") } for attempt := 1; attempt <= worktreeCaptureAttemptsMax; attempt++ { capture, coherent, err := repository.captureUnstagedAttempt(ctx, attempt, beforeValidation) if err != nil { return nil, err } if coherent { unit := capture.Unit() if unit.BaseCommit == unit.HeadCommit { return nil, errors.Join( fmt.Errorf("%w: tracked worktree is unchanged", ErrNoChanges), capture.Close(), ) } return capture, nil } } return nil, MutableCaptureInstabilityError{ kind: mutableCaptureUnstaged, attempts: worktreeCaptureAttemptsMax, }}
func (repository Repository) captureUnstagedAttempt( ctx context.Context, attempt int, beforeValidation func(int) error,) (result *MutableCapture, coherent bool, resultErr error) { index, err := repository.copyIndex(ctx) if err != nil { return nil, false, err } cleanupDirectory := index.directory defer func() { resultErr = errors.Join(resultErr, removeGitDirectoryIfSet(cleanupDirectory)) }() if err := repository.materializeFullIndex(ctx, index); err != nil { return nil, false, err } base, err := repository.writeTree(ctx, index) if err != nil { return nil, false, fmt.Errorf("git: capturing unstaged base tree: %w", err) } if err := markIndexEntriesRacy(index.path); err != nil { return nil, false, err } if err := repository.write( ctx, index.environment, nil, io.Discard, index.command("add", "-u", "--")..., ); err != nil { return nil, false, fmt.Errorf("git: capturing tracked worktree files: %w", err) } head, err := repository.writeTree(ctx, index) if err != nil { return nil, false, fmt.Errorf("git: capturing unstaged worktree tree: %w", err) } if beforeValidation != nil { if err := beforeValidation(attempt); err != nil { return nil, false, fmt.Errorf("git: preparing worktree capture validation: %w", err) } } if err := markIndexEntriesRacy(index.path); err != nil { return nil, false, err } clean, err := repository.indexMatchesWorktree(ctx, index) if err != nil { return nil, false, err } if !clean { return nil, false, nil } unchanged, err := index.sourceUnchanged() if err != nil { return nil, false, err } if !unchanged { return nil, false, nil } result = index.capture(repository, ResolvedUnit{ CommitID: "git-unstaged", BaseCommit: base, HeadCommit: head, Description: "unstaged changes", }) cleanupDirectory = "" return result, true, nil}
type temporaryIndex struct { directory string path string sourcePath string sourceDigest [sha256.Size]byte environment []string objectEnv []string materializeEnv []string sharedPath string sharedDigest [sha256.Size]byte}
func (repository Repository) copyIndex(ctx context.Context) (temporaryIndex, error) { sourcePath, err := repository.indexPath(ctx) if err != nil { return temporaryIndex{}, err } sharedPath, err := repository.sharedIndexPath(ctx) if err != nil { return temporaryIndex{}, err } realObjects, err := repository.objectDirectory(ctx) if err != nil { return temporaryIndex{}, err } directory, err := os.MkdirTemp("", "thresh-git-capture-") if err != nil { return temporaryIndex{}, fmt.Errorf("git: creating private capture directory: %w", err) } if err := os.Chmod(directory, 0o700); err != nil { return temporaryIndex{}, errors.Join( fmt.Errorf("git: protecting private capture directory: %w", err), removeGitDirectory(directory), ) } objects := filepath.Join(directory, "objects") if err := os.Mkdir(objects, 0o700); err != nil { return temporaryIndex{}, errors.Join( fmt.Errorf("git: creating private object database: %w", err), removeGitDirectory(directory), ) } path := filepath.Join(directory, "index") digest, err := copyIndexFile(sourcePath, path) if err != nil { return temporaryIndex{}, errors.Join(err, removeGitDirectory(directory)) } objectEnvironment := []string{ "GIT_OBJECT_DIRECTORY=" + objects, "GIT_ALTERNATE_OBJECT_DIRECTORIES=" + strconv.Quote(realObjects), } index := temporaryIndex{ directory: directory, path: path, sourcePath: sourcePath, sourceDigest: digest, environment: append(append([]string{}, objectEnvironment...), "GIT_INDEX_FILE="+path, "GIT_OPTIONAL_LOCKS=0", ), objectEnv: objectEnvironment, } if sharedPath == "" { return index, nil } privateGitDirectory := filepath.Join(directory, "git") if err := os.Mkdir(privateGitDirectory, 0o700); err != nil { return temporaryIndex{}, errors.Join( fmt.Errorf("git: creating private metadata directory: %w", err), index.remove(), ) } sharedDestination := filepath.Join(privateGitDirectory, filepath.Base(sharedPath)) sharedDigest, err := copyIndexFile(sharedPath, sharedDestination) if err != nil { return temporaryIndex{}, errors.Join(fmt.Errorf("git: copying shared index: %w", err), index.remove()) } head, err := repository.resolveCommit(ctx, "HEAD") if err != nil { return temporaryIndex{}, errors.Join(err, index.remove()) } if err := os.WriteFile(filepath.Join(privateGitDirectory, "HEAD"), []byte(head+"\n"), 0o600); err != nil { return temporaryIndex{}, errors.Join(fmt.Errorf("git: writing private HEAD: %w", err), index.remove()) } commonDirectory := filepath.Dir(realObjects) if err := os.WriteFile( filepath.Join(privateGitDirectory, "commondir"), []byte(commonDirectory+"\n"), 0o600, ); err != nil { return temporaryIndex{}, errors.Join( fmt.Errorf("git: writing private common-directory link: %w", err), index.remove(), ) } index.materializeEnv = append(append([]string{}, index.environment...), "GIT_DIR="+privateGitDirectory, "GIT_COMMON_DIR="+commonDirectory, "GIT_WORK_TREE="+repository.Root, ) index.sharedPath = sharedPath index.sharedDigest = sharedDigest return index, nil}
func (repository Repository) materializeFullIndex(ctx context.Context, index temporaryIndex) error { environment := index.environment if index.materializeEnv != nil { environment = index.materializeEnv } if err := repository.write( ctx, environment, nil, io.Discard, index.command("update-index", "--no-split-index")..., ); err != nil { return fmt.Errorf("git: materializing temporary index: %w", err) } return nil}
func (index temporaryIndex) remove() error { return removeGitDirectory(index.directory)}
func removeGitDirectory(directory string) error { if err := os.RemoveAll(directory); err != nil { return fmt.Errorf("git: removing private index and object database: %w", err) } return nil}
func removeGitDirectoryIfSet(directory string) error { if directory == "" { return nil } return removeGitDirectory(directory)}
func (index temporaryIndex) sourceUnchanged() (bool, error) { afterDigest, err := hashFile(index.sourcePath) if err != nil { return false, err } if index.sourceDigest != afterDigest { return false, nil } if index.sharedPath == "" { return true, nil } sharedAfter, err := hashFile(index.sharedPath) if err != nil { return false, err } return index.sharedDigest == sharedAfter, nil}
func (index temporaryIndex) capture( repository Repository, unit ResolvedUnit,) *MutableCapture { repository.environment = append([]string{}, index.objectEnv...) return &MutableCapture{repository: repository, unit: unit, directory: index.directory}}
func (index temporaryIndex) command(arguments ...string) []string { return append([]string{ "-c", "core.checkStat=default", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=" + index.directory, "-c", "core.ignoreStat=false", "-c", "core.trustctime=true", }, arguments...)}
func markIndexEntriesRacy(path string) error { oldNonzeroTime := time.Unix(1, 0) if err := os.Chtimes(path, oldNonzeroTime, oldNonzeroTime); err != nil { return fmt.Errorf("git: invalidating temporary index stat cache: %w", err) } return nil}
func (repository Repository) indexPath(ctx context.Context) (string, error) { output, err := repository.run(ctx, 1024*1024, "rev-parse", "--path-format=absolute", "--git-path", "index") if err != nil { return "", fmt.Errorf("git: finding worktree index: %w", err) } path := strings.TrimSuffix(string(output), "\n") if path == "" || !filepath.IsAbs(path) || strings.ContainsRune(path, 0) { return "", errors.New("git: worktree index path is invalid") } return filepath.Clean(path), nil}
func (repository Repository) sharedIndexPath(ctx context.Context) (string, error) { output, err := repository.run( ctx, 1024*1024, "rev-parse", "--path-format=absolute", "--shared-index-path", ) if err != nil { return "", fmt.Errorf("git: finding shared index: %w", err) } path := strings.TrimSuffix(string(output), "\n") if path == "" { return "", nil } if !filepath.IsAbs(path) || strings.ContainsRune(path, 0) || !strings.HasPrefix(filepath.Base(path), "sharedindex.") { return "", errors.New("git: shared index path is invalid") } return filepath.Clean(path), nil}
func (repository Repository) objectDirectory(ctx context.Context) (string, error) { output, err := repository.run( ctx, 1024*1024, "rev-parse", "--path-format=absolute", "--git-common-dir", ) if err != nil { return "", fmt.Errorf("git: finding common repository directory: %w", err) } commonDirectory := strings.TrimSuffix(string(output), "\n") if commonDirectory == "" || !filepath.IsAbs(commonDirectory) || strings.ContainsRune(commonDirectory, 0) { return "", errors.New("git: common repository directory is invalid") } objects := filepath.Join(filepath.Clean(commonDirectory), "objects") info, err := os.Stat(objects) if err != nil { return "", fmt.Errorf("git: opening common object database: %w", err) } if !info.IsDir() { return "", errors.New("git: common object database is not a directory") } return objects, nil}
func (repository Repository) resolveTree(ctx context.Context, revision string) (string, error) { output, err := repository.run(ctx, 256, "rev-parse", "--verify", revision+"^{tree}") if err != nil { return "", fmt.Errorf("git: resolving exact tree: %w", err) } tree := strings.TrimSuffix(string(output), "\n") if !validObjectID(tree) { return "", errors.New("git: resolved tree identity is malformed") } return tree, nil}
func (repository Repository) writeTree(ctx context.Context, index temporaryIndex) (string, error) { output := newBoundedBuffer(256) if err := repository.write( ctx, index.environment, nil, &output, index.command("write-tree")..., ); err != nil { return "", err } tree := strings.TrimSuffix(output.buffer.String(), "\n") if !validObjectID(tree) { return "", errors.New("git: written tree identity is malformed") } return tree, nil}
func (repository Repository) indexMatchesWorktree( ctx context.Context, index temporaryIndex,) (bool, error) { err := repository.write( ctx, index.environment, nil, io.Discard, index.command( "diff-files", "--quiet", "--no-ext-diff", "--", )..., ) if err == nil { return true, nil } var exitError interface{ ExitCode() int } if errors.As(err, &exitError) && exitError.ExitCode() == 1 { return false, nil } return false, fmt.Errorf("git: verifying tracked worktree snapshot: %w", err)}
func copyIndexFile(sourcePath, destinationPath string) ([sha256.Size]byte, error) { source, err := os.Open(sourcePath) if err != nil { return [sha256.Size]byte{}, fmt.Errorf("git: opening worktree index: %w", err) } destination, err := os.OpenFile(destinationPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { return [sha256.Size]byte{}, fmt.Errorf( "git: creating temporary index: %w", errors.Join(err, source.Close()), ) } digest := sha256.New() _, copyErr := io.Copy(io.MultiWriter(destination, digest), source) closeErr := errors.Join(source.Close(), destination.Close()) if err := errors.Join(copyErr, closeErr); err != nil { return [sha256.Size]byte{}, fmt.Errorf("git: copying worktree index: %w", err) } var result [sha256.Size]byte copy(result[:], digest.Sum(nil)) return result, nil}
func hashFile(path string) ([sha256.Size]byte, error) { file, err := os.Open(path) if err != nil { return [sha256.Size]byte{}, fmt.Errorf("git: reopening worktree index: %w", err) } digest := sha256.New() _, copyErr := io.Copy(digest, file) if err := errors.Join(copyErr, file.Close()); err != nil { return [sha256.Size]byte{}, fmt.Errorf("git: hashing worktree index: %w", err) } var result [sha256.Size]byte copy(result[:], digest.Sum(nil)) return result, nil}