Sha256: e3b7925c7f1450d0a5114c2acfc3ece5041878dc9c6b9317b3f6f6ab08ce244e

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

require 'yaml'
require 'chef/role'
require 'chef/environment'

module Knife
  module Undev
    class Converter
      
      def initialize(filename, klass = 'role')
        @filename = filename
        @klass = klass
        @comment_counter = 0
      end

      def to_yml
        case @klass
        when 'env'
          env_to_yml
        when 'role'
          role_to_yml
        end
      end

      def safe_delete(hash, key)
        hash.delete(key) if hash[key].nil? || hash[key].empty?
      end

      def comment(hash, value='')
        hash["#comment_#{@comment_counter+=1}"] = ""
      end

      def role_to_yml
        r = Chef::Role.new
        r.from_file(@filename)
        hash = r.to_hash.dup
        result_hash = Hash.new
        hash.delete('chef_type')
        hash.delete('json_class')
        safe_delete(hash, 'override_attributes')
        safe_delete(hash, 'run_list')
        result_hash['name'] = hash.delete('name')
        result_hash['description'] = hash.delete('description')
        comment(result_hash)
        result_hash['env_run_lists'] = hash.delete('env_run_lists')
        comment(result_hash)
        result_hash.merge(hash).to_yaml.each_line do |line|
          puts '' if line.match /#comment_\d+/
          next if line.match /#comment_\d+/
          next if line == '---'
          puts line
        end
      end

      def env_to_yml
        r = Chef::Environment.new
        r.from_file(@filename)
        hash = r.to_hash.dup
        hash.delete('chef_type')
        hash.delete('json_class')
        safe_delete(hash, 'override_attributes')
        safe_delete(hash, 'default_attributes')
        safe_delete(hash, 'cookbook_versions')
        safe_delete(hash, 'description')
        hash.to_yaml.each_line do |line|
          next if line == '---' 
        end
      end
      
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
knife-undev-0.0.5 lib/knife/undev/converter.rb