# Git worktree helpers. # Layout: # /.git bare repository # /. worktrees const WT_REPO_NAME = "wt.repo-name" const WT_MAIN_BRANCH = "wt.main-branch" const WT_SOURCE_PATH = "wt.source-path" # Run git and fail with stderr as Nushell error. def gitx [args: list, cwd?: path] { let res = if ($cwd == null) { ^git ...$args | complete } else { ^git -C $cwd ...$args | complete } if $res.exit_code != 0 { let msg = ($res.stderr | str trim) error make {msg: (if ($msg | is-empty) { $"git failed: git ($args | str join ' ')" } else { $msg })} } $res.stdout | str trim } # Run git, return completion record. def gitc [args: list, cwd?: path] { if ($cwd == null) { ^git ...$args | complete } else { ^git -C $cwd ...$args | complete } } # 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] { let base = ($source | path basename) $base | str replace --regex '\.git$' '' } # Current layout record. Fails outside co/wt layout. def layout [] { let common = (gitx ["rev-parse" "--path-format=absolute" "--git-common-dir"]) let bare = (gitc ["--git-dir" $common "config" "--bool" "--get" "core.bare"]) if (($bare.stdout | str trim) != "true") { error make {msg: "not inside co/wt layout: git common dir is not bare"} } let root = ($common | path dirname) let repo_res = (gitc ["--git-dir" $common "config" "--get" $WT_REPO_NAME]) let repo = if $repo_res.exit_code == 0 { $repo_res.stdout | str trim } else { $root | path basename | str replace --regex '\.wt$' '' } let main_res = (gitc ["--git-dir" $common "config" "--get" $WT_MAIN_BRANCH]) let main = if $main_res.exit_code == 0 { $main_res.stdout | str trim } else { "main" } {root: $root, git_dir: $common, repo: $repo, main: $main} } # Computed worktree path for branch. def wt-path [branch: string] { let l = (layout) [$l.root $"($l.repo).(branch-slug $branch)"] | path join } # 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| mut rec = {path: null, head: null, branch: null, detached: false, bare: false, locked: false, lock_reason: null, prunable: false} for line in ($block | lines) { if ($line | str starts-with "worktree ") { $rec = ($rec | upsert path ($line | str replace "worktree " "")) } else if ($line | str starts-with "HEAD ") { $rec = ($rec | upsert head ($line | str replace "HEAD " "")) } else if ($line | str starts-with "branch ") { let b = ($line | str replace "branch " "" | str replace "refs/heads/" "") $rec = ($rec | upsert branch $b) } else if $line == "detached" { $rec = ($rec | upsert detached true) } else if $line == "bare" { $rec = ($rec | upsert bare true) } else if ($line | str starts-with "locked") { let reason = ($line | str replace "locked" "" | str trim) $rec = ($rec | upsert locked true | upsert lock_reason (if ($reason | is-empty) { null } else { $reason })) } else if ($line | str starts-with "prunable") { $rec = ($rec | upsert prunable true) } } $rec } } # Worktree table, no dirty check. def worktrees-basic [] { let l = (layout) parse-worktree-list (gitx ["--git-dir" $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 } } # 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)"} } let exists = ((gitc ["--git-dir" $l.git_dir "show-ref" "--verify" "--quiet" $"refs/heads/($branch)"]).exit_code == 0) if $exists { gitx ["--git-dir" $l.git_dir "worktree" "add" $path $branch] | ignore } else { gitx ["--git-dir" $l.git_dir "worktree" "add" "-b" $branch $path $base] | ignore } $path } # Current branch, refusing detached HEAD. def current-branch [] { let b = (gitx ["rev-parse" "--abbrev-ref" "HEAD"]) if $b == "HEAD" { error make {msg: "detached HEAD is not supported"} } $b } # 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) let cwd_top = (try { gitx ["rev-parse" "--show-toplevel"] } catch { "" } | path expand) if $target == $cwd_top { if $branch == $l.main { cd $l.root } else { let main_path = (path-for-branch $l.main) if ($main_path | path exists) { cd $main_path } else { cd $l.root } } } let remove_args = if $force { ["--git-dir" $l.git_dir "worktree" "remove" "--force" $target] } else { ["--git-dir" $l.git_dir "worktree" "remove" $target] } gitx $remove_args | ignore if $delete_branch { let branch_flag = if $force { "-D" } else { "-d" } gitx ["--git-dir" $l.git_dir "branch" $branch_flag $branch] | ignore } $target } # 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 ".git"] | path join) if ($root | path exists) { error make {msg: $"target exists: ($root)"} } mkdir $root gitx ["clone" "--bare" $source $git_dir] | ignore let chosen_branch = if (($branch == null) or ($branch | is-empty)) { gitx ["--git-dir" $git_dir "symbolic-ref" "--short" "HEAD"] } else { $branch } gitx ["--git-dir" $git_dir "config" $WT_REPO_NAME $repo] | ignore gitx ["--git-dir" $git_dir "config" $WT_MAIN_BRANCH $chosen_branch] | ignore let worktree = ([$root $"($repo).(branch-slug $chosen_branch)"] | path join) gitx ["--git-dir" $git_dir "worktree" "add" $worktree $chosen_branch] | ignore cd $worktree {root: $root, worktree: $worktree, branch: $chosen_branch} } # Migrate current checkout into sibling .wt layout; original untouched. def --env co-current [name?: string, branch?: string, plan: bool = false, dirty: string = "refuse"] { let src = (gitx ["rev-parse" "--show-toplevel"] | path expand) let src_name = ($src | path basename) let repo = if ($name == null) { $src_name } else { $name } let parent = ($src | path dirname) let root = ([$parent $"($repo).wt"] | path join | path expand) let git_dir = ([$root ".git"] | path join) let current = (current-branch) let chosen_branch = if (($branch == null) or ($branch | is-empty)) { $current } else { $branch } let target = ([$root $"($repo).(branch-slug $chosen_branch)"] | path join) let status_before = (gitx ["status" "--porcelain=v1"] $src) let is_dirty = (not ($status_before | is-empty)) let stash_res = (gitc ["stash" "list"] $src) let stash_count = if $stash_res.exit_code == 0 { ($stash_res.stdout | lines | length) } else { 0 } if not ($dirty in ["refuse" "copy"]) { error make {msg: "--dirty must be one of: refuse, copy"} } let migration = { 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 stashes: $stash_count destructive: false } if $plan { return $migration } if ($root | path exists) { error make {msg: $"target exists: ($root)"} } if $is_dirty and $dirty == "refuse" { error make {msg: "working tree has changes; rerun with `co . --dirty copy` or commit/stash first"} } if $stash_count > 0 { print -e $"warning: ($stash_count) stash(es) remain only in original checkout: ($src)" } let tmp = (mktemp -d) let staged_patch = ([$tmp "staged.patch"] | path join) let unstaged_patch = ([$tmp "unstaged.patch"] | path join) if $is_dirty { ^git -C $src diff --binary --cached | save --force $staged_patch ^git -C $src diff --binary | save --force $unstaged_patch } mkdir $root gitx ["clone" "--bare" $src $git_dir] | ignore gitx ["--git-dir" $git_dir "config" $WT_REPO_NAME $repo] | ignore gitx ["--git-dir" $git_dir "config" $WT_MAIN_BRANCH $chosen_branch] | ignore gitx ["--git-dir" $git_dir "config" $WT_SOURCE_PATH $src] | ignore gitx ["--git-dir" $git_dir "worktree" "add" $target $chosen_branch] | ignore if $is_dirty { if (not ((open --raw $staged_patch) | is-empty)) { gitx ["apply" "--index" $staged_patch] $target | ignore } if (not ((open --raw $unstaged_patch) | is-empty)) { gitx ["apply" $unstaged_patch] $target | ignore } let rsync = (which rsync | length) > 0 if $rsync { gitx ["-C" $src "status"] | ignore # cheap sanity: source still repo ^rsync -a --ignore-existing --exclude .git $"($src)/" $"($target)/" | complete | ignore } else { ^cp -a -n $"($src)/." $target | complete | ignore } let status_after = (gitx ["status" "--porcelain=v1"] $target) if $status_before != $status_after { error make {msg: $"dirty-copy verification failed; original untouched at ($src), target left for inspection at ($root)"} } } rm -rf $tmp cd $target $migration } # Bootstrap checkout. export def --env co [ source: string = "." # URL/path, or `.` to migrate current checkout name?: string # repo/root name --branch (-b): string = "" # branch to check out; default remote/current HEAD --dir (-d): path = "." # parent dir for fresh checkout --plan # with `co .`: preview only --dirty: string = "refuse" # `refuse` | `copy` ] { if $source == "." { co-current $name $branch $plan $dirty } else { if $plan { error make {msg: "--plan only applies to `co .`"} } if $dirty != "refuse" { error make {msg: "--dirty only applies to `co .`"} } 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 } export def "wt ls" [] { let cwd_top = (try { gitx ["rev-parse" "--show-toplevel"] } catch { "" } | path expand) worktrees-basic | where bare == false | each {|row| let p = ($row.path | path expand) let dirty = if (($p | path exists) and (not $row.bare) and ($row.branch != null)) { not ((gitx ["status" "--porcelain=v1"] $p) | is-empty) } else { false } $row | upsert current ($p == $cwd_top) | upsert dirty $dirty } } export def --env "wt new" [ branch: string --base (-b): string = "HEAD" --switch (-s) ] { let p = (create-worktree $branch $base) if $switch { cd $p } $p } export def --env "wt go" [ branch: string --create (-c) --base (-b): string = "HEAD" ] { let p = (path-for-branch $branch) if (not ($p | path exists)) { if $create { create-worktree $branch $base | ignore } else { error make {msg: $"no worktree for branch `($branch)`; rerun with --create"} } } cd $p $p } 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" [] { let l = (layout) gitx ["--git-dir" $l.git_dir "worktree" "prune"] | ignore } export def "wt repair" [] { let l = (layout) gitx ["--git-dir" $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 p = (path-for-branch $b) let l = (layout) if ($reason == null) { gitx ["--git-dir" $l.git_dir "worktree" "lock" $p] | ignore } else { gitx ["--git-dir" $l.git_dir "worktree" "lock" "--reason" $reason $p] | ignore } } export def "wt unlock" [branch?: string] { let b = if ($branch == null) { current-branch } else { $branch } let p = (path-for-branch $b) let l = (layout) gitx ["--git-dir" $l.git_dir "worktree" "unlock" $p] | ignore } export def "wt move" [branch: string, dest: path] { let p = (path-for-branch $branch) let l = (layout) gitx ["--git-dir" $l.git_dir "worktree" "move" $p $dest] | ignore $dest } export def --env "wt remove" [name?: string, --branch (-b), --force (-f)] { wt rm $name --branch=$branch --force=$force }