-
Notifications
You must be signed in to change notification settings - Fork 249
/
cli.py
433 lines (341 loc) · 15.7 KB
/
cli.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2015 PyBuilder Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The PyBuilder cli module.
Contains the PyBuilder command-line entrypoint.
"""
import datetime
import optparse
import re
import sys
import traceback
from pybuilder import __version__
from pybuilder.core import Logger
from pybuilder.errors import PyBuilderException
from pybuilder.execution import ExecutionManager
from pybuilder.reactor import Reactor
from pybuilder.scaffolding import start_project, update_project
from pybuilder.terminal import (BOLD, BROWN, RED, GREEN, bold, styled_text,
fg, italic, print_text, print_text_line,
print_error, print_error_line, draw_line)
from pybuilder.utils import format_timestamp, get_dist_version_string
PROPERTY_OVERRIDE_PATTERN = re.compile(r'^[a-zA-Z0-9_]+=.*')
class CommandLineUsageException(PyBuilderException):
def __init__(self, usage, message):
super(CommandLineUsageException, self).__init__(message)
self.usage = usage
class StdOutLogger(Logger):
def _level_to_string(self, level):
if Logger.DEBUG == level:
return "[DEBUG]"
if Logger.INFO == level:
return "[INFO] "
if Logger.WARN == level:
return "[WARN] "
return "[ERROR]"
def _do_log(self, level, message, *arguments):
formatted_message = self._format_message(message, *arguments)
log_level = self._level_to_string(level)
print_text_line("{0} {1}".format(log_level, formatted_message))
class ColoredStdOutLogger(StdOutLogger):
def _level_to_string(self, level):
if Logger.DEBUG == level:
return italic("[DEBUG]")
if Logger.INFO == level:
return bold("[INFO] ")
if Logger.WARN == level:
return styled_text("[WARN] ", BOLD, fg(BROWN))
return styled_text("[ERROR]", BOLD, fg(RED))
def parse_options(args):
parser = optparse.OptionParser(usage="%prog [options] [+|^]task1 [[[+|^]task2] ...]",
version="%prog " + __version__)
def error(msg):
raise CommandLineUsageException(
parser.get_usage() + parser.format_option_help(), msg)
parser.error = error
list_tasks_option = parser.add_option("-t", "--list-tasks",
action="store_true",
dest="list_tasks",
default=False,
help="List tasks")
list_plan_tasks_option = parser.add_option("-T", "--list-plan-tasks",
action="store_true",
dest="list_plan_tasks",
default=False,
help="List execution plan tasks")
start_project_option = parser.add_option("--start-project",
action="store_true",
dest="start_project",
default=False,
help="Initialize build descriptors and python project structure")
update_project_option = parser.add_option("--update-project",
action="store_true",
dest="update_project",
default=False,
help="Update build descriptors and python project structure")
parser.add_option("-v", "--verbose",
action="store_true",
dest="verbose",
default=False,
help="Enable verbose output")
project_group = optparse.OptionGroup(
parser, "Project Options", "Customizes the project to build.")
project_group.add_option("-D", "--project-directory",
dest="project_directory",
help="Root directory to execute in",
metavar="<project directory>",
default=".")
project_group.add_option("-E", "--environment",
dest="environments",
help="Activate the given environment for this build. Can be used multiple times",
metavar="<environment>",
action="append",
default=[])
project_group.add_option("-P",
action="append",
dest="property_overrides",
default=[],
metavar="<property>=<value>",
help="Set/ override a property value")
project_group.add_option("-x", "--exclude",
action="append",
dest="exclude_optional_tasks",
default=[],
metavar="<task>",
help="Exclude optional task dependencies")
project_group.add_option("-o", "--exclude-all-optional",
action="store_true",
dest="exclude_all_optional",
default=False,
help="Exclude all optional task dependencies")
project_group.add_option("--force-exclude",
action="append",
dest="exclude_tasks",
default=[],
metavar="<task>",
help="Exclude any task dependencies "
"(dangerous, may break the build in unexpected ways)")
parser.add_option_group(project_group)
output_group = optparse.OptionGroup(
parser, "Output Options", "Modifies the messages printed during a build.")
output_group.add_option("-X", "--debug",
action="store_true",
dest="debug",
default=False,
help="Print debug messages")
output_group.add_option("-q", "--quiet",
action="store_true",
dest="quiet",
default=False,
help="Quiet mode; print only warnings and errors")
output_group.add_option("-Q", "--very-quiet",
action="store_true",
dest="very_quiet",
default=False,
help="Very quiet mode; print only errors")
output_group.add_option("-c", "--color",
action="store_true",
dest="force_color",
default=False,
help="Force colored output")
output_group.add_option("-C", "--no-color",
action="store_true",
dest="no_color",
default=False,
help="Disable colored output")
parser.add_option_group(output_group)
options, arguments = parser.parse_args(args=list(args))
if options.list_tasks and options.list_plan_tasks:
parser.error("%s and %s are mutually exclusive" % (list_tasks_option, list_plan_tasks_option))
if options.start_project and options.update_project:
parser.error("%s and %s are mutually exclusive" % (start_project_option, update_project_option))
property_overrides = {}
for pair in options.property_overrides:
if not PROPERTY_OVERRIDE_PATTERN.match(pair):
parser.error("%s is not a property definition." % pair)
key, val = pair.split("=")
property_overrides[key] = val
options.property_overrides = property_overrides
if options.very_quiet:
options.quiet = True
return options, arguments
def init_reactor(logger):
execution_manager = ExecutionManager(logger)
reactor = Reactor(logger, execution_manager)
return reactor
def should_colorize(options):
return options.force_color or (sys.stdout.isatty() and not options.no_color)
def init_logger(options):
threshold = Logger.INFO
if options.debug:
threshold = Logger.DEBUG
elif options.quiet:
threshold = Logger.WARN
if not should_colorize(options):
logger = StdOutLogger(threshold)
else:
logger = ColoredStdOutLogger(threshold)
return logger
def print_build_summary(options, summary):
print_text_line("Build Summary")
print_text_line("%20s: %s" % ("Project", summary.project.name))
print_text_line("%20s: %s%s" % ("Version", summary.project.version, get_dist_version_string(summary.project)))
print_text_line("%20s: %s" % ("Base directory", summary.project.basedir))
print_text_line("%20s: %s" %
("Environments", ", ".join(options.environments)))
task_summary = ""
for task in summary.task_summaries:
task_summary += " %s [%d ms]" % (task.task, task.execution_time)
print_text_line("%20s:%s" % ("Tasks", task_summary))
def print_styled_text(text, options, *style_attributes):
if should_colorize(options):
add_trailing_nl = False
if text[-1] == '\n':
text = text[:-1]
add_trailing_nl = True
text = styled_text(text, *style_attributes)
if add_trailing_nl:
text += '\n'
print_text(text)
def print_styled_text_line(text, options, *style_attributes):
print_styled_text(text + "\n", options, *style_attributes)
def print_build_status(failure_message, options, successful):
draw_line()
if successful:
print_styled_text_line("BUILD SUCCESSFUL", options, BOLD, fg(GREEN))
else:
print_styled_text_line(
"BUILD FAILED - {0}".format(failure_message), options, BOLD, fg(RED))
draw_line()
def print_elapsed_time_summary(start, end):
time_needed = end - start
millis = ((time_needed.days * 24 * 60 * 60) + time_needed.seconds) * 1000 + time_needed.microseconds / 1000
print_text_line("Build finished at %s" % format_timestamp(end))
print_text_line("Build took %d seconds (%d ms)" %
(time_needed.seconds, millis))
def print_summary(successful, summary, start, end, options, failure_message):
print_build_status(failure_message, options, successful)
if successful and summary:
print_build_summary(options, summary)
print_elapsed_time_summary(start, end)
def length_of_longest_string(list_of_strings):
if len(list_of_strings) == 0:
return 0
result = 0
for string in list_of_strings:
length_of_string = len(string)
if length_of_string > result:
result = length_of_string
return result
def task_description(task):
return " ".join(task.description) or "<no description available>"
def print_task_list(tasks, quiet=False):
if quiet:
print_text_line("\n".join([task.name + ":" + task_description(task)
for task in tasks]))
return
column_length = length_of_longest_string(
list(map(lambda task: task.name, tasks)))
column_length += 4
for task in tasks:
task_name = task.name.rjust(column_length)
print_text_line("{0} - {1}".format(task_name, task_description(task)))
if task.dependencies:
whitespace = (column_length + 3) * " "
depends_on_message = "depends on tasks: %s" % " ".join(
[str(dependency) for dependency in task.dependencies])
print_text_line(whitespace + depends_on_message)
def print_list_of_tasks(reactor, quiet=False):
tasks = reactor.get_tasks()
sorted_tasks = sorted(tasks)
if not quiet:
print_text_line('Tasks found for project "%s":' % reactor.project.name)
print_task_list(sorted_tasks, quiet)
def print_plan_list_of_tasks(options, arguments, reactor, quiet=False):
execution_plan = reactor.create_execution_plan(arguments, options.environments)
if not quiet:
print_text_line('Tasks that will be executed for project "%s":' % reactor.project.name)
print_task_list(execution_plan, quiet)
def main(*args):
if not args:
args = sys.argv[1:]
try:
options, arguments = parse_options(args)
except CommandLineUsageException as e:
print_error_line("Usage error: %s\n" % e)
print_error(e.usage)
return 1
start = datetime.datetime.now()
logger = init_logger(options)
reactor = init_reactor(logger)
if options.start_project:
return start_project()
if options.update_project:
return update_project()
if options.list_tasks or options.list_plan_tasks:
try:
reactor.prepare_build(property_overrides=options.property_overrides,
project_directory=options.project_directory,
exclude_optional_tasks=options.exclude_optional_tasks,
exclude_tasks=options.exclude_tasks,
exclude_all_optional=options.exclude_all_optional
)
if options.list_tasks:
print_list_of_tasks(reactor, quiet=options.very_quiet)
if options.list_plan_tasks:
print_plan_list_of_tasks(options, arguments, reactor, quiet=options.very_quiet)
return 0
except PyBuilderException as e:
print_build_status(str(e), options, successful=False)
return 1
if not options.very_quiet:
print_styled_text_line(
"PyBuilder version {0}".format(__version__), options, BOLD)
print_text_line("Build started at %s" % format_timestamp(start))
draw_line()
successful = True
failure_message = None
summary = None
try:
try:
reactor.prepare_build(property_overrides=options.property_overrides,
project_directory=options.project_directory,
exclude_optional_tasks=options.exclude_optional_tasks,
exclude_tasks=options.exclude_tasks,
exclude_all_optional=options.exclude_all_optional
)
if options.verbose or options.debug:
logger.debug("Verbose output enabled.\n")
reactor.project.set_property("verbose", True)
summary = reactor.build(
environments=options.environments, tasks=arguments)
except KeyboardInterrupt:
raise PyBuilderException("Build aborted")
except (Exception, SystemExit) as e:
successful = False
failure_message = str(e)
if options.debug:
traceback.print_exc(file=sys.stderr)
finally:
end = datetime.datetime.now()
if not options.very_quiet:
print_summary(
successful, summary, start, end, options, failure_message)
if not successful:
return 1
return 0