thor-interactive 0.1.0.pre.1

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9e51ddada105bae31b9bc637ed25fd88e4908c281c16779b46d023d16f31db4e
4
+ data.tar.gz: cbccf2e8dc47f73e7f1c101bd1a0dce0c2fa51cc21f9a26e24ed7f577245d2cf
5
+ SHA512:
6
+ metadata.gz: 0ea62f18e17ab19662bd3c8fac62dce8dd69582adc857664901e69729670d8de690161a111151df1ab4ee7b403521b9e9254d9d67942bdc36f244278887d2b21
7
+ data.tar.gz: a566b97836f0a11b75e35e35692f0996d3817b5b34dfa2d3c169d84dd125cac453cbeac14bfb76cd99f3253d144b4b550fd3e7a939f7b711e27a114242df2997
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/standardrb/standard
3
+ ruby_version: 3.1
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Chris Petersen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,472 @@
1
+ # Thor::Interactive
2
+
3
+ Turn any Thor CLI into an interactive REPL with persistent state and auto-completion.
4
+
5
+ Thor::Interactive automatically converts your existing Thor command-line applications into interactive REPLs, maintaining state between commands and providing auto-completion for commands and parameters. Perfect for applications that benefit from persistent sessions like RAG pipelines, database tools, or any CLI that maintains caches or connections.
6
+
7
+ ## Features
8
+
9
+ - **Zero Configuration**: Works with any existing Thor application without modifications
10
+ - **State Persistence**: Maintains class variables and instance state between commands
11
+ - **Auto-completion**: Tab completion for command names and basic parameter support
12
+ - **Default Handlers**: Configurable fallback for non-command input
13
+ - **Command History**: Persistent readline history with up/down arrow navigation
14
+ - **Both Modes**: Supports both traditional CLI usage and interactive REPL mode
15
+ - **Graceful Exit**: Proper handling of Ctrl+C interrupts and Ctrl+D/exit commands
16
+
17
+ ## Installation
18
+
19
+ Add to your application's Gemfile:
20
+
21
+ ```ruby
22
+ gem 'thor-interactive'
23
+ ```
24
+
25
+ Or install directly:
26
+
27
+ ```bash
28
+ gem install thor-interactive
29
+ ```
30
+
31
+ ## Quick Start
32
+
33
+ ### Option 1: Add Interactive Command (Recommended)
34
+
35
+ Add one line to your Thor class to get an `interactive` command:
36
+
37
+ ```ruby
38
+ require 'thor'
39
+ require 'thor/interactive'
40
+
41
+ class MyApp < Thor
42
+ include Thor::Interactive::Command
43
+
44
+ # Your existing Thor commands work unchanged
45
+ desc "hello NAME", "Say hello"
46
+ def hello(name)
47
+ puts "Hello #{name}!"
48
+ end
49
+ end
50
+ ```
51
+
52
+ Now your app supports both modes:
53
+
54
+ ```bash
55
+ # Normal CLI usage (unchanged)
56
+ ruby myapp.rb hello World
57
+
58
+ # New interactive mode
59
+ ruby myapp.rb interactive
60
+ myapp> hello Alice
61
+ Hello Alice!
62
+ myapp> exit
63
+ ```
64
+
65
+ ### Option 2: Programmatic Usage
66
+
67
+ Start an interactive shell programmatically:
68
+
69
+ ```ruby
70
+ require 'thor/interactive'
71
+
72
+ class MyApp < Thor
73
+ desc "hello NAME", "Say hello"
74
+ def hello(name)
75
+ puts "Hello #{name}!"
76
+ end
77
+ end
78
+
79
+ # Start interactive shell
80
+ Thor::Interactive.start(MyApp)
81
+ ```
82
+
83
+ ## State Persistence Example
84
+
85
+ The key benefit is maintaining state between commands:
86
+
87
+ ```ruby
88
+ class RAGApp < Thor
89
+ include Thor::Interactive::Command
90
+
91
+ # These persist between commands in interactive mode
92
+ class_variable_set(:@@llm_client, nil)
93
+ class_variable_set(:@@conversation_history, [])
94
+
95
+ desc "ask TEXT", "Ask the LLM a question"
96
+ def ask(text)
97
+ # Initialize once, reuse across commands
98
+ @@llm_client ||= expensive_llm_initialization
99
+
100
+ response = @@llm_client.chat(text)
101
+ @@conversation_history << {input: text, output: response}
102
+ puts response
103
+ end
104
+
105
+ desc "history", "Show conversation history"
106
+ def history
107
+ @@conversation_history.each_with_index do |item, i|
108
+ puts "#{i+1}. Q: #{item[:input]}"
109
+ puts " A: #{item[:output]}"
110
+ end
111
+ end
112
+ end
113
+ ```
114
+
115
+ In interactive mode:
116
+ ```bash
117
+ ruby rag_app.rb interactive
118
+
119
+ rag> ask "What is Ruby?"
120
+ # LLM initializes once
121
+ Ruby is a programming language...
122
+
123
+ rag> ask "Tell me more"
124
+ # LLM client reused, conversation context maintained
125
+ Based on our previous discussion about Ruby...
126
+
127
+ rag> history
128
+ 1. Q: What is Ruby?
129
+ A: Ruby is a programming language...
130
+ 2. Q: Tell me more
131
+ A: Based on our previous discussion about Ruby...
132
+ ```
133
+
134
+ ## Configuration
135
+
136
+ Configure interactive behavior:
137
+
138
+ ```ruby
139
+ class MyApp < Thor
140
+ include Thor::Interactive::Command
141
+
142
+ configure_interactive(
143
+ prompt: "myapp> ", # Custom prompt
144
+ allow_nested: false, # Prevent nested sessions (default)
145
+ nested_prompt_format: "[L%d] %s", # Format for nested prompts (if allowed)
146
+ default_handler: proc do |input, thor_instance|
147
+ # Handle unrecognized input
148
+ thor_instance.invoke(:search, [input])
149
+ end
150
+ )
151
+
152
+ desc "search QUERY", "Search for something"
153
+ def search(query)
154
+ puts "Searching for: #{query}"
155
+ end
156
+ end
157
+ ```
158
+
159
+ Now unrecognized input gets sent to the search command:
160
+
161
+ ```bash
162
+ myapp> hello world
163
+ Hello world!
164
+
165
+ myapp> some random text
166
+ Searching for: some random text
167
+ ```
168
+
169
+ ### Nested Session Management
170
+
171
+ By default, thor-interactive prevents nested interactive sessions to avoid confusion:
172
+
173
+ ```ruby
174
+ class MyApp < Thor
175
+ include Thor::Interactive::Command
176
+
177
+ configure_interactive(
178
+ prompt: "myapp> ",
179
+ allow_nested: false # Default behavior
180
+ )
181
+ end
182
+ ```
183
+
184
+ If you try to run `interactive` while already in an interactive session:
185
+
186
+ ```bash
187
+ myapp> interactive
188
+ Already in an interactive session.
189
+ To allow nested sessions, configure with: configure_interactive(allow_nested: true)
190
+ ```
191
+
192
+ #### Allowing Nested Sessions
193
+
194
+ For advanced use cases, you can enable nested sessions:
195
+
196
+ ```ruby
197
+ class AdvancedApp < Thor
198
+ include Thor::Interactive::Command
199
+
200
+ configure_interactive(
201
+ prompt: "advanced> ",
202
+ allow_nested: true,
203
+ nested_prompt_format: "[Level %d] %s" # Optional custom format
204
+ )
205
+ end
206
+ ```
207
+
208
+ With nested sessions enabled:
209
+
210
+ ```bash
211
+ $ ruby advanced_app.rb interactive
212
+ AdvancedApp Interactive Shell
213
+ Type 'help' for available commands, 'exit' to quit
214
+
215
+ advanced> interactive
216
+ AdvancedApp Interactive Shell (nested level 2)
217
+ Type 'exit' to return to previous level, or 'help' for commands
218
+
219
+ [Level 2] advanced> hello nested
220
+ Hello nested!
221
+
222
+ [Level 2] advanced> exit
223
+ Exiting nested session...
224
+
225
+ advanced> exit
226
+ Goodbye!
227
+ ```
228
+
229
+ ## Advanced Usage
230
+
231
+ ### Custom Options
232
+
233
+ Pass options to the interactive command:
234
+
235
+ ```bash
236
+ ruby myapp.rb interactive --prompt="custom> " --history-file=~/.my_history
237
+ ```
238
+
239
+ ### Multiple Applications
240
+
241
+ Use the same gem with different Thor applications:
242
+
243
+ ```ruby
244
+ # Database CLI
245
+ class DBApp < Thor
246
+ include Thor::Interactive::Command
247
+ configure_interactive(prompt: "db> ")
248
+ end
249
+
250
+ # API Testing CLI
251
+ class APIApp < Thor
252
+ include Thor::Interactive::Command
253
+ configure_interactive(prompt: "api> ")
254
+ end
255
+ ```
256
+
257
+ ### Without Mixin
258
+
259
+ Use programmatically without including the module:
260
+
261
+ ```ruby
262
+ default_handler = proc do |input, instance|
263
+ puts "You said: #{input}"
264
+ end
265
+
266
+ Thor::Interactive.start(MyThorApp,
267
+ prompt: "custom> ",
268
+ default_handler: default_handler,
269
+ history_file: "~/.custom_history"
270
+ )
271
+ ```
272
+
273
+ ## Examples
274
+
275
+ See the `examples/` directory for complete working examples:
276
+
277
+ - `sample_app.rb` - Demonstrates all features with a simple CLI
278
+ - `test_interactive.rb` - Test script showing the API
279
+
280
+ Run the example:
281
+
282
+ ```bash
283
+ cd examples
284
+ ruby sample_app.rb interactive
285
+ ```
286
+
287
+ ## How It Works
288
+
289
+ Thor::Interactive creates a persistent instance of your Thor class and invokes commands on that same instance, preserving any instance variables or class variables between commands. This is different from normal CLI usage where each command starts with a fresh instance.
290
+
291
+ The shell provides:
292
+ - Tab completion for command names
293
+ - Readline history with persistent storage
294
+ - Proper signal handling (Ctrl+C, Ctrl+D)
295
+ - Help system integration
296
+ - Configurable default handlers for non-commands
297
+
298
+ ## Development
299
+
300
+ ### Getting Started
301
+
302
+ After checking out the repo:
303
+
304
+ ```bash
305
+ bundle install # Install dependencies
306
+ bundle exec rspec # Run full test suite
307
+ bundle exec rake build # Build gem
308
+ ```
309
+
310
+ ### Testing
311
+
312
+ The gem includes comprehensive tests organized into unit and integration test suites:
313
+
314
+ ```bash
315
+ # Run all tests
316
+ bundle exec rspec
317
+
318
+ # Run with detailed output
319
+ bundle exec rspec --format documentation
320
+
321
+ # Run specific test suites
322
+ bundle exec rspec spec/unit/ # Unit tests only
323
+ bundle exec rspec spec/integration/ # Integration tests only
324
+
325
+ # Run specific test files
326
+ bundle exec rspec spec/unit/shell_spec.rb
327
+ bundle exec rspec spec/integration/shell_integration_spec.rb
328
+ ```
329
+
330
+ #### Test Structure
331
+
332
+ ```
333
+ spec/
334
+ ├── spec_helper.rb # Test configuration and shared setup
335
+ ├── support/
336
+ │ ├── test_thor_apps.rb # Test Thor applications (not packaged)
337
+ │ └── capture_helpers.rb # Test utilities for I/O capture
338
+ ├── unit/ # Unit tests for individual components
339
+ │ ├── shell_spec.rb # Thor::Interactive::Shell tests
340
+ │ ├── command_spec.rb # Thor::Interactive::Command mixin tests
341
+ │ └── completion_spec.rb # Completion system tests
342
+ └── integration/ # Integration tests for full workflows
343
+ └── shell_integration_spec.rb # End-to-end interactive shell tests
344
+ ```
345
+
346
+ #### Test Applications
347
+
348
+ Tests use dedicated Thor applications in `spec/support/test_thor_apps.rb`:
349
+
350
+ - `SimpleTestApp` - Basic Thor app with simple commands
351
+ - `StatefulTestApp` - App with state persistence and default handlers
352
+ - `SubcommandTestApp` - App with Thor subcommands
353
+ - `OptionsTestApp` - App with various Thor options and arguments
354
+
355
+ These test apps are excluded from the packaged gem but provide comprehensive test coverage.
356
+
357
+ ### Example Applications
358
+
359
+ The `examples/` directory contains working examples (these ARE packaged with the gem):
360
+
361
+ #### Running the Sample Application
362
+
363
+ ```bash
364
+ cd examples
365
+
366
+ # Run in normal CLI mode
367
+ ruby sample_app.rb help
368
+ ruby sample_app.rb hello World
369
+ ruby sample_app.rb count
370
+ ruby sample_app.rb add "Test item"
371
+
372
+ # Run in interactive mode
373
+ ruby sample_app.rb interactive
374
+ ```
375
+
376
+ #### Interactive Session Example
377
+
378
+ ```bash
379
+ $ ruby sample_app.rb interactive
380
+ SampleApp Interactive Shell
381
+ Type 'help' for available commands, 'exit' to quit
382
+
383
+ sample> hello Alice
384
+ Hello Alice!
385
+
386
+ sample> count
387
+ Count: 1
388
+
389
+ sample> count
390
+ Count: 2 # Note: state persisted!
391
+
392
+ sample> add "Buy groceries"
393
+ Added: Buy groceries
394
+
395
+ sample> add "Walk the dog"
396
+ Added: Walk the dog
397
+
398
+ sample> list
399
+ 1. Buy groceries
400
+ 2. Walk the dog
401
+
402
+ sample> status
403
+ Counter: 2, Items: 2
404
+
405
+ sample> This is random text that doesn't match a command
406
+ Echo: This is random text that doesn't match a command
407
+
408
+ sample> help
409
+ Available commands:
410
+ hello Say hello to NAME
411
+ count Show and increment counter (demonstrates state persistence)
412
+ add Add item to list (demonstrates state persistence)
413
+ list Show all items
414
+ clear Clear all items
415
+ echo Echo the text back (used as default handler)
416
+ status Show application status
417
+ interactive Start an interactive REPL for this application
418
+
419
+ Special commands:
420
+ help [COMMAND] Show help for command
421
+ exit/quit/q Exit the REPL
422
+
423
+ sample> exit
424
+ Goodbye!
425
+ ```
426
+
427
+ #### Key Features Demonstrated
428
+
429
+ 1. **State Persistence**: The counter and items list maintain their values between commands
430
+ 2. **Auto-completion**: Try typing `h<TAB>` or `co<TAB>` to see command completion
431
+ 3. **Default Handler**: Text that doesn't match a command gets sent to the `echo` command
432
+ 4. **Command History**: Use up/down arrows to navigate previous commands
433
+ 5. **Error Handling**: Try invalid commands or missing arguments
434
+ 6. **Both Modes**: The same application works as traditional CLI and interactive REPL
435
+
436
+ ### Performance Testing
437
+
438
+ For applications with expensive initialization (like LLM clients), you can measure the performance benefit:
439
+
440
+ ```bash
441
+ # CLI mode - initializes fresh each time
442
+ time ruby sample_app.rb count
443
+ time ruby sample_app.rb count
444
+ time ruby sample_app.rb count
445
+
446
+ # Interactive mode - initializes once, reuses state
447
+ ruby sample_app.rb interactive
448
+ # Then run: count, count, count
449
+ ```
450
+
451
+ ### Debugging
452
+
453
+ Enable debug mode to see backtraces on errors:
454
+
455
+ ```bash
456
+ DEBUG=1 ruby sample_app.rb interactive
457
+ ```
458
+
459
+ Or in your application:
460
+
461
+ ```ruby
462
+ ENV["DEBUG"] = "1"
463
+ Thor::Interactive.start(MyApp)
464
+ ```
465
+
466
+ ## Contributing
467
+
468
+ Bug reports and pull requests are welcome on GitHub at https://github.com/scientist-labs/thor-interactive.
469
+
470
+ ## License
471
+
472
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[spec standard]