diff --git a/spec/tests/test_12_worktree.sh b/spec/tests/test_12_worktree.sh index 8c903e5..67ae567 100644 --- a/spec/tests/test_12_worktree.sh +++ b/spec/tests/test_12_worktree.sh @@ -55,5 +55,50 @@ else fail "try . without name should show error" "error about name" "$output" "command_line.md#worktree" fi +# Test: try . inside a git subdirectory still emits git worktree add +mkdir -p "$FAKE_REPO/sub/nested" +output=$(cd "$FAKE_REPO/sub/nested" && try_run --path="$TEST_TRIES" exec . subfeature 2>&1) +if echo "$output" | grep -q "worktree add"; then + pass +else + fail "try . in git subdir should emit git worktree add" "worktree add command" "$output" "command_line.md#worktree" +fi + +# Test: try ./nonexistent inside a git repo does not falsely detect parent .git +output=$(cd "$FAKE_REPO" && try_run --path="$TEST_TRIES" exec ./does-not-exist nonexist-try 2>&1) +if echo "$output" | grep -q "worktree add"; then + fail "try ./does-not-exist should not emit git worktree add" "plain mkdir without worktree add" "$output" "command_line.md#worktree" +else + pass +fi + +# Test: dot-prefixed query (e.g. .env) is treated as search, not worktree path +output=$(try_run --path="$TEST_TRIES" --and-exit exec .env 2>&1) +if echo "$output" | grep -q "mkdir -p"; then + fail "try .env should open selector instead of mkdir" "TUI output without mkdir -p" "$output" "command_line.md#worktree" +else + pass +fi + +# Test: worktree with spaces and single quotes in repo/tries paths executes cleanly +SPACE_ROOT=$(mktemp -d) +SPACE_REPO="$SPACE_ROOT/my repo's dir" +SPACE_TRIES="$SPACE_ROOT/my tries's dir" +mkdir -p "$SPACE_REPO" "$SPACE_TRIES" +git -C "$SPACE_REPO" init -q +git -C "$SPACE_REPO" -c user.name=test -c user.email=test@example.com commit --allow-empty -q -m "init" +wt_script=$(cd "$SPACE_REPO" && try_run --path="$SPACE_TRIES" exec . space-wt) +if echo "$wt_script" | bash -n 2>/dev/null; then + (cd "$SPACE_REPO" && eval "$(echo "$wt_script" | grep -v '^#')") >/dev/null 2>&1 + wt_created=$(find "$SPACE_TRIES" -maxdepth 1 -type d -name "*-space-wt" | head -1) + if [ -n "$wt_created" ] && git -C "$wt_created" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + pass + else + fail "worktree with spaces/quotes should create real git worktree" "valid git worktree" "$wt_script" "command_line.md#worktree" + fi +else + fail "worktree script with spaces/quotes should be valid bash" "valid bash syntax" "$wt_script" "command_line.md#worktree" +fi + # Cleanup -rm -rf "$FAKE_REPO" "$PLAIN_DIR" +rm -rf "$FAKE_REPO" "$PLAIN_DIR" "$SPACE_ROOT" diff --git a/spec/tests/test_16_delete.sh b/spec/tests/test_16_delete.sh index a8aeb69..d8ebfe5 100644 --- a/spec/tests/test_16_delete.sh +++ b/spec/tests/test_16_delete.sh @@ -95,5 +95,13 @@ else fail "Delete should use basename in rm -rf" "rm -rf 'name'" "$output" "delete_spec.md#per-item-delete-commands" fi +# Test: Multi-delete across different search filters deletes all marked items +output=$(try_run --path="$DEL_TEST_DIR" --and-keys='TYPE=first,CTRL-D,CTRL-U,TYPE=third,CTRL-D,ENTER,Y,E,S,ENTER' exec 2>/dev/null) +if echo "$output" | grep -q "rm -rf '2025-11-01-first'" && echo "$output" | grep -q "rm -rf '2025-11-03-third'"; then + pass +else + fail "Multi-delete across filters should delete all marked items" "both first and third in rm -rf" "$output" "delete_spec.md#script-structure" +fi + # Cleanup rm -rf "$DEL_TEST_DIR" diff --git a/spec/tests/test_20_scroll_behavior.sh b/spec/tests/test_20_scroll_behavior.sh index 5030f58..8778843 100644 --- a/spec/tests/test_20_scroll_behavior.sh +++ b/spec/tests/test_20_scroll_behavior.sh @@ -152,5 +152,38 @@ else fail "scroll should stop at first entry" "selection visible" "$output" "tui_spec.md#scroll-bounds" fi +# Test: Scrolling reaches items beyond initial viewport height +SCROLL_DEEP_DIR=$(mktemp -d) +for i in $(seq 1 25); do + d="$SCROLL_DEEP_DIR/2025-11-01-item-$(printf '%02d' $i)" + mkdir -p "$d" + # Give item-01 newest mtime, item-25 oldest mtime so order is deterministic + touch -t "202511$(printf '%02d' $((26 - i)))0000" "$d" +done +keys="" +for i in $(seq 1 24); do + keys="${keys}DOWN," +done +keys="${keys}ENTER" +output=$(TRY_HEIGHT=12 try_run --path="$SCROLL_DEEP_DIR" --and-keys="$keys" exec 2>/dev/null) +if echo "$output" | grep -q "2025-11-01-item-25"; then + pass +else + fail "scrolling past viewport should reach last entry (item-25)" "2025-11-01-item-25" "$output" "tui_spec.md#scroll-bounds" +fi + +# Test: Selecting 'Create new' when matches exceed viewport keeps it visible +keys="TYPE=item," +for i in $(seq 1 25); do + keys="${keys}DOWN," +done +output=$(TRY_HEIGHT=12 try_run --path="$SCROLL_DEEP_DIR" --and-keys="${keys%,}" exec 2>&1) +if echo "$output" | strip_ansi | grep -q "Create new:"; then + pass +else + fail "Create new should remain visible when selected past full viewport" "Create new:" "$output" "tui_spec.md#scroll-bounds" +fi + +rm -rf "$SCROLL_DEEP_DIR" cleanup_scroll_dirs diff --git a/spec/tests/test_32_git_uri.sh b/spec/tests/test_32_git_uri.sh index 297030b..fbf3cef 100644 --- a/spec/tests/test_32_git_uri.sh +++ b/spec/tests/test_32_git_uri.sh @@ -93,3 +93,12 @@ if echo "$output" | grep -qE "cd '.*repo'"; then else fail "Clone output should use single-quoted paths" "single-quoted cd" "$output" "git_uri" fi + +# Test: Clone URI with single quote is safely shell-escaped (no command injection) +inj_uri="https://github.com/user/repo';echo INJECTED_CLONE;#.git" +inj_script=$(try_run --path="$TEST_TRIES" exec clone "$inj_uri") +if echo "$inj_script" | bash -n 2>/dev/null && echo "$inj_script" | grep -qF "'\"'\"'"; then + pass +else + fail "Clone URI with single quote should be properly escaped" "valid bash syntax with escaped quote" "$inj_script" "git_uri" +fi diff --git a/spec/tests/test_34_shell_init.sh b/spec/tests/test_34_shell_init.sh index 127bd8c..5bec53f 100644 --- a/spec/tests/test_34_shell_init.sh +++ b/spec/tests/test_34_shell_init.sh @@ -49,5 +49,22 @@ else fail "--path= form should show directories from specified path" "unique-marker-dir in output" "$output" "shell_init" fi +# Test: init accepts relative path and expands it +REL_BASE=$(mktemp -d) +rel_out=$(cd "$REL_BASE" && SHELL=/bin/bash try_run init ./my-rel-tries 2>&1) +if echo "$rel_out" | grep -qF -- "--path '$REL_BASE/my-rel-tries'"; then + pass +else + fail "init should expand relative path" "--path '$REL_BASE/my-rel-tries'" "$rel_out" "shell_init" +fi + +# Test: init safely escapes paths containing single quotes +quote_out=$(SHELL=/bin/bash try_run init "/tmp/it's-tries" 2>&1) +if echo "$quote_out" | bash -n 2>/dev/null && echo "$quote_out" | grep -qF "'\"'\"'"; then + pass +else + fail "init should safely escape single-quoted paths in bash" "valid bash syntax" "$quote_out" "shell_init" +fi + # Cleanup -rm -rf "$INIT_DIR" "$INIT_DIR2" +rm -rf "$INIT_DIR" "$INIT_DIR2" "$REL_BASE" diff --git a/spec/tests/test_36_shell_eval.sh b/spec/tests/test_36_shell_eval.sh index e19bc3c..83192fd 100644 --- a/spec/tests/test_36_shell_eval.sh +++ b/spec/tests/test_36_shell_eval.sh @@ -11,7 +11,7 @@ mkdir -p "$EVAL_DIR/2025-01-01-hello" # --- bash --- # Test: bash can eval the init output and defines try function -bash_out=$(bash -c " +bash_out=$(LC_ALL=C bash -c " eval \"\$('$TRY_BIN_PATH' init --path '$EVAL_DIR')\" type try " 2>&1) @@ -36,7 +36,7 @@ fi if command -v zsh >/dev/null 2>&1; then # Test: zsh can eval the init output and defines try function - zsh_out=$(zsh -c " + zsh_out=$(LC_ALL=C zsh -c " eval \"\$('$TRY_BIN_PATH' init --path '$EVAL_DIR')\" whence -w try " 2>&1) @@ -65,7 +65,7 @@ fi if command -v nix-shell >/dev/null 2>&1; then # Test: fish can eval the init output and defines try function - fish_out=$(nix-shell -p fish --run "SHELL=fish fish -c 'eval ($TRY_BIN_PATH init --path $EVAL_DIR | string collect); type try'" 2>&1) + fish_out=$(nix-shell -p fish --run "LC_ALL=C SHELL=fish fish -c 'eval ($TRY_BIN_PATH init --path $EVAL_DIR | string collect); type try'" 2>&1) if echo "$fish_out" | grep -qi "try is a function\|function try"; then pass else diff --git a/spec/tests/test_37_graduate.sh b/spec/tests/test_37_graduate.sh index e81aba4..61ede13 100644 --- a/spec/tests/test_37_graduate.sh +++ b/spec/tests/test_37_graduate.sh @@ -84,15 +84,15 @@ WT_DIR=$(mktemp -d) mkdir -p "$WT_DIR/2025-06-01-worktree-test" echo "gitdir: /tmp/fake-repo/.git/worktrees/worktree-test" > "$WT_DIR/2025-06-01-worktree-test/.git" output=$(try_run --path="$WT_DIR" --and-keys='CTRL-G,ENTER' exec 2>/dev/null) -if echo "$output" | grep -q "git worktree move"; then +if echo "$output" | grep -qE "git (-C .+ )?worktree move"; then pass else - fail "Git worktree should use git worktree move" "git worktree move" "$output" "graduate" + fail "Git worktree should use git worktree move" "git [-C ...] worktree move" "$output" "graduate" fi # Test: Regular directory uses plain mv (not git worktree move) output=$(try_run --path="$GRAD_DIR" --and-keys='CTRL-G,ENTER' exec 2>/dev/null) -if echo "$output" | grep -q "git worktree move"; then +if echo "$output" | grep -qE "git (-C .+ )?worktree move"; then fail "Non-worktree should use mv, not git worktree move" "plain mv" "$output" "graduate" else pass @@ -201,7 +201,7 @@ fi REG_DIR=$(mktemp -d) mkdir -p "$REG_DIR/2025-06-01-regular-repo/.git/objects" output=$(try_run --path="$REG_DIR" --and-keys='CTRL-G,ENTER' exec 2>/dev/null) -if echo "$output" | grep -q "git worktree move"; then +if echo "$output" | grep -qE "git (-C .+ )?worktree move"; then fail "Regular .git directory should use mv, not git worktree move" "plain mv" "$output" "graduate" else pass @@ -222,4 +222,29 @@ else fail "Should strip YYYY-MM-DD- prefix from various dates" "year-end" "$output" "graduate" fi -rm -rf "$GRAD_DIR" "$PROJ_DIR" "$NO_DATE_DIR" "$WT_DIR" "$EDIT_DIR" "$E2E_DIR" "$E2E_DEST" "$REG_DIR" "$MULTI_DIR" +# Test: Ctrl-G on already-graduated symlink is blocked +output=$(try_run --path="$E2E_DIR" --and-keys='CTRL-G,ENTER,ESC' exec 2>/dev/null) +if echo "$output" | grep -q "mv \|ln -s "; then + fail "Ctrl-G on symlink should not graduate again" "no mv or ln -s" "$output" "graduate" +else + pass +fi + +# Test: E2E git worktree graduate succeeds when invoked from outside the repo +WT_E2E_ROOT=$(mktemp -d) +WT_E2E_REPO="$WT_E2E_ROOT/main-repo" +WT_E2E_TRIES="$WT_E2E_ROOT/tries" +WT_E2E_PROJ="$WT_E2E_ROOT/projects" +mkdir -p "$WT_E2E_REPO" "$WT_E2E_TRIES" "$WT_E2E_PROJ" +git -C "$WT_E2E_REPO" init -q +git -C "$WT_E2E_REPO" -c user.name=test -c user.email=test@example.com commit --allow-empty -q -m "init" +git -C "$WT_E2E_REPO" worktree add --detach -q "$WT_E2E_TRIES/2025-06-01-wt-grad" +wt_script=$(cd /tmp && TRY_PROJECTS="$WT_E2E_PROJ" eval $TRY_CMD exec --path="$WT_E2E_TRIES" --and-keys='CTRL-G,ENTER' 2>/dev/null) +(cd /tmp && eval "$(echo "$wt_script" | grep -v '^#')") >/dev/null 2>&1 +if [ -d "$WT_E2E_PROJ/wt-grad" ] && [ -L "$WT_E2E_TRIES/2025-06-01-wt-grad" ]; then + pass +else + fail "E2E worktree graduate should succeed from outside repo" "graduated dir and symlink" "$wt_script" "graduate" +fi + +rm -rf "$GRAD_DIR" "$PROJ_DIR" "$NO_DATE_DIR" "$WT_DIR" "$EDIT_DIR" "$E2E_DIR" "$E2E_DEST" "$REG_DIR" "$MULTI_DIR" "$WT_E2E_ROOT" diff --git a/spec/tests/tmux/test_21_tmux_rename.sh b/spec/tests/tmux/test_21_tmux_rename.sh index 1a70f32..18cab36 100644 --- a/spec/tests/tmux/test_21_tmux_rename.sh +++ b/spec/tests/tmux/test_21_tmux_rename.sh @@ -28,10 +28,10 @@ tui_wait 0.3 tui_send C-r tui_wait 0.2 tui_capture -if echo "$TUI_LAST_OUTPUT" | grep -q "📝"; then +if echo "$TUI_LAST_OUTPUT" | grep -q "✏"; then pass else - fail "Rename mode should show pencil emoji" "📝" "$TUI_LAST_OUTPUT" + fail "Rename mode should show pencil emoji" "✏️" "$TUI_LAST_OUTPUT" fi # Test: Rename shows current name diff --git a/test/try_selector_test.rb b/test/try_selector_test.rb index d0b63a4..d151042 100644 --- a/test/try_selector_test.rb +++ b/test/try_selector_test.rb @@ -459,3 +459,59 @@ def test_no_raise_when_winch_unsupported end end +# ------------------------------------------------------------------- +# finalize_ascend / run_ascend_dialog / render_delete_dialog regressions +# ------------------------------------------------------------------- +class AscendAndDeleteRegressionTest < TrySelectorTestCase + def test_finalize_ascend_empty_destination_returns_error + sel = build_selector + entry = TrySelector::TryEntry.new( + { basename: "2025-06-01-demo", text: "2025-06-01-demo", path: File.join(@tmpdir, "2025-06-01-demo"), is_symlink: false }, + 1.0, [] + ) + assert_equal "Destination cannot be empty", sel.send(:finalize_ascend, entry, " ") + end + + def test_run_ascend_dialog_blocks_symlink + sel = build_selector + entry = TrySelector::TryEntry.new( + { basename: "2025-06-01-linked", text: "2025-06-01-linked", path: @tmpdir, is_symlink: true }, + 1.0, [] + ) + sel.send(:run_ascend_dialog, entry) + assert_equal "Already graduated (symlink)", sel.instance_variable_get(:@delete_status) + assert_nil sel.instance_variable_get(:@selected) + end + + def test_render_delete_dialog_keeps_confirm_prompt_visible_with_many_items + old_height = ENV["TRY_HEIGHT"] + ENV["TRY_HEIGHT"] = "12" + sel = build_selector + items = (1..20).map do |i| + TrySelector::TryEntry.new( + { basename: "2025-06-01-dir-#{i}", text: "2025-06-01-dir-#{i}", path: File.join(@tmpdir, "2025-06-01-dir-#{i}") }, + 1.0, [] + ) + end + + # Capture STDERR output from render_delete_dialog via a pipe + r, w = IO.pipe + saved_stderr = STDERR.dup + STDERR.reopen(w) + begin + sel.send(:render_delete_dialog, items, "", 0) + ensure + STDERR.reopen(saved_stderr) + saved_stderr.close + w.close + end + output = r.read + r.close + + assert_includes output, "Type YES to confirm:" + assert_includes output, "more" + ensure + ENV["TRY_HEIGHT"] = old_height + end +end + diff --git a/try.rb b/try.rb index c3b3c0a..b5f01c8 100755 --- a/try.rb +++ b/try.rb @@ -272,10 +272,8 @@ def get_tries end @last_query = @search.text - height = Tui::Terminal.size(STDERR)[0] || 24 - max_results = [height - 6, 3].max results = [] - @fuzzy.match(@search.text).limit(max_results).each do |entry, positions, score| + @fuzzy.match(@search.text).each do |entry, positions, score| results << TryEntry.new(entry, score, positions) end @cached_results = results @@ -298,7 +296,10 @@ def main_loop before = @search.text if @search.handle_key(key) - @cursor_pos = 0 if @search.text != before + if @search.text != before + @cursor_pos = 0 + @scroll_offset = 0 + end next end @@ -465,7 +466,7 @@ def render(tries) # Calculate max visible from actual header/footer counts header_lines = screen.header.lines.length footer_lines = screen.footer.lines.length - max_visible = [height - header_lines - footer_lines, 3].max + max_visible = [height - header_lines - footer_lines, 1].max show_create_new = !@search.text.empty? total_items = tries.length + (show_create_new ? 1 : 0) @@ -475,10 +476,17 @@ def render(tries) @scroll_offset = @cursor_pos - max_visible + 1 end + # Account for the blank separator line inserted before "Create new" so the + # selected "Create new" row is never clipped past body_space. + if show_create_new && !tries.empty? && @cursor_pos == tries.length && + tries.length > @scroll_offset && (@cursor_pos - @scroll_offset + 2) > max_visible + @scroll_offset += 1 + end + visible_end = [@scroll_offset + max_visible, total_items].min (@scroll_offset...visible_end).each do |idx| - if idx == tries.length && !tries.empty? && idx >= @scroll_offset + if idx == tries.length && !tries.empty? && idx > @scroll_offset screen.body.add_line end @@ -740,6 +748,11 @@ def run_ascend_dialog(entry) @delete_mode = false @marked_for_deletion.clear + if entry.is_symlink + @delete_status = "Already graduated (symlink)" + return + end + current_name = entry.basename # Strip date prefix for the default project name @@ -827,9 +840,9 @@ def render_ascend_dialog(current_name, ascend_buffer, ascend_cursor, ascend_erro def finalize_ascend(entry, ascend_buffer) dest = ascend_buffer.strip + return "Destination cannot be empty" if dest.empty? dest = File.expand_path(dest) - return "Destination cannot be empty" if dest.empty? return "Destination already exists: #{dest}" if File.exist?(dest) parent = File.dirname(dest) @@ -887,9 +900,15 @@ def handle_create_new end end - def confirm_batch_delete(tries) - # Find marked items with their info - marked_items = tries.select { |t| @marked_for_deletion.include?(t.path) } + def confirm_batch_delete(_tries) + # Find all marked items across all tries (preserving mark order) + by_path = {} + load_all_tries.each { |t| by_path[t[:path]] = t } + marked_items = [] + @marked_for_deletion.each do |path| + entry = by_path[path] + marked_items << TryEntry.new(entry, 0.0, []) if entry + end return if marked_items.empty? input = Tui::InputField.new(placeholder: "", text: "") @@ -944,9 +963,28 @@ def render_delete_dialog(marked_items, confirmation_buffer, confirmation_cursor) line = screen.header.add_line line.write.write_dim(fill("─")) - marked_items.each do |item| + # Cap rendered list so the confirmation input prompt is never clipped off-screen + # Reserve: header (2) + footer (2) + blank lines (2) + input prompt (1) = 7 rows + max_items = [screen.height - 7, 1].max + if count <= max_items + marked_items.each do |item| + line = screen.body.add_line(Tui::Palette::DANGER_BG) + line.write.write(emoji("🗑️")).write(" #{item.basename}") + end + elsif max_items == 1 line = screen.body.add_line(Tui::Palette::DANGER_BG) - line.write.write(emoji("🗑️")).write(" #{item.basename}") + line.write.write(emoji("🗑️")).write(" #{count} directories marked for deletion") + else + shown = max_items - 1 + i = 0 + while i < shown + item = marked_items[i] + line = screen.body.add_line(Tui::Palette::DANGER_BG) + line.write.write(emoji("🗑️")).write(" #{item.basename}") + i += 1 + end + line = screen.body.add_line + line.write.write_dim(" ... and #{count - shown} more") end # Add empty lines, then centered confirmation prompt @@ -1273,7 +1311,7 @@ def cmd_clone!(args, tries_path) def cmd_init!(args, tries_path) script_path = File.expand_path($0) - explicit_path = if args[0] && args[0].start_with?('/') + explicit_path = if args[0] && !args[0].empty? && !args[0].start_with?('-') File.expand_path(args.shift) end @@ -1286,7 +1324,7 @@ def cmd_init!(args, tries_path) def cmd_install!(args, tries_path) script_path = File.expand_path($0) - explicit_path = if args[0] && args[0].start_with?('/') + explicit_path = if args[0] && !args[0].empty? && !args[0].start_with?('-') File.expand_path(args.shift) end @@ -1366,7 +1404,7 @@ def shell_rc_file(shell) def init_snippet(shell, script_path, explicit_path, default_path) case shell when 'fish' - fish_path_arg = explicit_path ? " --path '#{explicit_path}'" : " --path (if set -q TRY_PATH; echo \"$TRY_PATH\"; else; echo '#{default_path}'; end)" + fish_path_arg = explicit_path ? " --path #{q(explicit_path)}" : " --path (if set -q TRY_PATH; echo \"$TRY_PATH\"; else; echo #{q(default_path)}; end)" <<~FISH function try set -l out (#{TryCompat.self_exec_prefix(script_path)} exec#{fish_path_arg} $argv 2>/dev/tty | string collect) @@ -1379,15 +1417,15 @@ def init_snippet(shell, script_path, explicit_path, default_path) FISH when 'pwsh' ps_path_expr = if explicit_path - "'#{explicit_path}'" + q_pwsh(explicit_path) else - "$(if ($env:TRY_PATH) { $env:TRY_PATH } else { '#{default_path}' })" + "$(if ($env:TRY_PATH) { $env:TRY_PATH } else { #{q_pwsh(default_path)} })" end <<~PWSH function try { $tryPath = #{ps_path_expr} $tempErr = [System.IO.Path]::GetTempFileName() - $out = & #{TryCompat.compiled_binary? ? q(script_path) : "ruby '#{script_path}'"} exec --path $tryPath @args 2>$tempErr + $out = & #{TryCompat.compiled_binary? ? q_pwsh(script_path) : "ruby #{q_pwsh(script_path)}"} exec --path $tryPath @args 2>$tempErr if ($LASTEXITCODE -eq 0) { $out | Invoke-Expression } else { @@ -1398,7 +1436,7 @@ def init_snippet(shell, script_path, explicit_path, default_path) } PWSH else # bash, zsh - path_arg = explicit_path ? " --path '#{explicit_path}'" : " --path \"${TRY_PATH:-#{default_path}}\"" + path_arg = explicit_path ? " --path #{q(explicit_path)}" : " --path \"${TRY_PATH:-#{escape_sh_dquote(default_path)}}\"" <<~SH try() { local out @@ -1418,8 +1456,9 @@ def cmd_cd!(args, tries_path, and_type, and_exit, and_keys, and_confirm) return cmd_clone!(args[1..-1] || [], tries_path) end - # Support: try . [name] and try ./path [name] - if args.first && args.first.start_with?('.') + # Support: try . [name] and try ./path [name] (without hijacking searches like .env) + first_arg = args.first + if first_arg && (first_arg == '.' || first_arg == '..' || first_arg.start_with?('./') || first_arg.start_with?('../')) path_arg = args.shift custom = args.join(' ') repo_dir = File.expand_path(path_arg) @@ -1437,8 +1476,8 @@ def cmd_cd!(args, tries_path, and_type, and_exit, and_keys, and_confirm) date_prefix = Time.now.strftime("%Y-%m-%d") base = resolve_unique_name_with_versioning(tries_path, date_prefix, base) full_path = File.join(tries_path, "#{date_prefix}-#{base}") - # Use worktree if .git exists (file in worktrees, directory in regular repos) - if File.exist?(File.join(repo_dir, '.git')) + # Use worktree if inside a git repo (checks current dir and ancestors) + if inside_git_repo?(repo_dir) return script_worktree(full_path, repo_dir) else return script_mkdir_cd(full_path) @@ -1496,7 +1535,31 @@ def cmd_cd!(args, tries_path, and_type, and_exit, and_keys, and_confirm) SCRIPT_WARNING = "# if you can read this, you didn't launch try from an alias. run try --help." def q(str) - "'" + str.gsub("'", %q('"'"')) + "'" + "'" + str.to_s.gsub("'", %q('"'"')) + "'" + end + + def q_pwsh(str) + "'" + str.to_s.gsub("'", "''") + "'" + end + + def escape_sh_dquote(str) + out = String.new + str.to_s.each_char do |ch| + out << '\\' if ch == '\\' || ch == '"' || ch == '$' || ch == '`' || ch == '}' + out << ch + end + out + end + + def inside_git_repo?(dir) + current = File.expand_path(dir.to_s) + return false unless Dir.exist?(current) + loop do + return true if File.exist?(File.join(current, '.git')) + parent = File.dirname(current) + return false if parent == current + current = parent + end end def emit_script(cmds) @@ -1547,7 +1610,7 @@ def script_mkdir_cd(path) end def script_clone(path, uri) - ["mkdir -p #{q(path)}", "echo #{q("Using git clone to create this trial from #{uri}.")}", "git clone '#{uri}' #{q(path)}"] + script_cd(path) + ["mkdir -p #{q(path)}", "echo #{q("Using git clone to create this trial from #{uri}.")}", "git clone #{q(uri)} #{q(path)}"] + script_cd(path) end def script_clone_pr(path, uri, pr_id) @@ -1562,11 +1625,10 @@ def script_clone_pr(path, uri, pr_id) end def script_worktree(path, repo = nil) - r = repo ? q(repo) : nil - worktree_cmd = if r - "/usr/bin/env sh -c 'if git -C #{r} rev-parse --is-inside-work-tree >/dev/null 2>&1; then repo=$(git -C #{r} rev-parse --show-toplevel); git -C \"$repo\" worktree add --detach #{q(path)} >/dev/null 2>&1 || true; fi; exit 0'" + worktree_cmd = if repo + "/usr/bin/env sh -c 'if git -C \"$1\" rev-parse --is-inside-work-tree >/dev/null 2>&1; then repo=$(git -C \"$1\" rev-parse --show-toplevel); git -C \"$repo\" worktree add --detach \"$2\" >/dev/null 2>&1 || true; fi; exit 0' _ #{q(repo)} #{q(path)}" else - "/usr/bin/env sh -c 'if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then repo=$(git rev-parse --show-toplevel); git -C \"$repo\" worktree add --detach #{q(path)} >/dev/null 2>&1 || true; fi; exit 0'" + "/usr/bin/env sh -c 'if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then repo=$(git rev-parse --show-toplevel); git -C \"$repo\" worktree add --detach \"$1\" >/dev/null 2>&1 || true; fi; exit 0' _ #{q(path)}" end src = repo || Dir.pwd ["mkdir -p #{q(path)}", "echo #{q("Using git worktree to create this trial from #{src}.")}", worktree_cmd] + script_cd(path) @@ -1587,8 +1649,8 @@ def script_ascend(source, dest, basename, base_path) cmds = [] if is_worktree - # Use git worktree move for proper bookkeeping - cmds << "git worktree move #{q(source)} #{q(dest)}" + # Use git worktree move for proper bookkeeping (-C works regardless of CWD) + cmds << "git -C #{q(source)} worktree move #{q(source)} #{q(dest)}" else cmds << "mv #{q(source)} #{q(dest)}" end