-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsgmake.py
361 lines (301 loc) · 10.6 KB
/
sgmake.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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
#!/usr/bin/python3
"""
Siege-Tools SiegeMake (\"sgmake\")
Universal Plug-in-Based Build Automation
Version 0.9.6
Copyright (c) 2013 Grady O'Connell
"""
from __future__ import unicode_literals
import os, sys
from common import Args
from common import Status
from common import Support
from common.Plugin import Plugin
import steps
import events
import json
def splash():
print(__doc__.strip())
def commands():
print("Commands: %s" % ", ".join(Args.valid_commands))
def help():
splash()
print()
commands()
def confirm(question, default="y"):
default = default.lower()
if default == "y":
options = "Y/n"
else:
options = "y/N"
# TODO: make this a single character read (no endline)
choice = raw_input("%s (%s)? " % (question, options))
choice = choice.lower()
if choice == "":
choice = default
return choice == "y"
class Project(object):
def __init__(self):
self.status = Status.UNSET
self.steps = []
if not self.run_user_config("sg.json"):
self.run_user_script("sg.py")
self.back_up_env = os.environ
try:
if "env" in self.options:
for k, v in env:
os.environ[k] = v
except AttributeError:
pass
def run_user_config(self, cfg):
for fn in os.listdir("."):
if fn.lower() == cfg and os.path.isfile(os.path.join(os.getcwd(), fn)):
config = json.load(open(cfg))
self.__dict__.update(config.get("options", {}))
return True
return False
def run_user_script(self, script):
## Project config
for fn in os.listdir("."):
if fn.lower() == script and os.path.isfile(os.path.join(os.getcwd(), fn)):
# if not Args.option("warn") or confirm("Run potentially insecure python script \"%s\"" % fn, "y"):
with open(fn) as source:
eval(compile(source.read(), fn, "exec"), {}, self.__dict__)
# else:
# sys.exit(1)
def complete(self):
# if not self.run_user_config("sg.json"):
# self.run_user_script("sg.py")
# update all plugins after script runs
steps = self.steps[:] # update may modify during iteration
for step in steps:
step.call("update", self)
# steps.update(step.type(), step.name(), self)
i = 1
self.event("status", "step_start")
for step in self.steps:
step_type = step.type[0].upper() + step.type[1:] # capitalize step name
print("%s step (plug-in: %s)..." % (step_type, step.name))
i += 1
# status = getattr(self, step)()
status = step.call(
step.type, self
) # example: install plugins call install() method
# status = steps.step(step.type, step.name, self)
if status == Status.SUCCESS:
self.event("status", "step_success")
# #print("...%s finished." % step_name)
elif status == Status.FAILURE:
print("...%s failed." % step_type)
self.event("status", "step_failure")
return False
elif status == Status.UNSUPPORTED:
self.event("status", "step_unsupported")
print("...%s unsupported." % step_type)
return True
def event(self, name, args):
r = []
try:
for e in self.events[name]:
r += [e.call(name, self, args)]
except TypeError:
pass
return r
def event(plugin_type, args):
r = []
try:
for plugin in events.events[plugin_type]:
e = Plugin("events", plugin_type, plugin)
r += [e.call(plugin_type, None, args)]
except TypeError:
pass
return r
def detect_project():
"""
Detects the projects build steps and checks for step support
"""
# for plugin in steps.base.values():
# try:
# if plugin.Project.compatible():
# return plugin.Project()
# except:
# pass
project = Project()
# Run all detection steps
for plugin in steps.steps["detect"]:
if not Plugin("steps", "detect", plugin).call("detect", project):
return None
# if not steps.step("detect", plugin, project):
# Add required steps to project
for plugin_type in iter(steps.steps.keys()):
if plugin_type == "detect":
continue
for plugin in steps.steps[plugin_type]:
# if steps.compatible(plugin_type, plugin, project) & Support.MASK == Support.MASK:
plugin = Plugin("steps", plugin_type, plugin)
if plugin.call("compatible", project) == Support.MASK:
project.steps += [plugin]
project.events = {}
for plugin_type in iter(events.events.keys()):
project.events[plugin_type] = []
for plugin in events.events[plugin_type]:
plugin = Plugin("events", plugin_type, plugin)
if plugin.call("compatible", project) == Support.MASK:
project.events[plugin_type] += [plugin]
# check if project meets standards for a sgmake project
if is_project(project):
return project
# otherwise, no project detected
return None
# minimum requirements for a project
def is_project(project):
"""
Checks if a project meets the minimum step standards
"""
for step in project.steps:
if step.type in ("make", "package"): # at least one make or package step
return True
return False
def try_project(fn):
"""
Calls necessary detection methods on a potential project path
Parameter is an os.path
"""
# save previous dir so we can pop back into it
wdir = os.getcwd()
if fn.startswith(".") and fn != "." and fn != "..": # check if path is hidden
return 0
if not os.path.isdir(os.path.join(fn)):
return 0
if os.path.islink(fn):
return 0
# push new dir
os.chdir(fn)
project = detect_project()
listed = False
if project and not project.status == Status.UNSUPPORTED:
print("%s (%s)" % (project.name, os.path.relpath(os.getcwd(), wdir)))
listed = True
if Args.anywhere("list"):
os.chdir(wdir)
return 1 if listed else 0
if listed:
if project.complete():
os.chdir(wdir)
return 1
else:
os.chdir(wdir)
return -1
os.chdir(wdir)
return 0
def main():
Args.valid_options = [
"clean",
"list",
"debug",
"version",
"verbose",
"strict",
"warn",
"recursive",
"reversive",
"execute",
"x",
] # , "interactive", "cache"
Args.valid_keys = ["ignore"]
Args.process()
# process the build step plugins
try:
steps.ignore(Args.value("ignore").split(",")) # disable requested steps
except AttributeError:
pass
steps.process()
events.process()
if Args.option("version"):
splash()
return 0
if Args.option("help") or Args.option("?"):
help()
return 0
# count of projects succeeded and failed
success_count = 0
failed_count = 0
# if no project filenames are specified, we'll use the current directory (".")
if not Args.filenames:
Args.filenames = ["."]
# check for forward recusion and backward scan settings
recursive = Args.option("recursive")
reversive = True
# reversive = Args.option("reversive")
execute = Args.option("x") or Args.option("execute")
event("status", "start")
if recursive:
# TODO this recursion sucks, fix it later
# recurse through directories until you find project(s)
for fn in Args.filenames:
if fn.startswith(".") and fn != "." and fn != "..":
continue
r = 0
for root, dirs, files in os.walk(fn):
stop_recurse = False
for d in dirs:
base = os.path.basename(os.path.join(root, d))
if base.startswith(".") and base != ".":
continue
# print(os.path.normpath(os.path.join(root,d)))
r = try_project(os.path.normpath(os.path.join(root, d)))
if r == 1:
if not Args.option("list"):
success_count += 1
stop_recurse = True
elif r == -1:
if not Args.option("list"):
failed_count += 1
if stop_recurse:
dirs[:] = []
elif reversive:
# TODO search for project by iterating dirs backwards
# To be used build a sgmake project from within a nested directory or source editor
for fn in Args.filenames:
path = os.path.abspath(os.path.join(os.getcwd(), fn))
while os.path.realpath(path) != os.path.expanduser("~"):
# while os.path.realpath(path) != os.path.realpath(os.path.join(path, "..")): # is root
r = try_project(os.path.normpath(path))
if r == 1:
if not Args.option("list"):
success_count += 1
break
elif r == -1:
if not Args.option("list"):
failed_count += 1
break
path = os.path.realpath(os.path.join(path, ".."))
# print("done: %s" % path)
# else:
# # try to build projects specified by the user, current dir is default
# for fn in Args.filenames:
# r = try_project(os.path.join(os.getcwd(),fn))
# if r == 1:
# success_count += 1
# elif r == -1:
# failed_count += 1
if not Args.command("list"):
# if not in list-only mode, display final status of built projects
if success_count:
print("%s project(s) completed." % success_count)
if not failed_count:
event("status", "success")
return 0
else:
return 1
if failed_count:
print("%s project(s) failed." % failed_count)
event("status", "failure")
return 1
elif not success_count and not failed_count:
event("status", "nothing")
print("Nothing to be done.")
return 1
return 0
if __name__ == "__main__":
exit(main())