Ejemplo n.º 1
0
def _GetTermSizeTput():
  """Returns the terminal x and y dimemsions from tput(1)."""
  # pylint: disable=g-import-not-at-top
  from googlecloudsdk.third_party.py27 import py27_subprocess as subprocess
  output = subprocess.check_output(['tput', 'cols'], stderr=subprocess.STDOUT)
  cols = int(output)
  output = subprocess.check_output(['tput', 'lines'], stderr=subprocess.STDOUT)
  rows = int(output)
  return (cols, rows)
Ejemplo n.º 2
0
def _GetTermSizeTput():
    """Returns the terminal x and y dimemsions from tput(1)."""
    # pylint: disable=g-import-not-at-top
    from googlecloudsdk.third_party.py27 import py27_subprocess as subprocess
    output = subprocess.check_output(['tput', 'cols'],
                                     stderr=subprocess.STDOUT)
    cols = int(output)
    output = subprocess.check_output(['tput', 'lines'],
                                     stderr=subprocess.STDOUT)
    rows = int(output)
    return (cols, rows)
Ejemplo n.º 3
0
def CheckIfJava7IsInstalled(for_text):
  """Checks if Java 7+ is installed.

  Args:
    for_text: str, the text explaining what Java 7 is necessary for

  Raises:
    Java7Error: if Java 7+ is not found on the path or is not executable.
  """
  java_path = files.FindExecutableOnPath('java')
  if not java_path:
    raise Java7Error('To use the {for_text}, a Java 7+ JRE must be installed '
                     'and on your system PATH'.format(for_text=for_text))
  try:
    output = subprocess.check_output([java_path, '-version'],
                                     stderr=subprocess.STDOUT)
  except subprocess.CalledProcessError:
    raise Java7Error('Unable to execute the java that was found on your PATH.'
                     ' The {for_text} requires a Java 7+ JRE installed and on '
                     'your system PATH'.format(for_text=for_text))

  match = re.search('version "1.([0-9]).', output)
  if not match or int(match.group(1)) < 7:
    raise Java7Error('The java executable on your PATH is not a Java 7+ JRE.'
                     ' The {for_text} requires a Java 7+ JRE installed and on '
                     'your system PATH'.format(for_text=for_text))
Ejemplo n.º 4
0
def CheckGitVersion(version_lower_bound):
  """Returns true when version of git is >= min_version.

  Args:
    version_lower_bound: (int,int,int), The lowest allowed version.

  Returns:
    True if version >= min_version.
  """
  try:
    output = subprocess.check_output(['git', 'version'])
    if not output:
      raise InvalidGitException('The git version string is empty.')
    if not output.startswith('git version '):
      raise InvalidGitException(('The git version string must start with '
                                 'git version .'))
    match = re.search(r'(\d+)\.(\d+)\.(\d+)', output)
    if not match:
      raise InvalidGitException('The git version string must contain a '
                                'version number.')
    cur_version = match.group(1, 2, 3)
    current_version = tuple([int(item) for item in cur_version])
    if current_version < version_lower_bound:
      min_version = '.'.join(str(i) for i in version_lower_bound)
      raise GitVersionException(
          ('Your git version {cur_version} is older than the minimum version '
           '{min_version}. Please install a newer version of git.'),
          output, min_version)
  except OSError as e:
    if e.errno == errno.ENOENT:
      raise NoGitException()
    raise
  return True
Ejemplo n.º 5
0
def CheckGitVersion(version_lower_bound):
    """Returns true when version of git is >= min_version.

  Args:
    version_lower_bound: (int,int,int), The lowest allowed version.

  Returns:
    True if version >= min_version.
  """
    try:
        output = subprocess.check_output(['git', 'version'])
        if not output:
            raise InvalidGitException('The git version string is empty.')
        if not output.startswith('git version '):
            raise InvalidGitException(
                ('The git version string must start with '
                 'git version .'))
        match = re.search(r'(\d+)\.(\d+)\.(\d+)', output)
        if not match:
            raise InvalidGitException('The git version string must contain a '
                                      'version number.')
        cur_version = match.group(1, 2, 3)
        current_version = tuple([int(item) for item in cur_version])
        if current_version < version_lower_bound:
            min_version = '.'.join(str(i) for i in version_lower_bound)
            raise GitVersionException((
                'Your git version {cur_version} is older than the minimum version '
                '{min_version}. Please install a newer version of git.'),
                                      output, min_version)
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NoGitException()
        raise
    return True
Ejemplo n.º 6
0
def CheckIfJava7IsInstalled(for_text):
    """Checks if Java 7+ is installed.

  Args:
    for_text: str, the text explaining what Java 7 is necessary for

  Raises:
    Java7Error: if Java 7+ is not found on the path or is not executable.
  """
    java_path = files.FindExecutableOnPath('java')
    if not java_path:
        raise Java7Error(
            'To use the {for_text}, a Java 7+ JRE must be installed '
            'and on your system PATH'.format(for_text=for_text))
    try:
        output = subprocess.check_output([java_path, '-version'],
                                         stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError:
        raise Java7Error(
            'Unable to execute the java that was found on your PATH.'
            ' The {for_text} requires a Java 7+ JRE installed and on '
            'your system PATH'.format(for_text=for_text))

    match = re.search('version "1.([0-9]).', output)
    if not match or int(match.group(1)) < 7:
        raise Java7Error(
            'The java executable on your PATH is not a Java 7+ JRE.'
            ' The {for_text} requires a Java 7+ JRE installed and on '
            'your system PATH'.format(for_text=for_text))
Ejemplo n.º 7
0
def _CallGit(cwd, *args):
  """Calls git with the given args, in the given working directory.

  Args:
    cwd: The working directory for the command.
    *args: Any arguments for the git command.
  Returns:
    The raw output of the command, or None if the command failed.
  """
  try:
    return subprocess.check_output(['git'] + list(args), cwd=cwd)
  except (OSError, subprocess.CalledProcessError) as e:
    logging.debug('Could not call git with args %s: %s', args, e)
    return None
    def Clone(self, destination_path, dry_run=False):
        """Clone a git repository into a gcloud workspace.

    If the resulting clone does not have a .gcloud directory, create one. Also,
    sets the credential.helper to use the gcloud credential helper.

    Args:
      destination_path: str, The relative path for the repository clone.
      dry_run: bool, If true do not run but print commands instead.

    Returns:
      str, The absolute path of cloned repository.

    Raises:
      CannotInitRepositoryException: If there is already a file or directory in
          the way of creating this repository.
      CannotFetchRepositoryException: If there is a problem fetching the
          repository from the remote host, or if the repository is otherwise
          misconfigured.
    """
        abs_repository_path = os.path.abspath(destination_path)
        if os.path.exists(abs_repository_path):
            CheckGitVersion(
            )  # Do this here, before we start running git commands
            # First check if it's already the repository we're looking for.
            with files.ChDir(abs_repository_path) as _:
                try:
                    output = subprocess.check_output(
                        ['git', 'remote', 'show', 'origin'])
                except subprocess.CalledProcessError:
                    raise CannotFetchRepositoryException(
                        'Repository in [{path}] is misconfigured.'.format(
                            path=abs_repository_path))
                output_match = _ORIGIN_URL_RE.search(output)
                if not output_match or output_match.group('url') != self._uri:
                    raise CannotInitRepositoryException((
                        'Repository [{url}] cannot be cloned to [{path}]: there'
                        ' is something already there.').format(
                            url=self._uri, path=abs_repository_path))
                else:
                    # Repository exists and is correctly configured: abort.
                    log.err.Print((
                        'Repository in [{path}] already exists and maps to [{uri}].'
                        .format(path=abs_repository_path, uri=self._uri)))
                    return None

        # Nothing is there, make a brand new repository.
        try:
            if (self._uri.startswith('https://code.google.com')
                    or self._uri.startswith(
                        'https://source.developers.google.com')):

                # If this is a Google-hosted repo, clone with the cred helper.
                try:
                    CheckGitVersion(_HELPER_MIN)
                except GitVersionException:
                    log.warn(
                        textwrap.dedent("""\
              You are cloning a Google-hosted repository with a version of git
              older than 1.7.9. If you upgrade to 1.7.9 or later, gcloud can
              handle authentication to this repository. Otherwise, to
              authenticate, use your Google account and the password found by
              running the following command.
               $ gcloud auth print-refresh-token
              """))
                    cmd = ['git', 'clone', self._uri, abs_repository_path]
                else:
                    cmd = [
                        'git', 'clone', self._uri, abs_repository_path,
                        '--config', 'credential.helper="{0}"'.format(
                            _GetCredentialHelper())
                    ]
                self._RunCommand(cmd, dry_run)
            else:
                # Otherwise, just do a simple clone. We do this clone, without the
                # credential helper, because a user may have already set a default
                # credential helper that would know the repo's auth info.
                subprocess.check_call(
                    ['git', 'clone', self._uri, abs_repository_path])
        except subprocess.CalledProcessError as e:
            raise CannotFetchRepositoryException(e)
        return abs_repository_path
Ejemplo n.º 9
0
  def CloneGitRepository(self, repository_url, repository_path):
    """Clone a git repository into a gcloud workspace.

    If the resulting clone does not have a .gcloud directory, create one. Also,
    sets the credential.helper to use the gcloud credential helper.

    Args:
      repository_url: str, The URL of the repository to clone.
      repository_path: str, The relative path from the root of the workspace to
          the repository clone.

    Raises:
      InvalidWorkspaceException: If workspace_dir_path is not a workspace.
      CannotInitRepositoryException: If there is already a file or directory in
          the way of creating this repository.
      CannotFetchRepositoryException: If there is a problem fetching the
          repository from the remote host, or if the repository is otherwise
          misconfigured.
    """

    abs_repository_path = os.path.join(self.root_directory, repository_path)
    if os.path.exists(abs_repository_path):
      # First check if it's already the repository we're looking for.
      with files.ChDir(abs_repository_path) as _:
        try:
          output = subprocess.check_output(['git', 'remote', 'show', 'origin'])
        except subprocess.CalledProcessError:
          raise CannotFetchRepositoryException(
              'Repository in [{path}] is misconfigured.'.format(
                  path=abs_repository_path))
        output_match = _ORIGIN_URL_RE.search(output)
        if not output_match or output_match.group('url') != repository_url:
          raise CannotInitRepositoryException(
              ('Repository [{url}] cannot be cloned to [{path}]: there'
               ' is something already there.').format(
                   url=repository_url,
                   path=os.path.join(self.root_directory, repository_path)))
        else:
          # Repository exists and is correctly configured: abort.
          log.err.Print(
              ('Repository in [{path}] exists and is correctly configured.'
               .format(path=abs_repository_path)))
          return

    # Nothing is there, make a brand new repository.
    try:
      if (repository_url.startswith('https://code.google.com') or
          repository_url.startswith('https://source.developers.google.com')):

        # If this is a Google-hosted repo, clone with the cred helper.
        try:
          CheckGitVersion(_HELPER_MIN)
        except GitVersionException:
          log.warn(textwrap.dedent("""\
              You are cloning a Google-hosted repository with a version of git
              older than 1.7.9. If you upgrade to 1.7.9 or later, gcloud can
              handle authentication to this repository. Otherwise, to
              authenticate, use your Google account and the password found by
              running the following command.
               $ gcloud auth print-refresh-token
              """))
          subprocess.check_call(
              ['git', 'clone', repository_url, abs_repository_path])
        else:
          if (platforms.OperatingSystem.Current() ==
              platforms.OperatingSystem.WINDOWS):
            helper_name = 'gcloud.cmd'
          else:
            helper_name = 'gcloud.sh'
          subprocess.check_call(
              ['git', 'clone', repository_url, abs_repository_path,
               '--config', 'credential.helper=%s' % helper_name])
      else:
        # Otherwise, just do a simple clone. We do this clone, without the
        # credential helper, because a user may have already set a default
        # credential helper that would know the repo's auth info.
        subprocess.check_call(
            ['git', 'clone', repository_url, abs_repository_path])
    except subprocess.CalledProcessError as e:
      raise CannotFetchRepositoryException(e)
Ejemplo n.º 10
0
    def CloneGitRepository(self, repository_url, repository_path):
        """Clone a git repository into a gcloud workspace.

    If the resulting clone does not have a .gcloud directory, create one. Also,
    sets the credential.helper to use the gcloud credential helper.

    Args:
      repository_url: str, The URL of the repository to clone.
      repository_path: str, The relative path from the root of the workspace to
          the repository clone.

    Raises:
      InvalidWorkspaceException: If workspace_dir_path is not a workspace.
      CannotInitRepositoryException: If there is already a file or directory in
          the way of creating this repository.
      CannotFetchRepositoryException: If there is a problem fetching the
          repository from the remote host, or if the repository is otherwise
          misconfigured.
    """

        abs_repository_path = os.path.join(self.root_directory,
                                           repository_path)
        if os.path.exists(abs_repository_path):
            # First check if it's already the repository we're looking for.
            with files.ChDir(abs_repository_path) as _:
                try:
                    output = subprocess.check_output(
                        ['git', 'remote', 'show', 'origin'])
                except subprocess.CalledProcessError:
                    raise CannotFetchRepositoryException(
                        'Repository in [{path}] is misconfigured.'.format(
                            path=abs_repository_path))
                output_match = _ORIGIN_URL_RE.search(output)
                if not output_match or output_match.group(
                        'url') != repository_url:
                    raise CannotInitRepositoryException((
                        'Repository [{url}] cannot be cloned to [{path}]: there'
                        ' is something already there.').format(
                            url=repository_url,
                            path=os.path.join(self.root_directory,
                                              repository_path)))
                else:
                    # Repository exists and is correctly configured: abort.
                    log.err.Print((
                        'Repository in [{path}] exists and is correctly configured.'
                        .format(path=abs_repository_path)))
                    return

        # Nothing is there, make a brand new repository.
        try:
            if (repository_url.startswith('https://code.google.com')
                    or repository_url.startswith(
                        'https://source.developers.google.com')):

                # If this is a Google-hosted repo, clone with the cred helper.
                try:
                    CheckGitVersion(_HELPER_MIN)
                except GitVersionException:
                    log.warn(
                        textwrap.dedent("""\
              You are cloning a Google-hosted repository with a version of git
              older than 1.7.9. If you upgrade to 1.7.9 or later, gcloud can
              handle authentication to this repository. Otherwise, to
              authenticate, use your Google account and the password found by
              running the following command.
               $ gcloud auth print-refresh-token
              """))
                    subprocess.check_call(
                        ['git', 'clone', repository_url, abs_repository_path])
                else:
                    if (platforms.OperatingSystem.Current() ==
                            platforms.OperatingSystem.WINDOWS):
                        helper_name = 'gcloud.cmd'
                    else:
                        helper_name = 'gcloud.sh'
                    subprocess.check_call([
                        'git', 'clone', repository_url, abs_repository_path,
                        '--config',
                        'credential.helper=%s' % helper_name
                    ])
            else:
                # Otherwise, just do a simple clone. We do this clone, without the
                # credential helper, because a user may have already set a default
                # credential helper that would know the repo's auth info.
                subprocess.check_call(
                    ['git', 'clone', repository_url, abs_repository_path])
        except subprocess.CalledProcessError as e:
            raise CannotFetchRepositoryException(e)
Ejemplo n.º 11
0
  def Clone(self, destination_path, dry_run=False):
    """Clone a git repository into a gcloud workspace.

    If the resulting clone does not have a .gcloud directory, create one. Also,
    sets the credential.helper to use the gcloud credential helper.

    Args:
      destination_path: str, The relative path for the repository clone.
      dry_run: bool, If true do not run but print commands instead.

    Returns:
      str, The absolute path of cloned repository.

    Raises:
      CannotInitRepositoryException: If there is already a file or directory in
          the way of creating this repository.
      CannotFetchRepositoryException: If there is a problem fetching the
          repository from the remote host, or if the repository is otherwise
          misconfigured.
    """
    abs_repository_path = os.path.abspath(destination_path)
    if os.path.exists(abs_repository_path):
      CheckGitVersion()  # Do this here, before we start running git commands
      # First check if it's already the repository we're looking for.
      with files.ChDir(abs_repository_path) as _:
        try:
          output = subprocess.check_output(['git', 'remote', 'show', 'origin'])
        except subprocess.CalledProcessError:
          raise CannotFetchRepositoryException(
              'Repository in [{path}] is misconfigured.'.format(
                  path=abs_repository_path))
        output_match = _ORIGIN_URL_RE.search(output)
        if not output_match or output_match.group('url') != self._uri:
          raise CannotInitRepositoryException(
              ('Repository [{url}] cannot be cloned to [{path}]: there'
               ' is something already there.').format(
                   url=self._uri, path=abs_repository_path))
        else:
          # Repository exists and is correctly configured: abort.
          log.err.Print(
              ('Repository in [{path}] already exists and maps to [{uri}].'
               .format(path=abs_repository_path, uri=self._uri)))
          return None

    # Nothing is there, make a brand new repository.
    try:
      if (self._uri.startswith('https://code.google.com') or
          self._uri.startswith('https://source.developers.google.com')):

        # If this is a Google-hosted repo, clone with the cred helper.
        try:
          CheckGitVersion(_HELPER_MIN)
        except GitVersionException:
          log.warn(textwrap.dedent("""\
              You are cloning a Google-hosted repository with a version of git
              older than 1.7.9. If you upgrade to 1.7.9 or later, gcloud can
              handle authentication to this repository. Otherwise, to
              authenticate, use your Google account and the password found by
              running the following command.
               $ gcloud auth print-refresh-token
              """))
          cmd = ['git', 'clone', self._uri, abs_repository_path]
        else:
          cmd = ['git', 'clone', self._uri, abs_repository_path,
                 '--config',
                 'credential.helper="{0}"'.format(_GetCredentialHelper())]
        self._RunCommand(cmd, dry_run)
      else:
        # Otherwise, just do a simple clone. We do this clone, without the
        # credential helper, because a user may have already set a default
        # credential helper that would know the repo's auth info.
        subprocess.check_call(
            ['git', 'clone', self._uri, abs_repository_path])
    except subprocess.CalledProcessError as e:
      raise CannotFetchRepositoryException(e)
    return abs_repository_path