Class: Knife::Undev::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/knife/undev/converter.rb

Instance Method Summary collapse

Constructor Details

#initialize(filename, klass = 'role') ⇒ Converter

Returns a new instance of Converter.



9
10
11
12
13
# File 'lib/knife/undev/converter.rb', line 9

def initialize(filename, klass = 'role')
  @filename = filename
  @klass = klass
  @comment_counter = 0
end

Instance Method Details

#comment(hash, value = '') ⇒ Object



34
35
36
# File 'lib/knife/undev/converter.rb', line 34

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

#env_to_ymlObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/knife/undev/converter.rb', line 60

def env_to_yml
  r = Chef::Environment.new
  r.from_file(@filename)
  hash = stringify_keys(r.to_hash)
  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.match '^---'
    puts line
  end
end

#role_to_ymlObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/knife/undev/converter.rb', line 38

def role_to_yml
  r = Chef::Role.new
  r.from_file(@filename)
  hash = stringify_keys(r.to_hash)
  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.match '^---'
    puts line
  end
end

#safe_delete(hash, key) ⇒ Object



30
31
32
# File 'lib/knife/undev/converter.rb', line 30

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

#stringify_keys(obj) ⇒ Object



15
16
17
18
19
# File 'lib/knife/undev/converter.rb', line 15

def stringify_keys(obj)
  return obj.inject({}){|memo,(k,v)| memo[k.to_s] =  stringify_keys(v); memo} if obj.is_a? Hash
  return obj.inject([]){|memo,v    | memo           << stringify_keys(v); memo} if obj.is_a? Array
  obj
end

#to_ymlObject



21
22
23
24
25
26
27
28
# File 'lib/knife/undev/converter.rb', line 21

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