Class: Fsorg

Inherits:
Object
  • Object
show all
Defined in:
lib/fsorg.rb

Overview

rubocop:disable Metrics/ClassLength,Style/Documentation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root_directory, data, document, absolute_path) ⇒ Fsorg

Returns a new instance of Fsorg.



18
19
20
21
22
23
24
25
26
# File 'lib/fsorg.rb', line 18

def initialize(root_directory, data, document, absolute_path)
  @root_directory = root_directory
  @shell = "/usr/bin/env bash"
  @document_path = absolute_path
  @data = { HERE: @root_directory.to_s }.merge data
  @document = document
  @current_line = 0
  @current_depth = -1
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



16
17
18
# File 'lib/fsorg.rb', line 16

def data
  @data
end

#documentObject

Returns the value of attribute document.



16
17
18
# File 'lib/fsorg.rb', line 16

def document
  @document
end

#document_pathObject

Returns the value of attribute document_path.



16
17
18
# File 'lib/fsorg.rb', line 16

def document_path
  @document_path
end

#root_directoryObject

Returns the value of attribute root_directory.



16
17
18
# File 'lib/fsorg.rb', line 16

def root_directory
  @root_directory
end

Instance Method Details

#ask_missing_variablesObject



270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/fsorg.rb', line 270

def ask_missing_variables
  @document.scan(/\{\{(?<variable>[^}]+?)\}\}/) do |variable|
    @data[variable[0].to_sym] = :ask unless @data.include? variable[0].to_sym
  end

  @data.each do |key, value|
    if value == :ask
      print "#{key}? "
      @data[key] = YAML.safe_load $stdin.gets.chomp
    end
  end
end

#current_locationObject



311
312
313
# File 'lib/fsorg.rb', line 311

def current_location
  @data[:HERE]
end

#depth_change(line) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/fsorg.rb', line 32

def depth_change(line)
  change = 0
  if /\}\s*$/ =~ line
    change -= 1
  end
  if /^\s*\{/ =~ line
    change += 1
  end
  change
end

#desugarObject

rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/fsorg.rb', line 86

def desugar # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity
  output = []
  inside_write_directive_shorthand = false
  @document.lines(chomp: true).each_with_index do |line, index|
    @current_line = index + 1
    if inside_write_directive_shorthand
      if line.strip == "]"
        inside_write_directive_shorthand = false
        output << "}"
      else
        output << line
      end
    elsif /^\}(\s*ELSE\s*\{)$/.match line.strip
      output << "}"
      output << $~[1]
    elsif /^FILE\s+(?<filename>.+?)$/ =~ line.strip
      output << "RUN touch #{filename.shellescape}"
    elsif /^(\s*[^{]+?\{)([^{]+?)\}$/.match line.strip
      output << $~[1]
      output << $~[2]
      output << "}"
    elsif /^(?<filename>.+?)\s*(\s+\((?<permissions>#{PERMISSIONS_PATTERN})\))?\s*\[$/.match line.strip
      output << "WRITE #{$~[:filename]} #{$~[:permissions] ? "MODE #{$~[:permissions]}" : ""} {"
      inside_write_directive_shorthand = true
    else
      output << line
    end
  end
  @document = output.join "\n"
end

#do_mkpath(path, dry_run, quiet) ⇒ Object



363
364
365
366
# File 'lib/fsorg.rb', line 363

def do_mkpath(path, dry_run, quiet)
  puts "#{"  " * @current_depth}+ ".cyan.bold + path.relative_path_from(@root_directory).to_s unless quiet
  path.mkpath unless dry_run
end

#do_run(command, inside, environment, dry_run, quiet, verbose) ⇒ Object

rubocop:disable Metrics/AbcSize,Metrics/MethodLength,Metrics/ParameterLists



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/fsorg.rb', line 392

def do_run(command, inside, environment, dry_run, quiet, verbose) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength,Metrics/ParameterLists
  indentation = "  " * @current_depth
  unless quiet
    puts "#{indentation}$ ".cyan.bold + command + (verbose ? " at #{inside.relative_path_from(@root_directory)}".light_blue + " with ".light_black + (format_environment_hash environment) : "")
  end

  return if dry_run

  stdout, stdout_w = IO.pipe
  stderr, stderr_w = IO.pipe

  system environment, command, { chdir: inside.to_s, out: stdout_w, err: stderr_w }
  stdout_w.close
  stderr_w.close

  stdout.read.each_line(chomp: true) do |line|
    puts "  #{indentation}#{line}"
  end
  stderr.read.each_line(chomp: true) do |line|
    puts "  #{indentation}#{line.red}"
  end
end

#do_write(future_file, dry_run, quiet) ⇒ Object

rubocop:disable Metrics/AbcSize



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/fsorg.rb', line 368

def do_write(future_file, dry_run, quiet) # rubocop:disable Metrics/AbcSize
  indentation = "  " * @current_depth
  dest = from_relative_to_root(current_location) / future_file[:destination]
  do_mkpath dest.parent, dry_run, quiet unless dest.parent.relative_path_from(@root_directory).to_s == "."

  unless quiet
    puts "#{indentation}> ".cyan.bold + dest.relative_path_from(@root_directory).to_s + (future_file[:permissions] ? " mode #{future_file[:permissions]}".yellow : "")
  end

  return if dry_run

  dest.write ensure_final_newline(dedent(replace_data(future_file[:content])))
  # Not using dest.chmod as the syntax for permissions is more than just integers,
  # and matches in fact the exact syntax of chmod's argument, per the manpage, chmod(1) (line "Each MODE is of the form…")
  `chmod #{future_file[:permissions]} #{dest}` if future_file[:permissions]
end

#evaluates_to_false?(condition) ⇒ Boolean

Returns:

  • (Boolean)


260
261
262
# File 'lib/fsorg.rb', line 260

def evaluates_to_false?(condition)
  !evaluates_to_true? condition
end

#evaluates_to_true?(condition) ⇒ Boolean

Returns:

  • (Boolean)


264
265
266
267
268
# File 'lib/fsorg.rb', line 264

def evaluates_to_true?(condition)
  raise "[#{@document_path}:#{@current_line}] Variable '#{condition}' not found. Available variables at this point: #{data.keys.join(", ")}." unless @data.include? condition.to_sym

  @data[condition.to_sym]
end

#format_environment_hash(environment) ⇒ Object



415
416
417
418
419
# File 'lib/fsorg.rb', line 415

def format_environment_hash(environment)
  "{ ".light_black + (environment.map do |key, value|
    "$#{key}".red + "=".light_black + "\"#{value}\"".green
  end.join ", ".light_black) + " }".light_black
end

#from_relative_to_root(path) ⇒ Object



28
29
30
# File 'lib/fsorg.rb', line 28

def from_relative_to_root(path)
  @root_directory / path
end

#preprocessObject



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/fsorg.rb', line 43

def preprocess
  process_front_matter
  strip_comments
  desugar
  process_includes
  # TODO: process_see
  process_for
  process_if
  turn_puts_into_runs
  ask_missing_variables
  process_root
  process_shell
end

#process_forObject

rubocop:disable Metrics/AbcSize,Metrics/MethodLength



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
# File 'lib/fsorg.rb', line 173

def process_for # rubocop:disable Metrics/AbcSize,Metrics/MethodLength
  output = []
  inside_for_directive = false
  body = []
  args = nil
  current_depth = 0
  @document.lines(chomp: true).each_with_index do |line, index|
    @current_line = index + 1
    if inside_for_directive
      current_depth += depth_change line.strip
      if current_depth.zero?
        inside_for_directive = false
        output += repeat_for_each(args[:iteratee], args[:iterator], body)
      else
        body << line
      end
    elsif /^FOR\s+(?<iteratee>\w+)\s+IN\s+(?<iterator>.+?)\s*\{$/.match(line.strip)
      args = $~
      current_depth = 1
      body = []
      inside_for_directive = true
    else
      output << line
    end
    @document = output.join "\n"
  end
end

#process_front_matterObject

rubocop:disable Metrics/MethodLength



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/fsorg.rb', line 57

def process_front_matter # rubocop:disable Metrics/MethodLength
  unless /^-+$/ =~ @document.lines(chomp: true).first
    return
  end

  # Remove front matter from document
  front_matter_raw = ""
  rest = ""
  inside_front_matter = false
  @document.lines(chomp: true).each_with_index do |line, index|
    @current_linecur = index + 1
    if /^-+$/ =~ line
      inside_front_matter = !inside_front_matter
      next
    end

    if inside_front_matter
      front_matter_raw += "#{line}\n"
    else
      rest += "#{line}\n"
    end
  end

  front_matter = YAML.safe_load(front_matter_raw, symbolize_names: true) or {}

  @data = front_matter.merge @data
  @document = rest
end

#process_ifObject

rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity



214
215
216
217
218
219
220
221
222
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
# File 'lib/fsorg.rb', line 214

def process_if # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity
  output = []
  inside_if = false
  body_if = []
  inside_else = false
  body_else = []
  current_condition = nil
  current_depth = 0

  @document.lines(chomp: true).each_with_index do |line, index| # rubocop:disable Metrics/BlockLength
    @current_line = index + 1
    if inside_if
      current_depth += depth_change line.strip
      if current_depth.zero?
        inside_if = false
        inside_else = false
        output += body_if if evaluates_to_true? current_condition
      else
        body_if << line
      end
    elsif inside_else
      current_depth += depth_change line.strip
      if current_depth.zero?
        inside_else = false
        inside_if = false
        output += body_else if evaluates_to_false? current_condition
        current_condition = nil
      else
        body_else << line
      end
    elsif /^IF\s+(?<condition>.+?)\s*\{$/.match(line.strip)
      current_condition = $~[:condition]
      current_depth = 1
      inside_if = true
    elsif /^(\}\s*)?ELSE\s*\{$/.match(line.strip)
      raise "[#{@document_path}:#{@current_line}] Cannot use ELSE without IF." if current_condition.nil?

      inside_else = true
      current_depth = 1
    else
      output << line
    end
    @document = output.join "\n"
  end
end

#process_includesObject

rubocop:disable Metrics/AbcSize,Metrics/MethodLength



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/fsorg.rb', line 129

def process_includes # rubocop:disable Metrics/AbcSize,Metrics/MethodLength
  output = []

  @document.lines(chomp: true).each_with_index do |line, index|
    @current_line = index + 1
    if line.start_with? "INCLUDE "
      filepath = @document_path.parent.join(line.sub(/^INCLUDE /, ""))
      included_raw = File.new(filepath).read.strip
      included_fsorg = Fsorg.new(@root_directory, @data, included_raw, filepath)
      included_fsorg.preprocess
      @data = included_fsorg.data.merge @data
      output += included_fsorg.document.lines(chomp: true)
    else
      output << line
    end
  end

  @document = output.join "\n"
end

#process_rootObject

rubocop:disable Metrics/MethodLength



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/fsorg.rb', line 283

def process_root # rubocop:disable Metrics/MethodLength
  @document = @document.lines(chomp: true).map.with_index do |line, index|
    @current_line = index + 1
    if /^ROOT\s+(?<root>.+?)$/.match line.strip
      @root_directory = if $~[:root].start_with? "/"
          Pathname.new $~[:root]
        else
          @root_directory.join $~[:root]
        end
      ""
    else
      line
    end
  end.join "\n"
end

#process_shellObject



299
300
301
302
303
304
305
306
307
308
309
# File 'lib/fsorg.rb', line 299

def process_shell
  @document = @document.lines(chomp: true).map.with_index do |line, index|
    @current_line = index + 1
    if /^SHELL\s+(?<shell>.+?)$/.match line.strip
      @shell = $~[:shell]
      ""
    else
      line
    end
  end.join "\n"
end

#repeat_for_each(iteratee, iterator, directives) ⇒ Object

rubocop:disable Metrics/AbcSize



201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/fsorg.rb', line 201

def repeat_for_each(iteratee, iterator, directives) # rubocop:disable Metrics/AbcSize
  output = []
  raise "[#{@document_path}:#{@current_line}]".colorize :red + "Variable '#{iterator}' not found (iterators cannot be asked for interactively). Available variables at this point: #{data.keys.join(", ")}." unless data[iterator.to_sym]
  raise "[#{@document_path}:#{@current_line}]".colorize :red + "Cannot iterate over '#{iterator}', which is of type #{data[iterator.to_sym].class}." unless data[iterator.to_sym].is_a? Array

  data[iterator.to_sym].each do |item|
    output += directives.map do |directive|
      directive.gsub "{{#{iteratee}}}", item.to_s
    end
  end
  output
end

#replace_data(content) ⇒ Object



385
386
387
388
389
390
# File 'lib/fsorg.rb', line 385

def replace_data(content)
  content.gsub(/\{\{(?<variable>[^}]+?)\}\}/) do |interpolation|
    variable = interpolation[2..-3]
    @data[variable.to_sym]
  end
end

#store_writesObject



149
150
151
152
153
# File 'lib/fsorg.rb', line 149

def store_writes
  output = []

  @document = output.join "\n"
end

#strip_commentsObject



117
118
119
120
121
122
123
124
125
126
127
# File 'lib/fsorg.rb', line 117

def strip_comments
  output = []
  @document.lines(chomp: true).each_with_index do |line, _index|
    output << if /^(?<content>.*)#\s.*$/ =~ line
      content
    else
      line
    end
  end
  @document = output.join "\n"
end

#turn_puts_into_runsObject

rubocop:disable Metrics/MethodLength



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/fsorg.rb', line 155

def turn_puts_into_runs # rubocop:disable Metrics/MethodLength
  output = []
  @document.lines(chomp: true).each_with_index do |line, index|
    @current_line = index + 1
    output << if /^PUT\s+(?<source>.+?)(\s+AS\s+(?<destination>.+?))?(\s+MODE\s+(?<permissions>.+?))?$/.match(line.strip) # rubocop:disable Lint/MixedRegexpCaptureTypes
      "RUN install -D \"$FSORG_ROOT/#{$~[:source]}\" #{($~[:destination] || $~[:source]).shellescape}" + (if $~[:permissions]
        " -m #{$~[:permissions].shellescape}"
      else
        ""
      end)
    else
      line
    end
  end

  @document = output.join "\n"
end

#walk(dry_run, quiet, verbose) ⇒ Object

rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/fsorg.rb', line 315

def walk(dry_run, quiet, verbose) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity
  current_path = [@root_directory]
  @data[:HERE] = @root_directory
  file_to_write = {}
  inside_write_directive = -> { !file_to_write.keys.empty? }
  current_path_as_pathname = -> { current_path.reduce(Pathname.new("")) { |path, fragment| path.join fragment } }

  puts "Data is #{@data.except :HERE}".light_black if verbose

  @document.lines(chomp: true).each_with_index do |line, index| # rubocop:disable Metrics/BlockLength
    @current_line = index + 1
    @current_depth = current_path.length - 1

    @data.each do |key, value|
      line = line.gsub "{{#{key}}}", value.to_s
    end

    if inside_write_directive.call
      if line.strip == "}"
        do_write file_to_write, dry_run, quiet
        file_to_write = {}
      else
        file_to_write[:content] += "#{line}\n"
      end
    elsif /^WRITE(\s+INTO)?\s+(?<destination>.+?)(?:\s+MODE\s+(?<permissions>.+?))?\s*\{$/.match line.strip # rubocop:disable Lint/MixedRegexpCaptureTypes
      file_to_write = $~.named_captures.transform_keys(&:to_sym)
      file_to_write[:content] = ""
    elsif /^(?<leaf>.+?)\s+\{/ =~ line.strip
      current_path << leaf
      @data[:HERE] = current_path_as_pathname.call
      puts "currenly #{current_path.map(&:to_s).join " -> "}".light_black if verbose
      do_mkpath current_location, dry_run, quiet
    elsif line.strip == "}"
      current_path.pop
      @data[:HERE] = current_path_as_pathname.call
      puts "currenly #{current_path.map(&:to_s).join " -> "}".light_black if verbose
    elsif /^RUN\s+(?<command>.+?)$/ =~ line.strip
      environment = {
        "FSORG_ROOT" => @root_directory.to_s,
        "HERE" => @data[:HERE].relative_path_from(@root_directory).to_s,
        "CWD" => Dir.pwd,
        "DOCUMENT_DIR" => @document_path.parent.to_s,
      }
      do_run command, current_location, environment, dry_run, quiet, verbose
    end
  end
end