2015-09-21 07:51:00 +00:00
|
|
|
# encoding: utf-8
|
2015-10-06 16:55:44 +00:00
|
|
|
# author: Christoph Hartmann
|
|
|
|
# author: Dominik Richter
|
2015-09-21 07:51:00 +00:00
|
|
|
|
|
|
|
# Parses a json document
|
|
|
|
# Usage:
|
2015-09-21 11:05:17 +00:00
|
|
|
# describe json('policyfile.lock.json') do
|
2015-09-21 07:51:00 +00:00
|
|
|
# its('cookbook_locks.omnibus.version') { should eq('2.2.0') }
|
|
|
|
# end
|
2015-10-26 03:04:18 +00:00
|
|
|
class JsonConfig < Inspec.resource(1)
|
2015-09-21 07:51:00 +00:00
|
|
|
name 'json'
|
|
|
|
|
|
|
|
# make params readable
|
|
|
|
attr_reader :params
|
|
|
|
|
|
|
|
def initialize(path)
|
|
|
|
@path = path
|
2015-10-26 03:04:18 +00:00
|
|
|
@file_content = inspec.file(@path).content
|
2015-09-21 07:51:00 +00:00
|
|
|
@params = parse(@file_content)
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse(content)
|
2015-09-21 08:31:31 +00:00
|
|
|
require 'json'
|
2015-09-21 10:11:20 +00:00
|
|
|
JSON.parse(content)
|
2015-09-21 07:51:00 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def extract_value(keys, value)
|
|
|
|
key = keys.shift
|
|
|
|
return nil if key.nil?
|
|
|
|
|
|
|
|
# check if key is a num, try to extract from array
|
|
|
|
if key.to_i.to_s == key
|
|
|
|
value = value[key.to_i]
|
|
|
|
# if value is an array, iterate over each child
|
|
|
|
elsif value.is_a?(Array)
|
|
|
|
value = value.map { |i|
|
|
|
|
extract_value([key], i)
|
|
|
|
}
|
|
|
|
# normal value extraction
|
|
|
|
else
|
|
|
|
value = value[key].nil? ? nil : value[key]
|
|
|
|
end
|
|
|
|
|
|
|
|
# check if further keys exist
|
|
|
|
if !keys.first.nil?
|
|
|
|
return extract_value(keys.clone, value)
|
|
|
|
else
|
|
|
|
return value
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def method_missing(name)
|
|
|
|
# split dotted path
|
|
|
|
keys = name.to_s.split('.')
|
|
|
|
extract_value(keys, @params.clone)
|
|
|
|
end
|
2015-10-12 11:01:58 +00:00
|
|
|
|
|
|
|
def to_s
|
|
|
|
"Json #{@path}"
|
|
|
|
end
|
2015-09-21 07:51:00 +00:00
|
|
|
end
|