Class: Terradoc

Inherits:
Object
  • Object
show all
Defined in:
lib/terradoc.rb,
lib/terradoc/version.rb

Overview

——————————————————————————– # ——————————————————————————– # ——————————————————————————– #

Constant Summary collapse

VERSION =
'0.1.8'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Terradoc

——————————————————————————– # ——————————————————————————– #

Raises:

  • (StandardError)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/terradoc.rb', line 13

def initialize(options = {})
    @command = 'hcl2json'

    raise StandardError.new("Failed to locate #{@command} please install (pip install #{@command})") unless which @command

    @base_path = '.'
    @base_path = options[:path] unless options[:path].nil?
    @base_path.chomp!('/')
    raise StandardError.new("Path #{@base_path} does not exist - Aborting") unless Dir.exist? @base_path

    @output_file = 'README.md'
    @output_file = options[:output] unless options[:output].nil?

    @raw_results = {}
    @files   = []
    @pattern = "#{@base_path}/*.tf"

    @config = {
                'data-sources' => {
                                    'start'          => '<!--Terradoc-data-sources-start-->',
                                    'end'            => '<!--Terradoc-data-sources-end-->',
                                    'raw_results'    => [],
                                    'sorted_results' => [],
                                    'data_table'     => []
                                  },
                'modules'      => {
                                    'start'          => '<!--Terradoc-modules-start-->',
                                    'end'            => '<!--Terradoc-modules-end-->',
                                    'raw_results'    => [],
                                    'sorted_results' => [],
                                    'data_table'     => []
                                  },
                'outputs'      => {
                                    'start'          => '<!--Terradoc-outputs-start-->',
                                    'end'            => '<!--Terradoc-outputs-end-->',
                                    'raw_results'    => [],
                                    'sorted_results' => [],
                                    'data_table'     => []
                                  },
                'providers'    => {
                                    'start'          => '<!--Terradoc-providers-start-->',
                                    'end'            => '<!--Terradoc-providers-end-->',
                                    'raw_results'    => [],
                                    'sorted_results' => [],
                                    'data_table'     => []
                                  },
                'resources'    => {
                                    'start'          => '<!--Terradoc-resources-start-->',
                                    'end'            => '<!--Terradoc-resources-end-->',
                                    'raw_results'    => [],
                                    'sorted_results' => [],
                                    'data_table'     => []
                                  },
                'variables'    => {
                                    'start'          => '<!--Terradoc-variables-start-->',
                                    'end'            => '<!--Terradoc-variables-end-->',
                                    'raw_results'    => [],
                                    'sorted_results' => [],
                                    'data_table'     => []
                                  }
              }

    terradoc_main
end

Instance Method Details

#cleanup_array(array) ⇒ Object

——————————————————————————– # ——————————————————————————– #



204
205
206
207
208
# File 'lib/terradoc.rb', line 204

def cleanup_array(array)
    array = array.uniq { |k| k[:name] } if array.count.positive?
    array = array.sort_by { |k| k[:name] } if array.count.positive?
    return array
end

#generate_data_tablesObject

——————————————————————————– # ——————————————————————————– #



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/terradoc.rb', line 223

def generate_data_tables
    if @config['data-sources']['sorted_results'].size.positive?
        @config['data-sources']['data_table'] << '| Name |'
        @config['data-sources']['data_table'] << '| ---- |'
        @config['data-sources']['sorted_results'].each do |item|
            @config['data-sources']['data_table'] << "| #{item[:name]} |"
        end
    else
        @config['data-sources']['data_table'] << '> No data sources found'
    end

    if @config['modules']['sorted_results'].size.positive?
        @config['modules']['data_table'] << '| Name |'
        @config['modules']['data_table'] << '| ---- |'
        @config['modules']['sorted_results'] .each do |item|
            @config['modules']['data_table']  << "| #{item[:name]} |"
        end
    else
        @config['modules']['data_table'] << '> No modules found'
    end

    if @config['outputs']['sorted_results'].size.positive?
        @config['outputs']['data_table'] << '| Name | Description |'
        @config['outputs']['data_table'] << '| ---- | ----------- |'
        @config['outputs']['sorted_results'].each do |item|
            @config['outputs']['data_table'] << "| #{item[:name]} | #{item[:description]} |"
        end
    else
        @config['outputs']['data_table'] << '> No outputs found'
    end

    if @config['providers']['sorted_results'].size.positive?
        @config['providers']['data_table'] << '| Name |'
        @config['providers']['data_table'] << '| ---- |'
        @config['providers']['sorted_results'].each do |item|
            @config['providers']['data_table'] << "| #{item[:name]} |"
        end
    else
        @config['providers']['data_table'] << '> No providers found'
    end

    if @config['resources']['sorted_results'].size.positive?
        @config['resources']['data_table'] << '| Name |'
        @config['resources']['data_table'] << '| ---- |'
        @config['resources']['sorted_results'].each do |item|
            @config['resources']['data_table'] << "| #{item[:name]} |"
        end
    else
        @config['resources']['data_table'] << '> No resources found'
    end

    if @config['variables']['sorted_results'].size.positive?
        @config['variables']['data_table'] << '| Name | Description | Type | Default | Required? |'
        @config['variables']['data_table'] << '| ---- | ----------- |:----:|:-------:|:---------:|'
        @config['variables']['sorted_results'].each do |item|
            @config['variables']['data_table'] << "| #{item[:name]} | #{item[:description]} | #{item[:type]} | #{item[:default]} | #{item[:required]} |"
        end
    else
        @config['variables']['data_table'] << '> No variables found'
    end
end

#generate_file_listObject

——————————————————————————– # ——————————————————————————– #



131
132
133
134
135
# File 'lib/terradoc.rb', line 131

def generate_file_list
    Dir.glob(@pattern).each do |file|
        @files << file
    end
end

#generate_output(lines, start_tag, end_tag, data_table) ⇒ Object

——————————————————————————– # ——————————————————————————– #



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/terradoc.rb', line 300

def generate_output(lines, start_tag, end_tag, data_table)
    processed = []

    skip_lines = false
    lines.each do |line|
        if line.casecmp?(end_tag) && skip_lines
            processed << line
            skip_lines = false
            next
        end

        next if skip_lines

        processed << line

        next unless line.casecmp?(start_tag)

        skip_lines = true
        data_table.each do |row|
            processed << row
        end
    end

    return processed
end

#load_file(filename) ⇒ Object

——————————————————————————– # ——————————————————————————– #



287
288
289
290
291
292
293
294
295
296
# File 'lib/terradoc.rb', line 287

def load_file(filename)
    lines = []

    begin
        lines = File.readlines(filename).each(&:chomp!)
    rescue SystemCallError
        raise StandardError.new("Failed to open file #{filename} for reading")
    end
    return lines
end

#process_filesObject

——————————————————————————– # ——————————————————————————– #



139
140
141
142
143
144
145
146
147
148
# File 'lib/terradoc.rb', line 139

def process_files
    @files.each do |file|
        Open3.popen3("hcl2json #{file}") do |_stdin, stdout, _stderr, _wait_thr|
            stdout_str = stdout.read

            json = JSON.parse(stdout_str, max_nesting: 256)
            @raw_results = @raw_results.merge(json)
        end
    end
end

#process_raw_resultsObject

——————————————————————————– # ——————————————————————————– #



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/terradoc.rb', line 152

def process_raw_results
    unless @raw_results['data'].nil?
        @raw_results['data'].each do |key, _value|
            name = key.gsub('_', '\_')
            @config['data-sources']['raw_results'] << { :name => name }
        end
    end

    unless @raw_results['module'].nil?
        @raw_results['module'].each do |key, value|
            name = key.gsub('_', '\_')
            @config['modules']['raw_results'] << { :name => name, :source => value['source'], :version => value['version'] }
        end
    end

    unless @raw_results['output'].nil?
        @raw_results['output'].each do |key, value|
            name = key.gsub('_', '\_')
            @config['outputs']['raw_results'] << { :name => name, :description => value['description'] }
        end
    end

    unless @raw_results['provider'].nil?
        @raw_results['provider'].each do |key, _value|
            name = key.gsub('_', '\_')
            @config['providers']['raw_results'] << { :name => name }
        end
    end

    unless @raw_results['resource'].nil?
        @raw_results['resource'].each do |key, _value|
            name = key.gsub('_', '\_')
            @config['resources']['raw_results'] << { :name => name }
        end
    end

    unless @raw_results['variable'].nil?
        @raw_results['variable'].each do |key, value|
            name = key.gsub('_', '\_')
            default = value['default'].to_s.gsub('_', '\_')
            required = if default.empty?
                           'Yes'
                       else
                           'No'
                       end
            @config['variables']['raw_results'] << { :name => name, :description => value['description'], :type => value['type'], :default => default, :required => required }
        end
    end
end

#sort_detailsObject

——————————————————————————– # ——————————————————————————– #



212
213
214
215
216
217
218
219
# File 'lib/terradoc.rb', line 212

def sort_details
    @config['data-sources']['sorted_results'] = cleanup_array(@config['data-sources']['raw_results'])
    @config['modules']['sorted_results'] = cleanup_array(@config['modules']['raw_results'])
    @config['outputs']['sorted_results'] = cleanup_array(@config['outputs']['raw_results'])
    @config['providers']['sorted_results'] = cleanup_array(@config['providers']['raw_results'])
    @config['resources']['sorted_results'] = cleanup_array(@config['resources']['raw_results'])
    @config['variables']['sorted_results'] = cleanup_array(@config['variables']['raw_results'])
end

#terradoc_mainObject

——————————————————————————– # ——————————————————————————– #



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/terradoc.rb', line 93

def terradoc_main
    spinners = TTY::Spinner::Multi.new("[:spinner] Terradoc is processing your files (Path: #{@base_path}, Output File: #{@output_file})")

    sp1 = spinners.register '[:spinner] Locating files'
    sp2 = spinners.register '[:spinner] Processing files'
    sp3 = spinners.register '[:spinner] Processing raw results'
    sp4 = spinners.register '[:spinner] Sorting the results'
    sp5 = spinners.register '[:spinner] Generating data tables'
    sp6 = spinners.register '[:spinner] Writing output'

    sp1.auto_spin
    sp2.auto_spin
    sp3.auto_spin
    sp4.auto_spin
    sp5.auto_spin
    sp6.auto_spin

    generate_file_list
    sp1.success

    process_files
    sp2.success

    process_raw_results
    sp3.success

    sort_details
    sp4.success

    generate_data_tables
    sp5.success

    write_output
    sp6.success
end

#which(cmd) ⇒ Object

——————————————————————————– # ——————————————————————————– #



80
81
82
83
84
85
86
87
88
89
# File 'lib/terradoc.rb', line 80

def which(cmd)
    exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
    ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
        exts.each do |ext|
            exe = File.join(path, "#{cmd}#{ext}")
            return exe if File.executable?(exe) && !File.directory?(exe)
        end
    end
    return nil
end

#write_outputObject

——————————————————————————– # ——————————————————————————– #



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/terradoc.rb', line 328

def write_output
    permissions = 0o0644

    lines = load_file(@output_file)

    lines = generate_output(lines, @config['data-sources']['start'], @config['data-sources']['end'], @config['data-sources']['data_table'])
    lines = generate_output(lines, @config['modules']['start'], @config['modules']['end'], @config['modules']['data_table'])
    lines = generate_output(lines, @config['outputs']['start'], @config['outputs']['end'], @config['outputs']['data_table'])
    lines = generate_output(lines, @config['providers']['start'], @config['providers']['end'], @config['providers']['data_table'])
    lines = generate_output(lines, @config['resources']['start'], @config['resources']['end'], @config['resources']['data_table'])
    lines = generate_output(lines, @config['variables']['start'], @config['variables']['end'], @config['variables']['data_table'])

    begin
        File.open(@output_file, 'w') do |f|
            lines.each do |line|
                f.puts line
            end
            f.chmod(permissions)
        end
    rescue SystemCallError
        raise StandardError.new("Failed to open file #{filename} for writing")
    end
end