-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrunit.py
executable file
·296 lines (231 loc) · 9.32 KB
/
runit.py
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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
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
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
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/env python3
import sys, os, subprocess
import os.path, fnmatch
import argparse
import time
def get_recipes():
"""Return all known recipes of this program"""
return [
{
"recipe": "cpp",
"ext": [".cpp", ".h"],
"run": "c++ -Wall -Wextra -std=c++14 {source} -o out && (./out {args}; rm ./out)",
"entr_prune": []
},
{
"recipe": "c",
"ext": [".c", ".h"],
"run": "gcc -Wall -Wextra -std=c11 {source} -o out && (./out {args}; rm ./out)",
"entr_prune": []
},
{
"recipe": "javascript",
"ext": [".js"],
"run": "node {source} {args}",
"entr_prune": ["./node_modules"]
},
{
"recipe": "osascript",
"ext": [".scpt"],
"run": "osascript {source} {args}",
"entr_prune": []
},
{
"recipe": "php",
"ext": [".php"],
"run": "php {source} {args}",
"entr_prune": []
},
{
"recipe": "cs",
"ext": [".cs"],
"run": run_cs,
"entr_prune": []
},
{
"recipe": "sh",
"ext": [".sh"],
"run": "sh {source} {args}",
"entr_prune": []
},
{
"recipe": "bash",
"ext": [".bash"],
"run": "bash {source} {args}",
"entr_prune": []
},
{
"recipe": "zsh",
"ext": [".zsh"],
"run": "zsh {source} {args}",
"entr_prune": []
},
{
"recipe": "objc++",
"ext": [".mm"],
"run": "clang++ -std=c++14 -ObjC++ -framework Foundation {source} -o out && (./out {args}; rm ./out)",
"entr_prune": []
},
{
"recipe": "r",
"ext": [".r"],
"run": "/Library/Frameworks/R.framework/Resources/Rscript {source} {args}",
"entr_prune": []
},
{
"recipe": "npm",
"ext": [".js", ".html", ".css"],
"run": "npm start --prefix {source}",
"entr_prune": ["./node_modules"]
},
{
"recipe": "python",
"ext": [".py", ".py3"],
"run": "python3 {source} {args}",
"entr_prune": []
},
{
"recipe": "matlab",
"ext": [".m"],
"run": "matlab -nodisplay -nosplash -nodesktop -noFigureWindows -r \"try, run('{source}'), catch e, fprintf('%s\\n', e.message), end;exit(0);\"",
"entr_prune": []
},
{
"recipe": "objc",
"ext": [".m"],
"run": "clang -framework Foundation {source} -o out && (./out {args}; rm ./out)",
"entr_prune": []
},
{
"recipe": "java",
"ext": [".java"],
"run": run_java,
"entr_prune": []
},
]
def get_sub_args(args):
return " ".join(args.args)
def run_java(filename, recipe, args):
"""Execute a java source code file"""
# Java uses the file's name to determine the entry point
executable = os.path.splitext(os.path.basename(filename))[0]
cmd = "javac '{}' -d . && java '{}' {} && rm '{}.class'".format(filename, executable, get_sub_args(args), executable)
run(cmd, recipe, args)
def find_cs_binaries():
roots = [
"/Applications/Unity/Hub/Editor/",
# Non unity hub installations
"/Applications/Unity/"
]
# Only "MonoBleedingEdge" seems to work.
compiler_executable = "*/MonoBleedingEdge/bin/mcs"
runtime_executable = "*/MonoBleedingEdge/bin/mono"
compiler = runtime = None
for root in roots:
for subroot, dirnames, filenames in os.walk(root):
for candidate in filenames:
candidate = os.path.join(subroot, candidate)
if fnmatch.fnmatch(candidate, compiler_executable):
compiler = candidate
if fnmatch.fnmatch(candidate, runtime_executable):
runtime = candidate
# early out
if compiler != None and runtime != None:
return (compiler, runtime)
return (compiler, runtime)
def run_cs(filename, recipe, args):
compiler, runtime = find_cs_binaries()
if compiler == None or runtime == None:
error(4, "Cannot run '{}' files. Either runtime or compiler isn't found.".format(extension))
tmp = "out.exe";
# Compile ...
cmd = "{} -out:'{}' '{}'".format(compiler, tmp, filename)
# ...and on success...
cmd += " && "
# ... execute and delete
cmd += "({} '{}' {}; rm -f '{}')".format(runtime, tmp, get_sub_args(args), tmp)
run(cmd, recipe, args)
def error(code, str):
sys.stderr.write(str + "\n")
sys.exit(code)
def execute_recipe(recipes, filename, args):
if len(recipes) == 1:
recipe = recipes[0]
# Fancy recipe, requires helper code to run
if callable(recipe["run"]):
recipe["run"](filename, recipe, args)
# Execute recipe based on a string
else:
run(recipe["run"].format(source=filename, args=get_sub_args(args)), recipe, args)
else:
errormessage = "recipe is ambigious, try one of the following:\n";
for r in recipes:
errormessage += " {} {} {} [args...]\n".format(os.path.basename(sys.argv[0]), r["recipe"], filename)
error(3, errormessage)
def run(cmd, recipe, args):
if args.bench:
ruler = "----------------------"
# Wrap in time, and use a custom format specifier to
# return the real time.
cmd = "TIMEFORMAT=\"\n{0}\ntook %R seconds starting at $(date +'%T')\"; echo '{0}'; time ({1}); unset TIMEFORMAT;".format(ruler, cmd)
if args.entr:
entr_cmd = "find . {} -type f {} -maxdepth {} -print | entr -c -r sh -c '{}';"
pattern = ""
for i, ext in enumerate(recipe["ext"]):
if i > 0:
pattern += "-o "
pattern += "-name '*{}' -print ".format(ext)
escaped_cmd = cmd.replace("'", "'\\''")
prune = ""
if not args.no_prune:
for d in recipe["entr_prune"]:
prune += "-path ./node_modules -prune -o ".format(d)
os.system(entr_cmd.format(prune, pattern, args.maxdepth, escaped_cmd))
else:
os.system(cmd)
# TODO: gerjo: this could be part of the recipe setup. Specify which
# files to sense for in order to deduce how to execute a path.
def deduce_recipes_from_path(path):
# Node projects have a package file.
if os.path.isfile(os.path.join(path, "package.json")):
return [r for r in get_recipes() if r["recipe"] == "npm"]
return []
def main(args):
filename = args.filename
pwd = os.getcwd()
extension = os.path.splitext(filename)[1].lower()
# Use explicitly defined recipe when provided
if args.recipe:
recipes = [r for r in get_recipes() if r["recipe"] == args.recipe]
if len(recipes) > 0:
execute_recipe(recipes, filename, args)
else:
error(7, "Requested recipe '{}' does not exist.".format(args.recipe))
# otherwise deduce it from file extension
elif extension != "":
recipes = [r for r in get_recipes() if extension in r["ext"]]
if len(recipes) > 0:
execute_recipe(recipes, filename, args)
else:
error(8, "No recipe available for file extension '{0}'.".format(extension))
# Deduce it from path
elif os.path.isdir(filename):
recipes = deduce_recipes_from_path(filename)
if len(recipes) > 0:
execute_recipe(recipes, filename, args)
else:
error(6, "Cannot determine recipe based on path '{}'.".format(filename))
# This code shouldn't normally be reached
else:
error(2, "Cannot execute '{}'. No known recipe could be deduced.".format(filename))
parser = argparse.ArgumentParser(description="Execute any sort of file.", epilog="This ought to make it easier to quickly test something, right?")
parser.add_argument("recipe", help="The recipe to use in case file extension is ambiguous", nargs="?", default=None)
parser.add_argument("filename", help="The to be executed file")
parser.add_argument("--entr", help="Monitor for file changes", dest="entr", action="store_const", default=False, const=True)
parser.add_argument("--entr-no-prune", help="Disable pruning entr folders.", dest="no_prune", action="store_const", default=False, const=True)
parser.add_argument("--maxdepth", help="Recursion depth of find, in case entr is used", dest="maxdepth", action="store", default=4)
parser.add_argument("--nobench", help="Remote benchmark and ruler", dest="bench", action="store_const", default=True, const=True)
parser.add_argument('args', nargs='*', default=None, help="Arguments passed onto the executed file")
args = parser.parse_args()
main(args)
sys.exit(0)