Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / chromite / scripts / cros.py
1 # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 """This implements the metacommand cros.
6
7 This script is normally invoked via depot_tools/cros which discovers
8 where chromite is located and invokes this script.
9
10 In turn, this script looks for a subcommand based on how it was invoked. For
11 example: cros lint.
12
13 See cros/command/cros_XXX.py for actual command implementations.
14 """
15
16 from __future__ import print_function
17
18 import sys
19
20 from chromite.cros import commands
21 from chromite.lib import commandline
22 from chromite.lib import stats
23
24
25 def GetOptions(my_commands):
26   """Returns the argparse to use for Cros."""
27   parser = commandline.ArgumentParser(caching=True)
28   if not commands:
29     return parser
30
31   subparsers = parser.add_subparsers(title='cros commands')
32   for cmd_name, class_def in sorted(my_commands.iteritems(), key=lambda x:x[0]):
33     epilog = getattr(class_def, 'EPILOG', None)
34     sub_parser = subparsers.add_parser(
35         cmd_name, description=class_def.__doc__, epilog=epilog,
36         caching=class_def.use_caching_options,
37         formatter_class=commandline.argparse.RawDescriptionHelpFormatter)
38     class_def.AddParser(sub_parser)
39
40   return parser
41
42
43 def _RunSubCommand(subcommand):
44   """Helper function for testing purposes."""
45   return subcommand.Run()
46
47
48 def main(argv):
49   parser = GetOptions(commands.ListCommands())
50   # Cros currently does nothing without a subcmd. Print help if no args are
51   # specified.
52   if not argv:
53     parser.print_help()
54     return 1
55
56   namespace = parser.parse_args(argv)
57   subcommand = namespace.cros_class(namespace)
58   with stats.UploadContext() as queue:
59     if subcommand.upload_stats:
60       cmd_base = subcommand.options.cros_class.command_name
61       cmd_stats = stats.Stats.SafeInit(cmd_line=sys.argv, cmd_base=cmd_base)
62       if cmd_stats:
63         queue.put([cmd_stats, stats.StatsUploader.URL,
64                    subcommand.upload_stats_timeout])
65     # TODO: to make command completion faster, send an interrupt signal to the
66     # stats uploader task after the subcommand completes.
67     code = _RunSubCommand(subcommand)
68     if code is not None:
69       return code
70
71   return 0