branchclean

package
v0.167.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClassifyDeleteError

func ClassifyDeleteError(stderr string) (msg string, notMerged bool)

ClassifyDeleteError normalizes a `git branch -d` failure for display. git's "not fully merged" refusal comes with two trailing advice lines — `hint: … run 'git branch -D <name>'` and `hint: Disable this message with …` — that both steer the user into raw git and, printed once per branch, bury the actual result. This keeps only the first substantive line (dropping git's redundant "error: " prefix) and reports whether the failure was that merge-safety refusal, so the caller can surface a single gk-idiomatic --force hint instead of echoing per-branch git advice.

func EffectivelyMerged

func EffectivelyMerged(ctx context.Context, r git.Runner, base, branch string) (bool, error)

EffectivelyMerged reports whether merging branch into base would change nothing — base already holds every change the branch carries, even when the branch is NOT an ancestor (squash merge, rebase-then-merge, cherry-picks). The test is content-level: `git merge-tree --write-tree <base> <branch>` (a real three-way against their merge-base) compared with base's own tree. A conflicted merge is a definitive "not merged", not an error.

func EffectivelyMergedSet

func EffectivelyMergedSet(ctx context.Context, r git.Runner, base string, branches []string) map[string]bool

EffectivelyMergedSet runs the content check over branches, resolving base^{tree} once. A branch whose check errors is simply absent from the result — under-claiming keeps it listed as unmerged work, the safe direction for every caller. Cost: one rev-parse plus one merge-tree per branch, and one shared patch-id pass over the branches whose merge conflicts, deliberately WITHOUT git cherry — cherry computes per-commit patch-ids on both sides of the fork point, which gets expensive against a long-lived base, and survey commands run this by default.

func ForceDeleteHint

func ForceDeleteHint(n int) string

ForceDeleteHint is the single line shown once, after the delete loop, when n branches were skipped because git's -d refused them as not merged into the current branch. It replaces the per-branch `git branch -D` advice with the gk way. Returns "" when n == 0 (nothing was skipped for that reason).

func ParseCherryOutput

func ParseCherryOutput(output string) (allApplied bool, mixed bool, err error)

ParseCherryOutput은 git cherry 출력을 파싱하여 모든 커밋이 반영되었는지 판별한다. 반환값: allApplied (모두 `-`), mixed (`+`와 `-` 혼합), err

func RemoveWorktreeForBranchDelete

func RemoveWorktreeForBranchDelete(ctx context.Context, r git.Runner, path string) error

RemoveWorktreeForBranchDelete removes the worktree at path so the branch it holds can subsequently be deleted. Git refuses to remove a worktree with uncommitted or untracked changes unless --force is given, so a dirty worktree surfaces here as an error and the caller skips the branch — no uncommitted work is lost. Returns nil once the worktree is gone (or was already absent).

func WorktreeHint

func WorktreeHint(name, stderr string) string

WorktreeHint returns a one-line remediation hint when a branch deletion failed because a worktree has the branch checked out (git refuses `git branch -d/-D` in that case), or "" for any other failure. The caller prints it right after the error line.

Types

type BranchEntry

type BranchEntry struct {
	Name           string
	LastCommitMsg  string
	DiffStat       string
	LastCommitDate time.Time
	// CreatedAt is the timestamp of the first reflog entry for the
	// branch — i.e. when the branch ref itself was first written.
	// Differs from LastCommitDate when the branch was created from an
	// older base commit. Zero when reflog is unavailable / expired.
	CreatedAt time.Time
	Status    BranchStatus
	Upstream  string
	Gone      bool
	// IsRemote = true marks remote-only branches (e.g. origin/feat-x
	// with no local counterpart). The cleaner uses `git push <remote>
	// --delete <name>` for these, never `git branch -d`.
	IsRemote   bool
	RemoteName string // populated when IsRemote (e.g. "origin")
	// Worktree holds the path of the worktree that has this branch
	// checked out, when any. Git refuses to delete such a branch (even
	// with -D), so the cleaner deselects these by default, marks them in
	// the picker, and points the user at `gk wt remove`.
	Worktree string
}

BranchEntry는 수집된 브랜치 하나의 정보를 담는다.

func DeduplicateEntries

func DeduplicateEntries(entries []BranchEntry) []BranchEntry

DeduplicateEntries는 이름 기준으로 중복을 제거한다. 순수 함수. 동일 이름이 여러 번 나타나면 첫 번째만 유지한다.

func FilterProtected

func FilterProtected(entries []BranchEntry, protected map[string]bool) []BranchEntry

FilterProtected는 protected set에 포함된 브랜치를 제거한다. 순수 함수.

type BranchStatus

type BranchStatus string

BranchStatus는 브랜치의 현재 상태를 나타낸다.

const (
	StatusMerged       BranchStatus = "merged"
	StatusGone         BranchStatus = "gone"
	StatusStale        BranchStatus = "stale"
	StatusSquashMerged BranchStatus = "squash-merged"
	StatusAmbiguous    BranchStatus = "ambiguous"
	StatusActive       BranchStatus = "active"
	StatusRemoteOnly   BranchStatus = "remote-only"
)

type CleanCandidate

type CleanCandidate struct {
	BranchEntry
	AICategory string // "completed", "experiment", "in_progress", "preserve", "" (AI 미사용)
	AISummary  string // 최대 80자
	SafeDelete bool   // AI 권장 삭제 여부
	Selected   bool   // TUI에서 기본 선택 여부
	// Protected가 true면 base/protected 목록의 브랜치다. --force일 때만
	// 후보로 등장하며, 사고 방지를 위해 기본 미선택 + [protected] 마커로
	// 표시한다(사용자가 TUI에서 직접 체크해야 삭제).
	Protected bool
}

CleanCandidate는 삭제 후보 브랜치와 AI 분석 결과를 결합한 구조체이다.

func BuildCandidates

func BuildCandidates(
	entries []BranchEntry,
	analyses map[string]provider.BranchAnalysis,
	force bool,
	worktrees bool,
	protectedNames map[string]bool,
) []CleanCandidate

BuildCandidates는 수집된 브랜치와 AI 분석 결과를 결합하여 CleanCandidate 목록을 생성한다. 순수 함수.

Selected 필드 규칙:

  • merged/gone/squash-merged → Selected=true
  • AI completed/experiment → Selected=true
  • AI in_progress/preserve → Selected=false (force=true → Selected=true)
  • AI 미사용 + stale → Selected=true

type CleanOptions

type CleanOptions struct {
	DryRun       bool
	Force        bool
	Yes          bool
	NoAI         bool
	Gone         bool
	Stale        int // 0이면 비활성
	All          bool
	SquashMerged bool
	Remote       bool // remote-tracking refs 정리 (git remote prune)
	// IncludeRemote가 true면 remote-only 브랜치(로컬에 동일 이름이 없는
	// origin/X 등)도 후보에 포함된다. 확정 시 git push <remote> --delete로
	// 삭제되므로 의도가 분명할 때만 사용한다.
	IncludeRemote bool
	// Worktrees가 true면 worktree가 점유한 브랜치도 삭제 대상이 된다.
	// 삭제 시 해당 worktree를 먼저 제거(git worktree remove)한 뒤 브랜치를
	// 지운다. 단 worktree에 미커밋 변경(dirty)이 있으면 건너뛰고 경고한다.
	// false면 worktree 점유 브랜치는 기본 미선택 + [worktree] 마커로 남는다.
	Worktrees  bool
	BaseBranch string // 빈 문자열이면 자동 감지
	RemoteName string // 빈 문자열이면 "origin"
	Protected  []string
	StaleDays  int // config에서 가져온 기본값
	Lang       string
}

CleanOptions는 Branch_Cleaner의 실행 옵션이다.

type CleanResult

type CleanResult struct {
	Deleted []string
	Failed  map[string]error
	DryRun  []CleanCandidate
	Pruned  bool
	AIUsed  bool
	AIModel string
}

CleanResult는 정리 실행 결과이다.

type Cleaner

type Cleaner struct {
	Runner   git.Runner
	Client   *git.Client
	Provider provider.Provider // nil이면 AI 비활성
	Stderr   io.Writer
	Stdout   io.Writer
}

Cleaner는 브랜치 정리의 전체 흐름을 orchestrate한다.

func (*Cleaner) Run

func (c *Cleaner) Run(ctx context.Context, opts CleanOptions) (*CleanResult, error)

Run은 옵션에 따라 브랜치 정리를 실행한다.

type Collector

type Collector struct {
	Runner git.Runner
	Client *git.Client
}

Collector는 다양한 조건으로 브랜치를 수집한다.

func (*Collector) CollectAll

func (c *Collector) CollectAll(ctx context.Context, opts CleanOptions) ([]BranchEntry, error)

CollectAll은 옵션에 따라 삭제 후보 브랜치를 수집한다. protected, current, base branch는 항상 제외된다.

func (*Collector) CollectGone

func (c *Collector) CollectGone(ctx context.Context, protected map[string]bool) ([]BranchEntry, error)

CollectGone은 upstream이 삭제된 브랜치를 수집한다.

func (*Collector) CollectMerged

func (c *Collector) CollectMerged(ctx context.Context, base string, protected map[string]bool) ([]BranchEntry, error)

CollectMerged는 base branch에 merged된 브랜치를 수집한다.

func (*Collector) CollectRemoteOnly

func (c *Collector) CollectRemoteOnly(ctx context.Context, remote string, protected map[string]bool) ([]BranchEntry, error)

CollectRemoteOnly returns remote branches whose name doesn't exist as a local branch (excluding the remote's HEAD pointer). The cleaner deletes these via `git push <remote> --delete <name>`.

func (*Collector) CollectStale

func (c *Collector) CollectStale(ctx context.Context, days int, protected map[string]bool) ([]BranchEntry, error)

CollectStale은 마지막 커밋이 N일 이상 경과한 브랜치를 수집한다.

type SquashDetector

type SquashDetector struct {
	Runner git.Runner
}

SquashDetector는 git cherry와 merge-tree 콘텐츠 검사로 squash merge를 감지한다.

func (*SquashDetector) DetectSquashMerged

func (d *SquashDetector) DetectSquashMerged(
	ctx context.Context,
	branches []string,
	base string,
	protected map[string]bool,
) (squashMerged []string, ambiguous []string, warnings []string)

DetectSquashMerged는 각 브랜치를 두 단계로 판별한다:

  1. git cherry — 커밋 단위 patch-id 동등성. 리베이스·체리픽처럼 커밋이 하나씩 base에 대응되는 경우를 잡는다.
  2. merge-tree 콘텐츠 검사 — cherry가 확인하지 못한 브랜치에 대해, base로 머지해도 트리가 변하지 않는지를 본다. GitHub "Squash & Merge"처럼 여러 커밋이 하나로 합쳐지면 합쳐진 커밋의 patch-id는 원본 어느 커밋과도 일치하지 않아 cherry에는 전부 `+`로 보인다 — 가장 흔한 squash merge가 정확히 이 단계에서만 잡힌다.

base^{tree}를 해석할 수 없으면 콘텐츠 검사 없이 cherry 판정만 남는다 (해석 "실패"는 경고, FakeRunner류의 빈 성공 출력은 조용히 비활성). 브랜치 개별 실행 실패는 그 브랜치를 건너뛰고 경고를 반환한다.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL