def testGetChoiceLists(self):
        """Verify GetChoice behavior w/lists."""
        m = self.PatchObject(cros_build_lib, 'GetInput')

        m.return_value = '1'
        ret = cros_build_lib.GetChoice('title', ['a', 'b', 'c'])
        self.assertEqual(ret, 1)
示例#2
0
  def _FindPackage(self, pkg):
    """Returns the (CP, slot) pair for a package matching |pkg|.

    Args:
      pkg: Path to a binary package or a (partial) package CPV specifier.

    Returns:
      A (CP, slot) pair for the given package; slot may be None (unspecified).

    Raises:
      ValueError: if |pkg| is not a binpkg file nor does it match something
      that's in the bintree.
    """
    if pkg.endswith('.tbz2') and os.path.isfile(pkg):
      package = os.path.basename(os.path.splitext(pkg)[0])
      category = os.path.basename(os.path.dirname(pkg))
      return self._GetCP(os.path.join(category, package)), None

    matches = self._FindPackageMatches(pkg)
    if not matches:
      raise ValueError('No package found for %s' % pkg)

    idx = 0
    if len(matches) > 1:
      # Ask user to pick among multiple matches.
      idx = cros_build_lib.GetChoice('Multiple matches found for %s: ' % pkg,
                                     ['%s:%s' % (cp, slot) if slot else cp
                                      for cp, slot in matches])

    return matches[idx]
    def testGetChoiceGenerator(self):
        """Verify GetChoice behavior w/generators."""
        m = self.PatchObject(cros_build_lib, 'GetInput')

        m.return_value = '2'
        ret = cros_build_lib.GetChoice('title', list(range(3)))
        self.assertEqual(ret, 2)
示例#4
0
  def Run(self):
    """Run cros debug."""
    commandline.RunInsideChroot(self)
    self.options.Freeze()
    self._ReadOptions()
    with remote_access.ChromiumOSDeviceHandler(
        self.ssh_hostname, port=self.ssh_port, username=self.ssh_username,
        private_key=self.ssh_private_key) as device:
      self.board = cros_build_lib.GetBoard(device_board=device.board,
                                           override_board=self.options.board,
                                           strict=True)
      logging.info('Board is %s', self.board)

      self.gdb_cmd = [
          'gdb_remote', '--ssh',
          '--board', self.board,
          '--remote', self.ssh_hostname,
      ]
      if self.ssh_port:
        self.gdb_cmd.extend(['--ssh_port', str(self.ssh_port)])

      if not (self.pid or self.exe):
        cros_build_lib.Die(
            'Must use --exe or --pid to specify the process to debug.')

      if self.pid:
        if self.list or self.exe:
          cros_build_lib.Die(
              '--list and --exe are disallowed when --pid is used.')
        self._DebugRunningProcess(self.pid)
        return

      if not self.exe.startswith('/'):
        cros_build_lib.Die('--exe must have a full pathname.')
      logging.debug('Executable path is %s', self.exe)
      if not device.IsFileExecutable(self.exe):
        cros_build_lib.Die(
            'File path "%s" does not exist or is not executable on device %s',
            self.exe, self.ssh_hostname)

      pids = device.GetRunningPids(self.exe)
      self._ListProcesses(device, pids)

      if self.list:
        # If '--list' flag is on, do not launch GDB.
        return

      if pids:
        choices = ['Start a new process under GDB']
        choices.extend(pids)
        idx = cros_build_lib.GetChoice(
            'Please select the process pid to debug (select [0] to start a '
            'new process):', choices)
        if idx == 0:
          self._DebugNewProcess()
        else:
          self._DebugRunningProcess(pids[idx - 1])
      else:
        self._DebugNewProcess()
示例#5
0
    def ChooseRemovableDevice(self, devices):
        """Lists all removable devices and asks user to select/confirm.

    Args:
      devices: a list of device names (e.g. ['sda', 'sdb']).

    Returns:
      The device name chosen by the user.
    """
        idx = cros_build_lib.GetChoice(
            'Removable device(s) found. Please select/confirm to continue:',
            [self.GetRemovableDeviceDescription(x) for x in devices])

        return devices[idx]
    def testGetChoiceWindow(self):
        """Verify GetChoice behavior w/group_size set."""
        m = self.PatchObject(cros_build_lib, 'GetInput')

        cnt = [0]

        def _Gen():
            while True:
                cnt[0] += 1
                yield 'a'

        m.side_effect = ['\n', '2']
        ret = cros_build_lib.GetChoice('title', _Gen(), group_size=2)
        self.assertEqual(ret, 2)

        # Verify we showed the correct number of times.
        self.assertEqual(cnt[0], 5)
示例#7
0
def _ChooseImageFromDirectory(dir_path):
  """Lists all image files in |dir_path| and ask user to select one.

  Args:
    dir_path: Path to the directory.
  """
  images = sorted([x for x in os.listdir(dir_path) if
                   _IsFilePathGPTDiskImage(os.path.join(dir_path, x))])
  idx = 0
  if len(images) == 0:
    raise ValueError('No image found in %s.' % dir_path)
  elif len(images) > 1:
    idx = cros_build_lib.GetChoice(
        'Multiple images found in %s. Please select one to continue:' % (
            (dir_path,)),
        images)

  return os.path.join(dir_path, images[idx])
示例#8
0
    def pin(self, work_dir):
        """Pin chrome."""

        overlay = os.path.join(work_dir, 'overlay')
        priv_overlay = os.path.join(work_dir, 'priv_overlay')
        print('Setting up working directory...')
        CloneWorkingRepo(overlay, OVERLAY_URL, OVERLAY, self.options.branch)
        CloneWorkingRepo(priv_overlay, PRIV_OVERLAY_URL, PRIV_OVERLAY,
                         self.options.branch)
        print('Done')

        # Interesting paths.
        chrome_dir = os.path.join(overlay, constants.CHROME_CP)
        other_dirs = [
            os.path.join(overlay, pkg)
            for pkg in constants.OTHER_CHROME_PACKAGES
        ]

        # Let the user pick what version to pin chrome to.
        uprev_list = UprevList(chrome_dir)
        choice = cros_build_lib.GetChoice('Versions of chrome to pin to:',
                                          uprev_list,
                                          group_size=5)
        pin_version = uprev_list.uprevs[choice]
        commit_subject = ('Chrome: Pin to version %s' %
                          pin_version.from_parts.version)

        # Public branch.
        git.CreateBranch(overlay,
                         self.branch_name,
                         track=True,
                         branch_point='origin/%s' % self.options.branch)

        target_sha = pin_version.sha + '~'
        ebs = [RevertStableEBuild(chrome_dir, target_sha)]
        for pkg_dir in other_dirs:
            ebs.append(RevertStableEBuild(pkg_dir, target_sha))
        RevertBinhostConf(overlay, pin_version.conf_files, target_sha)
        git.RevertPath(os.path.join(overlay, 'chromeos', 'binhost'),
                       'chromium.json', target_sha)
        MaskNewerPackages(overlay, (eb for eb in ebs if eb))

        pub_cid = git.Commit(overlay, 'Public overlay commit')
        if not pub_cid:
            raise Exception(
                "Don't know the commit ID of the public overlay CL.")

        # Find out what package directory the binhost configs should point to.
        binhost_dir = os.path.join(overlay, 'chromeos', 'binhost')
        target_file = os.path.join(binhost_dir, 'target',
                                   pin_version.conf_files[0])
        host_file = os.path.join(binhost_dir, 'host',
                                 pin_version.conf_files[0])
        conf_file = target_file if os.path.exists(target_file) else host_file
        conf_content = osutils.ReadFile(conf_file)
        match = re.search('/(?P<package_dir>[^/\n]*)/packages', conf_content)
        if not match:
            raise Exception('Failed to parse binhost conf %s' %
                            conf_content.strip())
        pkg_dir = match.group('package_dir')

        # Private branch.
        git.CreateBranch(priv_overlay,
                         self.branch_name,
                         track=True,
                         branch_point='origin/%s' % self.options.branch)

        binhost_uprev = FindPrivateConfCL(priv_overlay, pkg_dir)
        if not binhost_uprev:
            raise Exception('Failed to find private binhost uprev.')
        target_sha = binhost_uprev.sha
        RevertBinhostConf(priv_overlay, binhost_uprev.conf_files, target_sha)
        git.RevertPath(os.path.join(priv_overlay, 'chromeos', 'binhost'),
                       'chrome.json', target_sha)

        commit_message = self.CommitMessage(commit_subject, pub_cid)
        priv_cid = git.Commit(priv_overlay, commit_message)
        if not priv_cid:
            raise Exception(
                "Don't know the commit ID of the private overlay CL.")

        # Update the commit message on the public overlay CL.
        commit_message = self.CommitMessage(commit_subject, '*' + priv_cid,
                                            pub_cid)
        git.Commit(overlay, commit_message, amend=True)

        # Upload the CLs.
        external_push = git.UploadCL(overlay,
                                     OVERLAY_URL,
                                     self.options.branch,
                                     skip=self.options.dryrun)
        print(external_push.output)
        internal_push = git.UploadCL(priv_overlay,
                                     PRIV_OVERLAY_URL,
                                     self.options.branch,
                                     skip=self.options.dryrun)
        print(internal_push.output)

        print('\n** Both of the changes above need to be submitted for chrome '
              'to be pinned. **\n')