Class: KBSecret::CLI::Command::New

Inherits:
Abstract
  • Object
show all
Defined in:
lib/kbsecret/cli/command/new.rb

Overview

The implementation of kbsecret new.

Instance Attribute Summary

Attributes inherited from Abstract

#cli

Instance Method Summary collapse

Methods inherited from Abstract

command_name, config

Constructor Details

#initialize(argv) ⇒ New

Returns a new instance of New.



12
13
14
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
# File 'lib/kbsecret/cli/command/new.rb', line 12

def initialize(argv)
  super(argv) do |cli|
    cli.slop do |o|
      o.banner = <<~HELP
        Usage:
          kbsecret new [options] <type> <label>
      HELP

      o.string "-s", "--session", "the session to contain the record", default: :default
      o.bool "-f", "--force", "force creation (ignore overwrites, etc.)"
      o.bool "-e", "--echo", "echo input to tty (only affects interactive input)"
      o.bool "-G", "--generate", "generate secret fields (interactive only)"
      o.string "-g", "--generator", "the generator to use for secret fields",
               default: :default
      o.bool "-x", "--terse", "read fields from input in a terse format"
      o.string "-i", "--ifs", "separate terse fields with this string", default: cli.ifs
    end

    cli.dreck do
      string :type
      string :label
    end

    cli.ensure_generator!
    cli.ensure_type! :argument
    cli.ensure_session!
  end
end

Instance Method Details

#run!Object

See Also:



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/kbsecret/cli/command/new.rb', line 57

def run!
  generator = KBSecret::Generator.new(cli.opts[:generator]) if cli.opts.generate?

  fields = if cli.opts.terse?
             cli.stdin.read.chomp.split cli.opts[:ifs]
           else
             klass = Record.class_for(@type)
             klass.external_fields.map do |field|
               if cli.opts.generate? && klass.sensitive?(field)
                 generator.secret
               else
                 cli.prompt "#{field.capitalize}?",
                            echo: !klass.sensitive?(field) || cli.opts.echo?
               end
             end
           end

  cli.session.add_record @type, @label, *fields, overwrite: cli.opts.force?
end

#setup!Object

See Also:



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

def setup!
  @label = cli.args[:label]
  @type  = TYPE_ALIASES[cli.args[:type]]
end

#validate!Object

See Also:



48
49
50
51
52
53
54
# File 'lib/kbsecret/cli/command/new.rb', line 48

def validate!
  # the code below actually handles the overwriting if necessary, but we fail early here
  # for friendliness and to avoid prompting the user for input unnecessarily
  if cli.session.record?(@label) && !cli.opts.force?
    cli.die "Refusing to overwrite a record without --force."
  end
end