Class: Fsorg

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Fsorg.



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

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
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



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

def data
  @data
end

#documentObject

Returns the value of attribute document.



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

def document
  @document
end

#document_pathObject

Returns the value of attribute document_path.



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

def document_path
  @document_path
end

#root_directoryObject

Returns the value of attribute root_directory.



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

def root_directory
  @root_directory
end

Class Method Details

.from_command_lineObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/fsorg.rb', line 41

def self.from_command_line
  args = Docopt.docopt "    Usage:\n        fsorg [options] <filepath>\n        fsorg [options] <data> <filepath>\n\n    Options:\n        -h --help                 Show this screen.\n        -v --version              Show version.\n        -r --root=ROOT_DIRECTORY  Set the root directory.\n  DOC\n\n  filepath = Pathname.new args[\"<filepath>\"]\n  document = File.new(filepath).read.strip\n  data_raw = args[\"<data>\"] || \"{}\"\n  data = YAML.load data_raw, symbolize_names: true\n  root_directory = Pathname.new(args[\"--root\"] || \"\")\n\n  return Fsorg.new root_directory, data, document, Pathname.new(Dir.pwd).join(filepath)\nend\n"

Instance Method Details

#ask_missing_variablesObject



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

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



343
344
345
# File 'lib/fsorg.rb', line 343

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



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/fsorg.rb', line 104

def desugar
  output = []
  @document.lines(chomp: true).each_with_index do |line, index|
    @current_line = index + 1
    if /^\}(\s*ELSE\s*\{)$/.match line
      output << "}"
      output << $~[1]
    elsif /^(\s*[^{]+?\{)([^{]+?)\}$/.match line.strip
      output << $~[1]
      output << $~[2]
      output << "}"
    else
      output << line
    end
  end
  @document = output.join "\n"
end

#evaluates_to_false?(condition) ⇒ Boolean

Returns:

  • (Boolean)


288
289
290
# File 'lib/fsorg.rb', line 288

def evaluates_to_false?(condition)
  !evaluates_to_true? condition
end

#evaluates_to_true?(condition) ⇒ Boolean

Returns:

  • (Boolean)


292
293
294
295
296
297
298
# File 'lib/fsorg.rb', line 292

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

#preprocessObject



62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/fsorg.rb', line 62

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

#process_forObject



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/fsorg.rb', line 197

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



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/fsorg.rb', line 76

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



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
284
285
286
# File 'lib/fsorg.rb', line 241

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



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/fsorg.rb', line 122

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



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/fsorg.rb', line 315

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



331
332
333
334
335
336
337
338
339
340
341
# File 'lib/fsorg.rb', line 331

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

#relative_to_root(path) ⇒ Object



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

def relative_to_root(path)
  File.join(@root_directory, path)
end

#repeat_for_each(iteratee, iterator, directives) ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/fsorg.rb', line 225

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

#turn_puts_into_runsObject



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/fsorg.rb', line 179

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 \"$FSORG_ROOT/#{$~[:source]}\" #{($~[:destination] || $~[:source]).shellescape}" + (if $~[:permissions]
        " -D #{$~[:permissions].shellescape}"
      else
        ""
      end)
    else
      output << line
    end
  end

  @document = output.join "\n"
end

#turn_writes_into_runsObject



142
143
144
145
146
147
148
149
150
151
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
# File 'lib/fsorg.rb', line 142

def turn_writes_into_runs
  output = []
  inside_write_directive = false
  compact = nil
  current_content = []
  destination = nil
  permissions = nil

  @document.lines(chomp: true).each_with_index do |line, index|
    @current_line = index + 1
    if inside_write_directive
      if line.strip == (compact ? "]" : "}")
        inside_write_directive = false
        content = deindent(current_content.join("\n")).gsub "\n", '\n'
        content = content.shellescape.gsub('\{\{', "{{").gsub('\}\}', "}}")
        output << "RUN" + (destination.include?("/") ? "mkdir -p #{Pathname.new(destination.strip).parent.to_s.shellescape}" : "") + "echo -ne #{content} > #{destination.strip.shellescape}" + (permissions ? " && chmod #{permissions} #{destination.strip.shellescape}" : "")
      else
        current_content << line
      end
    elsif /^WRITE(\s+INTO)?\s+(?<destination>.+?)(?:\s+MODE\s+(?<permissions>.+?))?\s*\{$/ =~ line.strip
      inside_write_directive = true
      compact = false
    elsif /^(?<destination>.+)(\s*\((?<permissions>#{PERMISSIONS_PATTERN})\))?\s*\[$/ =~ line.strip
      # Shouldn't be needed, as =~ should assign to destination, but heh, it doesn't work for some reason ¯\_(ツ)_/¯
      if destination.nil?
        destination = $~[:destination]
      end
      inside_write_directive = true
      compact = true
    else
      output << line
    end
  end

  @document = output.join "\n"
end

#walkObject



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/fsorg.rb', line 347

def walk
  current_path = [@root_directory]
  current_path_as_pathname = -> { current_path.reduce(Pathname.new "") { |path, fragment| path.join fragment } }
  @data[:HERE] = @root_directory

  @document.lines(chomp: true).each_with_index do |line, index|
    @current_line = index + 1
    
    @data.each do |key, value|
      line = line.gsub "{{#{key}}}", value.to_s
    end

    if /^RUN\s+(?<command>.+?)$/ =~ line.strip
      puts "run ".colorize(:cyan) + command + " at ".colorize(:blue) + current_location.to_s.colorize(:blue)
    elsif line.strip == "}"
      current_path.pop
    elsif /^(?<leaf>.+?)\s+\{/ =~ line.strip
      current_path << leaf
      @data[:HERE] = current_path_as_pathname.()
      puts "mk  ".colorize(:cyan) + current_location.to_s
    end
  end
end