| 1 | # spinel-flatten: inline a require_relative graph into one self-contained file,
|
| 2 | # so spinel-reduce and bug reports operate on a single input. Resolves the same
|
| 3 | # require_relative paths spinel does; cycle-safe; records each region's origin.
|
| 4 | #
|
| 5 | # Usage: spinel-flatten [-o OUT] app.rb
|
| 6 |
|
| 7 | require_relative "tool_common"
|
| 8 |
|
| 9 | # Extract the path from a `require_relative "x"` / `require_relative 'x'` line,
|
| 10 | # or "" if the line is not a require_relative.
|
| 11 | def require_target(line)
|
| 12 | s = line.strip
|
| 13 | return "" if !s.start_with?("require_relative")
|
| 14 | q = "\""
|
| 15 | i = s.index(q)
|
| 16 | if !i
|
| 17 | q = "'"
|
| 18 | i = s.index(q)
|
| 19 | end
|
| 20 | return "" if !i
|
| 21 | rest = s[i + 1, s.length - i - 1]
|
| 22 | j = rest.index(q)
|
| 23 | return "" if !j
|
| 24 | rest[0, j]
|
| 25 | end
|
| 26 |
|
| 27 | # Resolve a require_relative target against the requiring file's directory,
|
| 28 | # adding ".rb" when absent.
|
| 29 | def resolve(from_file, target)
|
| 30 | base = dir_name(from_file) + "/" + target
|
| 31 | return base if base.end_with?(".rb")
|
| 32 | base + ".rb"
|
| 33 | end
|
| 34 |
|
| 35 | def inline(real, out, seen)
|
| 36 | seen.each { |p| return if p == real }
|
| 37 | seen.push(real)
|
| 38 | if !File.exist?(real)
|
| 39 | out.push("# spinel-flatten: missing file: " + real)
|
| 40 | return
|
| 41 | end
|
| 42 | out.push("# >>> " + real)
|
| 43 | text = File.read(real)
|
| 44 | text.split("\n").each { |line|
|
| 45 | t = require_target(line)
|
| 46 | if t.length > 0
|
| 47 | inline(resolve(real, t), out, seen)
|
| 48 | else
|
| 49 | out.push(line)
|
| 50 | end
|
| 51 | }
|
| 52 | out.push("# <<< " + real)
|
| 53 | end
|
| 54 |
|
| 55 | def main
|
| 56 | src = ""
|
| 57 | outfile = ""
|
| 58 | i = 0
|
| 59 | while i < ARGV.length
|
| 60 | a = ARGV[i]
|
| 61 | if a == "-o"
|
| 62 | i = i + 1
|
| 63 | outfile = ARGV[i] if i < ARGV.length
|
| 64 | elsif a == "-h" || a == "--help"
|
| 65 | puts "usage: spinel-flatten [-o OUT] app.rb"
|
| 66 | puts " inline the require_relative graph of app.rb into one file"
|
| 67 | exit(0)
|
| 68 | else
|
| 69 | src = a
|
| 70 | end
|
| 71 | i = i + 1
|
| 72 | end
|
| 73 | die("usage: spinel-flatten [-o OUT] app.rb", 2) if src.length == 0
|
| 74 | die("spinel-flatten: no such file: " + src, 2) if !File.exist?(src)
|
| 75 |
|
| 76 | out = []
|
| 77 | seen = []
|
| 78 | inline(src, out, seen)
|
| 79 | text = out.join("\n") + "\n"
|
| 80 | if outfile.length > 0
|
| 81 | File.write(outfile, text)
|
| 82 | $stderr.puts "spinel-flatten: wrote " + outfile
|
| 83 | else
|
| 84 | print text
|
| 85 | end
|
| 86 | exit(0)
|
| 87 | end
|
| 88 |
|
| 89 | main
|