repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
nushell/modules/git.nu
Raw# Git worktree helpers.
# Layout:
# <root>/.bare bare repository
# <root>/<main> main worktree
# <root>/wt/<branch> 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 BARE_DIR = ".bare"
const WT_DIR = "wt"
const DEFAULT_MAIN_BRANCH = "main"
const HEAD = "HEAD"
const REF_HEADS = "refs/heads/"
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
}
def git-config-unset [git_dir: path, key: string] {
git-dir-complete $git_dir ["config" "--unset" $key] | ignore
}
def git-dir-absolute-output [git_dir: path, args: list<string>] {
git-output (["--git-dir" $git_dir "-c" "worktree.useRelativePaths=false"] | append $args)
}
def configure-bare-layout [git_dir: path] {
git-config-set $git_dir "core.bare" "true"
git-config-unset $git_dir "core.worktree"
git-config-set $git_dir "worktree.useRelativePaths" "false"
git-config-unset $git_dir "extensions.relativeWorktrees"
}
# 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))
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)
if $branch == $l.main {
[$l.root (branch-slug $branch)] | path join
} else {
[$l.root $WT_DIR (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] {
mkdir ($path | path dirname)
let args = if (branch-exists $git_dir $branch) {
["worktree" "add" $path $branch]
} else {
["worktree" "add" "-b" $branch $path $base]
}
git-dir-absolute-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
configure-bare-layout $git_dir
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
}
}
# 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 $BARE_DIR] | path join)
if ($root | path exists) {
error make {msg: $"target exists: ($root)"}
}
mkdir $root
mkdir ([$root $WT_DIR] | path join)
init-bare-layout $source $git_dir $repo $DEFAULT_MAIN_BRANCH
let chosen_branch = (choose-fresh-branch $git_dir $branch)
git-config-set $git_dir $WT_MAIN_BRANCH $chosen_branch
let worktree = ([$root (branch-slug $chosen_branch)] | path join)
git-dir-absolute-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 public-migration [plan: record] {
$plan | reject status_before
}
def migrate-stamp [] {
date now | format date "%Y%m%d%H%M%S"
}
def bare-common-dir [] {
try {
let git_dir = (git-output ["rev-parse" "--path-format=absolute" "--git-common-dir"])
if (git-config-bool $git_dir "core.bare") == "true" { $git_dir } else { null }
} catch { null }
}
def is-new-layout [git_dir: path] {
($git_dir | path basename) == $BARE_DIR
}
def migration-plan-normal [] {
let source = (git-output ["rev-parse" "--show-toplevel"] | path expand)
let branch = (current-branch)
let repo = ($source | path basename)
let parent = ($source | path dirname)
let stamp = (migrate-stamp)
let temp_root = ([$parent $".($repo).migrate-($stamp)"] | path join)
let backup_root = ([$parent $".($repo).pre-wt-migrate-($stamp)"] | path join)
let target_git_dir = ([$temp_root $BARE_DIR] | path join)
let target_worktree = ([$temp_root (branch-slug $branch)] | path join)
{
mode: "normal-checkout"
source: $source
temp_root: $temp_root
backup_root: $backup_root
final_root: $source
target_git_dir: $target_git_dir
target_worktree: $target_worktree
final_worktree: ([$source (branch-slug $branch)] | path join)
repo: $repo
branch: $branch
dirty: (not ((status-porcelain $source) | is-empty))
stashes: (stash-count $source)
status_before: (status-porcelain $source)
}
}
def migration-plan-bare-container [git_dir: path] {
let root = ($git_dir | path dirname)
let repo = (git-config $git_dir $WT_REPO_NAME | default ($root | path basename))
let main = (git-config $git_dir $WT_MAIN_BRANCH | default (current-branch))
let current = (current-branch)
let target_git_dir = ([$root $BARE_DIR] | path join)
{
mode: (if (is-new-layout $git_dir) { "already-migrated" } else { "bare-container" })
source: $root
final_root: $root
target_git_dir: $target_git_dir
repo: $repo
branch: $main
current_branch: $current
final_worktree: (canonical-worktree-path $root $main $current)
worktrees: (parse-worktree-list (git-dir-output $git_dir ["worktree" "list" "--porcelain"]))
status_before: ""
}
}
def migration-plan [] {
let git_dir = (bare-common-dir)
if $git_dir != null { migration-plan-bare-container $git_dir } else { migration-plan-normal }
}
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-normal-migration-layout [plan: record] {
mkdir $plan.temp_root
mkdir ([$plan.temp_root $WT_DIR] | path join)
assert-external-ok "cp" (^cp -a ([$plan.source $DOT_GIT] | path join) $plan.target_git_dir | complete)
configure-bare-layout $plan.target_git_dir
git-config-set $plan.target_git_dir $WT_REPO_NAME $plan.repo
git-config-set $plan.target_git_dir $WT_MAIN_BRANCH $plan.branch
remember-source $plan.target_git_dir $plan.source
git-dir-absolute-output $plan.target_git_dir ["worktree" "add" $plan.target_worktree $plan.branch] | ignore
}
def --env swap-migrated-normal [plan: record] {
cd ($plan.source | path dirname)
mv $plan.source $plan.backup_root
mv $plan.temp_root $plan.final_root
}
def --env migrate-normal [plan: record] {
if ($plan.temp_root | path exists) { error make {msg: $"target exists: ($plan.temp_root)"} }
if ($plan.backup_root | path exists) { error make {msg: $"backup exists: ($plan.backup_root)"} }
let tmp = (mktemp -d)
try {
let patches = (write-dirty-patches $plan.source $tmp)
create-normal-migration-layout $plan
copy-dirty-state $plan $patches
swap-migrated-normal $plan
let final_git_dir = ([$plan.final_root $BARE_DIR] | path join)
repair-bare-worktrees $final_git_dir [{path: $plan.final_worktree, bare: false}]
let final_status = (status-porcelain $plan.final_worktree)
if $plan.status_before != $final_status {
error make {msg: $"post-swap status verification failed; backup kept at ($plan.backup_root)"}
}
rm -rf $tmp
} catch {|err|
rm -rf $tmp
error make {msg: $err.msg}
}
cd $plan.final_worktree
public-migration $plan
}
def repair-bare-worktrees [git_dir: path, worktrees: list<any>] {
let paths = ($worktrees | where bare == false | get path)
if ($paths | is-empty) {
git-dir-absolute-output $git_dir ["worktree" "repair"] | ignore
} else {
git-dir-absolute-output $git_dir (["worktree" "repair"] | append $paths) | ignore
}
}
def canonical-worktree-path [root: path, main: string, branch: string] {
if $branch == $main {
[$root (branch-slug $branch)] | path join
} else {
[$root $WT_DIR (branch-slug $branch)] | path join
}
}
def move-legacy-worktrees [git_dir: path, root: path, main: string] {
let rows = (parse-worktree-list (git-dir-output $git_dir ["worktree" "list" "--porcelain"]) | where bare == false | where branch != null)
for row in $rows {
let dest = (canonical-worktree-path $root $main $row.branch)
if ($row.path | path expand) == ($dest | path expand) { continue }
if ($dest | path exists) { error make {msg: $"target exists: ($dest)"} }
mkdir ($dest | path dirname)
git-dir-absolute-output $git_dir ["worktree" "move" $row.path $dest] | ignore
}
}
def --env migrate-bare-container [plan: record] {
if $plan.mode == "already-migrated" {
configure-bare-layout $plan.target_git_dir
mkdir ([$plan.final_root $WT_DIR] | path join)
git-dir-absolute-output $plan.target_git_dir ["worktree" "repair"] | ignore
cd $plan.final_worktree
return (public-migration $plan)
}
if ($plan.target_git_dir | path exists) { error make {msg: $"target exists: ($plan.target_git_dir)"} }
mv ([$plan.final_root $DOT_GIT] | path join) $plan.target_git_dir
configure-bare-layout $plan.target_git_dir
git-config-set $plan.target_git_dir $WT_REPO_NAME $plan.repo
git-config-set $plan.target_git_dir $WT_MAIN_BRANCH $plan.branch
mkdir ([$plan.final_root $WT_DIR] | path join)
repair-bare-worktrees $plan.target_git_dir $plan.worktrees
cd $plan.final_root
move-legacy-worktrees $plan.target_git_dir $plan.final_root $plan.branch
cd $plan.final_worktree
public-migration $plan
}
# Bootstrap fresh checkout.
export def --env co [
source: string # URL/path
name?: string # repo/root name
--branch (-b): string = "" # branch to check out; default remote/current HEAD
--dir (-d): path = "." # parent dir for fresh checkout
] {
if $source == "." {
error make {msg: "use `wt migrate` to convert the current checkout"}
}
co-fresh $source $name $branch $dir
}
# 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 migrate" [
--dry
] {
let plan = (migration-plan)
if $dry { return (public-migration $plan) }
if $plan.mode == "normal-checkout" {
migrate-normal $plan
} else {
migrate-bare-container $plan
}
}
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" [] {
let l = (layout)
configure-bare-layout $l.git_dir
git-dir-absolute-output $l.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
}