Class: Consolle::CLI

Inherits:
Thor
  • Object
show all
Defined in:
lib/consolle/cli.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.exit_on_failure?Boolean

Returns:

  • (Boolean)


128
129
130
# File 'lib/consolle/cli.rb', line 128

def self.exit_on_failure?
  true
end

.help(shell, subcommand = false) ⇒ Object



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
# File 'lib/consolle/cli.rb', line 79

def help(shell, subcommand = false)
  if subcommand == false
    shell.say 'Consolle - Rails console management tool', :cyan
    shell.say
    shell.say 'USAGE:', :yellow
    shell.say '  cone [COMMAND] [OPTIONS]'
    shell.say
    shell.say 'COMMANDS:', :yellow
    shell.say '  cone start              # Start Rails console in background'
    shell.say '  cone stop               # Stop Rails console'
    shell.say '  cone restart            # Restart Rails console'
    shell.say '  cone status             # Show Rails console status'
    shell.say '  cone exec CODE          # Execute Ruby code in Rails console'
    shell.say '  cone rails SUBCOMMAND   # Rails convenience commands'
    shell.say '  cone ls                 # List active sessions (use -a for all)'
    shell.say '  cone history            # Show command history'
    shell.say '  cone rm SESSION         # Remove session and its history'
    shell.say '  cone prune              # Remove all stopped sessions'
    shell.say '  cone stop_all           # Stop all Rails console sessions'
    shell.say '  cone rule FILE          # Write cone command guide to FILE'
    shell.say '  cone version            # Show version'
    shell.say
    shell.say 'GLOBAL OPTIONS:', :yellow
    shell.say '  -v, --verbose           # Enable verbose output'
    shell.say '  -t, --target NAME       # Target session name (default: cone)'
    shell.say '  -h, --help              # Show this help message'
    shell.say
    shell.say 'EXAMPLES:', :yellow
    shell.say "  cone exec 'User.count'                    # Execute code in default session"
    shell.say "  RAILS_ENV=production cone start           # Start console in production"
    shell.say "  cone exec -t api 'Rails.env'              # Execute code in 'api' session"
    shell.say '  cone exec -f script.rb                    # Execute code from file'
    shell.say
    shell.say 'For more information on a specific command:'
    shell.say '  cone COMMAND --help'
    shell.say
  else
    super
  end
end

.start(given_args = ARGV, config = {}) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/consolle/cli.rb', line 69

def start(given_args = ARGV, config = {})
  # Intercept --help at the top level
  if given_args == ['--help'] || given_args == ['-h'] || given_args.empty?
    shell = Thor::Base.shell.new
    help(shell)
    return
  end
  super
end

Instance Method Details

#exec(*code_parts) ⇒ Object



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
# File 'lib/consolle/cli.rb', line 622

def exec(*code_parts)
  ensure_rails_project!
  ensure_project_directories
  validate_session_name!(options[:target])

  # Handle code input from file or arguments first
  code = if options[:file]
           path = File.expand_path(options[:file])
           unless File.file?(path)
             puts "Error: File not found: #{path}"
             exit 1
           end
           File.read(path, mode: 'r:UTF-8')
         else
           code_parts.join(' ')
         end

  if code.strip.empty?
    puts 'Error: No code provided (pass CODE or use -f FILE)'
    exit 1
  end

  session_info = load_session_info
  server_running = false

  # Check if server is running
  if session_info
    begin
      # Try to connect to socket and get status
      socket = UNIXSocket.new(session_info[:socket_path])
      request = {
        'action' => 'status',
        'request_id' => SecureRandom.uuid
      }
      socket.write(JSON.generate(request))
      socket.write("\n")
      socket.flush
      response_data = socket.gets
      socket.close

      response = JSON.parse(response_data)
      server_running = response['success'] && response['running']
    rescue StandardError
      # Server not responsive
      server_running = false
    end
  end

  # Check if server is running
  unless server_running
    puts '✗ Rails console is not running'
    puts 'Please start it first with: cone start'
    exit 1
  end

  # Apply Claude Code escape fix unless --raw option is specified
  code = code.gsub('\\!', '!') unless options[:raw]

  puts "Executing: #{code}" if options[:verbose]

  # Send code to socket
  send_opts = { timeout: options[:timeout] }
  send_opts[:pre_sigint] = options[:pre_sigint] unless options[:pre_sigint].nil?
  result = send_code_to_socket(
    session_info[:socket_path],
    code,
    **send_opts
  )

  # Log the request and response
  log_session_activity(session_info[:process_pid], code, result)

  if result['success']
    # Always print result, even if empty (multiline code often returns empty string)
    puts result['result'] unless result['result'].nil?
    # Show execution time only in verbose mode
    puts "Execution time: #{result['execution_time'].round(3)}s" if options[:verbose] && result['execution_time']
  else
    # Display error information
    if result['error_code']
      puts "Error: #{result['error_code']}"
    else
      puts "Error: #{result['error']}"
    end
    
    # Show error class in verbose mode
    if options[:verbose] && result['error_class']
      puts "Error Class: #{result['error_class']}"
    end
    
    puts result['message']
    puts result['backtrace']&.join("\n") if options[:verbose] && result['backtrace']

    # Show execution time for errors too (verbose only)
    puts "Execution time: #{result['execution_time'].round(3)}s" if options[:verbose] && result['execution_time']

    exit 1
  end
end

#help(command = nil) ⇒ Object



156
157
158
159
160
161
162
# File 'lib/consolle/cli.rb', line 156

def help(command = nil)
  if command
    self.class.command_help(shell, command)
  else
    self.class.help(shell)
  end
end

#historyObject



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
# File 'lib/consolle/cli.rb', line 881

def history
  ensure_rails_project!

  history_manager = Consolle::History.new

  entries = history_manager.query(
    session_id: options[:session],
    target: options[:target],
    limit: options[:limit],
    today: options[:today],
    date: options[:date],
    success_only: options[:success],
    failed_only: options[:failed],
    grep: options[:grep],
    all_sessions: options[:all]
  )

  if entries.empty?
    puts 'No history found'
    if options[:session] || options[:target]
      puts "Try 'cone history' without filters to see all history"
    else
      puts "Execute some commands first with 'cone exec'"
    end
    return
  end

  if options[:json]
    puts history_manager.format_json(entries)
  elsif options[:verbose]
    entries.each do |entry|
      puts history_manager.format_entry_verbose(entry)
      puts
    end
  else
    entries.each do |entry|
      puts history_manager.format_entry(entry)
      puts
    end
  end

  unless options[:json]
    puts "Showing #{entries.size} entries"
  end
end

#lsObject



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
# File 'lib/consolle/cli.rb', line 337

def ls
  ensure_rails_project!

  include_stopped = options[:all]
  sessions = session_registry.list_sessions(include_stopped: include_stopped)

  # Also check legacy sessions.json for backward compatibility
  legacy_sessions = load_sessions
  legacy_sessions.each do |name, info|
    next if name == '_schema'
    next unless info['process_pid'] && process_alive?(info['process_pid'])

    # Check if already in registry
    existing = sessions.find { |s| s['target'] == name && s['status'] == 'running' }
    next if existing

    # Add legacy session (will be migrated on next start)
    sessions << {
      'short_id' => '----',
      'target' => name,
      'rails_env' => 'development',
      'status' => 'running',
      'pid' => info['process_pid'],
      'created_at' => info['started_at'] ? Time.at(info['started_at']).iso8601 : Time.now.iso8601,
      'command_count' => 0,
      '_legacy' => true
    }
  end

  if sessions.empty?
    if include_stopped
      puts 'No sessions found'
    else
      puts 'No active sessions'
      puts "Use 'cone ls -a' to see stopped sessions"
    end
    return
  end

  # Verify running sessions are actually running
  sessions.each do |session|
    next unless session['status'] == 'running'
    next if session['_legacy']

    unless session['pid'] && process_alive?(session['pid'])
      session_registry.stop_session(session_id: session['id'], reason: 'process_died')
      session['status'] = 'stopped'
    end
  end

  # Re-filter if needed
  sessions = sessions.select { |s| s['status'] == 'running' } unless include_stopped

  if sessions.empty?
    puts 'No active sessions'
    puts "Use 'cone ls -a' to see stopped sessions"
    return
  end

  # Display header
  if include_stopped
    puts 'ALL SESSIONS:'
  else
    puts 'ACTIVE SESSIONS:'
  end
  puts
  puts format('  %-8s %-12s %-12s %-9s %-10s %s', 'ID', 'TARGET', 'ENV', 'STATUS', 'UPTIME', 'COMMANDS')

  sessions.each do |session|
    short_id = session['short_id'] || session['id']&.[](0, 4) || '----'
    target = session['target'] || 'unknown'
    env = session['rails_env'] || 'dev'
    status = session['status'] || 'unknown'
    commands = session['command_count'] || 0

    if session['status'] == 'running'
      started = session['started_at'] || session['created_at']
      uptime = started ? format_uptime(Time.now - Time.parse(started)) : '---'
    else
      stopped = session['stopped_at']
      uptime = stopped ? format_time_ago(Time.now - Time.parse(stopped)) : '---'
    end

    puts format('  %-8s %-12s %-12s %-9s %-10s %d', short_id, target, env, status, uptime, commands)
  end

  puts
  if include_stopped
    puts "Use 'cone history --session ID' to view session history"
    puts "Use 'cone rm ID' to remove session and history"
  else
    puts 'Usage: cone exec -t TARGET CODE'
    puts '       cone exec --session ID CODE'
  end
end

#pruneObject



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
# File 'lib/consolle/cli.rb', line 807

def prune
  ensure_rails_project!

  stopped = session_registry.list_stopped_sessions

  if stopped.empty?
    puts 'No stopped sessions to remove'
    return
  end

  # Show what will be removed
  total_commands = stopped.sum { |s| s['command_count'] || 0 }

  puts "Found #{stopped.size} stopped session(s):"
  stopped.each do |session|
    stopped_at = session['stopped_at'] ? Time.parse(session['stopped_at']).strftime('%Y-%m-%d') : '---'
    commands = session['command_count'] || 0
    puts "  #{session['short_id']}  #{session['target'].ljust(12)} stopped #{stopped_at}  #{commands} commands"
  end
  puts

  # Confirm
  unless options[:yes]
    print "Remove all stopped sessions and their history? [y/N]: "
    response = $stdin.gets&.strip&.downcase
    unless response == 'y' || response == 'yes'
      puts 'Cancelled'
      return
    end
  end

  # Remove all stopped sessions
  removed = session_registry.prune_sessions

  puts "✓ Removed #{removed.size} sessions (#{total_commands} commands)"
end

#restartObject



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
# File 'lib/consolle/cli.rb', line 531

def restart
  ensure_rails_project!
  validate_session_name!(options[:target])

  adapter = create_rails_adapter(current_rails_env, options[:target])

  if adapter.running?
    # Check if environment needs to be changed
    current_status = begin
      adapter.get_status
    rescue StandardError
      nil
    end
    current_env = current_status&.dig('rails_env') || 'development'
    desired_env = current_rails_env
    needs_full_restart = options[:force] || (current_env != desired_env)

    if needs_full_restart
      if current_env != desired_env
        puts "Environment change detected (#{current_env} -> #{desired_env})"
        puts 'Performing full server restart...'
      else
        puts 'Force restarting Rails console server...'
      end

      stop
      sleep 1
      invoke(:start, [], {})
    else
      puts 'Restarting Rails console subprocess...'

      # Send restart request to the socket server
      request = {
        'action' => 'restart',
        'request_id' => SecureRandom.uuid
      }

      begin
        # Use direct socket connection for restart request
        socket = UNIXSocket.new(adapter.socket_path)
        socket.write(JSON.generate(request))
        socket.write("\n")
        socket.flush
        response_data = socket.gets
        socket.close

        response = JSON.parse(response_data)

        if response['success']
          puts '✓ Rails console subprocess restarted'
          puts "  New PID: #{response['pid']}" if response['pid']
        else
          puts "✗ Failed to restart: #{response['message']}"
          puts "You can try 'cone restart --force' to restart the entire server"
        end
      rescue StandardError => e
        puts "✗ Error restarting: #{e.message}"
        puts "You can try 'cone restart --force' to restart the entire server"
      end
    end
  else
    puts 'Rails console is not running. Starting it...'
    invoke(:start)
  end
end

#rm(session_id) ⇒ Object



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
# File 'lib/consolle/cli.rb', line 742

def rm(session_id)
  ensure_rails_project!

  # Try to find session
  session = session_registry.find_session(session_id: session_id) ||
            session_registry.find_session(target: session_id)

  unless session
    puts "✗ Session not found: #{session_id}"
    puts "Use 'cone ls -a' to see all sessions"
    exit 1
  end

  # Check if running
  if session['status'] == 'running'
    if options[:force]
      # Force stop first
      puts "Stopping running session '#{session['target']}'..."
      adapter = create_rails_adapter('development', session['target'])
      adapter.stop
      session_registry.stop_session(session_id: session['id'], reason: 'force_remove')
      clear_session_info if options[:target] == session['target']
    else
      puts "✗ Session #{session['short_id']} (#{session['target']}) is still running"
      puts "  Use 'cone stop -t #{session['target']}' first, or 'cone rm -f #{session_id}' to force"
      exit 1
    end
  end

  # Confirm deletion
  unless options[:force]
    command_count = session['command_count'] || 0
    print "Remove session #{session['id']} (#{session['target']}, #{command_count} commands)?\n"
    print 'This will permanently delete all history. [y/N]: '
    response = $stdin.gets&.strip&.downcase
    unless response == 'y' || response == 'yes'
      puts 'Cancelled'
      return
    end
  end

  # Remove session
  result = session_registry.remove_session(session_id: session['id'])

  if result && !result.is_a?(Hash)
    puts "✓ Session #{session['id']} removed"
  else
    puts "✗ Failed to remove session"
    exit 1
  end
end

#rule(file_path) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
# File 'lib/consolle/cli.rb', line 165

def rule(file_path)
  # Read the embedded rule content
  rule_content = File.read(File.expand_path('../../rule.md', __dir__))

  # Write to the specified file
  File.write(file_path, rule_content)
  puts "✓ Cone command guide written to #{file_path}"
rescue StandardError => e
  puts "✗ Failed to write rule file: #{e.message}"
  exit 1
end

#startObject



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
# File 'lib/consolle/cli.rb', line 206

def start
  ensure_rails_project!
  ensure_project_directories
  validate_session_name!(options[:target])

  # Check if already running using session info
  session_info = load_session_info
  if session_info && session_info[:process_pid]
    # Check if process is still running
    begin
      Process.kill(0, session_info[:process_pid])
      # Check if socket is ready
      if File.exist?(session_info[:socket_path])
        puts "Rails console is already running (PID: #{session_info[:process_pid]})"
        puts "Socket: #{session_info[:socket_path]}"
        return
      end
    rescue Errno::ESRCH
      # Process not found, clean up session
      clear_session_info
    end
  elsif session_info
    # Session file exists but no valid PID, clean up
    clear_session_info
  end

  adapter = create_rails_adapter(
    current_rails_env,
    options[:target],
    options[:command],
    options[:wait_timeout],
    options[:mode]
  )

  puts 'Starting Rails console...'

  begin
    adapter.start

    # Register session in registry
    session = session_registry.create_session(
      target: options[:target],
      socket_path: adapter.socket_path,
      pid: adapter.process_pid,
      rails_env: current_rails_env,
      mode: options[:mode] || 'pty'
    )

    puts '✓ Rails console started'
    puts "  Session ID: #{session['id']} (#{session['short_id']})"
    puts "  Target: #{session['target']}"
    puts "  Environment: #{current_rails_env}"
    puts "  PID: #{adapter.process_pid}"
    puts "  Socket: #{adapter.socket_path}"

    # Also save to legacy sessions.json for backward compatibility
    save_session_info(adapter, session['id'])
  rescue StandardError => e
    puts "✗ Failed to start Rails console: #{e.message}"
    exit 1
  end
end

#statusObject



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
# File 'lib/consolle/cli.rb', line 270

def status
  ensure_rails_project!
  validate_session_name!(options[:target])

  # Try to find session in registry first
  session = session_registry.find_running_session(target: options[:target])
  session_info = load_session_info

  if session_info.nil? && session.nil?
    puts 'No active Rails console session found'
    return
  end

  # Check if server is actually responsive
  adapter = create_rails_adapter(current_rails_env, options[:target])
  server_status = begin
    adapter.get_status
  rescue StandardError
    nil
  end
  process_running = server_status && server_status['success'] && server_status['running']

  if process_running
    rails_env = server_status['rails_env'] || 'unknown'
    console_pid = server_status['pid'] || 'unknown'
    uptime = session_info&.dig(:started_at) ? format_uptime(Time.now - Time.at(session_info[:started_at])) : 'unknown'
    command_count = session ? session['command_count'] : 0

    puts '✓ Rails console is running'
    if session
      puts "  Session ID: #{session['id']} (#{session['short_id']})"
    end
    puts "  Target: #{options[:target]}"
    puts "  Environment: #{rails_env}"
    puts "  PID: #{console_pid}"
    puts "  Uptime: #{uptime}"
    puts "  Commands: #{command_count}"
    puts "  Socket: #{session_info&.dig(:socket_path) || session&.dig('socket_path')}"
  else
    puts '✗ Rails console is not running'
    # Mark session as stopped in registry
    session_registry.stop_session(target: options[:target], reason: 'process_died') if session
    clear_session_info
  end
end

#stopObject



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
# File 'lib/consolle/cli.rb', line 434

def stop
  ensure_rails_project!
  validate_session_name!(options[:target])

  adapter = create_rails_adapter('development', options[:target])

  if adapter.running?
    puts 'Stopping Rails console...'

    if adapter.stop
      puts '✓ Rails console stopped'

      # Mark session as stopped in registry (preserves history)
      session_registry.stop_session(target: options[:target], reason: 'user_requested')
    else
      puts '✗ Failed to stop Rails console'
    end
  else
    puts 'Rails console is not running'
    # Mark as stopped anyway in case registry is out of sync
    session_registry.stop_session(target: options[:target], reason: 'not_running')
  end

  clear_session_info
end

#stop_allObject



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
# File 'lib/consolle/cli.rb', line 462

def stop_all
  ensure_rails_project!

  # Get running sessions from registry
  running_sessions = session_registry.list_sessions(include_stopped: false)

  # Also check legacy sessions
  legacy_sessions = load_sessions
  legacy_sessions.each do |name, info|
    next if name == '_schema'
    next unless info['process_pid'] && process_alive?(info['process_pid'])

    existing = running_sessions.find { |s| s['target'] == name }
    next if existing

    running_sessions << { 'target' => name, 'pid' => info['process_pid'], '_legacy' => true }
  end

  if running_sessions.empty?
    puts 'No active sessions to stop'
    return
  end

  puts "Found #{running_sessions.size} active session(s)"

  # Stop each active session
  running_sessions.each do |session|
    name = session['target']

    puts "\nStopping session '#{name}'..."

    adapter = create_rails_adapter('development', name)

    if adapter.stop
      puts "✓ Session '#{name}' stopped"

      # Mark session as stopped in registry
      session_registry.stop_session(target: name, reason: 'stop_all_requested') unless session['_legacy']

      # Clear from legacy sessions.json
      with_sessions_lock do
        sessions = load_sessions
        sessions.delete(name)
        save_sessions(sessions)
      end
    else
      puts "✗ Failed to stop session '#{name}'"
    end
  end

  puts "\n✓ All sessions stopped"
end

#versionObject



150
151
152
# File 'lib/consolle/cli.rb', line 150

def version
  puts "Consolle version #{Consolle::VERSION}"
end