# frozen_string_literal: true require 'yaml' module NoradCli class UiSeedGenerator REQUIRED_ATTRIBUTES = %w[name prog_args test_types].freeze OPTIONAL_ATTRIBUTES = %w[category multi_host configurable help_url default_config service].freeze ALLOWED_ATTRIBUTES = REQUIRED_ATTRIBUTES | OPTIONAL_ATTRIBUTES def initialize(manifest_paths) @manifest_paths = if manifest_paths.empty? Dir.glob('./**/manifest.yml') else manifest_paths end end def process! configurations = [] @manifest_paths.each { |manifest_path| configurations << configuration_from_manifest(manifest_path) } save_seed_file!(configurations) rescue ManifestError => e puts e.message end private def seed_path "#{Dir.pwd}/seed.yml" end def save_seed_file!(configurations) File.open(seed_path, 'w') { |f| f.write YAML.dump(configurations) } end def configuration_from_manifest(manifest_path) raise ManifestNotFoundError, manifest_path unless File.exist?(manifest_path) seed = YAML.safe_load(File.read(manifest_path)) validate_seed(manifest_path, seed) seed['name'] = seed['version'] ? "#{seed['name']}:#{seed['version']}" : seed['name'] sanitize_seed(seed) end def sanitize_seed(seed) seed.each_key { |key| seed.delete(key) unless ALLOWED_ATTRIBUTES.include?(key) } end def validate_seed(manifest_path, seed) raise InvalidManifestError, manifest_path unless seed.is_a?(Hash) return if REQUIRED_ATTRIBUTES & seed.keys == REQUIRED_ATTRIBUTES raise ManifestMissingAttributesError.new(manifest_path, REQUIRED_ATTRIBUTES - seed.keys) end class ManifestError < StandardError attr_reader :manifest_path def initialize(manifest_path) @manifest_path = manifest_path end end class ManifestNotFoundError < ManifestError def message "Could not find manifest provided: #{manifest_path}" end end class ManifestMissingAttributesError < ManifestError attr_reader :attributes def initialize(manifest_path, attributes) @manifest_path = manifest_path @attributes = attributes end def message "Invalid manifest: #{manifest_path}. Missing attributes: #{attributes.join(', ')}" end end class InvalidManifestError < ManifestError def message "Invalid manifest: #{manifest_path}. See Norad security test repositories page for guidelines." end end end end