Documentation
¶
Overview ¶
Package forget implements `gk forget` — history-rewriting removal of files that should never have been committed (DBs, secrets, build artefacts). The package wraps `git filter-repo` and adds gk-flavour safety: ref backups, origin URL restoration, and a tracked-but-ignored auto-detection step that turns ".gitignore + gk forget" into a one-line recovery for the common case.
The package itself does not call filter-repo synchronously — Run lives in runner.go and is exported separately so the cobra command can orchestrate preview, confirm, and execute in three independent steps.
Index ¶
- Constants
- Variables
- func AutoDetectIgnored(ctx context.Context, r git.Runner) ([]string, error)
- func ClearAlreadyRanMarker(gitDir string)
- func CountTouchingCommits(ctx context.Context, r git.Runner, paths []string) (int, error)
- func EnsureFilterRepo() error
- func FilterKept(paths, patterns []string) ([]string, error)
- func HumanBytes(n int64) string
- func PathInHistory(ctx context.Context, r git.Runner, paths []string) ([]string, error)
- func RenderAudit(entries []AuditEntry, opts RenderOpts) string
- func RestoreOrigin(ctx context.Context, r git.Runner, remote *CapturedRemote) error
- func RunFilterRepo(ctx context.Context, repoDir, gitDir string, paths []string) error
- func WriteCommitMap(path string, cm map[string]string) error
- type AnalysisEntry
- type AuditEntry
- type Backup
- type BarMode
- type CapturedRemote
- type NativeResult
- type RefSnapshot
- type RenderOpts
- type SortMode
Constants ¶
const BackupRefPrefix = "refs/gk/forget-backup"
BackupRefPrefix groups all forget-related backup refs under a single reflog namespace so users can list them with one for-each-ref query and clean them up with `git update-ref -d` once the rewrite is confirmed-good.
Variables ¶
var ErrFilterRepoNotInstalled = fmt.Errorf(
"git filter-repo not found on PATH; install via: brew install git-filter-repo (or: pip install git-filter-repo)",
)
ErrFilterRepoNotInstalled is returned when `git filter-repo` is not on PATH. gk does not bundle filter-repo and does not fall back to the deprecated `git filter-branch` — that tool has subtle bugs around ref updates and the upstream documentation actively recommends against using it.
Functions ¶
func AutoDetectIgnored ¶
AutoDetectIgnored returns the list of paths that are currently tracked in the index but would be ignored by .gitignore — i.e. paths the user added before adding the matching ignore rule. This is the natural target set for `.gitignore + gk forget` workflows.
Implementation uses `git ls-files -i -c --exclude-standard`, which is the same query `git status` runs internally for its "tracked but ignored" warning. Output is sorted, de-duplicated, and free of empty lines so callers can hand it straight to filter-repo.
func ClearAlreadyRanMarker ¶
func ClearAlreadyRanMarker(gitDir string)
ClearAlreadyRanMarker removes filter-repo's continuation marker. Every gk forget run is an independent fresh rewrite, but filter-repo treats a leftover <gitdir>/filter-repo/already_ran from a previous run as a rewrite to *continue*: within a day it silently switches to continuation semantics, and past a day it blocks on an interactive Y/N prompt — which crashes with EOFError here because filter-repo runs without a terminal (stdin is /dev/null). Removing just the marker restores fresh-run semantics while keeping the rest of the metadata directory (commit-map, ref-map) around for forensics. Missing marker is the normal case and a no-op.
func CountTouchingCommits ¶
CountTouchingCommits returns the number of commits across all refs that modified any of the given paths. Used in the preview step so the user can see how invasive the rewrite will be before consenting.
Counts each commit once even if it touches multiple target paths, matching what a user actually cares about ("how many SHAs change?").
func EnsureFilterRepo ¶
func EnsureFilterRepo() error
EnsureFilterRepo verifies that filter-repo is callable. Done as a dedicated step rather than letting the rewrite fail mid-flight so the preflight phase can abort cleanly with an actionable error message.
func FilterKept ¶
FilterKept returns the subset of `paths` whose entries do NOT match any of the supplied keep patterns. Patterns use filepath.Match syntax (the same shape gk's privacy_gate and ai-commit deny_paths use), so users can write `db/keep/*` without learning a new glob dialect.
Each path is checked against the patterns themselves and against every directory prefix — so `db/keep/foo.txt` matches a pattern of `db/keep` or `db/keep/*`. This mirrors how `.gitignore` rules work in spirit: matching a directory keeps everything underneath it.
Invalid patterns return an error so the user gets a clean diagnostic instead of silent "did not match" surprise.
func HumanBytes ¶
HumanBytes renders n with an SI-ish suffix (KiB, MiB, GiB) and one decimal where useful. Kept tiny on purpose — the alternative is pulling in dustin/go-humanize for one call site.
func PathInHistory ¶
PathInHistory reports, for each candidate path, whether at least one commit in the entire history (--all) ever touched the path. Used as a quick "is this even worth rewriting?" filter before invoking filter-repo, since filter-repo on a path that does not appear is a no-op that still rewrites every commit SHA.
Returns the subset of `paths` that have history hits, preserving the caller's order. An empty input returns an empty slice with no error.
func RenderAudit ¶
func RenderAudit(entries []AuditEntry, opts RenderOpts) string
RenderAudit returns a single string suitable for printing. Trailing newline is included so callers can `fmt.Fprint(w, RenderAudit(...))` without managing line endings.
The function never panics on empty input — an empty entries slice produces a single line saying so. Same goes for a single entry: the "max" denominator falls back to that entry's TotalBytes so the bar still renders as full rather than dividing by zero.
func RestoreOrigin ¶
RestoreOrigin re-adds the captured remote. No-op when CapturedRemote is empty. Idempotent: tries `git remote add` first and falls back to `git remote set-url` if a remote with the same name already exists (filter-repo's removal is not always complete).
func RunFilterRepo ¶
RunFilterRepo invokes `git filter-repo --invert-paths --path X --path Y --force` against the working repo. We always pass --force because gk has already gated the flow with its own confirmation; filter-repo's internal "fresh clone" check would just produce a confusing error after the user already typed `yes`. gitDir is used to clear a stale continuation marker first (see ClearAlreadyRanMarker).
The rewrite is limited to the enumerated branches and tags via --refs. Without it, filter-repo exports --all: gk's own refs/gk/forget-backup/* refs get rewritten to the NEW history and the post-run gc prunes the old objects — which silently turns the printed rollback instruction into a lie. The --refs form leaves refs/gk/* and refs/remotes/* untouched and skips the aggressive gc, so pre-rewrite objects stay reachable through the backup refs (verified SHA-identical to the full rewrite for branch/tag results).
Types ¶
type AnalysisEntry ¶
type AnalysisEntry struct {
Path string // the target path as the user typed it
UniqueBlobs int // distinct blob OIDs ever stored at Path across all refs
TotalBytes int64 // sum of all unique blobs
LargestBytes int64 // size of the single biggest blob — useful for "what made this commit huge?"
}
AnalysisEntry summarises how much repo weight a single forget target would shed. Sizes are pre-pack — they reflect the on-the-wire bytes git would have to ship, not the compressed pack size, which is closer to what users perceive as "repo bloat".
func Analyze ¶
func Analyze(ctx context.Context, r git.Runner, repoDir string, paths []string) ([]AnalysisEntry, error)
Analyze walks every commit on every ref and computes per-path blob statistics for the supplied targets. Implementation:
- `git log --all --pretty=format: --raw --no-renames -- <path>` lists every diff that touched <path>. Each output line carries the pre- and post-image blob OIDs in fields 3 and 4.
- The post-image OIDs are de-duplicated across all output lines and piped through `git cat-file --batch-check='%(objectname) %(objectsize)'` in a single batch so we make exactly one cat-file call per path instead of N.
Empty targets returns an empty slice with no error. Paths that never appeared in history yield an entry with zero blobs/bytes — surfacing "this path is not in history" is more useful than silently dropping it.
type AuditEntry ¶
type AuditEntry struct {
Path string `json:"path"`
UniqueBlobs int `json:"unique_blobs"`
TotalBytes int64 `json:"total_bytes"`
LargestBytes int64 `json:"largest_bytes"`
// InHEAD is true when at least one path under this bucket still
// exists in the current HEAD tree. Buckets with InHEAD=false are
// "history only" — already deleted from the working tree but still
// inflating clones. These are the highest-leverage forget targets.
InHEAD bool `json:"in_head"`
}
AuditEntry summarises one bucket in a repo-wide history audit.
Buckets are formed by truncating each blob's path to the requested depth, so an entry's Path is either a directory prefix (e.g. "node_modules") or — when Depth was 0 — an individual file. Unique blob counts are within the bucket, so a directory that committed the same artefact a hundred times still shows UniqueBlobs=N where N is the number of distinct OIDs, not the number of commits that touched it.
func Audit ¶
func Audit(ctx context.Context, r git.Runner, repoDir string, depth, top int, sortMode SortMode) ([]AuditEntry, error)
Audit walks every reachable object on every ref and produces per- bucket size/blob statistics. The implementation streams `git rev-list --all --objects | git cat-file --batch-check` so that even multi-million-object repos do not need to materialise the full listing in memory.
`depth` controls bucket granularity:
- 0 every blob path is its own bucket (individual files)
- 1 top-level directory only (e.g. "node_modules")
- N>=2 first N path segments
`top` caps the returned slice; entries are sorted by `sort` (default SortBySize when caller passes the zero value). Pass top=0 for "return everything".
type Backup ¶
type Backup struct {
Stamp int64 // unix seconds — also embedded in ref namespace and manifest filename
Refs []RefSnapshot
Manifest string // absolute path to the text manifest
RefPrefix string // refs/gk/forget-backup/<stamp>
}
Backup captures the state of every branch and tag immediately before a forget rewrite, recorded both as a sibling backup ref and as a flat text manifest under .git/gk/ for offline rollback.
The dual format is deliberate:
- Backup refs (refs/gk/forget-backup/<unix>/<original>) survive a normal `git gc`, are visible in `gk timemachine list`, and let users rollback a single branch with `git update-ref` without touching the rest of the repo.
- The manifest .git/gk/forget-backup-<unix>.txt survives even an accidental `git update-ref -d refs/gk/forget-backup/...` and is trivial to apply with `git update-ref --stdin`.
func CreateBackup ¶
CreateBackup snapshots refs/heads, refs/tags, and HEAD into both a ref namespace and a text manifest. Returns the populated Backup struct so the caller can surface paths in CLI output.
Backup ref shape is `refs/gk/forget-backup/<sanitized-source>/<unix>`, matching the gitsafe convention used by undo/wipe/timemachine backups. That keeps `gk timemachine list` and gitsafe.ListBackups in sync without either side carrying a special case for forget.
gitDir is the absolute path to the repo's .git directory; the manifest lands at <gitDir>/gk/forget-backup-<unix>.txt.
type BarMode ¶
type BarMode int
BarMode controls how Audit results are visualised in the terminal.
const ( // BarAuto picks filled when the output is an interactive terminal // with colour support, plain otherwise. Designed so piping the // command into grep / tee does not leak ANSI escapes. BarAuto BarMode = iota // BarFilled paints each row as a single line where the label // (path/blobs/size) sits on top of a coloured background that // covers a fraction of the row equal to the entry's share of the // heaviest entry. This is the htop / du-dust style. BarFilled // BarBlock keeps the label in plain text and adds a separate // column drawn with the sub-cell block glyphs `█▉▊▋▌▍▎▏`. Useful // when colour is unavailable but length-as-ratio still helps. BarBlock // BarNone is plain text — what the original analyze output looked // like. Default when stdout is not a TTY or when --no-color is // asserted. BarNone )
func ParseBarMode ¶
ParseBarMode is the spf13/cobra flag accessor.
type CapturedRemote ¶
type CapturedRemote struct {
Name string // typically "origin" — empty when no remote was configured
URL string
}
CapturedRemote holds the URL of an origin remote that we capture before running filter-repo and re-attach afterwards. filter-repo deliberately detaches origin to make accidental force-pushes harder; gk re-attaches it because the next thing the user wants to do is `git push --force`, which is impossible without a remote.
func CaptureOrigin ¶
CaptureOrigin reads the origin URL so RestoreOrigin can re-add it later. Missing origin is not an error; users who never had one (e.g. forking a local repo) shouldn't be blocked.
type NativeResult ¶
type NativeResult struct {
CommitsSeen int
CommitsPruned int
MergesSimplified int
RefsUpdated int
RefsDeleted []string
// CommitMap maps original commit SHAs to their rewritten SHAs. Pruned
// commits map to the SHA of their surviving ancestor ("" when the
// entire history of that commit vanished).
CommitMap map[string]string
}
NativeResult summarizes a completed native rewrite.
type RefSnapshot ¶
RefSnapshot is one (refname, sha) pair captured pre-rewrite. We do not chase tag objects to commits — annotated tags should round-trip as-is, and a lightweight tag is just a ref pointing at a commit either way.
type RenderOpts ¶
type RenderOpts struct {
Mode BarMode
NoColor bool
Width int // terminal columns; 0 = auto-detect, fall back to 100
}
RenderOpts captures every knob the renderer consults so the cobra layer does not have to plumb individual fields through.
type SortMode ¶
type SortMode int
SortMode chooses how Audit results are ordered before --top truncation.
const ( // SortBySize ranks by TotalBytes descending — the historical default // answer to "what is biggest?". SortBySize SortMode = iota // SortByChurn ranks by UniqueBlobs descending. Useful for finding // rewrite-heavy paths (lock files, generated outputs) where each // commit is small but the cumulative cost is large. SortByChurn // SortByName ranks alphabetically. Stable across runs, helpful for // diffing audit output. SortByName )
func ParseSortMode ¶
ParseSortMode converts a flag string to a SortMode.