thor-interactive 0.1.0.pre.4 → 0.1.0.pre.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c927c297d565d278a09334334217dca98c5e05e72277f7fec4f5d07568f19c30
4
- data.tar.gz: 353b4acde28a2a780a2b7a1ce85d7fb6e510f20d2862dd3dc4b2505140e2c014
3
+ metadata.gz: 7166b4156516b241939081e8c9fc67aba249ceae1be85b4693d4afdb7638b08d
4
+ data.tar.gz: 8c3f92ab064d86f27a028dd685037d8e205e452ae840a674c39025d21fd8acfb
5
5
  SHA512:
6
- metadata.gz: 77f42909ede7bb049ea1675bc2ccc4f486437be713bc2dd9c16cb5bfdd98b8723b77cacb87147335cb85d439f79c57b0ae18f0bbb0d874f80dd56b27a39bd5c9
7
- data.tar.gz: 11f5c9a01fa32839b669d968c7cb154827bfd4cbe910c272094403280193c5115bef46fa4eb430ad476f9437d75fe13a515f12eadaa1d91080e48d4724c4866d
6
+ metadata.gz: 66f640e0df6d3f1699c6cd1e9612bd6f149da4a7716bcc66e49092a4dbe0f6e568eb98e97dc9e8eecc12548f8149eadbf01ab4149e0ab832d6a57fcf7c3237fe
7
+ data.tar.gz: a5993427b1e28efaa8849440ff0a16e724cb25dc746d0f49292bad78c2d1f364f5526e57d30e73361c236c1460c248ddb4eaf7c32ec370965622583982881232
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "thor/interactive"
6
+
7
+ class CompletionDemo < Thor
8
+ include Thor::Interactive::Command
9
+
10
+ configure_interactive(
11
+ prompt: "demo> "
12
+ )
13
+
14
+ desc "process FILE", "Process a file"
15
+ option :output, type: :string, aliases: "-o", desc: "Output file"
16
+ option :format, type: :string, enum: ["json", "xml", "yaml"], desc: "Output format"
17
+ option :verbose, type: :boolean, aliases: "-v", desc: "Verbose output"
18
+ def process(file)
19
+ puts "Processing: #{file}"
20
+ puts "Output to: #{options[:output]}" if options[:output]
21
+ puts "Format: #{options[:format]}" if options[:format]
22
+ puts "Verbose: ON" if options[:verbose]
23
+ end
24
+
25
+ desc "convert INPUT OUTPUT", "Convert file format"
26
+ option :from, type: :string, required: true, desc: "Source format"
27
+ option :to, type: :string, required: true, desc: "Target format"
28
+ def convert(input, output)
29
+ puts "Converting: #{input} -> #{output}"
30
+ puts "Format: #{options[:from]} -> #{options[:to]}"
31
+ end
32
+
33
+ desc "read FILE", "Read a file"
34
+ def read(file)
35
+ if File.exist?(file)
36
+ puts "Reading #{file}:"
37
+ puts "-" * 40
38
+ puts File.read(file).lines.first(10).join
39
+ puts "-" * 40
40
+ puts "(Showing first 10 lines)"
41
+ else
42
+ puts "File not found: #{file}"
43
+ end
44
+ end
45
+
46
+ desc "list [DIR]", "List files in directory"
47
+ option :all, type: :boolean, aliases: "-a", desc: "Show hidden files"
48
+ option :long, type: :boolean, aliases: "-l", desc: "Long format"
49
+ def list(dir = ".")
50
+ puts "Listing files in: #{dir}"
51
+
52
+ pattern = options[:all] ? "*" : "[^.]*"
53
+ files = Dir.glob(File.join(dir, pattern))
54
+
55
+ if options[:long]
56
+ files.each do |file|
57
+ stat = File.stat(file)
58
+ type = File.directory?(file) ? "d" : "-"
59
+ size = stat.size.to_s.rjust(10)
60
+ name = File.basename(file)
61
+ name += "/" if File.directory?(file)
62
+ puts "#{type} #{size} #{name}"
63
+ end
64
+ else
65
+ files.each { |f| puts File.basename(f) }
66
+ end
67
+ end
68
+
69
+ desc "test", "Test completion features"
70
+ def test
71
+ puts <<~TEST
72
+
73
+ === Path Completion Demo ===
74
+
75
+ This demo showcases the new completion features:
76
+
77
+ 1. PATH COMPLETION
78
+ Start typing a path and press TAB:
79
+ /process <TAB> # Shows files in current directory
80
+ /process ex<TAB> # Completes to 'examples/'
81
+ /process ~/Doc<TAB> # Completes home directory paths
82
+ /process ./lib/<TAB> # Shows files in lib directory
83
+
84
+ 2. OPTION COMPLETION
85
+ Type - or -- and press TAB:
86
+ /process file.txt --<TAB> # Shows all options
87
+ /process file.txt --v<TAB> # Completes to --verbose
88
+ /process file.txt -<TAB> # Shows short options
89
+
90
+ 3. SMART DETECTION
91
+ After file options, paths are completed:
92
+ /process --output <TAB> # Completes paths
93
+ /process -o <TAB> # Also completes paths
94
+
95
+ 4. COMMAND COMPLETION
96
+ Still works as before:
97
+ /proc<TAB> # Completes to /process
98
+ /con<TAB> # Completes to /convert
99
+
100
+ TRY THESE EXAMPLES:
101
+
102
+ Basic file completion:
103
+ /read <TAB>
104
+ /read README<TAB>
105
+ /read lib/<TAB>
106
+
107
+ Option completion:
108
+ /process file.txt --<TAB>
109
+ /process file.txt --verb<TAB>
110
+ /convert input.txt output.json --<TAB>
111
+
112
+ Path after options:
113
+ /process --output <TAB>
114
+ /process -o ~/Desktop/<TAB>
115
+
116
+ Directory listing:
117
+ /list <TAB>
118
+ /list examples/<TAB>
119
+ /list --<TAB>
120
+
121
+ TEST
122
+ end
123
+
124
+ desc "create_test_files", "Create test files for demo"
125
+ def create_test_files
126
+ puts "Creating test files..."
127
+
128
+ # Create some test files
129
+ files = [
130
+ "test_file.txt",
131
+ "test_data.json",
132
+ "test_doc.md",
133
+ "test_config.yaml",
134
+ "test_log.log"
135
+ ]
136
+
137
+ files.each do |file|
138
+ File.write(file, "Test content for #{file}\n")
139
+ puts " Created: #{file}"
140
+ end
141
+
142
+ # Create a test directory
143
+ Dir.mkdir("test_dir") unless Dir.exist?("test_dir")
144
+ File.write("test_dir/nested.txt", "Nested file content\n")
145
+ puts " Created: test_dir/nested.txt"
146
+
147
+ puts "\nTest files created! Try tab completion with these files."
148
+ end
149
+
150
+ desc "clean_test_files", "Remove test files"
151
+ def clean_test_files
152
+ puts "Cleaning up test files..."
153
+
154
+ files = [
155
+ "test_file.txt",
156
+ "test_data.json",
157
+ "test_doc.md",
158
+ "test_config.yaml",
159
+ "test_log.log",
160
+ "test_dir/nested.txt"
161
+ ]
162
+
163
+ files.each do |file|
164
+ if File.exist?(file)
165
+ File.delete(file)
166
+ puts " Removed: #{file}"
167
+ end
168
+ end
169
+
170
+ Dir.rmdir("test_dir") if Dir.exist?("test_dir") && Dir.empty?("test_dir")
171
+ puts "Cleanup complete!"
172
+ end
173
+
174
+ default_task :test
175
+ end
176
+
177
+ if __FILE__ == $0
178
+ puts "Path Completion Demo"
179
+ puts "==================="
180
+ puts
181
+ puts "Tab completion now supports:"
182
+ puts " • File and directory paths"
183
+ puts " • Command option names"
184
+ puts " • Smart detection of when to complete paths"
185
+ puts
186
+ puts "Type '/test' for examples or '/create_test_files' to create test files"
187
+ puts "Press TAB at any time to see completions!"
188
+ puts
189
+
190
+ CompletionDemo.new.interactive
191
+ end
@@ -149,10 +149,182 @@ class Thor
149
149
  end
150
150
 
151
151
  def complete_command_options(text, preposing)
152
- # Basic implementation - can be enhanced later
153
- # For now, just return empty array to let Reline handle file completion
152
+ # Parse the command and check what we're completing
153
+ parts = preposing.split(/\s+/)
154
+ command = parts[0].sub(/^\//, '') if parts[0]
155
+
156
+ # Check if this is a subcommand
157
+ subcommand_class = @thor_class.subcommand_classes[command] if command
158
+ if subcommand_class
159
+ return complete_subcommand_args(subcommand_class, text, parts)
160
+ end
161
+
162
+ # Get the Thor task if it exists
163
+ task = @thor_class.tasks[command] if command
164
+
165
+ # Check if we're likely completing a path
166
+ if path_like?(text) || after_path_option?(preposing)
167
+ complete_path(text)
168
+ elsif text.start_with?('--') || text.start_with?('-')
169
+ # Complete option names
170
+ complete_option_names(task, text)
171
+ else
172
+ # Default to path completion for positional args that might be files
173
+ # This helps with commands that take file arguments
174
+ complete_path(text)
175
+ end
176
+ end
177
+
178
+ def complete_subcommand_args(subcommand_class, text, parts)
179
+ # parts[0] = "/db" or "db", parts[1..] = subcommand args
180
+ if parts.length <= 1
181
+ # No subcommand yet typed, complete subcommand names
182
+ # e.g. "/db <TAB>"
183
+ complete_subcommands(subcommand_class, text)
184
+ else
185
+ # A subcommand name has been typed, check for option completion
186
+ sub_cmd_name = parts[1]
187
+ sub_task = subcommand_class.tasks[sub_cmd_name]
188
+
189
+ if text.start_with?('--') || text.start_with?('-')
190
+ complete_option_names(sub_task, text)
191
+ else
192
+ # Could be completing a subcommand name or a positional arg
193
+ if parts.length == 2 && !text.empty?
194
+ # Still typing the subcommand name, e.g. "/db cr<TAB>"
195
+ # But only if 'text' is part of a subcommand name being typed
196
+ # (parts[1] is the preposing word, text is what's being completed)
197
+ complete_subcommands(subcommand_class, text)
198
+ else
199
+ complete_path(text)
200
+ end
201
+ end
202
+ end
203
+ end
204
+
205
+ def complete_subcommands(subcommand_class, text)
206
+ return [] if text.nil?
207
+
208
+ command_names = subcommand_class.tasks.keys
209
+ command_names.select { |cmd| cmd.start_with?(text) }.sort
210
+ end
211
+
212
+ def path_like?(text)
213
+ # Check if text looks like a path
214
+ text.match?(%r{^[~./]|/}) || text.match?(/\.(txt|rb|md|json|xml|yaml|yml|csv|log|html|css|js)$/i)
215
+ end
216
+
217
+ def after_path_option?(preposing)
218
+ # Check if we're after a common file/path option
219
+ preposing.match?(/(?:--file|--output|--input|--path|--dir|--directory|-f|-o|-i|-d)\s*$/)
220
+ end
221
+
222
+ def complete_path(text)
223
+ return [] if text.nil?
224
+
225
+ # Special case for empty text - show files in current directory
226
+ if text.empty?
227
+ matches = Dir.glob("*", File::FNM_DOTMATCH).select do |path|
228
+ basename = File.basename(path)
229
+ basename != '.' && basename != '..'
230
+ end
231
+ return format_path_completions(matches, text)
232
+ end
233
+
234
+ # Expand ~ to home directory for matching
235
+ expanded = text.start_with?('~') ? File.expand_path(text) : text
236
+
237
+ # Determine directory and prefix for matching
238
+ if text.end_with?('/')
239
+ # User typed a directory with trailing slash - show its contents
240
+ dir = expanded
241
+ prefix = ''
242
+ elsif File.directory?(expanded) && !text.end_with?('/')
243
+ # It's a directory without trailing slash - complete the directory name
244
+ dir = File.dirname(expanded)
245
+ prefix = File.basename(expanded)
246
+ else
247
+ # Completing a partial filename
248
+ dir = File.dirname(expanded)
249
+ prefix = File.basename(expanded)
250
+ end
251
+
252
+ # Get matching files/dirs
253
+ pattern = File.join(dir, "#{prefix}*")
254
+ matches = Dir.glob(pattern, File::FNM_DOTMATCH).select do |path|
255
+ # Filter out . and .. entries
256
+ basename = File.basename(path)
257
+ basename != '.' && basename != '..'
258
+ end
259
+
260
+ format_path_completions(matches, text)
261
+ rescue => e
262
+ # If path completion fails, return empty array
154
263
  []
155
264
  end
265
+
266
+ def format_path_completions(matches, original_text)
267
+ # Format the completions based on how the user typed the path
268
+ matches.map do |path|
269
+ # Add trailing / for directories
270
+ display_path = File.directory?(path) && !path.end_with?('/') ? "#{path}/" : path
271
+
272
+ # Handle paths with spaces by escaping them
273
+ display_path = display_path.gsub(' ', '\ ')
274
+
275
+ # Return path as user would type it
276
+ if original_text.start_with?('~')
277
+ # Replace home directory with ~
278
+ home = ENV['HOME']
279
+ if display_path.start_with?(home)
280
+ "~#{display_path[home.length..-1]}"
281
+ else
282
+ display_path.sub(ENV['HOME'], '~')
283
+ end
284
+ elsif original_text.start_with?('./')
285
+ # Keep ./ prefix and make path relative
286
+ if display_path.start_with?(Dir.pwd)
287
+ rel_path = display_path.sub(/^#{Regexp.escape(Dir.pwd)}\//, '')
288
+ "./#{rel_path}"
289
+ else
290
+ # Already relative, just ensure ./ prefix
291
+ display_path.start_with?('./') ? display_path : "./#{File.basename(display_path)}"
292
+ end
293
+ elsif original_text.start_with?('/')
294
+ # Absolute path - return as is
295
+ display_path
296
+ else
297
+ # Relative path without ./ prefix
298
+ # If the matched path is in current dir, just return the basename
299
+ dir = File.dirname(display_path)
300
+ if dir == '.' || display_path.start_with?('./')
301
+ basename = File.basename(display_path)
302
+ basename += '/' if File.directory?(display_path.gsub('\ ', ' ')) && !basename.end_with?('/')
303
+ basename
304
+ else
305
+ display_path.sub(/^#{Regexp.escape(Dir.pwd)}\//, '')
306
+ end
307
+ end
308
+ end.sort
309
+ end
310
+
311
+ def complete_option_names(task, text)
312
+ return [] unless task && task.options
313
+
314
+ # Get all option names (long and short forms)
315
+ options = []
316
+ task.options.each do |name, option|
317
+ options << "--#{name}"
318
+ if option.aliases
319
+ # Aliases can be string or array
320
+ aliases = option.aliases.is_a?(Array) ? option.aliases : [option.aliases]
321
+ aliases.each { |a| options << a if a.start_with?('-') }
322
+ end
323
+ end
324
+
325
+ # Filter by what user has typed
326
+ options.select { |opt| opt.start_with?(text) }.sort
327
+ end
156
328
 
157
329
  def process_input(input)
158
330
  # Handle completely empty input
@@ -300,8 +472,11 @@ class Thor
300
472
 
301
473
  if task && task.options && !task.options.empty?
302
474
  # Parse options if the command has them defined
303
- parsed_args, parsed_options = parse_thor_options(args, task)
304
-
475
+ result = parse_thor_options(args, task)
476
+ return unless result # Parse failed, error already shown
477
+
478
+ parsed_args, parsed_options = result
479
+
305
480
  # Set options on the Thor instance
306
481
  @thor_instance.options = Thor::CoreExt::HashWithIndifferentAccess.new(parsed_options)
307
482
 
@@ -341,12 +516,11 @@ class Thor
341
516
  # Convert args array to a format Thor's option parser expects
342
517
  remaining_args = []
343
518
  parsed_options = {}
344
-
345
- # Create a temporary parser using Thor's options
346
- parser = Thor::Options.new(task.options)
347
-
348
- # Parse the arguments
519
+
349
520
  begin
521
+ # Create a temporary parser using Thor's options
522
+ parser = Thor::Options.new(task.options)
523
+
350
524
  if args.is_a?(Array)
351
525
  # Parse the options from the array
352
526
  parsed_options = parser.parse(args)
@@ -358,17 +532,32 @@ class Thor
358
532
  remaining_args = parser.remaining
359
533
  end
360
534
  rescue Thor::Error => e
361
- # If parsing fails, treat everything as arguments (backward compatibility)
362
- puts "Option parsing error: #{e.message}" if ENV["DEBUG"]
363
- remaining_args = args.is_a?(Array) ? args : [args]
364
- parsed_options = {}
535
+ # Show user-friendly error for option parsing failures (e.g. invalid numeric value)
536
+ puts "Option error: #{e.message}"
537
+ return nil
365
538
  end
366
-
539
+
540
+ # Check for unknown options left in remaining args
541
+ unknown = remaining_args.select { |a| a.start_with?('--') || (a.start_with?('-') && a.length > 1 && !a.match?(/^-\d/)) }
542
+ unless unknown.empty?
543
+ puts "Unknown option#{'s' if unknown.length > 1}: #{unknown.join(', ')}"
544
+ puts "Run '/help #{task.name}' to see available options."
545
+ return nil
546
+ end
547
+
367
548
  [remaining_args, parsed_options]
368
549
  end
369
550
 
370
551
  def show_help(command = nil)
371
- if command && @thor_class.tasks.key?(command)
552
+ if command && @thor_class.subcommand_classes.key?(command)
553
+ # Show help for a subcommand — list its available commands
554
+ subcommand_class = @thor_class.subcommand_classes[command]
555
+ puts "Commands for '#{command}':"
556
+ subcommand_class.tasks.each do |name, task|
557
+ puts " /#{command} #{name.ljust(15)} #{task.description}"
558
+ end
559
+ puts
560
+ elsif command && @thor_class.tasks.key?(command)
372
561
  @thor_class.command_help(Thor::Base.shell.new, command)
373
562
  else
374
563
  puts "Available commands (prefix with /):"
@@ -4,5 +4,5 @@
4
4
  # This file is separate to avoid circular dependencies during gem installation
5
5
 
6
6
  module ThorInteractive
7
- VERSION = "0.1.0.pre.4"
7
+ VERSION = "0.1.0.pre.5"
8
8
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: thor-interactive
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0.pre.4
4
+ version: 0.1.0.pre.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - Chris Petersen
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2025-09-08 00:00:00.000000000 Z
11
+ date: 2026-01-28 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: thor
@@ -54,6 +54,7 @@ files:
54
54
  - README.md
55
55
  - Rakefile
56
56
  - examples/README.md
57
+ - examples/completion_demo.rb
57
58
  - examples/demo_session.rb
58
59
  - examples/edge_case_test.rb
59
60
  - examples/nested_example.rb