Beispiel #1
0
def _ImportCommands():
    """Directly imports all subcommand python modules.

  This method imports the modules which may contain subcommands. When
  these modules are loaded, declared commands (those that use
  CommandDecorator) will automatically get added to |_commands|.
  """
    for file_path in _FindModules(_SUBCOMMAND_MODULE_DIRECTORY):
        module_path = os.path.splitext(file_path)[0]
        import_path = os.path.relpath(os.path.realpath(module_path),
                                      os.path.dirname(constants.CHROMITE_DIR))
        cros_import.ImportModule(import_path.split(os.path.sep))
Beispiel #2
0
def GetBuilderClass(name):
  """Locate the builder class with |name|.

  Examples:
    If you want to create a new SimpleBuilder, you'd do:
    cls = builders.GetBuilderClass('simple_builders.SimpleBuilder')
    builder = cls(...)

    If you want a site specific builder class, do:
    cls = builders.GetBuilderClass('config.my_builders.MyBuilder')
    builder = cls(...)

  Args:
    name: The base name of the builder class.

  Returns:
    The class used to instantiate this type of builder.

  Raises:
    AttributeError when |name| could not be found.
  """
  if '.' not in name:
    raise ValueError('name should be "<module>.<builder>" not "%s"' % name)

  name_parts = name.split('.')

  # Last part is the class name.
  builder_class_name = name_parts.pop()

  if name_parts[0] == 'config':
    # config means pull from the site specific config.
    # config.my_builders -> chromite.config.my_builders
    name_parts = ['chromite'] + name_parts
  else:
    # Otherwise pull from chromite.
    # simple_builders -> chromite.cbuidlbot.builders.simple_builders
    name_parts = ['chromite', 'cbuildbot', 'builders'] + name_parts

  target = '.'.join(name_parts)
  module = cros_import.ImportModule(target)

  # See if this module has the builder we care about.
  if hasattr(module, builder_class_name):
    return getattr(module, builder_class_name)

  raise AttributeError('could not locate %s builder' % builder_class_name)
Beispiel #3
0
def ImportCommand(name):
    """Directly import the specified subcommand.

  This method imports the module which must contain the single subcommand.  When
  the module is loaded, the declared command (those that use CommandDecorator)
  will automatically get added to |_commands|.

  Args:
    name: The subcommand to load.

  Returns:
    A reference to the subcommand class.
  """
    module_path = os.path.join(_SUBCOMMAND_MODULE_DIRECTORY,
                               'cros_%s' % (name.replace('-', '_'), ))
    import_path = os.path.relpath(os.path.realpath(module_path),
                                  os.path.dirname(constants.CHROMITE_DIR))
    cros_import.ImportModule(import_path.split(os.path.sep))
    return _commands[name]
Beispiel #4
0
 def _testImportModule(self, target):
     """Verify we can import |target| successfully."""
     module = cros_import.ImportModule(target)
     self.assertTrue(hasattr(module, 'ImportModule'))
Beispiel #5
0
def FindTarget(target):
    """Turn the path into something we can import from the chromite tree.

  This supports a variety of ways of running chromite programs:
  # Loaded via depot_tools in $PATH.
  $ cros_sdk --help
  # Loaded via .../chromite/bin in $PATH.
  $ cros --help
  # No $PATH needed.
  $ ./bin/cros --help
  # Loaded via ~/bin in $PATH to chromite bin/ subdir.
  $ ln -s $PWD/bin/cros ~/bin; cros --help
  # No $PATH needed.
  $ ./cbuildbot/cbuildbot --help
  # No $PATH needed, but symlink inside of chromite dir.
  $ ln -s ./cbuildbot/cbuildbot; ./cbuildbot --help
  # Loaded via ~/bin in $PATH to non-chromite bin/ subdir.
  $ ln -s $PWD/cbuildbot/cbuildbot ~/bin/; cbuildbot --help
  # No $PATH needed, but a relative symlink to a symlink to the chromite dir.
  $ cd ~; ln -s bin/cbuildbot ./; ./cbuildbot --help
  # External chromite module
  $ ln -s ../chromite/scripts/wrapper.py foo; ./foo

  Args:
    target: Path to the script we're trying to run.

  Returns:
    The module main functor.
  """
    # We assume/require the script we're wrapping ends in a .py.
    full_path = target + '.py'
    while True:
        # Walk back one symlink at a time until we get into the chromite dir.
        parent, base = os.path.split(target)
        parent = os.path.realpath(parent)
        if parent.startswith(CHROMITE_PATH):
            target = base
            break
        target = os.path.join(os.path.dirname(target), os.readlink(target))

    # If we walked all the way back to wrapper.py, it means we're trying to run
    # an external module.  So we have to import it by filepath and not via the
    # chromite.xxx.yyy namespace.
    if target != 'wrapper.py':
        assert parent.startswith(CHROMITE_PATH), (
            'could not figure out leading path\n'
            '\tparent: %s\n'
            '\tCHROMITE_PATH: %s' % (parent, CHROMITE_PATH))
        parent = parent[len(CHROMITE_PATH):].split(os.sep)
        target = ['chromite'] + parent + [target]

        if target[-2] == 'bin':
            # Convert <path>/bin/foo -> <path>/scripts/foo.
            target[-2] = 'scripts'
        elif target[1] == 'bootstrap' and len(target) == 3:
            # Convert <git_repo>/bootstrap/foo -> <git_repo>/bootstrap/scripts/foo.
            target.insert(2, 'scripts')

        try:
            module = cros_import.ImportModule(target)
        except ImportError as e:
            print('%s: could not import chromite module: %s: %s' %
                  (sys.argv[0], full_path, e),
                  file=sys.stderr)
            sys.exit(1)
    else:
        try:
            module = imp.load_source('main', full_path)
        except IOError as e:
            print('%s: could not import external module: %s: %s' %
                  (sys.argv[0], full_path, e),
                  file=sys.stderr)
            sys.exit(1)

    # Run the module's main func if it has one.
    main = getattr(module, 'main', None)
    if main:
        return main

    # Is this a unittest?
    if target[-1].rsplit('_', 1)[-1] in ('test', 'unittest'):
        from chromite.lib import cros_test_lib
        return lambda _argv: cros_test_lib.main(module=module)