Module: Prompt::Console

Defined in:
lib/prompt/console/builtins.rb,
lib/prompt/console/console_module.rb

Defined Under Namespace

Classes: Builtins

Constant Summary collapse

HISTORY_MAX_SIZE =
100
CompletionProc =
proc do |word_starting_with|
  line_starting_with = Readline.line_buffer[0...Readline.point]
  Prompt.application.completions(line_starting_with, word_starting_with)
end

Class Method Summary collapse

Class Method Details

.command_exception(e) ⇒ Object



77
78
79
80
# File 'lib/prompt/console/console_module.rb', line 77

def self.command_exception e
  puts e.message
  puts e.backtrace.map {|s| "  #{s}" }.join("\n")
end

.command_not_found(line) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/prompt/console/console_module.rb', line 64

def self.command_not_found line
  words = self.split line
  suggestions = Prompt.application.commands.select { |cmd| cmd.could_match? words }
  if suggestions.empty?
    puts "Command not found"
  else
    puts "Command not found. Did you mean one of these?"
    suggestions.each do |cmd|
      puts "  #{cmd.usage}"
    end
  end
end

.load_history(file) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/prompt/console/console_module.rb', line 56

def self.load_history file
  if File.exist? file
    File.readlines(file).each do |line|
      Readline::HISTORY.push line.strip
    end
  end
end

.save_history(file) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/prompt/console/console_module.rb', line 47

def self.save_history file
  history_no_dups = Readline::HISTORY.to_a.reverse.uniq[0,HISTORY_MAX_SIZE].reverse
  File.open(file, "w") do |f|
    history_no_dups.each do |line|
      f.puts line
    end
  end
end

.start(history_file = nil) ⇒ Object



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
# File 'lib/prompt/console/console_module.rb', line 15

def self.start(history_file = nil)
  # Store the state of the terminal
  stty_save = `stty -g`.chomp
  # ...and restore it when exiting
  at_exit do
    system('stty', stty_save)
    save_history history_file if history_file
  end

  # Exit immediately on Ctrl-C
  trap('INT') do
    puts
    exit
  end

  Readline.completion_proc = CompletionProc

  load_history history_file if history_file

  while line = Readline.readline(Prompt.application.prompt, true)
    begin
      words = split(line)
      next if words == []
      Prompt.application.exec words
    rescue CommandNotFound
      command_not_found line
    rescue => e
      command_exception e
    end
  end
end