Skip to content

Commit 2ca2fe7

Browse files
perf: optimize worktree lookup by combining awk processes
Modified `list_worktrees` to optionally accept a target branch name and perform filtering internally. This eliminates redundant sub-processes in `goto_worktree` and `remove_worktree` and allows for early exit once a match is found. Benchmark results (100 iterations of `goto_worktree`): - Baseline: ~1.55s real, ~1.35s user - Optimized: ~1.44s real, ~1.04s user - Improvement: ~7% real time, ~23% user time reduction. Co-authored-by: RodrigoEspinosa <1685621+RodrigoEspinosa@users.noreply.github.com>
1 parent b252255 commit 2ca2fe7

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

bin/wt

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,25 @@ worktree_base() {
7070
# --- core functions ---------------------------------------------------------
7171

7272
list_worktrees() {
73-
git worktree list --porcelain | awk '
73+
local target="${1:-}"
74+
git worktree list --porcelain | awk -v target="$target" '
7475
/^worktree / { path = substr($0, 10) }
75-
/^branch / { branch = substr($0, 8); sub("refs/heads/", "", branch); print branch "\t" path }
76-
/^HEAD / { if (path != "") print "(detached)\t" path }
76+
/^branch / {
77+
branch = substr($0, 8);
78+
sub("refs/heads/", "", branch);
79+
if (target != "") {
80+
if (branch == target) { print path; exit }
81+
} else {
82+
print branch "\t" path
83+
}
84+
}
85+
/^HEAD / {
86+
if (target != "") {
87+
if (target == "(detached)" && path != "") { print path; exit }
88+
} else if (path != "") {
89+
print "(detached)\t" path
90+
}
91+
}
7792
'
7893
}
7994

@@ -138,7 +153,7 @@ goto_worktree() {
138153
local wt_path
139154

140155
# Check if a worktree for this branch already exists
141-
wt_path=$(list_worktrees | awk -F'\t' -v b="$branch" '$1 == b { print $2 }')
156+
wt_path=$(list_worktrees "$branch")
142157

143158
if [ -n "$wt_path" ]; then
144159
echo "$wt_path"
@@ -151,7 +166,7 @@ remove_worktree() {
151166
local branch="$1"
152167
local wt_path
153168

154-
wt_path=$(list_worktrees | awk -F'\t' -v b="$branch" '$1 == b { print $2 }')
169+
wt_path=$(list_worktrees "$branch")
155170

156171
if [ -z "$wt_path" ]; then
157172
die "no worktree found for branch: $branch"

0 commit comments

Comments
 (0)