Add ability to export metadata and README

Signed-off-by: Clinton Wolfe <clintoncwolfe@gmail.com>
This commit is contained in:
Clinton Wolfe 2022-05-09 15:08:07 -04:00
parent a83dae4a2a
commit 5592f22e78
4 changed files with 46 additions and 14 deletions

View file

@ -94,6 +94,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
configure_logger(o)
what = o[:what] || "profile"
what.downcase!
raise Inspec::Error.new("Unrecognized option '#{what}' for --what - expected one of profile, readme, or metadata.") unless %w{profile readme metadata}.include?(what)
default_format_for_what = {
@ -117,6 +118,8 @@ class Inspec::InspecCLI < Inspec::BaseCLI
profile = Inspec::Profile.for_target(target, o)
dst = o[:output].to_s
case what
when "profile"
if format == "json"
require "json" unless defined?(JSON)
# Write JSON
@ -130,6 +133,13 @@ class Inspec::InspecCLI < Inspec::BaseCLI
write_path: dst
)
end
when "readme"
out = dst.empty? ? $stdout : File.open(dst, "w")
out.write(profile.readme)
when "metadata"
out = dst.empty? ? $stdout : File.open(dst, "w")
out.write(profile.metadata_src)
end
rescue StandardError => e
pretty_handle_exception(e)
end

View file

@ -746,6 +746,14 @@ module Inspec
@source_reader.target.files
end
def readme
@source_reader.readme&.values.first
end
def metadata_src
@source_reader.metadata_src
end
#
# TODO(ssd): Relative path handling really needs to be carefully
# thought through, especially with respect to relative paths in

View file

@ -12,7 +12,7 @@ module SourceReaders
nil
end
attr_reader :metadata, :tests, :libraries, :data_files, :target
attr_reader :metadata, :metadata_src, :tests, :libraries, :data_files, :target, :readme
# This create a new instance of an InSpec profile source reader
#
@ -24,14 +24,16 @@ module SourceReaders
@tests = load_tests
@libraries = load_libs
@data_files = load_data_files
@readme = load_readme
end
private
def load_metadata(metadata_source)
@metadata_src = @target.read(metadata_source)
Inspec::Metadata.from_ref(
metadata_source,
@target.read(metadata_source),
@metadata_src,
nil
)
rescue Psych::SyntaxError => e
@ -62,5 +64,9 @@ module SourceReaders
def load_data_files
load_all(%r{^files/})
end
def load_readme
load_all(/README.md/)
end
end
end

View file

@ -92,4 +92,12 @@ describe "inspec export" do
_(out.stderr).must_equal ""
_(out.stdout).must_equal File.read("#{profile_path}/old-examples/profile/README.md")
end
it "exports missing readme as blank" do
out = run_inspec_process("export --what readme #{profile_path}/git-fetcher/basic")
assert_exit_code 0, out
_(out.stderr).must_equal ""
_(out.stdout).must_equal ""
end
end