forked from tobi/try
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry.rb
More file actions
executable file
·1612 lines (1407 loc) · 51.6 KB
/
Copy pathtry.rb
File metadata and controls
executable file
·1612 lines (1407 loc) · 51.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
require 'io/console'
require 'time'
require 'fileutils'
require 'set'
require_relative 'lib/tui'
require_relative 'lib/fuzzy'
class TrySelector
include Tui::Helpers
TRY_PATH = ENV['TRY_PATH'] || File.expand_path("~/src/tries")
TRY_PROJECTS = ENV['TRY_PROJECTS']
# Precompiled regex constants
INPUT_CHAR_RE = /[a-zA-Z0-9\-\_\. ]/
WORD_CHAR_RE = /[a-zA-Z0-9]/
def initialize(search_term = "", base_path: TRY_PATH, initial_input: nil, test_render_once: false, test_no_cls: false, test_keys: nil, test_confirm: nil)
@search_term = search_term.gsub(/\s+/, '-')
@cursor_pos = 0 # Navigation cursor (list position)
@input_cursor_pos = 0 # Text cursor (position within search buffer)
@scroll_offset = 0
@input_buffer = initial_input ? initial_input.gsub(/\s+/, '-') : @search_term
@input_cursor_pos = @input_buffer.length # Start at end of buffer
@selected = nil
@all_trials = nil # Memoized trials
@base_path = base_path
@delete_status = nil # Status message for deletions
@delete_mode = false # Whether we're in deletion mode
@marked_for_deletion = [] # Paths marked for deletion
@test_render_once = test_render_once
@test_no_cls = test_no_cls
@test_keys = test_keys
@test_had_keys = test_keys && !test_keys.empty?
@test_confirm = test_confirm
@old_winch_handler = nil # Store original SIGWINCH handler
@needs_redraw = false
FileUtils.mkdir_p(@base_path) unless Dir.exist?(@base_path)
end
def run
# Always use STDERR for rendering (it stays connected to TTY)
# This allows stdout to be captured for the shell commands
setup_terminal
# In test mode with no keys, render once and exit without TTY requirements
# If test_keys are provided, run the full loop
if @test_render_once && (@test_keys.nil? || @test_keys.empty?)
tries = get_tries
render(tries)
return nil
end
# Check if we have a TTY; allow tests with injected keys
if !STDIN.tty? || !STDERR.tty?
if @test_keys.nil? || @test_keys.empty?
STDERR.puts "Error: try requires an interactive terminal"
return nil
end
main_loop
else
STDERR.raw do
main_loop
end
end
ensure
restore_terminal
end
private
def setup_terminal
unless @test_no_cls
# Switch to alternate screen buffer (like vim, less, etc.)
STDERR.print("#{Tui::ANSI::ALT_SCREEN_ON}#{Tui::ANSI.set_title("try")}#{Tui::ANSI::CURSOR_BLINK}")
end
@old_winch_handler = Signal.trap('WINCH') { @needs_redraw = true }
end
def restore_terminal
unless @test_no_cls
STDERR.print(Tui::ANSI::RESET)
STDERR.print(Tui::ANSI::CURSOR_DEFAULT)
# Return to main screen buffer
STDERR.print(Tui::ANSI::ALT_SCREEN_OFF)
end
Signal.trap('WINCH', @old_winch_handler) if @old_winch_handler
end
def load_all_tries
# Load trials only once - single pass through directory
@all_tries ||= begin
tries = []
now = Time.now
Dir.foreach(@base_path) do |entry|
# exclude . and .. but also .git, and any other hidden dirs.
next if entry.start_with?('.')
path = File.join(@base_path, entry)
begin
stat = File.stat(path)
rescue Errno::ENOENT, Errno::EACCES
next
end
# Only include directories
next unless stat.directory?
# Compute base_score from recency + date prefix bonus
mtime = stat.mtime
hours_since_access = (now - mtime) / 3600.0
base_score = 3.0 / Math.sqrt(hours_since_access + 1)
# Bonus for date-prefixed directories
base_score += 2.0 if entry.match?(/^\d{4}-\d{2}-\d{2}-/)
is_symlink = File.symlink?(path)
tries << {
text: entry,
basename: entry,
path: is_symlink ? File.realpath(path) : path,
is_new: false,
is_symlink: is_symlink,
ctime: stat.ctime,
mtime: mtime,
base_score: base_score
}
end
tries
end
end
# Result wrapper to avoid Hash#merge allocation per entry
TryEntry = Data.define(:data, :score, :highlight_positions) do
def [](key)
case key
when :score then score
when :highlight_positions then highlight_positions
else data[key]
end
end
def method_missing(name, *)
data[name]
end
def respond_to_missing?(name, include_private = false)
data.key?(name) || super
end
end
def get_tries
load_all_tries
@fuzzy ||= Fuzzy.new(@all_tries)
# Cache results - only re-match when query changes
if @last_query == @input_buffer && @cached_results
return @cached_results
end
@last_query = @input_buffer
height = IO.console&.winsize&.first || 24
max_results = [height - 6, 3].max
results = []
@fuzzy.match(@input_buffer).limit(max_results).each do |entry, positions, score|
results << TryEntry.new(entry, score, positions)
end
@cached_results = results
end
def main_loop
loop do
tries = get_tries
show_create_new = !@input_buffer.empty?
total_items = tries.length + (show_create_new ? 1 : 0)
# Ensure cursor is within bounds
@cursor_pos = [[@cursor_pos, 0].max, [total_items - 1, 0].max].min
render(tries)
key = read_key
# nil means terminal resize - just re-render with new dimensions
next unless key
case key
when "\r" # Enter (carriage return)
if @delete_mode && !@marked_for_deletion.empty?
# Confirm deletion of marked items
confirm_batch_delete(tries)
break if @selected
elsif @cursor_pos < tries.length
handle_selection(tries[@cursor_pos])
break if @selected
elsif show_create_new
# Selected "Create new"
handle_create_new
break if @selected
end
when "\e[A", "\x10" # Up arrow or Ctrl-P
@cursor_pos = [@cursor_pos - 1, 0].max
when "\e[B", "\x0E" # Down arrow or Ctrl-N
@cursor_pos = [@cursor_pos + 1, total_items - 1].min
when "\e[C" # Right arrow - ignore
# Do nothing
when "\e[D" # Left arrow - ignore
# Do nothing
when "\x7F", "\b" # Backspace (DEL and BS)
if @input_cursor_pos > 0
@input_buffer = @input_buffer[0...(@input_cursor_pos-1)] + @input_buffer[@input_cursor_pos..]
@input_cursor_pos -= 1
end
@cursor_pos = 0 # Reset list selection when typing
when "\x01" # Ctrl-A - beginning of line
@input_cursor_pos = 0
when "\x05" # Ctrl-E - end of line
@input_cursor_pos = @input_buffer.length
when "\x02" # Ctrl-B - backward char
@input_cursor_pos = [@input_cursor_pos - 1, 0].max
when "\x06" # Ctrl-F - forward char
@input_cursor_pos = [@input_cursor_pos + 1, @input_buffer.length].min
when "\x0B" # Ctrl-K - kill to end of line
@input_buffer = @input_buffer[0...@input_cursor_pos]
when "\x17" # Ctrl-W - delete word backward (alphanumeric)
if @input_cursor_pos > 0
new_pos = word_boundary_backward(@input_buffer, @input_cursor_pos)
@input_buffer = @input_buffer[0...new_pos] + @input_buffer[@input_cursor_pos..]
@input_cursor_pos = new_pos
end
when "\x04" # Ctrl-D - toggle mark for deletion
if @cursor_pos < tries.length
path = tries[@cursor_pos][:path]
if @marked_for_deletion.include?(path)
@marked_for_deletion.delete(path)
else
@marked_for_deletion << path
@delete_mode = true
end
# Exit delete mode if no more marks
@delete_mode = false if @marked_for_deletion.empty?
end
when "\x14" # Ctrl-T - create new try (immediate)
handle_create_new
break if @selected
when "\x12" # Ctrl-R - rename selected entry
if @cursor_pos < tries.length
run_rename_dialog(tries[@cursor_pos])
break if @selected
end
when "\x07" # Ctrl-G - graduate/ascend selected entry
if @cursor_pos < tries.length
run_ascend_dialog(tries[@cursor_pos])
break if @selected
end
when "\x03", "\e" # Ctrl-C or ESC
if @delete_mode
# Exit delete mode, clear marks
@marked_for_deletion.clear
@delete_mode = false
else
@selected = nil
break
end
when String
# Only accept printable characters, not escape sequences
if key.length == 1 && key.match?(INPUT_CHAR_RE)
@input_buffer = @input_buffer[0...@input_cursor_pos] + key + @input_buffer[@input_cursor_pos..]
@input_cursor_pos += 1
@cursor_pos = 0 # Reset list selection when typing
end
end
end
@selected
end
def read_key
if @test_keys && !@test_keys.empty?
return @test_keys.shift
end
# In test mode with no more keys, auto-exit by returning ESC
return "\e" if @test_had_keys && @test_keys && @test_keys.empty?
# Use IO.select with timeout to allow checking for resize
loop do
if @needs_redraw
@needs_redraw = false
clear_screen unless @test_no_cls
return nil
end
ready = IO.select([STDIN], nil, nil, 0.1)
return read_keypress if ready
end
end
def read_keypress
input = STDIN.getc
return nil if input.nil?
if input == "\e"
begin
input << STDIN.read_nonblock(3)
input << STDIN.read_nonblock(2)
rescue IO::WaitReadable, EOFError
# No more escape sequence data available
end
end
input
end
def clear_screen
STDERR.print("\e[2J\e[H")
end
def hide_cursor
STDERR.print(Tui::ANSI::HIDE)
end
def show_cursor
STDERR.print(Tui::ANSI::SHOW)
end
def render(tries)
screen = Tui::Screen.new(io: STDERR)
width = screen.width
height = screen.height
screen.header.add_line { |line| line.write << emoji("🏠") << Tui::Text.accent(" Try Directory Selection") }
screen.header.add_line { |line| line.write.write_dim(fill("─")) }
screen.header.add_line do |line|
prefix = "Search: "
line.write.write_dim(prefix)
line.write << screen.input("", value: @input_buffer, cursor: @input_cursor_pos).to_s
line.mark_has_input(Tui::Metrics.visible_width(prefix))
end
screen.header.add_line { |line| line.write.write_dim(fill("─")) }
# Add footer first to get accurate line count
screen.footer.add_line { |line| line.write.write_dim(fill("─")) }
if @delete_status
screen.footer.add_line { |line| line.write.write_bold(@delete_status) }
@delete_status = nil
elsif @delete_mode
screen.footer.add_line(background: Tui::Palette::DANGER_BG) do |line|
line.write.write_bold(" DELETE MODE ")
line.write << " #{@marked_for_deletion.length} marked | Ctrl-D: Toggle Enter: Confirm Esc: Cancel"
end
else
screen.footer.add_line do |line|
line.center.write_dim("↑/↓: Navigate Enter: Select ^R: Rename ^G: Graduate ^D: Delete Esc: Cancel")
end
end
# 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
show_create_new = !@input_buffer.empty?
total_items = tries.length + (show_create_new ? 1 : 0)
if @cursor_pos < @scroll_offset
@scroll_offset = @cursor_pos
elsif @cursor_pos >= @scroll_offset + max_visible
@scroll_offset = @cursor_pos - max_visible + 1
end
visible_end = [@scroll_offset + max_visible, total_items].min
(@scroll_offset...visible_end).each do |idx|
if idx == tries.length && tries.any? && idx >= @scroll_offset
screen.body.add_line
end
if idx < tries.length
render_entry_line(screen, tries[idx], idx == @cursor_pos, width)
else
render_create_line(screen, idx == @cursor_pos, width)
end
end
screen.flush
end
def render_entry_line(screen, entry, is_selected, width)
is_marked = @marked_for_deletion.include?(entry[:path])
# Marked items always show red; selection shows via arrow only
background = if is_marked
Tui::Palette::DANGER_BG
elsif is_selected
Tui::Palette::SELECTED_BG
end
line = screen.body.add_line(background: background)
line.write << (is_selected ? Tui::Text.highlight("→ ") : " ")
icon = if is_marked
emoji("🗑️")
elsif entry[:is_symlink]
emoji("🔗")
else
emoji("📁")
end
line.write << icon << " "
plain_name, rendered_name = formatted_entry_name(entry)
prefix_width = 5
meta_text = "#{format_relative_time(entry[:mtime])}, #{format('%.1f', entry[:score])}"
# Only truncate name if it exceeds total line width (not to make room for metadata)
max_name_width = width - prefix_width - 1
if plain_name.length > max_name_width && max_name_width > 2
display_rendered = truncate_with_ansi(rendered_name, max_name_width - 1) + "…"
else
display_rendered = rendered_name
end
line.write << display_rendered
# Right content is lower layer - will be overwritten by left if they overlap
line.right.write_dim(meta_text)
end
def render_create_line(screen, is_selected, width)
background = is_selected ? Tui::Palette::SELECTED_BG : nil
line = screen.body.add_line(background: background)
line.write << (is_selected ? Tui::Text.highlight("→ ") : " ")
date_prefix = Time.now.strftime("%Y-%m-%d")
label = if @input_buffer.empty?
"📂 Create new: #{date_prefix}-"
else
"📂 Create new: #{date_prefix}-#{@input_buffer}"
end
line.write << label
end
def formatted_entry_name(entry)
basename = entry[:basename]
positions = entry[:highlight_positions] || []
if basename =~ /^(\d{4}-\d{2}-\d{2})-(.+)$/
date_part = $1
name_part = $2
date_len = date_part.length + 1 # +1 for the hyphen
rendered = Tui::Text.dim(date_part)
# Highlight hyphen if it's in positions
rendered += positions.include?(10) ? Tui::Text.highlight('-') : Tui::Text.dim('-')
rendered += highlight_with_positions(name_part, positions, date_len)
["#{date_part}-#{name_part}", rendered]
else
[basename, highlight_with_positions(basename, positions, 0)]
end
end
def highlight_with_positions(text, positions, offset)
pos_set = positions.is_a?(Set) ? positions : positions.to_set
result = String.new
chars = text.chars
i = 0
while i < chars.length
if pos_set.include?(i + offset)
# Batch consecutive highlighted characters
batch_start = i
i += 1
i += 1 while i < chars.length && pos_set.include?(i + offset)
result << Tui::Text.highlight(chars[batch_start...i].join)
else
result << chars[i]
i += 1
end
end
result
end
# Find the position of the previous word boundary for Ctrl-W deletion.
# Skips non-alphanumeric chars, then skips alphanumeric chars.
def word_boundary_backward(buffer, cursor)
pos = cursor - 1
pos -= 1 while pos >= 0 && !buffer[pos].match?(WORD_CHAR_RE)
pos -= 1 while pos >= 0 && buffer[pos].match?(WORD_CHAR_RE)
pos + 1
end
def format_relative_time(time)
return "?" unless time
seconds = Time.now - time
minutes = seconds / 60
hours = minutes / 60
days = hours / 24
if seconds < 60
"just now"
elsif minutes < 60
"#{minutes.to_i}m ago"
elsif hours < 24
"#{hours.to_i}h ago"
elsif days < 7
"#{days.to_i}d ago"
else
"#{(days/7).to_i}w ago"
end
end
def truncate_with_ansi(text, max_length)
# Simple truncation that preserves ANSI codes
visible_count = 0
result = ""
in_ansi = false
text.chars.each do |char|
if char == "\e"
in_ansi = true
result += char
elsif in_ansi
result += char
in_ansi = false if char == "m"
else
break if visible_count >= max_length
result += char
visible_count += 1
end
end
result
end
# Rename dialog - dedicated screen similar to delete
def run_rename_dialog(entry)
@delete_mode = false
@marked_for_deletion.clear
current_name = entry[:basename]
rename_buffer = current_name.dup
rename_cursor = rename_buffer.length
rename_error = nil
loop do
render_rename_dialog(current_name, rename_buffer, rename_cursor, rename_error)
ch = read_key
case ch
when "\r" # Enter - confirm
result = finalize_rename(entry, rename_buffer)
if result == true
break
else
rename_error = result # Error message string
end
when "\e", "\x03" # ESC or Ctrl-C - cancel
break
when "\x7F", "\b" # Backspace
if rename_cursor > 0
rename_buffer = rename_buffer[0...(rename_cursor - 1)] + rename_buffer[rename_cursor..].to_s
rename_cursor -= 1
end
rename_error = nil
when "\x01" # Ctrl-A - start of line
rename_cursor = 0
when "\x05" # Ctrl-E - end of line
rename_cursor = rename_buffer.length
when "\x02" # Ctrl-B - back one char
rename_cursor = [rename_cursor - 1, 0].max
when "\x06" # Ctrl-F - forward one char
rename_cursor = [rename_cursor + 1, rename_buffer.length].min
when "\x0B" # Ctrl-K - kill to end
rename_buffer = rename_buffer[0...rename_cursor]
rename_error = nil
when "\x17" # Ctrl-W - delete word backward
if rename_cursor > 0
new_pos = word_boundary_backward(rename_buffer, rename_cursor)
rename_buffer = rename_buffer[0...new_pos] + rename_buffer[rename_cursor..].to_s
rename_cursor = new_pos
end
rename_error = nil
when String
if ch.length == 1 && ch =~ /[a-zA-Z0-9\-_\.\s\/]/
rename_buffer = rename_buffer[0...rename_cursor] + ch + rename_buffer[rename_cursor..].to_s
rename_cursor += 1
rename_error = nil
end
end
end
@needs_redraw = true
end
def render_rename_dialog(current_name, rename_buffer, rename_cursor, rename_error)
screen = Tui::Screen.new(io: STDERR)
screen.header.add_line do |line|
line.center << emoji("✏️") << Tui::Text.accent(" Rename directory")
end
screen.header.add_line { |line| line.write.write_dim(fill("─")) }
screen.body.add_line do |line|
line.write << emoji("📁") << " #{current_name}"
end
# Add empty lines, then centered input prompt
2.times { screen.body.add_line }
screen.body.add_line do |line|
prefix = "New name: "
line.center.write_dim(prefix)
line.center << screen.input("", value: rename_buffer, cursor: rename_cursor).to_s
# Input displays buffer + trailing space when cursor at end
# Use (width - 1) to match Line.render's max_content calculation
input_width = [rename_buffer.length, rename_cursor + 1].max
prefix_width = Tui::Metrics.visible_width(prefix)
max_content = screen.width - 1
center_start = (max_content - prefix_width - input_width) / 2
line.mark_has_input(center_start + prefix_width)
end
if rename_error
screen.body.add_line
screen.body.add_line { |line| line.center.write_bold(rename_error) }
end
screen.footer.add_line { |line| line.write.write_dim(fill("─")) }
screen.footer.add_line { |line| line.center.write_dim("Enter: Confirm Esc: Cancel") }
screen.flush
end
def finalize_rename(entry, rename_buffer)
new_name = rename_buffer.strip.gsub(/\s+/, '-')
old_name = entry[:basename]
return "Name cannot be empty" if new_name.empty?
return "Name cannot contain /" if new_name.include?('/')
return true if new_name == old_name # No change, just exit
return "Directory exists: #{new_name}" if Dir.exist?(File.join(@base_path, new_name))
@selected = { type: :rename, old: old_name, new: new_name, base_path: @base_path }
true
end
# Ascend dialog - promote a try to a permanent project directory
def run_ascend_dialog(entry)
@delete_mode = false
@marked_for_deletion.clear
current_name = entry[:basename]
# Strip date prefix for the default project name
project_name = current_name.sub(/^\d{4}-\d{2}-\d{2}-/, '')
# Compute default destination directory
projects_dir = if TRY_PROJECTS
File.expand_path(TRY_PROJECTS)
else
File.dirname(@base_path)
end
ascend_buffer = File.join(projects_dir, project_name)
ascend_cursor = ascend_buffer.length
ascend_error = nil
loop do
render_ascend_dialog(current_name, ascend_buffer, ascend_cursor, ascend_error, projects_dir)
ch = read_key
case ch
when "\r" # Enter - confirm
result = finalize_ascend(entry, ascend_buffer)
if result == true
break
else
ascend_error = result
end
when "\e", "\x03" # ESC or Ctrl-C - cancel
break
when "\x7F", "\b" # Backspace
if ascend_cursor > 0
ascend_buffer = ascend_buffer[0...(ascend_cursor - 1)] + ascend_buffer[ascend_cursor..].to_s
ascend_cursor -= 1
end
ascend_error = nil
when "\x01" # Ctrl-A - start of line
ascend_cursor = 0
when "\x05" # Ctrl-E - end of line
ascend_cursor = ascend_buffer.length
when "\x02" # Ctrl-B - back one char
ascend_cursor = [ascend_cursor - 1, 0].max
when "\x06" # Ctrl-F - forward one char
ascend_cursor = [ascend_cursor + 1, ascend_buffer.length].min
when "\x0B" # Ctrl-K - kill to end
ascend_buffer = ascend_buffer[0...ascend_cursor]
ascend_error = nil
when "\x17" # Ctrl-W - delete word backward
if ascend_cursor > 0
new_pos = word_boundary_backward(ascend_buffer, ascend_cursor)
ascend_buffer = ascend_buffer[0...new_pos] + ascend_buffer[ascend_cursor..].to_s
ascend_cursor = new_pos
end
ascend_error = nil
when String
if ch.length == 1 && ch =~ /[a-zA-Z0-9\-_\.\s\/~]/
ascend_buffer = ascend_buffer[0...ascend_cursor] + ch + ascend_buffer[ascend_cursor..].to_s
ascend_cursor += 1
ascend_error = nil
end
end
end
@needs_redraw = true
end
def render_ascend_dialog(current_name, ascend_buffer, ascend_cursor, ascend_error, projects_dir)
screen = Tui::Screen.new(io: STDERR)
screen.header.add_line do |line|
line.center << emoji("🚀") << Tui::Text.accent(" Graduate try to project")
end
screen.header.add_line { |line| line.write.write_dim(fill("─")) }
screen.body.add_line do |line|
line.write << emoji("📁") << " #{current_name}"
end
screen.body.add_line
env_hint = TRY_PROJECTS ? "$TRY_PROJECTS" : "parent of $TRY_PATH"
screen.body.add_line do |line|
line.center.write_dim("Destination (#{env_hint}: #{projects_dir})")
end
screen.body.add_line do |line|
prefix = "Move to: "
line.center.write_dim(prefix)
line.center << screen.input("", value: ascend_buffer, cursor: ascend_cursor).to_s
input_width = [ascend_buffer.length, ascend_cursor + 1].max
prefix_width = Tui::Metrics.visible_width(prefix)
max_content = screen.width - 1
center_start = (max_content - prefix_width - input_width) / 2
line.mark_has_input(center_start + prefix_width)
end
screen.body.add_line
screen.body.add_line do |line|
line.center.write_dim("A symlink will be left in the tries directory")
end
if ascend_error
screen.body.add_line
screen.body.add_line { |line| line.center.write_bold(ascend_error) }
end
screen.footer.add_line { |line| line.write.write_dim(fill("─")) }
screen.footer.add_line { |line| line.center.write_dim("Enter: Confirm Esc: Cancel") }
screen.flush
end
def finalize_ascend(entry, ascend_buffer)
dest = ascend_buffer.strip
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)
return "Parent directory does not exist: #{parent}" unless Dir.exist?(parent)
@selected = {
type: :ascend,
source: entry[:path],
dest: dest,
basename: entry[:basename],
base_path: @base_path
}
true
end
def handle_selection(try_dir)
# Select existing try directory
@selected = { type: :cd, path: try_dir[:path] }
end
def handle_create_new
# Create new try directory
date_prefix = Time.now.strftime("%Y-%m-%d")
# If user already typed a name, use it directly
if !@input_buffer.empty?
final_name = "#{date_prefix}-#{@input_buffer}".gsub(/\s+/, '-')
full_path = File.join(@base_path, final_name)
@selected = { type: :mkdir, path: full_path }
else
# No name typed, prompt for one
entry = ""
begin
clear_screen unless @test_no_cls
show_cursor
STDERR.puts "Enter new try name"
STDERR.puts
STDERR.print("> #{date_prefix}-")
STDERR.flush
STDERR.cooked do
STDIN.iflush
entry = STDIN.gets&.chomp.to_s
end
ensure
hide_cursor unless @test_no_cls
end
return if entry.nil? || entry.empty?
final_name = "#{date_prefix}-#{entry}".gsub(/\s+/, '-')
full_path = File.join(@base_path, final_name)
@selected = { type: :mkdir, path: full_path }
end
end
def confirm_batch_delete(tries)
# Find marked items with their info
marked_items = tries.select { |t| @marked_for_deletion.include?(t[:path]) }
return if marked_items.empty?
confirmation_buffer = ""
confirmation_cursor = 0
# Handle test mode
if @test_keys && !@test_keys.empty?
while @test_keys && !@test_keys.empty?
ch = @test_keys.shift
break if ch == "\r" || ch == "\n"
confirmation_buffer << ch
confirmation_cursor = confirmation_buffer.length
end
process_delete_confirmation(marked_items, confirmation_buffer)
return
elsif @test_confirm || !STDERR.tty?
confirmation_buffer = (@test_confirm || STDIN.gets)&.chomp.to_s
process_delete_confirmation(marked_items, confirmation_buffer)
return
end
# Interactive delete confirmation dialog
# Clear screen once before dialog to ensure clean slate
clear_screen unless @test_no_cls
loop do
render_delete_dialog(marked_items, confirmation_buffer, confirmation_cursor)
ch = read_key
case ch
when "\r" # Enter - confirm
process_delete_confirmation(marked_items, confirmation_buffer)
break
when "\e" # Escape - cancel
@delete_status = "Delete cancelled"
@marked_for_deletion.clear
@delete_mode = false
break
when "\x7F", "\b" # Backspace
if confirmation_cursor > 0
confirmation_buffer = confirmation_buffer[0...confirmation_cursor-1] + confirmation_buffer[confirmation_cursor..]
confirmation_cursor -= 1
end
when "\x03" # Ctrl-C
@delete_status = "Delete cancelled"
@marked_for_deletion.clear
@delete_mode = false
break
when String
if ch.length == 1 && ch.ord >= 32
confirmation_buffer = confirmation_buffer[0...confirmation_cursor] + ch + confirmation_buffer[confirmation_cursor..]
confirmation_cursor += 1
end
end
end
@needs_redraw = true
end
def render_delete_dialog(marked_items, confirmation_buffer, confirmation_cursor)
screen = Tui::Screen.new(io: STDERR)
count = marked_items.length
screen.header.add_line do |line|
line.center << emoji("🗑️") << Tui::Text.accent(" Delete #{count} #{count == 1 ? 'directory' : 'directories'}?")
end
screen.header.add_line { |line| line.write.write_dim(fill("─")) }
marked_items.each do |item|
screen.body.add_line(background: Tui::Palette::DANGER_BG) do |line|
line.write << emoji("🗑️") << " #{item[:basename]}"
end
end
# Add empty lines, then centered confirmation prompt
2.times { screen.body.add_line }
screen.body.add_line do |line|
prefix = "Type YES to confirm: "
line.center.write_dim(prefix)
line.center << screen.input("", value: confirmation_buffer, cursor: confirmation_cursor).to_s
# Input displays buffer + trailing space when cursor at end
# Use (width - 1) to match Line.render's max_content calculation
input_width = [confirmation_buffer.length, confirmation_cursor + 1].max
prefix_width = Tui::Metrics.visible_width(prefix)
max_content = screen.width - 1
center_start = (max_content - prefix_width - input_width) / 2
line.mark_has_input(center_start + prefix_width)
end
screen.footer.add_line { |line| line.write.write_dim(fill("─")) }
screen.footer.add_line { |line| line.center.write_dim("Enter: Confirm Esc: Cancel") }
screen.flush
end
def process_delete_confirmation(marked_items, confirmation)
if confirmation == "YES"
begin
base_real = File.realpath(@base_path)
# Validate all paths first
validated_paths = []
marked_items.each do |item|
target_real = File.realpath(item[:path])
unless target_real.start_with?(base_real + "/")
raise "Safety check failed: #{target_real} is not inside #{base_real}"
end
validated_paths << { path: target_real, basename: item[:basename] }
end
# Return delete action with all paths
@selected = { type: :delete, paths: validated_paths, base_path: base_real }
names = validated_paths.map { |p| p[:basename] }.join(", ")
@delete_status = "Deleted: #{names}"
@all_tries = nil # Clear cache
@fuzzy = nil
@cached_results = nil
@last_query = nil
@marked_for_deletion.clear
@delete_mode = false
rescue => e
@delete_status = "Error: #{e.message}"
end
else
@delete_status = "Delete cancelled"
@marked_for_deletion.clear
@delete_mode = false
end
end
end
# Main execution with OptionParser subcommands
if __FILE__ == $0
VERSION = "1.9.3"
def print_global_help
text = <<~HELP
try v#{VERSION} - ephemeral workspace manager
To use try, add to your shell config:
# bash/zsh (~/.bashrc or ~/.zshrc)
eval "$(try init ~/src/tries)"
# fish (~/.config/fish/config.fish)
eval (try init ~/src/tries | string collect)
Usage:
try [query] Interactive directory selector
try clone <url> Clone repo into dated directory
try worktree <name> Create worktree from current git repo
try --help Show this help
Commands:
init [path] Output shell function definition
clone <url> [name] Clone git repo into date-prefixed directory
worktree <name> Create worktree in dated directory
Examples:
try Open interactive selector
try project Selector with initial filter
try clone https://github.com/user/repo
try worktree feature-branch
Manual mode (without alias):
try exec [query] Output shell script to eval
Environment:
TRY_PATH Tries directory (default: ~/src/tries)
TRY_PROJECTS Graduate destination (default: parent of TRY_PATH)
Keyboard:
↑/↓, Ctrl-P/N Navigate
Enter Select / Create new
Ctrl-R Rename
Ctrl-G Graduate (promote try to project)