Module: Quickpress::CLI

Defined in:
lib/quickpress/cli.rb

Overview

Basic input/output functions for the console.

They’re not how we handle the quickpress commands - for that check ‘bin/qp`.

These are ways to interact with the user - get password input, ask yes-or-no questions and such.

Class Method Summary collapse

Class Method Details

.ask(prompt) ⇒ Object

Asks ‘prompt` and returns a true/false answer.



51
52
53
54
55
56
57
58
# File 'lib/quickpress/cli.rb', line 51

def ask prompt
  print "#{prompt} (Y/n) "

  ans = $stdin.gets.lstrip.strip

  return true if ans.empty?
  ['y', 'Y'].include? ans
end

.clear_lineObject

Erases from the cursor to the beginning of line.



61
62
63
# File 'lib/quickpress/cli.rb', line 61

def clear_line
  print "\r\e[0K"
end

.get(prompt, allow_empty = false) ⇒ Object

Shows ‘prompt` and gets a string from the user.

This ensures that the string is not empty and pre/post spaces are removed.

If ‘allow_empty` is true, allows the user to type an empty input.



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/quickpress/cli.rb', line 25

def get(prompt, allow_empty=false)
  print "#{prompt} "

  ret = ""

  if allow_empty
    ret = $stdin.gets.lstrip.strip
  else
    ret = $stdin.gets.lstrip.strip while ret.empty?
  end
  ret
end

.get_secret(prompt) ⇒ Object

Shows ‘prompt` and gets a secret string from the user.

Hides things the user is typing.



41
42
43
44
45
46
47
48
# File 'lib/quickpress/cli.rb', line 41

def get_secret prompt
  ret = ""

  $stdin.noecho { ret = get(prompt) }

  puts
  ret
end

.tab_complete(prompt, completions, separator = " ") ⇒ Object

Shows ‘prompt` and reads a line from commandline, doing tab-completion according to `completions` Array.

‘separator` is the character to use when separating words.



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

def tab_complete(prompt, completions, separator=" ")

  abbrevs = Abbrev::abbrev completions
  word = ""
  line = ""

  $stdin.raw do
    while (char = $stdin.getch) != "\r"

      if char == "\t"
        if abbrevs.include?(word)
          word = abbrevs[word]
        end

      elsif (char == "\b" || char.ord == 127) # strange...
        if word.empty?
          line.chop!
        else
          word.chop!
        end

      else
        word += char

        if char == separator
          line += word
          word.clear
        end
      end

      clear_line
      print (line + word)
    end
    line += word
  end
  puts

  line
end

.with_status(prompt) ⇒ Object

Runs a block of code withing a quick status ‘prompt`.



66
67
68
69
70
# File 'lib/quickpress/cli.rb', line 66

def with_status(prompt)
  print prompt
  yield
  clear_line
end