def testNoSdkRootRaisesError(self):
     self.sdk_root_mock.return_value = None
     with self.AssertRaisesExceptionMatches(
             cli_tree.SdkRootNotFoundError,
             'SDK root not found for this installation. '
             'CLI tree cannot be loaded or generated.'):
         cli_tree.CliTreePath()
def UpdateCliTrees(cli=None, commands=None, directory=None,
                   verbose=False, warn_on_exceptions=False):
  """(re)generates the CLI trees in directory if non-existent or out ot date.

  This function uses the progress tracker because some of the updates can
  take ~minutes.

  Args:
    cli: The default CLI. If not None then the default CLI is also updated.
    commands: Update only the commands in this list.
    directory: The directory containing the CLI tree JSON files. If None
      then the default installation directories are used.
    verbose: Display a status line for up to date CLI trees if True.
    warn_on_exceptions: Emits warning messages in lieu of exceptions. Used
      during installation.

  Raises:
    NoCliTreeGeneratorForCommand: A command in commands is not supported
      (doesn't have a generator).
  """
  # Initialize the list of directories to search for CLI tree files. The default
  # CLI tree is only searched for and generated in directories[0]. Other
  # existing trees are updated in the directory in which they were found. New
  # trees are generated in directories[-1].
  directories = []
  if directory:
    directories.append(directory)
  else:
    try:
      directories.append(cli_tree.CliTreeDir())
    except cli_tree.SdkRootNotFoundError as e:
      if not warn_on_exceptions:
        raise
      log.warn(str(e))
    directories.append(cli_tree.CliTreeConfigDir())

  if not commands:
    commands = set([cli_tree.DEFAULT_CLI_NAME] + GENERATORS.keys())

  failed = []
  for command in sorted(commands):
    if command != cli_tree.DEFAULT_CLI_NAME:
      generator = GetCliTreeGenerator(command)
      try:
        generator.LoadOrGenerate(directories=directories, verbose=verbose,
                                 warn_on_exceptions=warn_on_exceptions)
      except subprocess.CalledProcessError:
        failed.append(command)
    elif cli:
      cli_tree.Load(cli=cli,
                    path=cli_tree.CliTreePath(directory=directories[0]),
                    verbose=verbose)
  if failed:
    message = 'No CLI tree {} for [{}].'.format(
        text_utils.Pluralize(len(failed), 'generator'),
        ', '.join(sorted(failed)))
    if not warn_on_exceptions:
      raise NoCliTreeGeneratorForCommand(message)
    log.warn(message)
    def testFirstUpdate(self):
        # Ensure table file does not exist
        table_path = cli_tree.CliTreePath()
        self.assertEqual(self.table_file_path, table_path)

        # Update the table
        cli_tree.Dump(self.test_cli)

        # Ensure table exists
        self.assertTrue(os.path.isfile(self.table_file_path))
Beispiel #4
0
def UpdateCliTrees(cli=None,
                   commands=None,
                   directory=None,
                   force=False,
                   verbose=False,
                   warn_on_exceptions=False):
    """(re)generates the CLI trees in directory if non-existent or out ot date.

  This function uses the progress tracker because some of the updates can
  take ~minutes.

  Args:
    cli: The default CLI. If not None then the default CLI is also updated.
    commands: Update only the commands in this list.
    directory: The directory containing the CLI tree JSON files. If None
      then the default installation directories are used.
    force: Update all exitsing trees by forcing them to be out of date if True.
    verbose: Display a status line for up to date CLI trees if True.
    warn_on_exceptions: Emits warning messages in lieu of exceptions. Used
      during installation.

  Raises:
    NoCliTreeGeneratorForCommand: A command in commands is not supported
      (doesn't have a generator).
  """
    directories = _GetDirectories(directory=directory,
                                  warn_on_exceptions=warn_on_exceptions)
    if not commands:
        commands = set([cli_tree.DEFAULT_CLI_NAME] + list(GENERATORS.keys()))

    failed = []
    for command in sorted(commands):
        if command != cli_tree.DEFAULT_CLI_NAME:
            tree = LoadOrGenerate(command,
                                  directories=directories,
                                  force=force,
                                  verbose=verbose,
                                  warn_on_exceptions=warn_on_exceptions)
            if not tree:
                failed.append(command)
        elif cli:
            cli_tree.Load(cli=cli,
                          path=cli_tree.CliTreePath(directory=directories[0]),
                          force=force,
                          verbose=verbose)
    if failed:
        message = 'No CLI tree {} for [{}].'.format(
            text_utils.Pluralize(len(failed), 'generator'),
            ', '.join(sorted(failed)))
        if not warn_on_exceptions:
            raise NoCliTreeGeneratorForCommand(message)
        log.warning(message)
  def SetUp(self):
    self.table_dir_path = self.CreateTempDir('cli')
    self.StartObjectPatch(
        cli_tree, 'CliTreeDir', return_value=self.table_dir_path)

    self.table_file_path = cli_tree.CliTreePath()

    # Load the mock CLI and write the help table.
    self.test_cli = self.LoadTestCli('sdk8', modules=['broken_sdk'])
    self.parent = cli_tree.Load(cli=self.test_cli)

    # Store names of commands to be used.
    self.sdk = self.parent.get(lookup.COMMANDS, {}).get('sdk', {})
    self.long_help = self.sdk.get(lookup.COMMANDS, {}).get('long-help', {})
    self.xyzzy = self.sdk.get(lookup.COMMANDS, {}).get('xyzzy', {})
    self.subgroup = self.sdk.get(lookup.COMMANDS, {}).get('subgroup', {})
Beispiel #6
0
    def Run(self, args):
        # Re-compile python files.
        state = local_state.InstallationState.ForCurrent()
        state.CompilePythonFiles()

        # Delete the deprecated completion cache.
        resource_cache.DeleteDeprecatedCache()

        # Delete the completion cache.
        try:
            resource_cache.ResourceCache(create=False).Delete()
        except cache_exceptions.CacheNotFound:
            pass
        except cache_exceptions.Error as e:
            log.info('Unexpected resource cache error ignored: [%s].', e)

        # Re-generate the static gcloud CLI tree.
        cli_tree.Dump(self._cli_power_users_only, path=cli_tree.CliTreePath())
Beispiel #7
0
    def SetUp(self):
        self.table_dir_path = self.CreateTempDir('help_text')
        self.StartObjectPatch(cli_tree,
                              'CliTreeDir',
                              return_value=self.table_dir_path)
        # Mock the console width.
        self.StartObjectPatch(console_attr.ConsoleAttr,
                              'GetTermSize',
                              return_value=(80, 100))
        self.SetEncoding('ascii')

        self.table_file_path = cli_tree.CliTreePath()

        # Load the mock CLI and write the help table.
        self.test_cli = self.LoadTestCli('sdk8')
        self.parent = cli_tree.Load(cli=self.test_cli)

        self.sdk = self.parent.get(lookup.COMMANDS, {}).get('sdk', {})
        self.long_help = self.sdk.get(lookup.COMMANDS, {}).get('long-help', {})
        self.xyzzy = self.sdk.get(lookup.COMMANDS, {}).get('xyzzy', {})
Beispiel #8
0
def UpdateCliTrees(cli=None, commands=None, directory=None, tarball=None,
                   force=False, verbose=False, warn_on_exceptions=False):
  """(re)generates the CLI trees in directory if non-existent or out of date.

  This function uses the progress tracker because some of the updates can
  take ~minutes.

  Args:
    cli: The default CLI. If not None then the default CLI is also updated.
    commands: Update only the commands in this list.
    directory: The directory containing the CLI tree JSON files. If None
      then the default installation directories are used.
    tarball: For packaging CLI trees. --commands specifies one command that is
      a relative path in this tarball. The tarball is extracted to a temporary
      directory and the command path is adjusted to point to the temporary
      directory.
    force: Update all exitsing trees by forcing them to be out of date if True.
    verbose: Display a status line for up to date CLI trees if True.
    warn_on_exceptions: Emits warning messages in lieu of exceptions. Used
      during installation.

  Raises:
    NoCliTreeGeneratorForCommand: A command in commands is not supported
      (doesn't have a generator).
  """
  directories = _GetDirectories(
      directory=directory, warn_on_exceptions=warn_on_exceptions)
  if not commands:
    commands = set([cli_tree.DEFAULT_CLI_NAME] + list(GENERATORS.keys()))

  failed = []
  for command in sorted(commands):
    if command != cli_tree.DEFAULT_CLI_NAME:
      tree = LoadOrGenerate(command,
                            directories=directories,
                            tarball=tarball,
                            force=force,
                            verbose=verbose,
                            warn_on_exceptions=warn_on_exceptions)
      if not tree:
        failed.append(command)
    elif cli:

      def _Mtime(path):
        try:
          return os.path.getmtime(path)
        except OSError:
          return 0

      # Update the CLI tree.
      cli_tree_path = cli_tree.CliTreePath(directory=directories[0])
      cli_tree.Load(cli=cli, path=cli_tree_path, force=force, verbose=verbose)

      # Update the static completion CLI tree if older than the CLI tree. To
      # keep static completion startup lightweight we don't track the release
      # in the tree data. Using the modify time is a minimal sanity check.
      completion_tree_path = lookup.CompletionCliTreePath(
          directory=directories[0])
      cli_tree_mtime = _Mtime(cli_tree_path)
      completion_tree_mtime = _Mtime(completion_tree_path)
      if (force or not completion_tree_mtime or
          completion_tree_mtime < cli_tree_mtime):
        files.MakeDir(os.path.dirname(completion_tree_path))
        with files.FileWriter(completion_tree_path) as f:
          generate_static.ListCompletionTree(cli, out=f)
      elif verbose:
        log.status.Print(
            '[{}] static completion CLI tree is up to date.'.format(command))

  if failed:
    message = 'No CLI tree {} for [{}].'.format(
        text_utils.Pluralize(len(failed), 'generator'),
        ', '.join(sorted(failed)))
    if not warn_on_exceptions:
      raise NoCliTreeGeneratorForCommand(message)
    log.warning(message)
Beispiel #9
0
 def testTableExistsAndUsedBySearchHelp(self):
     """Test that in bundled SDK, table already exists and help search runs."""
     self.assertTrue(os.path.exists(cli_tree.CliTreePath()))
     # Make basic assertion that we can run search and find results.
     results = self.Run('help -- dataflow')
     self.assertTrue(results)
 def testTableExists(self):
     # The table should already exist
     path = cli_tree.CliTreePath()
     self.AssertFileExists(path)