def ArgsForGcloud(): """Constructs an argument list to run gcloud.""" if not sys.executable: # In hermetic par/stub files sys.executable is None. In regular installs, # and in classic par/stub files it is a non-empty string. return _GetToolArgs(None, None, argv_utils.GetDecodedArgv()[0]) return ArgsForPythonTool(config.GcloudPath())
def _DisableLongRunningCliTreeGeneration(command): """Returns True if long running CLI tree generation is disabled.""" # Only a few command generators are long running. if command not in ('bq', 'gsutil', 'kubectl'): return False # Only generate these CLI trees on the fly for explicit requests. # It can take ~1minute, not good, especially at the interactive prompt. decoded_argv = argv_utils.GetDecodedArgv() if 'update-cli-trees' in decoded_argv or '--update-cli-trees' in decoded_argv: return False # It's a long running generator, not explicitly requested -- disable. return True
def Execute(self, args=None, call_arg_complete=True): """Execute the CLI tool with the given arguments. Args: args: [str], The arguments from the command line or None to use sys.argv call_arg_complete: Call the _ArgComplete function if True Returns: The result of executing the command determined by the command implementation. Raises: ValueError: for ill-typed arguments. """ if isinstance(args, six.string_types): raise ValueError( 'Execute expects an iterable of strings, not a string.') # The argparse module does not handle unicode args when run in Python 2 # because it uses str(x) even when type(x) is unicode. This sets itself up # for failure because it converts unicode strings back to byte strings which # will trigger ASCII codec exceptions. It works in Python 3 because str() is # equivalent to unicode() in Python 3. The next Pythonically magic and dirty # statement coaxes the Python 3 behavior out of argparse running in # Python 2. Doing it here ensures that the workaround is in place for # calliope argparse use cases. argparse.str = six.text_type # We need the argparse 1.2.1 patch in _SubParsersActionCall. # TODO(b/77288697) delete after py3 tests use non-hermetic python if argparse.__version__ == '1.1': argparse._SubParsersAction.__call__ = _SubParsersActionCall # pylint: disable=protected-access if call_arg_complete: _ArgComplete(self.__top_element.ai) if not args: args = argv_utils.GetDecodedArgv()[1:] # Look for a --configuration flag and update property state based on # that before proceeding to the main argparse parse step. named_configs.FLAG_OVERRIDE_STACK.PushFromArgs(args) properties.VALUES.PushInvocationValues() # Set the command name in case an exception happens before the command name # is finished parsing. command_path_string = self.__name specified_arg_names = None # Convert py2 args to text. argv = [console_attr.Decode(arg) for arg in args] if six.PY2 else args old_user_output_enabled = None old_verbosity = None try: args = self.__parser.parse_args(_ApplyFlagsFile(argv)) if args.CONCEPT_ARGS is not None: args.CONCEPT_ARGS.ParseConcepts() calliope_command = args._GetCommand() # pylint: disable=protected-access command_path_string = '.'.join(calliope_command.GetPath()) specified_arg_names = args.GetSpecifiedArgNames() # If the CLI has not been reloaded since the last command execution (e.g. # in test runs), args.CONCEPTS may contain cached values. if args.CONCEPTS is not None: args.CONCEPTS.Reset() # -h|--help|--document are dispatched by parse_args and never get here. # Now that we have parsed the args, reload the settings so the flags will # take effect. These will use the values from the properties. old_user_output_enabled = log.SetUserOutputEnabled(None) old_verbosity = log.SetVerbosity(None) # Set the command_name property so it is persisted until the process ends. # Only do this for the top level command that can be detected by looking # at the stack. It will have one initial level, and another level added by # the PushInvocationValues earlier in this method. if len(properties.VALUES.GetInvocationStack()) == 2: properties.VALUES.metrics.command_name.Set(command_path_string) # Set the invocation value for all commands, this is lost when popped properties.VALUES.SetInvocationValue( properties.VALUES.metrics.command_name, command_path_string, None) for hook in self.__pre_run_hooks: hook.Run(command_path_string) resources = calliope_command.Run(cli=self, args=args) for hook in self.__post_run_hooks: hook.Run(command_path_string) # Preserve generator or static list resources. if isinstance(resources, types.GeneratorType): def _Yield(): """Activates generator exceptions.""" try: for resource in resources: yield resource except Exception as exc: # pylint: disable=broad-except self._HandleAllErrors(exc, command_path_string, specified_arg_names) return _Yield() # Do this last. If there is an error, the error handler will log the # command execution along with the error. metrics.Commands(command_path_string, config.CLOUD_SDK_VERSION, specified_arg_names) return resources except Exception as exc: # pylint: disable=broad-except self._HandleAllErrors(exc, command_path_string, specified_arg_names) finally: properties.VALUES.PopInvocationValues() named_configs.FLAG_OVERRIDE_STACK.Pop() # Reset these values to their previous state now that we popped the flag # values. if old_user_output_enabled is not None: log.SetUserOutputEnabled(old_user_output_enabled) if old_verbosity is not None: log.SetVerbosity(old_verbosity)
"""Standalone markdown document renderer.""" parser = argparse.ArgumentParser( description='Renders markdown on the standard input into a document on ' 'the standard output.') parser.add_argument( '--notes', metavar='SENTENCES', help='Inserts SENTENCES into the NOTES section which is created if ' 'needed.') parser.add_argument('--style', metavar='STYLE', choices=sorted(STYLES.keys()), default='text', help='The output style.') parser.add_argument('--title', metavar='TITLE', help='The document title.') args = parser.parse_args(argv[1:]) RenderDocument(args.style, notes=args.notes, title=args.title, command_metadata=None) if __name__ == '__main__': main(argv_utils.GetDecodedArgv())
# for a response. TIMEOUT_IN_SEC = 10 def ReportMetrics(metrics_file_path): """Sends the specified anonymous usage event to the given analytics endpoint. Args: metrics_file_path: str, File with pickled metrics (list of tuples). """ with files.BinaryFileReader(metrics_file_path) as metrics_file: metrics = pickle.load(metrics_file) os.remove(metrics_file_path) http_client = http.HttpClient(timeout=TIMEOUT_IN_SEC, proxy_info=http_proxy.GetHttpProxyInfo()) for metric in metrics: http_client.request(metric[0], method=metric[1], body=metric[2], headers=metric[3]) if __name__ == '__main__': try: ReportMetrics(argv_utils.GetDecodedArgv()[1]) # pylint: disable=bare-except, Never fail or output a stacktrace here. except: pass