Class: Inspec::Plugin::V2::ConfigFile

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/inspec/plugin/v2/config_file.rb

Overview

Represents the plugin config file on disk.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = nil) ⇒ ConfigFile

Returns a new instance of ConfigFile.



10
11
12
13
14
15
# File 'lib/inspec/plugin/v2/config_file.rb', line 10

def initialize(path = nil)
  @path = path || self.class.default_path
  @data = blank_structure

  read_and_validate_file if File.exist?(@path)
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



8
9
10
# File 'lib/inspec/plugin/v2/config_file.rb', line 8

def path
  @path
end

Class Method Details

.default_pathObject

Returns the defaut path for a config file. This respects ENV.



19
20
21
# File 'lib/inspec/plugin/v2/config_file.rb', line 19

def self.default_path
  File.join(Inspec.config_dir, "plugins.json")
end

Instance Method Details

#add_entry(proposed_entry) ⇒ Object

Add an entry with full validation.



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/inspec/plugin/v2/config_file.rb', line 41

def add_entry(proposed_entry)
  unless proposed_entry.keys.all? { |field| field.is_a? Symbol }
    raise Inspec::Plugin::V2::ConfigError, "All keys to ConfigFile#add_entry must be symbols"
  end

  validate_entry(proposed_entry)

  if existing_entry?(proposed_entry[:name])
    raise Inspec::Plugin::V2::ConfigError, "Duplicate plugin name in call to ConfigFile#add_entry: '#{proposed_entry[:name]}'"
  end

  @data[:plugins] << proposed_entry
end

#each(&block) ⇒ Object

Implement Enumerable. All Enumerable methds act on the plugins list, and yield Hashes that represent an entry.



26
27
28
# File 'lib/inspec/plugin/v2/config_file.rb', line 26

def each(&block)
  @data[:plugins].each(&block)
end

#existing_entry?(name) ⇒ Boolean

Check for a plugin

Returns:

  • (Boolean)


36
37
38
# File 'lib/inspec/plugin/v2/config_file.rb', line 36

def existing_entry?(name)
  !plugin_by_name(name).nil?
end

#plugin_by_name(name) ⇒ Object

Look for a plugin by name.



31
32
33
# File 'lib/inspec/plugin/v2/config_file.rb', line 31

def plugin_by_name(name)
  detect { |entry| entry[:name] == name.to_sym }
end

#remove_entry(name) ⇒ Object

Removes an entry specified by plugin name.



56
57
58
59
60
61
62
# File 'lib/inspec/plugin/v2/config_file.rb', line 56

def remove_entry(name)
  unless existing_entry?(name)
    raise Inspec::Plugin::V2::ConfigError, "No such entry with plugin name '#{name}'"
  end

  @data[:plugins].delete_if { |entry| entry[:name] == name.to_sym }
end

#saveObject

Save the file to disk as a JSON structure at the path.



65
66
67
68
69
# File 'lib/inspec/plugin/v2/config_file.rb', line 65

def save
  dir = File.dirname(path)
  FileUtils.mkdir_p(dir)
  File.write(path, JSON.pretty_generate(@data))
end