Class: KBSecret::CLI

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/kbsecret/cli.rb,
lib/kbsecret/cli/command.rb,
lib/kbsecret/cli/command/cp.rb,
lib/kbsecret/cli/command/rm.rb,
lib/kbsecret/cli/command/env.rb,
lib/kbsecret/cli/command/new.rb,
lib/kbsecret/cli/command/conf.rb,
lib/kbsecret/cli/command/help.rb,
lib/kbsecret/cli/command/list.rb,
lib/kbsecret/cli/command/pass.rb,
lib/kbsecret/cli/command/todo.rb,
lib/kbsecret/cli/command/login.rb,
lib/kbsecret/cli/command/types.rb,
lib/kbsecret/cli/command/session.rb,
lib/kbsecret/cli/command/version.rb,
lib/kbsecret/cli/command/abstract.rb,
lib/kbsecret/cli/command/commands.rb,
lib/kbsecret/cli/command/raw_edit.rb,
lib/kbsecret/cli/command/sessions.rb,
lib/kbsecret/cli/command/generator.rb,
lib/kbsecret/cli/command/generators.rb,
lib/kbsecret/cli/command/stash_edit.rb,
lib/kbsecret/cli/command/stash_file.rb,
lib/kbsecret/cli/command/dump_fields.rb

Overview

An encapsulation of useful methods for kbsecret's CLI. Most methods in this class assume that they are being called from the context of a command-line utility.

Defined Under Namespace

Modules: Command

Constant Summary collapse

TYPE_ALIASES =

Abbreviations for record types (e.g., env for environment).

Abbrev.abbrev Record.record_types

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv = ARGV) ⇒ CLI

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deprecated.

see create

Returns a new instance of CLI.



110
111
112
113
# File 'lib/kbsecret/cli.rb', line 110

def initialize(argv = ARGV)
  @argv = argv.dup
  guard { yield self }
end

Instance Attribute Details

#argsDreck::Result? (readonly)

Returns the result of trailing argument parsing, if requested via #dreck.

Returns:

  • (Dreck::Result, nil)

    the result of trailing argument parsing, if requested via #dreck



31
32
33
# File 'lib/kbsecret/cli.rb', line 31

def args
  @args
end

#optsSlop::Result? (readonly)

Returns the result of option parsing, if requested via #slop.

Returns:

  • (Slop::Result, nil)

    the result of option parsing, if requested via #slop



27
28
29
# File 'lib/kbsecret/cli.rb', line 27

def opts
  @opts
end

#sessionSession? (readonly)

Returns the session associated with the command, if requested via #ensure_session!.

Returns:



35
36
37
# File 'lib/kbsecret/cli.rb', line 35

def session
  @session
end

Class Method Details

.create(argv = ARGV) {|CLI| ... } ⇒ CLI

Encapsulate both the options and trailing arguments passed to a kbsecret command.

Examples:

cmd = KBSecret::CLI.create do |c|
  c.slop do |o|
    o.string "-s", "--session", "session label"
    o.bool "-f", "--foo", "whatever"
  end

  c.dreck do
    string :name
  end

  c.ensure_session!
end

cmd.opts # => Slop::Result
cmd.args # => Dreck::Result

Yields:

Returns:

  • (CLI)

    the command's initial state



104
105
106
# File 'lib/kbsecret/cli.rb', line 104

def self.create(argv = ARGV, &block)
  CLI.new(argv, &block)
end

.die(msg) ⇒ void

Note:

This method does not return!

This method returns an undefined value.

Print an error message and terminate.

Parameters:

  • msg (String)

    the message to print



42
43
44
45
# File 'lib/kbsecret/cli.rb', line 42

def die(msg)
  fatal = ENV["NO_COLOR"] ? "Fatal" : RED["Fatal"]
  abort "#{fatal}: #{msg}"
end

.ifsString

Finds a reasonable default field separator by checking the environment first and then falling back to ":".

Returns:

  • (String)

    the field separator



50
51
52
# File 'lib/kbsecret/cli.rb', line 50

def ifs
  ENV["IFS"] || ":"
end

.installed?(util) ⇒ Boolean

Searches for an executable on the user's $PATH.

Examples:

CLI.installed? "foo" # => false
CLI.installed? "gcc" # => true

Parameters:

  • util (String)

    the name of the executable to search for.

Returns:

  • (Boolean)

    whether or not util is available on the $PATH.



78
79
80
81
82
# File 'lib/kbsecret/cli.rb', line 78

def installed?(util)
  ENV["PATH"].split(File::PATH_SEPARATOR).any? do |path|
    File.executable?(File.join(path, util))
  end
end

.stderrIO

Note:

Internal kbsecret commands should use this, and not STDERR.

Returns the IO object corresponding to the current standard error.

Returns:

  • (IO)

    the IO object corresponding to the current standard error



68
69
70
# File 'lib/kbsecret/cli.rb', line 68

def stderr
  $stderr
end

.stdinIO

Note:

Internal kbsecret commands should use this, and not STDIN.

Returns the IO object corresponding to the current standard input.

Returns:

  • (IO)

    the IO object corresponding to the current standard input



56
57
58
# File 'lib/kbsecret/cli.rb', line 56

def stdin
  $stdin
end

.stdoutIO

Note:

Internal kbsecret commands should use this, and not STDOUT.

Returns the IO object corresponding to the current standard output.

Returns:

  • (IO)

    the IO object corresponding to the current standard output



62
63
64
# File 'lib/kbsecret/cli.rb', line 62

def stdout
  $stdout
end

Instance Method Details

#bye(msg) ⇒ void

Note:

This method does not return!

This method returns an undefined value.

Print an informational message via #info and exit successfully.

Parameters:

  • msg (String)

    the message to print



245
246
247
248
# File 'lib/kbsecret/cli.rb', line 245

def bye(msg)
  info msg
  exit
end

#dreck(errors: true, &block) ⇒ Object

Note:

If #slop is called, it must be called before this.

Parse trailing arguments for a kbsecret command, using the elements remaining after options have been removed and interpreted via #slop.

Parameters:

  • errors (Boolean) (defaults to: true)

    whether or not to produce (strict) Dreck errors



152
153
154
155
156
# File 'lib/kbsecret/cli.rb', line 152

def dreck(errors: true, &block)
  @args = Dreck.parse @argv, strict: errors do
    instance_eval(&block)
  end
end

#ensure_generator!(where = :option) ⇒ void

Note:

#slop and #dreck should be called before this, depending on whether options or arguments are being tested for a valid session.

This method returns an undefined value.

Ensure that a generator profile passed in as an option or argument already exists (i.e., is already configured).

Parameters:

  • where (Symbol) (defaults to: :option)

    Where to look for the session label to test. If :option is passed, then the generator is expected to be the value of the --generator option. If :argument is passed, then the type is expected to be in the argument list labeled as :generator by Dreck.



195
196
197
198
# File 'lib/kbsecret/cli.rb', line 195

def ensure_generator!(where = :option)
  gen = where == :option ? @opts[:generator] : @args[:generator]
  Config.generator gen
end

#ensure_session!(where = :option) ⇒ void

Note:

#slop and #dreck should be called before this, depending on whether options or arguments are being tested for a valid session.

This method returns an undefined value.

Ensure that a session passed in as an option or argument already exists (i.e., is already configured).

Parameters:

  • where (Symbol) (defaults to: :option)

    Where to look for the session label to test. If :option is passed, then the session is expected to be the value of the --session option. If :argument is passed, then the session is expected to be in the argument list labeled as :argument by Dreck.



167
168
169
170
# File 'lib/kbsecret/cli.rb', line 167

def ensure_session!(where = :option)
  label = where == :option ? @opts[:session] : @args[:session]
  @session = Session[label]
end

#ensure_type!(where = :option) ⇒ void

Note:

#slop and #dreck should be called before this, depending on whether options or arguments are being tested for a valid session.

This method returns an undefined value.

Ensure that a record type passed in as an option or argument is resolvable to a record class.

Parameters:

  • where (Symbol) (defaults to: :option)

    Where to look for the record type to test. If :option is passed, then the type is expected to be the value of the --type option. If :argument is passed, then the type is expected to be in the argument list labeled as :type by Dreck.



181
182
183
184
# File 'lib/kbsecret/cli.rb', line 181

def ensure_type!(where = :option)
  type = TYPE_ALIASES[where == :option ? @opts[:type] : @args[:type]]
  Record.class_for type
end

#guardObject

Note:

This should be used to guard chunks of code that are likely to raise exceptions. The amount of code guarded should be minimized.

"Guard" a block by propagating any exceptions as fatal (unrecoverable) errors.

Returns:

  • (Object)

    the result of the block



205
206
207
208
209
210
# File 'lib/kbsecret/cli.rb', line 205

def guard
  yield
rescue => e
  stderr.puts e.backtrace if @opts&.debug?
  die "#{e.to_s.capitalize}."
end

#info(msg) ⇒ void

This method returns an undefined value.

Print an informational message.

Parameters:

  • msg (String)

    the message to print



228
229
230
231
# File 'lib/kbsecret/cli.rb', line 228

def info(msg)
  info = ENV["NO_COLOR"] ? "Info" : GREEN["Info"]
  stderr.puts "#{info}: #{msg}"
end

#prompt(question, echo: true) ⇒ String

Prompt the user for some input.

Parameters:

  • question (String)

    the question to ask the user

  • echo (Boolean) (defaults to: true)

    whether or not to echo the user's input

Returns:

  • (String)

    the user's response, with trailing newline removed



216
217
218
219
220
221
222
223
# File 'lib/kbsecret/cli.rb', line 216

def prompt(question, echo: true)
  if !echo && stdin.tty?
    stdin.getpass("#{question} ")
  else
    stdout.print "#{question} "
    stdin.gets.chomp
  end
end

#slop(cmds: [], errors: true) ⇒ Slop::Result

Note:

This should be called within the block passed to #initialize.

Parse options for a kbsecret command, adding some default options for introspection, verbosity, and help output.

Parameters:

  • cmds (Array<String>) (defaults to: [])

    additional commands to print in --introspect-flags

  • errors (Boolean) (defaults to: true)

    whether or not to produce Slop errors

Returns:

  • (Slop::Result)

    the result of argument parsing



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/kbsecret/cli.rb', line 123

def slop(cmds: [], errors: true)
  @opts = Slop.parse @argv, suppress_errors: !errors do |o|
    o.separator "Options:"

    yield o

    o.bool "-V", "--verbose", "produce more verbose output"
    o.bool "-w", "--no-warn", "suppress warning messages"
    o.bool "--debug", "produce full backtraces on errors"

    o.on "-h", "--help", "show this help message" do
      puts o.to_s prefix: "  "
      exit
    end

    o.on "--introspect-flags", "dump recognized flags and subcommands" do
      comp = o.options.flat_map(&:flags) + cmds
      puts comp.join "\n"
      exit
    end
  end

  @argv = @opts.args
end

#verbose(msg) ⇒ void

This method returns an undefined value.

Print an information message, but only if verbose output has been enabled.

Parameters:

  • msg (String)

    the message to print



236
237
238
239
# File 'lib/kbsecret/cli.rb', line 236

def verbose(msg)
  return unless @opts.verbose?
  info msg
end

#warn(msg) ⇒ void

This method returns an undefined value.

Print a warning message unless warnings have been suppressed.

Parameters:

  • msg (String)

    the message to print



253
254
255
256
257
# File 'lib/kbsecret/cli.rb', line 253

def warn(msg)
  return if @opts.no_warn?
  warning = ENV["NO_COLOR"] ? "Warning" : YELLOW["Warning"]
  stderr.puts "#{warning}: #{msg}"
end