Class: Inspec::InspecCLI

Inherits:
BaseCLI
  • Object
show all
Defined in:
lib/inspec/cli.rb

Instance Method Summary collapse

Methods inherited from BaseCLI

default_options, detect, exec_options, exit_on_failure?, parse_reporters, profile_options, target_options, validate_reporters

Instance Method Details

#archive(path) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/inspec/cli.rb', line 150

def archive(path)
  o = opts.dup
  diagnose(o)

  o[:logger] = Logger.new(STDOUT)
  o[:logger].level = get_log_level(o.log_level)
  o[:backend] = Inspec::Backend.create(target: 'mock://')

  # Force vendoring with overwrite when archiving
  vendor_options = o.dup
  vendor_options[:overwrite] = true
  vendor_deps(path, vendor_options)

  profile = Inspec::Profile.for_target(path, o)
  result = profile.check

  if result && !o[:ignore_errors] == false
    o[:logger].info 'Profile check failed. Please fix the profile before generating an archive.'
    return exit 1
  end

  # generate archive
  exit 1 unless profile.archive(o)
rescue StandardError => e
  pretty_handle_exception(e)
end

#check(path) ⇒ Object

rubocop:disable Metrics/AbcSize



77
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
117
118
119
120
121
122
123
124
# File 'lib/inspec/cli.rb', line 77

def check(path) # rubocop:disable Metrics/AbcSize
  o = opts.dup
  diagnose(o)
  o[:backend] = Inspec::Backend.create(target: 'mock://')
  o[:check_mode] = true
  o[:vendor_cache] = Inspec::Cache.new(o[:vendor_cache])

  # run check
  profile = Inspec::Profile.for_target(path, o)
  result = profile.check

  if o['format'] == 'json'
    puts JSON.generate(result)
  else
    %w{location profile controls timestamp valid}.each do |item|
      puts format('%-12s %s', item.to_s.capitalize + ':',
                  mark_text(result[:summary][item.to_sym]))
    end
    puts

    if result[:errors].empty? and result[:warnings].empty?
      puts 'No errors or warnings'
    else
      red    = "\033[31m"
      yellow = "\033[33m"
      rst    = "\033[0m"

      item_msg = lambda { |item|
        pos = [item[:file], item[:line], item[:column]].compact.join(':')
        pos.empty? ? item[:msg] : pos + ': ' + item[:msg]
      }
      result[:errors].each do |item|
        puts "#{red}#{item_msg.call(item)}#{rst}"
      end
      result[:warnings].each do |item|
        puts "#{yellow}  !  #{item_msg.call(item)}#{rst}"
      end

      puts
      puts format('Summary:     %s%d errors%s, %s%d warnings%s',
                  red, result[:errors].length, rst,
                  yellow, result[:warnings].length, rst)
    end
  end
  exit 1 unless result[:summary][:valid]
rescue StandardError => e
  pretty_handle_exception(e)
end

#detectObject



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/inspec/cli.rb', line 262

def detect
  o = opts(:detect).dup
  o[:command] = 'platform.params'
  (_, res) = run_command(o)
  if o['format'] == 'json'
    puts res.to_json
  else
    headline('Platform Details')
    puts Inspec::BaseCLI.detect(params: res, indent: 0, color: 36)
  end
rescue ArgumentError, RuntimeError, Train::UserError => e
  $stderr.puts e.message
  exit 1
rescue StandardError => e
  pretty_handle_exception(e)
end

#env(shell = nil) ⇒ Object



318
319
320
321
322
323
# File 'lib/inspec/cli.rb', line 318

def env(shell = nil)
  p = Inspec::EnvPrinter.new(self.class, shell)
  p.print_and_exit!
rescue StandardError => e
  pretty_handle_exception(e)
end

#exec(*targets) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/inspec/cli.rb', line 243

def exec(*targets)
  o = opts(:exec).dup
  diagnose(o)
  configure_logger(o)

  runner = Inspec::Runner.new(o)
  targets.each { |target| runner.add_target(target) }

  exit runner.run
rescue ArgumentError, RuntimeError, Train::UserError => e
  $stderr.puts e.message
  exit 1
rescue StandardError => e
  pretty_handle_exception(e)
end

#json(target) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/inspec/cli.rb', line 41

def json(target)
  o = opts.dup
  diagnose(o)
  o['log_location'] = STDERR
  configure_logger(o)

  o[:backend] = Inspec::Backend.create(target: 'mock://')
  o[:check_mode] = true
  o[:vendor_cache] = Inspec::Cache.new(o[:vendor_cache])

  profile = Inspec::Profile.for_target(target, o)
  info = profile.info
  # add in inspec version
  info[:generator] = {
    name: 'inspec',
    version: Inspec::VERSION,
  }
  dst = o[:output].to_s
  if dst.empty?
    puts JSON.dump(info)
  else
    if File.exist? dst
      puts "----> updating #{dst}"
    else
      puts "----> creating #{dst}"
    end
    fdst = File.expand_path(dst)
    File.write(fdst, JSON.dump(info))
  end
rescue StandardError => e
  pretty_handle_exception(e)
end

#schema(name) ⇒ Object



326
327
328
329
330
331
# File 'lib/inspec/cli.rb', line 326

def schema(name)
  puts Inspec::Schema.json(name)
rescue StandardError => e
  puts e
  puts "Valid schemas are #{Inspec::Schema.names.join(', ')}"
end

#shell_funcObject



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
315
# File 'lib/inspec/cli.rb', line 290

def shell_func
  o = opts(:shell).dup
  diagnose(o)
  o[:debug_shell] = true

  log_device = suppress_log_output?(o) ? nil : STDOUT
  o[:logger] = Logger.new(log_device)
  o[:logger].level = get_log_level(o.log_level)

  if o[:command].nil?
    runner = Inspec::Runner.new(o)
    return Inspec::Shell.new(runner).start
  end

  run_type, res = run_command(o)
  exit res unless run_type == :ruby_eval

  # No InSpec tests - just print evaluation output.
  res = (res.respond_to?(:to_json) ? res.to_json : JSON.dump(res)) if o['reporter']&.keys&.include?('json')
  puts res
  exit 0
rescue RuntimeError, Train::UserError => e
  $stderr.puts e.message
rescue StandardError => e
  pretty_handle_exception(e)
end

#vendor(path = nil) ⇒ Object



129
130
131
132
133
134
135
136
# File 'lib/inspec/cli.rb', line 129

def vendor(path = nil)
  o = opts.dup
  configure_logger(o)
  o[:logger] = Logger.new(STDOUT)
  o[:logger].level = get_log_level(o.log_level)

  vendor_deps(path, o)
end

#versionObject



335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/inspec/cli.rb', line 335

def version
  if opts['format'] == 'json'
    v = { version: Inspec::VERSION }
    puts v.to_json
  else
    puts Inspec::VERSION
    # display outdated version
    latest = LatestInSpecVersion.new.latest
    if Gem::Version.new(Inspec::VERSION) < Gem::Version.new(latest)
      puts "\nYour version of InSpec is out of date! The latest version is #{latest}."
    end
  end
end