forked from memotype/bj.sh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrollup.rb
executable file
·87 lines (73 loc) · 1.94 KB
/
rollup.rb
1
2
3
4
5
6
7
8
9
10
11
12
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
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/ruby -w
require 'securerandom'
# Regexes to save and replace literals (strings, escaped semicolons, etc)
lits_re = [
/(?<!\\)"(?:[^"\\]|\\.)*"/,
/(?<!\\)'[^']*'/,
/\\;/
]
# List of keywords that shouldn't have semicolons after them
ns_kws = [
'if',
'then',
'elif',
'else',
'while',
'until',
'do',
'in'
]
# Regexes to further transform the script, and their replacements
trans_re = [
[/: ENDBJ(?:.|\n)*/, ''],
[/#.*\n/, ''],
[/: :.*\n/, ''],
[/\\\n/, ''],
[/\n+[[:blank:]]*\n*/, ';'],
[/[[:blank:]]*;[[:blank:]]*/, ';'],
[/[[:blank:]]+/, ' '],
[/ {;/, '{ '],
[/ \(;/, '('],
[/ ?&& ?/, '&&'],
[/;case ([^ ]*) in; *([^\)]*\)) */, ';case \1 in \2'],
[/ ?;;;* ?/, ';;'],
[/(;;[^;\(]*\)) *;? */, '\1'],
[/ *\|\| */, '||'],
[/ *</, '<'],
[/^;/, ''],
[/;$/, ''],
]
ns_kws.each { |kw|
# [/;if;/, ';if '] etc...
trans_re << [/;(#{kw});/, ';\1 ']
}
if infile = ARGV.shift
f = File.open infile
script = f.read
else
script = STDIN.read
end
if outfile = ARGV.shift
output = File.open outfile, 'w'
else
output = STDOUT
end
# Array of replaced literals. We use an array so we can be sure to replace
# them back in the right order, in case there are 'nested' literals.
lits = []
lits_re.each { |re|
script.gsub!(re) { |str|
repl = SecureRandom.hex(16)
lits.unshift [repl, str]
next repl
}
}
trans_re.each { |re,repl|
script.gsub! re, repl
}
lits.each { |repl, str|
script.gsub! repl, str
}
output.puts ("# (C) Isaac Freeman ([email protected]). " \
+ "See https://github.com/memotype/bj.sh")
output.puts script