repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
nushell/modules/git.nu
Raw# Git worktree helpers.
# Layout:
# <root>/.git bare repository
# <root>/<repo>.<branch> worktrees
const WT_REPO_NAME = "wt.repo-name"
const WT_MAIN_BRANCH = "wt.main-branch"
const WT_SOURCE_PATH = "wt.source-path"
const DOT_GIT = ".git"
const WT_ROOT_SUFFIX = ".wt"
const DEFAULT_MAIN_BRANCH = "main"
const HEAD = "HEAD"
const REF_HEADS = "refs/heads/"
const DIRTY_REFUSE = "refuse"
const DIRTY_COPY = "copy"
const DIRTY_MODES = ["refuse" "copy"]
const STATUS_PORCELAIN = ["status" "--porcelain=v1"]
const STAGED_PATCH = "staged.patch"
const UNSTAGED_PATCH = "unstaged.patch"
const LINE_WORKTREE = "worktree "
const LINE_HEAD = "HEAD "
const LINE_BRANCH = "branch "
const LINE_DETACHED = "detached"
const LINE_BARE = "bare"
const LINE_LOCKED = "locked"
const LINE_PRUNABLE = "prunable"
# Run git and return completion record.
def git-complete [args: list<string>, cwd?: path] {
if $cwd == null {
^git ...$args | complete
} else {
^git -C $cwd ...$args | complete
}
}
# Format a failed git invocation.
def git-failure [args: list<string>, stderr: string] {
let msg = ($stderr | str trim)
if ($msg | is-empty) {
$"git failed: git ($args | str join ' ')"
} else {
$msg
}
}
# Run git and return trimmed stdout; fail with stderr as Nushell error.
def git-output [args: list<string>, cwd?: path] {
let res = if $cwd == null { git-complete $args } else { git-complete $args $cwd }
if $res.exit_code != 0 {
error make {msg: (git-failure $args $res.stderr)}
}
$res.stdout | str trim
}
# Compatibility wrappers used by the rest of this module.
def gitx [args: list<string>, cwd?: path] {
if $cwd == null { git-output $args } else { git-output $args $cwd }
}
def gitc [args: list<string>, cwd?: path] {
if $cwd == null { git-complete $args } else { git-complete $args $cwd }
}
def git-dir-args [git_dir: path, args: list<string>] {
["--git-dir" $git_dir] | append $args
}
def git-dir-output [git_dir: path, args: list<string>] {
git-output (git-dir-args $git_dir $args)
}
def git-dir-complete [git_dir: path, args: list<string>] {
git-complete (git-dir-args $git_dir $args)
}
def git-config [git_dir: path, key: string] {
let res = (git-dir-complete $git_dir ["config" "--get" $key])
if $res.exit_code == 0 { $res.stdout | str trim } else { null }
}
def git-config-bool [git_dir: path, key: string] {
let res = (git-dir-complete $git_dir ["config" "--bool" "--get" $key])
if $res.exit_code == 0 { $res.stdout | str trim } else { null }
}
def git-config-set [git_dir: path, key: string, value: string] {
git-dir-output $git_dir ["config" $key $value] | ignore
}
# Branch name -> path-safe suffix.
def branch-slug [branch: string] {
$branch
| str replace --all --regex '[^A-Za-z0-9._-]+' '-'
| str trim --char '-'
}
# URL/path -> repo name.
def repo-name-from [source: string] {
$source | path basename | str replace --regex '\.git$' ''
}
# Current layout record. Fails outside co/wt layout.
def layout [] {
let git_dir = (git-output ["rev-parse" "--path-format=absolute" "--git-common-dir"])
if (git-config-bool $git_dir "core.bare") != "true" {
error make {msg: "not inside co/wt layout: git common dir is not bare"}
}
let root = ($git_dir | path dirname)
let repo = (git-config $git_dir $WT_REPO_NAME | default ($root | path basename | str replace --regex $"($WT_ROOT_SUFFIX)$" ""))
let main = (git-config $git_dir $WT_MAIN_BRANCH | default $DEFAULT_MAIN_BRANCH)
{root: $root, git_dir: $git_dir, repo: $repo, main: $main}
}
# Computed conventional worktree path for branch.
def wt-path [branch: string] {
let l = (layout)
[$l.root $"($l.repo).(branch-slug $branch)"] | path join
}
def empty-worktree-record [] {
{path: null, head: null, branch: null, detached: false, bare: false, locked: false, lock_reason: null, prunable: false}
}
def strip-prefix [line: string, prefix: string] {
$line | str replace $prefix ""
}
def parse-lock-line [line: string] {
let reason = (strip-prefix $line $LINE_LOCKED | str trim)
if ($reason | is-empty) { null } else { $reason }
}
def parse-worktree-line [rec: record, line: string] {
if ($line | str starts-with $LINE_WORKTREE) {
return ($rec | upsert path (strip-prefix $line $LINE_WORKTREE))
}
if ($line | str starts-with $LINE_HEAD) {
return ($rec | upsert head (strip-prefix $line $LINE_HEAD))
}
if ($line | str starts-with $LINE_BRANCH) {
let branch = (strip-prefix $line $LINE_BRANCH | str replace $REF_HEADS "")
return ($rec | upsert branch $branch)
}
if $line == $LINE_DETACHED {
return ($rec | upsert detached true)
}
if $line == $LINE_BARE {
return ($rec | upsert bare true)
}
if ($line | str starts-with $LINE_LOCKED) {
return ($rec | upsert locked true | upsert lock_reason (parse-lock-line $line))
}
if ($line | str starts-with $LINE_PRUNABLE) {
return ($rec | upsert prunable true)
}
$rec
}
def parse-worktree-block [block: string] {
$block | lines | reduce --fold (empty-worktree-record) {|line, rec| parse-worktree-line $rec $line }
}
# Parse `git worktree list --porcelain` into records.
def parse-worktree-list [text: string] {
$text
| split row "\n\n"
| where {|block| not (($block | str trim) | is-empty) }
| each {|block| parse-worktree-block $block }
}
# Worktree table, no dirty check.
def worktrees-basic [] {
let l = (layout)
parse-worktree-list (git-dir-output $l.git_dir ["worktree" "list" "--porcelain"])
}
# Find actual worktree path by branch; fallback to convention path.
def path-for-branch [branch: string] {
let found = (worktrees-basic | where branch == $branch | first)
if ($found == null) { wt-path $branch } else { $found.path }
}
def branch-exists [git_dir: path, branch: string] {
(git-dir-complete $git_dir ["show-ref" "--verify" "--quiet" $"($REF_HEADS)($branch)"]).exit_code == 0
}
def add-worktree [git_dir: path, path: path, branch: string, base: string] {
let args = if (branch-exists $git_dir $branch) {
["worktree" "add" $path $branch]
} else {
["worktree" "add" "-b" $branch $path $base]
}
git-dir-output $git_dir $args | ignore
}
# Create branch + worktree, or add existing branch.
def create-worktree [branch: string, base: string] {
let l = (layout)
let path = (wt-path $branch)
if ($path | path exists) {
error make {msg: $"path exists: ($path)"}
}
add-worktree $l.git_dir $path $branch $base
$path
}
# Current branch, refusing detached HEAD.
def current-branch [] {
let branch = (git-output ["rev-parse" "--abbrev-ref" $HEAD])
if $branch == $HEAD { error make {msg: "detached HEAD is not supported"} }
$branch
}
def current-repo-top [] {
try { git-output ["rev-parse" "--show-toplevel"] | path expand } catch { "" }
}
def existing-main-or-root [layout: record] {
let main_path = (path-for-branch $layout.main)
if ($main_path | path exists) { $main_path } else { $layout.root }
}
def --env cd-away-from-target [layout: record, target: path, branch: string] {
if $target != (current-repo-top) { return }
if $branch == $layout.main {
cd $layout.root
} else {
cd (existing-main-or-root $layout)
}
}
def remove-worktree-args [target: path, force: bool] {
if $force { ["worktree" "remove" "--force" $target] } else { ["worktree" "remove" $target] }
}
def delete-branch [git_dir: path, branch: string, force: bool] {
let flag = if $force { "-D" } else { "-d" }
git-dir-output $git_dir ["branch" $flag $branch] | ignore
}
# Remove worktree, maybe branch, and cd away if removing current worktree.
def --env remove-worktree [branch: string, delete_branch: bool, force: bool] {
let l = (layout)
let target = (path-for-branch $branch | path expand)
cd-away-from-target $l $target $branch
git-dir-output $l.git_dir (remove-worktree-args $target $force) | ignore
if $delete_branch {
delete-branch $l.git_dir $branch $force
}
$target
}
def init-bare-layout [source: string, git_dir: path, repo: string, main: string] {
git-output ["clone" "--bare" $source $git_dir] | ignore
git-config-set $git_dir $WT_REPO_NAME $repo
git-config-set $git_dir $WT_MAIN_BRANCH $main
}
def remember-source [git_dir: path, source: path] {
git-config-set $git_dir $WT_SOURCE_PATH $source
}
def choose-fresh-branch [git_dir: path, branch: any] {
if (($branch == null) or ($branch | is-empty)) {
git-dir-output $git_dir ["symbolic-ref" "--short" $HEAD]
} else {
$branch
}
}
def selected-branch [branch: any] {
if (($branch == null) or ($branch | is-empty)) { current-branch } else { $branch }
}
# Create fresh layout from remote/local repo URL/path.
def --env co-fresh [source: string, name?: string, branch?: string, dir?: path] {
let repo = if ($name == null) { repo-name-from $source } else { $name }
let parent = if ($dir == null) { "." } else { $dir }
let root = ([$parent $repo] | path join | path expand)
let git_dir = ([$root $DOT_GIT] | path join)
if ($root | path exists) {
error make {msg: $"target exists: ($root)"}
}
mkdir $root
git-output ["clone" "--bare" $source $git_dir] | ignore
let chosen_branch = (choose-fresh-branch $git_dir $branch)
git-config-set $git_dir $WT_REPO_NAME $repo
git-config-set $git_dir $WT_MAIN_BRANCH $chosen_branch
let worktree = ([$root $"($repo).(branch-slug $chosen_branch)"] | path join)
git-dir-output $git_dir ["worktree" "add" $worktree $chosen_branch] | ignore
cd $worktree
{root: $root, worktree: $worktree, branch: $chosen_branch}
}
def status-porcelain [cwd: path] {
git-output $STATUS_PORCELAIN $cwd
}
def stash-count [cwd: path] {
let res = (git-complete ["stash" "list"] $cwd)
if $res.exit_code == 0 { $res.stdout | lines | length } else { 0 }
}
def assert-dirty-mode [dirty: string] {
if not ($dirty in $DIRTY_MODES) {
error make {msg: $"--dirty must be one of: ($DIRTY_MODES | str join ', ')"}
}
}
def migration-plan [dirty_mode: string, name: any, branch: any] {
assert-dirty-mode $dirty_mode
let src = (git-output ["rev-parse" "--show-toplevel"] | path expand)
let repo = if ($name == null) { $src | path basename } else { $name }
let parent = ($src | path dirname)
let root = ([$parent $"($repo)($WT_ROOT_SUFFIX)"] | path join | path expand)
let git_dir = ([$root $DOT_GIT] | path join)
let chosen_branch = (selected-branch $branch)
let target = ([$root $"($repo).(branch-slug $chosen_branch)"] | path join)
let status_before = (status-porcelain $src)
let is_dirty = (not ($status_before | is-empty))
{
mode: "current-checkout"
source: $src
target_root: $root
target_git_dir: $git_dir
target_worktree: $target
repo: $repo
branch: $chosen_branch
dirty: $is_dirty
dirty_mode: $dirty_mode
stashes: (stash-count $src)
destructive: false
status_before: $status_before
}
}
def public-migration [plan: record] {
$plan | reject status_before
}
def assert-migration-ready [plan: record] {
if ($plan.target_root | path exists) {
error make {msg: $"target exists: ($plan.target_root)"}
}
if $plan.dirty and $plan.dirty_mode == $DIRTY_REFUSE {
error make {msg: "working tree has changes; rerun with `co . --dirty copy` or commit/stash first"}
}
}
def warn-stashes [plan: record] {
if $plan.stashes > 0 {
print -e $"warning: ($plan.stashes) stash(es) remain only in original checkout: ($plan.source)"
}
}
def patch-paths [tmp: path] {
{staged: ([$tmp $STAGED_PATCH] | path join), unstaged: ([$tmp $UNSTAGED_PATCH] | path join)}
}
def write-dirty-patches [source: path, tmp: path] {
let patches = (patch-paths $tmp)
^git -C $source diff --binary --cached | save --force $patches.staged
^git -C $source diff --binary | save --force $patches.unstaged
$patches
}
def patch-has-data [patch: path] {
not ((open --raw $patch) | is-empty)
}
def apply-patch [target: path, args: list<string>, patch: path] {
if (patch-has-data $patch) {
git-output (["apply"] | append $args | append $patch) $target | ignore
}
}
def apply-dirty-patches [target: path, patches: record] {
apply-patch $target ["--index"] $patches.staged
apply-patch $target [] $patches.unstaged
}
def assert-external-ok [name: string, res: record] {
if $res.exit_code != 0 {
let msg = ($res.stderr | str trim)
error make {msg: (if ($msg | is-empty) { $"($name) failed" } else { $msg })}
}
}
def copy-untracked [source: path, target: path] {
git-output ["status"] $source | ignore # sanity: source still repo
if (which rsync | is-not-empty) {
assert-external-ok "rsync" (^rsync -a --ignore-existing --exclude .git $"($source)/" $"($target)/" | complete)
} else {
assert-external-ok "cp" (^cp -a -n $"($source)/." $target | complete)
}
}
def copy-dirty-state [plan: record, patches: record] {
apply-dirty-patches $plan.target_worktree $patches
copy-untracked $plan.source $plan.target_worktree
let status_after = (status-porcelain $plan.target_worktree)
if $plan.status_before != $status_after {
error make {msg: $"dirty-copy verification failed; original untouched at ($plan.source), target left for inspection at ($plan.target_root)"}
}
}
def create-migration-layout [plan: record] {
mkdir $plan.target_root
init-bare-layout $plan.source $plan.target_git_dir $plan.repo $plan.branch
remember-source $plan.target_git_dir $plan.source
git-dir-output $plan.target_git_dir ["worktree" "add" $plan.target_worktree $plan.branch] | ignore
}
# Migrate current checkout into sibling .wt layout; original untouched.
def --env co-current [name?: string, branch?: string, plan: bool = false, dirty: string = $DIRTY_REFUSE] {
let migration = (migration-plan $dirty $name $branch)
if $plan { return (public-migration $migration) }
assert-migration-ready $migration
warn-stashes $migration
let tmp = if $migration.dirty { mktemp -d } else { null }
try {
let patches = if $migration.dirty { write-dirty-patches $migration.source $tmp } else { null }
create-migration-layout $migration
if $migration.dirty {
copy-dirty-state $migration $patches
}
if $tmp != null { rm -rf $tmp }
} catch {|err|
if $tmp != null { rm -rf $tmp }
error make {msg: $err.msg}
}
cd $migration.target_worktree
public-migration $migration
}
# Bootstrap a new bare+worktree layout from a URL/path.
export def --env "wt clone" [
source: string # URL/path
name?: string # repo/root name
--branch (-b): string = "" # branch to check out; default remote HEAD
--dir (-d): path = "." # parent dir
] {
co-fresh $source $name $branch $dir
}
# Migrate the current checkout into a sibling bare+worktree layout.
export def --env "wt migrate" [
name?: string # repo/root name
--branch (-b): string = "" # branch to check out; default current branch
--plan # preview only
--dirty: string = $DIRTY_REFUSE # `refuse` | `copy`
] {
co-current $name $branch $plan $dirty
}
# Summary.
export def wt [] { wt ls }
export def "wt root" [] { (layout).root }
export def "wt repo" [] { (layout).repo }
export def "wt path" [branch: string] { wt-path $branch }
def worktree-dirty [row: record] {
if (($row.path | path exists) and (not $row.bare) and ($row.branch != null)) {
not ((status-porcelain $row.path) | is-empty)
} else {
false
}
}
export def "wt ls" [] {
let cwd_top = (current-repo-top)
worktrees-basic | where bare == false | each {|row|
let path = ($row.path | path expand)
$row
| upsert current ($path == $cwd_top)
| upsert dirty (worktree-dirty $row)
}
}
export def --env "wt new" [
branch: string
--base (-b): string = $HEAD
--switch (-s)
] {
let path = (create-worktree $branch $base)
if $switch { cd $path }
$path
}
export def --env "wt go" [
branch: string
--create (-c)
--base (-b): string = $HEAD
] {
let path = (path-for-branch $branch)
if not ($path | path exists) {
if not $create {
error make {msg: $"no worktree for branch `($branch)`; rerun with --create"}
}
create-worktree $branch $base | ignore
}
cd $path
$path
}
export def --env "wt rm" [
name?: string
--branch (-b) # also delete git branch
--force (-f)
] {
let b = if ($name == null) { current-branch } else { $name }
remove-worktree $b $branch $force
}
export def --env "wt done" [
branch?: string
--force (-f)
] {
let b = if ($branch == null) { current-branch } else { $branch }
remove-worktree $b true $force
}
export def "wt prune" [] {
git-dir-output (layout).git_dir ["worktree" "prune"] | ignore
}
export def "wt repair" [] {
git-dir-output (layout).git_dir ["worktree" "repair"] | ignore
}
# Thin native aliases for muscle memory / git parity.
export def --env "wt add" [branch: string, --base (-b): string = $HEAD, --switch (-s)] {
wt new $branch --base $base --switch=$switch
}
export def "wt list" [] { wt ls }
export def "wt lock" [branch?: string, reason?: string] {
let b = if ($branch == null) { current-branch } else { $branch }
let path = (path-for-branch $b)
let l = (layout)
let args = if ($reason == null) { ["worktree" "lock" $path] } else { ["worktree" "lock" "--reason" $reason $path] }
git-dir-output $l.git_dir $args | ignore
}
export def "wt unlock" [branch?: string] {
let b = if ($branch == null) { current-branch } else { $branch }
git-dir-output (layout).git_dir ["worktree" "unlock" (path-for-branch $b)] | ignore
}
export def "wt move" [branch: string, dest: path] {
git-dir-output (layout).git_dir ["worktree" "move" (path-for-branch $branch) $dest] | ignore
$dest
}
export def --env "wt remove" [name?: string, --branch (-b), --force (-f)] {
wt rm $name --branch=$branch --force=$force
}