Esempio n. 1
0
def main(argv):
    parser = GetParser()
    opts = parser.parse_args(argv)

    # A cache of gerrit helpers we'll load on demand.
    opts.gerrit = {}

    # Convert user friendly command line option into a gerrit parameter.
    opts.notify = 'ALL' if opts.send_email else 'NONE'
    opts.Freeze()

    # pylint: disable=global-statement
    global COLOR
    COLOR = terminal.Color(enabled=opts.color)

    # Now look up the requested user action and run it.
    functor = globals().get(ACTION_PREFIX + opts.action.capitalize())
    if functor:
        argspec = inspect.getargspec(functor)
        if argspec.varargs:
            arg_min = getattr(functor, 'arg_min', len(argspec.args))
            if len(opts.args) < arg_min:
                parser.error(
                    'incorrect number of args: %s expects at least %s' %
                    (opts.action, arg_min))
        elif len(argspec.args) - 1 != len(opts.args):
            parser.error('incorrect number of args: %s expects %s' %
                         (opts.action, len(argspec.args) - 1))
        try:
            functor(opts, *opts.args)
        except (cros_build_lib.RunCommandError, gerrit.GerritException,
                gob_util.GOBError) as e:
            cros_build_lib.Die(e)
    else:
        parser.error('unknown action: %s' % (opts.action, ))
Esempio n. 2
0
def main(argv):
    parser = GetParser()
    options = parser.parse_args(argv)
    options.Freeze()

    if options.command == 'list-all':
        board_to_packages = workon_helper.ListAllWorkedOnAtoms()
        color = terminal.Color()
        for board in sorted(board_to_packages):
            print(color.Start(color.GREEN) + board + ':' + color.Stop())
            for package in board_to_packages[board]:
                print('    ' + package)
            print('')
        return 0

    # TODO(wiley): Assert that we're not running as root.
    cros_build_lib.AssertInsideChroot()

    if options.host:
        friendly_name = 'host'
        sysroot = '/'
    elif options.board:
        friendly_name = options.board
        sysroot = cros_build_lib.GetSysroot(board=options.board)
    else:
        cros_build_lib.Die('You must specify either --host, --board')

    helper = workon_helper.WorkonHelper(sysroot, friendly_name)
    try:
        if options.command == 'start':
            helper.StartWorkingOnPackages(options.packages,
                                          use_all=options.all,
                                          use_workon_only=options.workon_only)
        elif options.command == 'stop':
            helper.StopWorkingOnPackages(options.packages,
                                         use_all=options.all,
                                         use_workon_only=options.workon_only)
        elif options.command == 'info':
            triples = helper.GetPackageInfo(
                options.packages,
                use_all=options.all,
                use_workon_only=options.workon_only)
            for package, repos, paths in triples:
                print(package, ','.join(repos), ','.join(paths))
        elif options.command == 'list':
            packages = helper.ListAtoms(use_all=options.all,
                                        use_workon_only=options.workon_only)
            if packages:
                print('\n'.join(packages))
        elif options.command == 'iterate':
            helper.RunCommandInPackages(options.packages,
                                        options.iterate_command,
                                        use_all=options.all,
                                        use_workon_only=options.workon_only)
    except workon_helper.WorkonError as e:
        cros_build_lib.Die(e)

    return 0
Esempio n. 3
0
    def __init__(self, *args, **kwargs):
        """Initializes the formatter.

    Args:
      args: See logging.Formatter for specifics.
      kwargs: See logging.Formatter for specifics.
      enable_color: Whether to enable colored logging. Defaults
        to None, where terminal.Color will set to a sane default.
    """
        self.color = terminal.Color(enabled=kwargs.pop('enable_color', None))
        super(ColoredFormatter, self).__init__(*args, **kwargs)
Esempio n. 4
0
  def __init__(self, verbose=WARNING, stdout=sys.stdout):
    """Initialize a new output object.

    Args:
      verbose: Verbosity level (0-4).
      stdout: File to use for stdout.
    """
    self.verbose = verbose
    self._progress = ''          # Our last progress message
    self._color = terminal.Color()
    self._stdout = stdout

    # TODO(sjg): Move this into Chromite libraries when we have them
    self.stdout_is_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
Esempio n. 5
0
def main(argv):
    shared = commandline.SharedParser()
    shared.add_argument('--board',
                        default=cros_build_lib.GetDefaultBoard(),
                        help='The board to set package keywords for.')
    shared.add_argument('--host',
                        default=False,
                        action='store_true',
                        help='Uses the host instead of board')
    shared.add_argument('--remote',
                        default='',
                        help='For non-workon projects, the git remote to use.')
    shared.add_argument('--revision',
                        default='',
                        help='Use to override the manifest defined default '
                        'revision used for a project')
    shared.add_argument('--command',
                        default='git status',
                        dest='iterate_command',
                        help='The command to be run by forall.')
    shared.add_argument(
        '--workon_only',
        default=False,
        action='store_true',
        help='Apply to packages that have a workon ebuild only')
    shared.add_argument('--all',
                        default=False,
                        action='store_true',
                        help='Apply to all possible packages for the '
                        'given command (overrides workon_only)')

    parser = commandline.ArgumentParser(description=__doc__,
                                        parents=[
                                            shared,
                                        ])

    # Add the shared 'packages' argument after creating the main parser so that
    # it is only bound/shared with the subcommands and doesn't confuse argparse.
    shared.add_argument('packages',
                        nargs='*',
                        help='The packages to run command against.')

    commands = [
        ('start', 'Moves an ebuild to live (intended to support development)'),
        ('stop', 'Moves an ebuild to stable (use last known good)'),
        ('info', 'Print package name, repo name, and source directory.'),
        ('list', 'List of live ebuilds (workon ebuilds if --all)'),
        ('list-all', 'List all of the live ebuilds for all setup boards'),
        ('iterate', 'For each ebuild, cd to the source dir and run a command'),
    ]
    command_parsers = parser.add_subparsers(dest='command', title='commands')
    for command, description in commands:
        command_parsers.add_parser(command,
                                   parents=(shared, ),
                                   help=description,
                                   description=description)

    options = parser.parse_args(argv)
    options.Freeze()

    if options.command == 'list-all':
        board_to_packages = workon_helper.ListAllWorkedOnAtoms()
        color = terminal.Color()
        for board in sorted(board_to_packages):
            print(color.Start(color.GREEN) + board + ':' + color.Stop())
            for package in board_to_packages[board]:
                print('    ' + package)
            print('')
        return 0

    # TODO(wiley): Assert that we're not running as root.
    cros_build_lib.AssertInsideChroot()

    if options.host:
        friendly_name = 'host'
        sysroot = '/'
    elif options.board:
        friendly_name = options.board
        sysroot = cros_build_lib.GetSysroot(board=options.board)
    else:
        cros_build_lib.Die('You must specify either --host, --board')

    helper = workon_helper.WorkonHelper(sysroot, friendly_name)
    try:
        if options.command == 'start':
            helper.StartWorkingOnPackages(options.packages,
                                          use_all=options.all,
                                          use_workon_only=options.workon_only)
        elif options.command == 'stop':
            helper.StopWorkingOnPackages(options.packages,
                                         use_all=options.all,
                                         use_workon_only=options.workon_only)
        elif options.command == 'info':
            triples = helper.GetPackageInfo(
                options.packages,
                use_all=options.all,
                use_workon_only=options.workon_only)
            for package, repos, paths in triples:
                print(package, ','.join(repos), ','.join(paths))
        elif options.command == 'list':
            packages = helper.ListAtoms(use_all=options.all,
                                        use_workon_only=options.workon_only)
            if packages:
                print('\n'.join(packages))
        elif options.command == 'iterate':
            helper.RunCommandInPackages(options.packages,
                                        options.iterate_command,
                                        use_all=options.all,
                                        use_workon_only=options.workon_only)
    except workon_helper.WorkonError as e:
        cros_build_lib.Die(e.message)

    return 0
Esempio n. 6
0
def main(argv):
    # Locate actions that are exposed to the user.  All functions that start
    # with "UserAct" are fair game.
    act_pfx = 'UserAct'
    actions = [x for x in globals() if x.startswith(act_pfx)]

    usage = """%(prog)s [options] <action> [action args]

There is no support for doing line-by-line code review via the command line.
This helps you manage various bits and CL status.

For general Gerrit documentation, see:
  https://gerrit-review.googlesource.com/Documentation/
The Searching Changes page covers the search query syntax:
  https://gerrit-review.googlesource.com/Documentation/user-search.html

Example:
  $ gerrit todo             # List all the CLs that await your review.
  $ gerrit mine             # List all of your open CLs.
  $ gerrit inspect 28123    # Inspect CL 28123 on the public gerrit.
  $ gerrit inspect *28123   # Inspect CL 28123 on the internal gerrit.
  $ gerrit verify 28123 1   # Mark CL 28123 as verified (+1).
Scripting:
  $ gerrit ready `gerrit --raw mine` 1      # Mark *ALL* of your public CLs \
ready.
  $ gerrit ready `gerrit --raw -i mine` 1   # Mark *ALL* of your internal CLs \
ready.

Actions:"""
    indent = max([len(x) - len(act_pfx) for x in actions])
    for a in sorted(actions):
        cmd = a[len(act_pfx):]
        # Sanity check for devs adding new commands.  Should be quick.
        if cmd != cmd.lower().capitalize():
            raise RuntimeError('callback "%s" is misnamed; should be "%s"' %
                               (cmd, cmd.lower().capitalize()))
        usage += '\n  %-*s: %s' % (indent, cmd.lower(), globals()[a].__doc__)

    parser = commandline.ArgumentParser(usage=usage)
    parser.add_argument('-i',
                        '--internal',
                        dest='gob',
                        action='store_const',
                        default=site_config.params.EXTERNAL_GOB_INSTANCE,
                        const=site_config.params.INTERNAL_GOB_INSTANCE,
                        help='Query internal Chromium Gerrit instance')
    parser.add_argument(
        '-g',
        '--gob',
        default=site_config.params.EXTERNAL_GOB_INSTANCE,
        help=('Gerrit (on borg) instance to query (default: %s)' %
              (site_config.params.EXTERNAL_GOB_INSTANCE)))
    parser.add_argument('--sort',
                        default='number',
                        help='Key to sort on (number, project)')
    parser.add_argument('--raw',
                        default=False,
                        action='store_true',
                        help='Return raw results (suitable for scripting)')
    parser.add_argument(
        '-n',
        '--dry-run',
        default=False,
        action='store_true',
        dest='dryrun',
        help='Show what would be done, but do not make changes')
    parser.add_argument('-v',
                        '--verbose',
                        default=False,
                        action='store_true',
                        help='Be more verbose in output')
    parser.add_argument('-b',
                        '--branch',
                        help='Limit output to the specific branch')
    parser.add_argument('--draft',
                        default=False,
                        action='store_true',
                        help="Show draft changes (applicable to 'mine' only)")
    parser.add_argument('-p',
                        '--project',
                        help='Limit output to the specific project')
    parser.add_argument('-t',
                        '--topic',
                        help='Limit output to the specific topic')
    parser.add_argument('args', nargs='+')
    opts = parser.parse_args(argv)

    # A cache of gerrit helpers we'll load on demand.
    opts.gerrit = {}
    opts.Freeze()

    # pylint: disable=W0603
    global COLOR
    COLOR = terminal.Color(enabled=opts.color)

    # Now look up the requested user action and run it.
    cmd = opts.args[0].lower()
    args = opts.args[1:]
    functor = globals().get(act_pfx + cmd.capitalize())
    if functor:
        argspec = inspect.getargspec(functor)
        if argspec.varargs:
            arg_min = getattr(functor, 'arg_min', len(argspec.args))
            if len(args) < arg_min:
                parser.error(
                    'incorrect number of args: %s expects at least %s' %
                    (cmd, arg_min))
        elif len(argspec.args) - 1 != len(args):
            parser.error('incorrect number of args: %s expects %s' %
                         (cmd, len(argspec.args) - 1))
        try:
            functor(opts, *args)
        except (cros_build_lib.RunCommandError, gerrit.GerritException,
                gob_util.GOBError) as e:
            cros_build_lib.Die(e.message)
    else:
        parser.error('unknown action: %s' % (cmd, ))
Esempio n. 7
0
def main(argv):
  # Locate actions that are exposed to the user.  All functions that start
  # with "UserAct" are fair game.
  act_pfx = 'UserAct'
  actions = [x for x in globals() if x.startswith(act_pfx)]

  usage = """%prog [options] <action> [action args]

There is no support for doing line-by-line code review via the command line.
This helps you manage various bits and CL status.

Example:
  $ gerrit todo             # List all the CLs that await your review.
  $ gerrit mine             # List all of your open CLs.
  $ gerrit inspect 28123    # Inspect CL 28123 on the public gerrit.
  $ gerrit inspect *28123   # Inspect CL 28123 on the internal gerrit.
  $ gerrit verify 28123 1   # Mark CL 28123 as verified (+1).

Actions:"""
  indent = max([len(x) - len(act_pfx) for x in actions])
  for a in sorted(actions):
    usage += '\n  %-*s: %s' % (indent, a[len(act_pfx):].lower(),
                               globals()[a].__doc__)

  parser = commandline.OptionParser(usage=usage)
  parser.add_option('-i', '--internal', default=None, action='store_true',
                    help='Query gerrit-int')
  parser.add_option('-e', '--external', dest='internal', action='store_false',
                    help='Query gerrit (default)')
  parser.add_option('--sort', default='number', help='Key to sort on '
                                                     '(number, project)')
  parser.add_option('-v', '--verbose', default=False, action='store_true',
                    help='Be more verbose in output')
  opts, args = parser.parse_args(argv)
  if not args:
    parser.error('missing action')

  # pylint: disable=W0603
  global COLOR
  COLOR = terminal.Color(enabled=opts.color)

  # TODO: This sucks.  We assume that all actions which take an argument are
  # a CL #.  Or at least, there's no other reason for it to start with a *.
  # We do this to automatically select internal vs external gerrit as this
  # convention is encoded in much of our system.  However, the rest of this
  # script doesn't expect (or want) the leading *.
  if len(args) > 1:
    if args[1][0] == '*':
      if opts.internal is None:
        opts.internal = True
      args[1] = args[1][1:]

  opts.gerrit = gerrit.GetGerritHelper(
      constants.INTERNAL_REMOTE if opts.internal else constants.EXTERNAL_REMOTE,
      print_cmd=opts.debug)

  # Now look up the requested user action and run it.
  cmd = args[0].lower()
  args = args[1:]
  functor = globals().get(act_pfx + cmd.capitalize())
  if functor:
    argspec = inspect.getargspec(functor)
    if argspec.varargs:
      if len(args) < len(argspec.args):
        parser.error('incorrect number of args: %s expects at least %s' %
                     (cmd, len(argspec.args)))
    elif len(argspec.args) - 1 != len(args):
      parser.error('incorrect number of args: %s expects %s' %
                   (cmd, len(argspec.args) - 1))
    try:
      functor(opts, *args)
    except (cros_build_lib.RunCommandError, gerrit.GerritException) as e:
      cros_build_lib.Die(e.message)
  else:
    parser.error('unknown action: %s' % (cmd,))
    def Run(self):
        if self.options.build_target_name:
            self.options.build_target = build_target_lib.BuildTarget(
                self.options.build_target_name)
        else:
            self.options.build_target = None

        self.options.Freeze()

        has_target = self.options.host or self.options.build_target
        needs_target = self.options.action != 'list-all'
        if needs_target and not has_target:
            cros_build_lib.Die(
                f'{self.options.action} requires a build target or '
                'specifying the host.')

        commandline.RunInsideChroot(self)

        if self.options.action == 'list-all':
            build_target_to_packages = workon_helper.ListAllWorkedOnAtoms()
            color = terminal.Color()
            for build_target_name in sorted(build_target_to_packages):
                print(
                    color.Start(color.GREEN) + build_target_name + ':' +
                    color.Stop())
                for package in build_target_to_packages[build_target_name]:
                    print('    ' + package)
                print('')
            return 0

        if self.options.build_target:
            target = self.options.build_target.name
            sysroot = self.options.build_target.root
        else:
            target = 'host'
            sysroot = '/'

        helper = workon_helper.WorkonHelper(sysroot, target)
        try:
            if self.options.action == 'start':
                helper.StartWorkingOnPackages(
                    self.options.packages,
                    use_all=self.options.all,
                    use_workon_only=self.options.workon_only)
            elif self.options.action == 'stop':
                helper.StopWorkingOnPackages(
                    self.options.packages,
                    use_all=self.options.all,
                    use_workon_only=self.options.workon_only)
            elif self.options.action == 'info':
                triples = helper.GetPackageInfo(
                    self.options.packages,
                    use_all=self.options.all,
                    use_workon_only=self.options.workon_only)
                for package, repos, paths in triples:
                    print(package, ','.join(repos), ','.join(paths))
            elif self.options.action == 'list':
                packages = helper.ListAtoms(
                    use_all=self.options.all,
                    use_workon_only=self.options.workon_only)
                if packages:
                    print('\n'.join(packages))
            elif self.options.action == 'iterate':
                helper.RunCommandInPackages(
                    self.options.packages,
                    self.options.iterate_command,
                    use_all=self.options.all,
                    use_workon_only=self.options.workon_only)
            else:
                cros_build_lib.Die(
                    f'No implementation for {self.options.action}')
        except workon_helper.WorkonError as e:
            cros_build_lib.Die(e)
        return 0
Esempio n. 9
0
Internal Note:
To expose a function directly to the command line interface, name your function
with the prefix "UserAct".
"""

import inspect
import os

from chromite.buildbot import constants
from chromite.lib import commandline
from chromite.lib import cros_build_lib
from chromite.lib import gerrit
from chromite.lib import terminal

COLOR = terminal.Color()

# Map the internal names to the ones we normally show on the web ui.
GERRIT_APPROVAL_MAP = {
    'COMR': [
        'CQ',
        'Commit Queue',
    ],
    'CRVW': [
        'CR',
        'Code Review ',
    ],
    'SUBM': [
        'S ',
        'Submitted   ',
    ],