Class: Fsorg

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Fsorg.



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

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.



14
15
16
# File 'lib/fsorg.rb', line 14

def data
  @data
end

#documentObject

Returns the value of attribute document.



14
15
16
# File 'lib/fsorg.rb', line 14

def document
  @document
end

#document_pathObject

Returns the value of attribute document_path.



14
15
16
# File 'lib/fsorg.rb', line 14

def document_path
  @document_path
end

#root_directoryObject

Returns the value of attribute root_directory.



14
15
16
# File 'lib/fsorg.rb', line 14

def root_directory
  @root_directory
end

Instance Method Details

#ask_missing_variablesObject



273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/fsorg.rb', line 273

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

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

#current_locationObject



316
317
318
# File 'lib/fsorg.rb', line 316

def current_location
  @data[:HERE]
end

#depth_change(line) ⇒ Object



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

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

#desugarObject



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

def desugar
  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.to_s})\))?\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



374
375
376
377
378
379
380
381
# File 'lib/fsorg.rb', line 374

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

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



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/fsorg.rb', line 408

def do_run(command, inside, environment, dry_run, quiet, verbose)
  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
  unless 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
end

#do_write(future_file, dry_run, quiet) ⇒ Object



383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/fsorg.rb', line 383

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

  unless quiet
    puts "#{indentation}> ".cyan.bold + dest.relative_path_from(@root_directory).to_s + (future_file[:permissions] ? " mode #{future_file[:permissions]}".yellow : "")
  end
  unless dry_run
    dest.write ensure_final_newline deindent 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
end

#evaluates_to_false?(condition) ⇒ Boolean

Returns:

  • (Boolean)


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

def evaluates_to_false?(condition)
  !evaluates_to_true? condition
end

#evaluates_to_true?(condition) ⇒ Boolean

Returns:

  • (Boolean)


265
266
267
268
269
270
271
# File 'lib/fsorg.rb', line 265

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

  @data[condition.to_sym]
end

#format_environment_hash(environment) ⇒ Object



430
431
432
433
434
# File 'lib/fsorg.rb', line 430

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



26
27
28
# File 'lib/fsorg.rb', line 26

def from_relative_to_root(path)
  @root_directory / path
end

#preprocessObject



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

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



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

def process_for
  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 == 0
        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



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

def process_front_matter
  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.load(front_matter_raw, symbolize_names: true) or {}

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

#process_ifObject



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

def process_if
  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|
    @current_line = index + 1
    if inside_if
      current_depth += depth_change line.strip
      if current_depth == 0
        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 == 0
        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)
      if current_condition.nil?
        raise "[#{@document_path}:#{@current_line}] Cannot use ELSE without IF."
      end
      inside_else = true
      current_depth = 1
    else
      output << line
    end
    @document = output.join "\n"
  end
end

#process_includesObject



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

def process_includes
  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



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/fsorg.rb', line 288

def process_root
  @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



304
305
306
307
308
309
310
311
312
313
314
# File 'lib/fsorg.rb', line 304

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



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

def repeat_for_each(iteratee, iterator, directives)
  output = []
  unless data[iterator.to_sym]
    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(", ")}."
  end
  unless data[iterator.to_sym].is_a? Array
    raise "[#{@document_path}:#{@current_line}]".colorize :red + "Cannot iterate over '#{iterator}', which is of type #{data[iterator.to_sym].class}."
  end
  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



401
402
403
404
405
406
# File 'lib/fsorg.rb', line 401

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

#store_writesObject



146
147
148
149
150
# File 'lib/fsorg.rb', line 146

def store_writes
  output = []

  @document = output.join "\n"
end

#strip_commentsObject



114
115
116
117
118
119
120
121
122
123
124
# File 'lib/fsorg.rb', line 114

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

#turn_puts_into_runsObject



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

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

  @document = output.join "\n"
end

#walk(dry_run, quiet, verbose) ⇒ Object



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
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/fsorg.rb', line 320

def walk(dry_run, quiet, verbose)
  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 } }

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

  @document.lines(chomp: true).each_with_index do |line, index|
    @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.()
      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
      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.()
      if verbose
        puts "currenly #{current_path.map { |fragment| fragment.to_s }.join " -> "}".light_black
      end
      do_mkpath current_location, dry_run, quiet
    elsif line.strip == "}"
      current_path.pop
      @data[:HERE] = current_path_as_pathname.()
      if verbose
        puts "currenly #{current_path.map { |fragment| fragment.to_s }.join " -> "}".light_black
      end
    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