コード例 #1
0
ファイル: gclient_scm.py プロジェクト: mlkt/depot_tools
  def _CheckClean(self, revision, fixup=False):
    lockfile = os.path.join(self.checkout_path, ".git", "index.lock")
    if os.path.exists(lockfile):
      raise gclient_utils.Error(
        '\n____ %s at %s\n'
        '\tYour repo is locked, possibly due to a concurrent git process.\n'
        '\tIf no git executable is running, then clean up %r and try again.\n'
        % (self.relpath, revision, lockfile))

    # Make sure the tree is clean; see git-rebase.sh for reference
    try:
      scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
                      cwd=self.checkout_path)
    except subprocess2.CalledProcessError:
      raise gclient_utils.Error('\n____ %s at %s\n'
                                '\tYou have unstaged changes.\n'
                                '\tPlease commit, stash, or reset.\n'
                                  % (self.relpath, revision))
    try:
      scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
                       '--ignore-submodules', 'HEAD', '--'],
                       cwd=self.checkout_path)
    except subprocess2.CalledProcessError:
      raise gclient_utils.Error('\n____ %s at %s\n'
                                '\tYour index contains uncommitted changes\n'
                                '\tPlease commit, stash, or reset.\n'
                                  % (self.relpath, revision))
コード例 #2
0
def DoConfig(options, args):
    """Handle the config subcommand.

  Args:
    options: If options.spec set, a string providing contents of config file.
    args: The command line args.  If spec is not set,
          then args[0] is a string URL to get for config file.

  Raises:
    Error: on usage error
  """
    if len(args) < 1 and not options.spec:
        raise gclient_utils.Error(
            "required argument missing; see 'gclient help "
            "config'")
    if os.path.exists(options.config_filename):
        raise gclient_utils.Error(
            "%s file already exists in the current directory" %
            options.config_filename)
    client = GClient('.', options)
    if options.spec:
        client.SetConfig(options.spec)
    else:
        # TODO(darin): it would be nice to be able to specify an alternate relpath
        # for the given URL.
        base_url = args[0].rstrip('/')
        name = base_url.split("/")[-1]
        safesync_url = ""
        if len(args) > 1:
            safesync_url = args[1]
        client.SetDefaultConfig(name, base_url, safesync_url)
    client.SaveConfig()
コード例 #3
0
ファイル: gclient_scm.py プロジェクト: mlkt/depot_tools
  def RunCommand(self, command, options, args, file_list=None):
    commands = ['update', 'updatesingle', 'revert',
                'revinfo', 'status', 'diff', 'pack', 'runhooks']

    if not command in commands:
      raise gclient_utils.Error('Unknown command %s' % command)

    if not command in dir(self):
      raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
          command, self.__class__.__name__))

    return getattr(self, command)(options, args, file_list)
コード例 #4
0
ファイル: gclient_scm.py プロジェクト: mlkt/depot_tools
def CreateSCM(url, root_dir=None, relpath=None, out_fh=None, out_cb=None):
  SCM_MAP = {
    'git' : GitWrapper,
  }

  scm_name = GetScmName(url)
  if not scm_name in SCM_MAP:
    raise gclient_utils.Error('No SCM found for url %s' % url)
  scm_class = SCM_MAP[scm_name]
  if not scm_class.BinaryExists():
    raise gclient_utils.Error('%s command not found' % scm_name)
  return scm_class(url, root_dir, relpath, out_fh, out_cb)
コード例 #5
0
 def Lookup(self, var_name):
     """Implements the Var syntax."""
     if var_name in self._custom_vars:
         return self._custom_vars[var_name]
     elif var_name in self._local_scope.get("vars", {}):
         return self._local_scope["vars"][var_name]
     raise gclient_utils.Error("Var is not defined: %s" % var_name)
コード例 #6
0
def DoExport(options, args):
    """Handle the export subcommand.

  Raises:
    Error: on usage error
  """
    if len(args) != 1:
        raise gclient_utils.Error("Need directory name")
    client = GClient.LoadCurrentConfig(options)

    if not client:
        raise gclient_utils.Error(
            "client not configured; see 'gclient config'")

    if options.verbose:
        # Print out the .gclient file.  This is longer than if we just printed the
        # client dict, but more legible, and it might contain helpful comments.
        print(client.ConfigContent())
    return client.RunOnDeps('export', args)
コード例 #7
0
def DispatchCommand(command, options, args, command_map=None):
    """Dispatches the appropriate subcommand based on command line arguments."""
    if command_map is None:
        command_map = gclient_command_map

    if command in command_map:
        return command_map[command](options, args)
    else:
        raise gclient_utils.Error(
            "unknown subcommand '%s'; see 'gclient help'" % command)
コード例 #8
0
ファイル: gclient_scm.py プロジェクト: mlkt/depot_tools
 def BinaryExists():
   """Returns true if the command exists."""
   try:
     # We assume git is newer than 1.7.  See: crbug.com/114483
     result, version = scm.GIT.AssertVersion('1.7')
     if not result:
       raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
     return result
   except OSError:
     return False
コード例 #9
0
def DoRevert(options, args):
    """Handle the revert subcommand.

  Raises:
    Error: if client isn't configured properly.
  """
    client = GClient.LoadCurrentConfig(options)
    if not client:
        raise gclient_utils.Error(
            "client not configured; see 'gclient config'")
    return client.RunOnDeps('revert', args)
コード例 #10
0
ファイル: gclient_scm.py プロジェクト: mlkt/depot_tools
 def _AskForData(self, prompt, options):
   if options.jobs > 1:
     self.Print(prompt)
     raise gclient_utils.Error("Background task requires input. Rerun "
                               "gclient with --jobs=1 so that\n"
                               "interaction is possible.")
   try:
     return raw_input(prompt)
   except KeyboardInterrupt:
     # Hide the exception.
     sys.exit(1)
コード例 #11
0
def DoHelp(options, args):
    """Handle the help subcommand giving help for another subcommand.

  Raises:
    Error: if the command is unknown.
  """
    __pychecker__ = 'unusednames=options'
    if len(args) == 1 and args[0] in COMMAND_USAGE_TEXT:
        print(COMMAND_USAGE_TEXT[args[0]])
    else:
        raise gclient_utils.Error(
            "unknown subcommand '%s'; see 'gclient help'" % args[0])
コード例 #12
0
def DoRevInfo(options, args):
    """Handle the revinfo subcommand.

  Raises:
    Error: if client isn't configured properly.
  """
    __pychecker__ = 'unusednames=args'
    client = GClient.LoadCurrentConfig(options)
    if not client:
        raise gclient_utils.Error(
            "client not configured; see 'gclient config'")
    client.PrintRevInfo()
コード例 #13
0
def DoPack(options, args):
    """Handle the pack subcommand.

  Raises:
    Error: if client isn't configured properly.
  """
    client = GClient.LoadCurrentConfig(options)
    if not client:
        raise gclient_utils.Error(
            "client not configured; see 'gclient config'")
    if options.verbose:
        # Print out the .gclient file.  This is longer than if we just printed the
        # client dict, but more legible, and it might contain helpful comments.
        print(client.ConfigContent())
    return client.RunOnDeps('pack', args)
コード例 #14
0
    def ParseTasksFile(self):
        """Parses the tasks file for this tasks."""

        tasks_content = None
        use_strict = False
        filepath = os.path.join(self.root_dir, self.tasks_file)
        if not os.path.isfile(filepath):
            logging.info('ParseTasksFile(%s): No %s file found at %s' %
                         (self.name, self.tasks_file, filepath))
        else:
            tasks_content = gclient_utils.FileRead(filepath)
            logging.debug('ParseTasksFile(%s) read:\n%s' %
                          (self.name, tasks_content))
            use_strict = 'use strict' in tasks_content.splitlines()[0]

        local_scope = {}
        if tasks_content:
            # One thing is unintuitive, vars = {} must happen before Var() use.
            var = self.VarImpl(self.custom_vars, local_scope)
            if use_strict:
                logging.info('ParseTasksFile(%s): Strict Mode Enabled',
                             self.name)
                global_scope = {
                    '__builtins__': {
                        'None': None
                    },
                    'Var': var.Lookup,
                    'tasks_os': {},
                }
            else:
                global_scope = {
                    'Var': var.Lookup,
                    'tasks_os': {},
                }
            # Eval the content.
            try:
                exec(tasks_content, global_scope, local_scope)
            except SyntaxError, e:
                gclient_utils.SyntaxErrorToError(filepath, e)
            if use_strict:
                for key, val in local_scope.iteritems():
                    if not isinstance(val, (dict, list, tuple, str)):
                        raise gclient_utils.Error(
                            'ParseTasksFile(%s): Strict mode disallows %r -> %r'
                            % (self.name, key, val))
コード例 #15
0
 def SetConfig(self, content):
     self._config_dict = {}
     self._config_content = content
     try:
         exec(content, self._config_dict)
     except SyntaxError, e:
         try:
             __pychecker__ = 'no-objattrs'
             # Try to construct a human readable error message
             error_message = [
                 'There is a syntax error in your configuration file.',
                 'Line #%s, character %s:' % (e.lineno, e.offset),
                 '"%s"' % re.sub(r'[\r\n]*$', '', e.text)
             ]
         except:
             # Something went wrong, re-raise the original exception
             raise e
         else:
             # Raise a new exception with the human readable message:
             raise gclient_utils.Error('\n'.join(error_message))
コード例 #16
0
def DoUpdate(options, args):
    """Handle the update and sync subcommands.

  Raises:
    Error: if client isn't configured properly.
  """
    client = GClient.LoadCurrentConfig(options)

    if not client:
        raise gclient_utils.Error(
            "client not configured; see 'gclient config'")

    if not options.head:
        solutions = client.GetVar('solutions')
        if solutions:
            for s in solutions:
                if s.get('safesync_url', ''):
                    # rip through revisions and make sure we're not over-riding
                    # something that was explicitly passed
                    has_key = False
                    for r in options.revisions:
                        if r.split('@')[0] == s['name']:
                            has_key = True
                            break

                    if not has_key:
                        handle = urllib.urlopen(s['safesync_url'])
                        rev = handle.read().strip()
                        handle.close()
                        if len(rev):
                            options.revisions.append(s['name'] + '@' + rev)

    if options.verbose:
        # Print out the .gclient file.  This is longer than if we just printed the
        # client dict, but more legible, and it might contain helpful comments.
        print(client.ConfigContent())
    return client.RunOnDeps('update', args)