From ed6f279dd3b7ce23e493d06239a6e220c0375135 Mon Sep 17 00:00:00 2001 From: Craig Citro Date: Wed, 28 Mar 2018 22:28:18 -0700 Subject: [PATCH 1/2] Drop all code related to generating CLIs. All of the generated CLI code depends on google-apputils, which is a python2.7-only library. Given that no one is directly using the generated CLIs right now, there's no point in porting it to (say) argparse. Fixes #8. The bulk of the change here is just deletion; I suspect there are now more dangling references, so some tree-shaking/dead-code-elimination could be fruitful. Other changes: * the client generation test now ensures each client can be imported, as opposed to invoking ` --help`. * the samples and sample generating script drop the CLIs. Note that I *did* keep the flag for `gen_client`, so that any existing code passing `--nogenerate_cli` wouldn't be broken. --- apitools/base/py/app2.py | 373 -- apitools/base/py/base_cli.py | 162 - apitools/base/py/cli.py | 35 - apitools/gen/client_generation_test.py | 25 +- apitools/gen/command_registry.py | 608 --- apitools/gen/gen_client.py | 13 +- apitools/gen/gen_client_lib.py | 21 +- apitools/gen/gen_client_test.py | 8 - apitools/gen/service_registry.py | 6 +- apitools/gen/util.py | 8 - .../bigquery_v2/bigquery_v2.py | 1096 ----- samples/dns_sample/dns_v1/dns_v1.py | 554 --- .../fusiontables_v1/fusiontables_v1.py | 1797 --------- samples/iam_sample/iam_v1/iam_v1.py | 921 ----- .../servicemanagement_v1.py | 1520 ------- .../storage_sample/storage_v1/storage_v1.py | 3578 ----------------- samples/uptodate_check_test.py | 2 - setup.py | 7 +- tox.ini | 5 +- 19 files changed, 14 insertions(+), 10725 deletions(-) delete mode 100644 apitools/base/py/app2.py delete mode 100644 apitools/base/py/base_cli.py delete mode 100644 apitools/base/py/cli.py delete mode 100644 apitools/gen/command_registry.py delete mode 100644 samples/bigquery_sample/bigquery_v2/bigquery_v2.py delete mode 100644 samples/dns_sample/dns_v1/dns_v1.py delete mode 100644 samples/fusiontables_sample/fusiontables_v1/fusiontables_v1.py delete mode 100644 samples/iam_sample/iam_v1/iam_v1.py delete mode 100644 samples/servicemanagement_sample/servicemanagement_v1/servicemanagement_v1.py delete mode 100644 samples/storage_sample/storage_v1/storage_v1.py diff --git a/apitools/base/py/app2.py b/apitools/base/py/app2.py deleted file mode 100644 index c0ea9e0a..00000000 --- a/apitools/base/py/app2.py +++ /dev/null @@ -1,373 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Appcommands-compatible command class with extra fixins.""" -from __future__ import absolute_import -from __future__ import print_function - -import cmd -import inspect -import pdb -import shlex -import sys -import traceback -import types - -import gflags as flags -from google.apputils import app -from google.apputils import appcommands -import six - - -__all__ = [ - 'NewCmd', - 'Repl', -] - -flags.DEFINE_boolean( - 'debug_mode', False, - 'Show tracebacks on Python exceptions.') -flags.DEFINE_boolean( - 'headless', False, - 'Assume no user is at the controlling console.') -FLAGS = flags.FLAGS - - -def _SafeMakeAscii(s): - if isinstance(s, six.text_type): - return s.encode('ascii') - elif isinstance(s, str): - return s.decode('ascii') - return six.text_type(s).encode('ascii', 'backslashreplace') - - -class NewCmd(appcommands.Cmd): - - """Featureful extension of appcommands.Cmd.""" - - def __init__(self, name, flag_values): - super(NewCmd, self).__init__(name, flag_values) - run_with_args = getattr(self, 'RunWithArgs', None) - self._new_style = isinstance(run_with_args, types.MethodType) - if self._new_style: - func = run_with_args.__func__ - - argspec = inspect.getargspec(func) - if argspec.args and argspec.args[0] == 'self': - argspec = argspec._replace( # pylint: disable=protected-access - args=argspec.args[1:]) - self._argspec = argspec - # TODO(craigcitro): Do we really want to support all this - # nonsense? - self._star_args = self._argspec.varargs is not None - self._star_kwds = self._argspec.keywords is not None - self._max_args = len(self._argspec.args or ()) - self._min_args = self._max_args - len(self._argspec.defaults or ()) - if self._star_args: - self._max_args = sys.maxsize - - self._debug_mode = FLAGS.debug_mode - self.surface_in_shell = True - self.__doc__ = self.RunWithArgs.__doc__ - - def __getattr__(self, name): - if name in self._command_flags: - return self._command_flags[name].value - return super(NewCmd, self).__getattribute__(name) - - def _GetFlag(self, flagname): - if flagname in self._command_flags: - return self._command_flags[flagname] - return None - - def Run(self, argv): - """Run this command. - - If self is a new-style command, we set up arguments and call - self.RunWithArgs, gracefully handling exceptions. If not, we - simply call self.Run(argv). - - Args: - argv: List of arguments as strings. - - Returns: - 0 on success, nonzero on failure. - """ - if not self._new_style: - return super(NewCmd, self).Run(argv) - - # TODO(craigcitro): We need to save and restore flags each time so - # that we can per-command flags in the REPL. - args = argv[1:] - fail = None - fail_template = '%s positional args, found %d, expected at %s %d' - if len(args) < self._min_args: - fail = fail_template % ('Not enough', len(args), - 'least', self._min_args) - if len(args) > self._max_args: - fail = fail_template % ('Too many', len(args), - 'most', self._max_args) - if fail: - print(fail) - if self.usage: - print('Usage: %s' % (self.usage,)) - return 1 - - if self._debug_mode: - return self.RunDebug(args, {}) - return self.RunSafely(args, {}) - - def RunCmdLoop(self, argv): - """Hook for use in cmd.Cmd-based command shells.""" - try: - args = shlex.split(argv) - except ValueError as e: - raise SyntaxError(self.EncodeForPrinting(e)) - return self.Run([self._command_name] + args) - - @staticmethod - def EncodeForPrinting(s): - """Safely encode a string as the encoding for sys.stdout.""" - encoding = sys.stdout.encoding or 'ascii' - return six.text_type(s).encode(encoding, 'backslashreplace') - - def _FormatError(self, e): - """Hook for subclasses to modify how error messages are printed.""" - return _SafeMakeAscii(e) - - def _HandleError(self, e): - message = self._FormatError(e) - print('Exception raised in %s operation: %s' % ( - self._command_name, message)) - return 1 - - def _IsDebuggableException(self, e): - """Hook for subclasses to skip debugging on certain exceptions.""" - return not isinstance(e, app.UsageError) - - def RunDebug(self, args, kwds): - """Run this command in debug mode.""" - try: - return_value = self.RunWithArgs(*args, **kwds) - except BaseException as e: - # Don't break into the debugger for expected exceptions. - if not self._IsDebuggableException(e): - return self._HandleError(e) - print() - print('****************************************************') - print('** Unexpected Exception raised in execution! **') - if FLAGS.headless: - print('** --headless mode enabled, exiting. **') - print('** See STDERR for traceback. **') - else: - print('** --debug_mode enabled, starting pdb. **') - print('****************************************************') - print() - traceback.print_exc() - print() - if not FLAGS.headless: - pdb.post_mortem() - return 1 - return return_value - - def RunSafely(self, args, kwds): - """Run this command, turning exceptions into print statements.""" - try: - return_value = self.RunWithArgs(*args, **kwds) - except BaseException as e: - return self._HandleError(e) - return return_value - - -class CommandLoop(cmd.Cmd): - - """Instance of cmd.Cmd built to work with NewCmd.""" - - class TerminateSignal(Exception): - - """Exception type used for signaling loop completion.""" - - def __init__(self, commands, prompt): - cmd.Cmd.__init__(self) - self._commands = {'help': commands['help']} - self._special_command_names = ['help', 'repl', 'EOF'] - for name, command in commands.items(): - if (name not in self._special_command_names and - isinstance(command, NewCmd) and - command.surface_in_shell): - self._commands[name] = command - setattr(self, 'do_%s' % (name,), command.RunCmdLoop) - self._default_prompt = prompt - self._set_prompt() - self._last_return_code = 0 - - @property - def last_return_code(self): - return self._last_return_code - - def _set_prompt(self): # pylint: disable=invalid-name - self.prompt = self._default_prompt - - def do_EOF(self, *unused_args): # pylint: disable=invalid-name - """Terminate the running command loop. - - This function raises an exception to avoid the need to do - potentially-error-prone string parsing inside onecmd. - - Args: - *unused_args: unused. - - Returns: - Never returns. - - Raises: - CommandLoop.TerminateSignal: always. - """ - raise CommandLoop.TerminateSignal() - - def postloop(self): - print('Goodbye.') - - # pylint: disable=arguments-differ - def completedefault(self, unused_text, line, unused_begidx, unused_endidx): - if not line: - return [] - else: - command_name = line.partition(' ')[0].lower() - usage = '' - if command_name in self._commands: - usage = self._commands[command_name].usage - if usage: - print() - print(usage) - print('%s%s' % (self.prompt, line), end=' ') - return [] - # pylint: enable=arguments-differ - - def emptyline(self): - print('Available commands:', end=' ') - print(' '.join(list(self._commands))) - - def precmd(self, line): - """Preprocess the shell input.""" - if line == 'EOF': - return line - if line.startswith('exit') or line.startswith('quit'): - return 'EOF' - words = line.strip().split() - if len(words) == 1 and words[0] not in ['help', 'ls', 'version']: - return 'help %s' % (line.strip(),) - return line - - def onecmd(self, line): - """Process a single command. - - Runs a single command, and stores the return code in - self._last_return_code. Always returns False unless the command - was EOF. - - Args: - line: (str) Command line to process. - - Returns: - A bool signaling whether or not the command loop should terminate. - """ - try: - self._last_return_code = cmd.Cmd.onecmd(self, line) - except CommandLoop.TerminateSignal: - return True - except BaseException as e: - name = line.split(' ')[0] - print('Error running %s:' % name) - print(e) - self._last_return_code = 1 - return False - - def get_names(self): - names = dir(self) - commands = (name for name in self._commands - if name not in self._special_command_names) - names.extend('do_%s' % (name,) for name in commands) - names.remove('do_EOF') - return names - - def do_help(self, arg): - """Print the help for command_name (if present) or general help.""" - - command_name = arg - - # TODO(craigcitro): Add command-specific flags. - def FormatOneCmd(name, command, command_names): - """Format one command.""" - indent_size = appcommands.GetMaxCommandLength() + 3 - if len(command_names) > 1: - indent = ' ' * indent_size - command_help = flags.TextWrap( - command.CommandGetHelp('', cmd_names=command_names), - indent=indent, - firstline_indent='') - first_help_line, _, rest = command_help.partition('\n') - first_line = '%-*s%s' % (indent_size, - name + ':', first_help_line) - return '\n'.join((first_line, rest)) - default_indent = ' ' - return '\n' + flags.TextWrap( - command.CommandGetHelp('', cmd_names=command_names), - indent=default_indent, - firstline_indent=default_indent) + '\n' - - if not command_name: - print('\nHelp for commands:\n') - command_names = list(self._commands) - print('\n\n'.join( - FormatOneCmd(name, command, command_names) - for name, command in self._commands.items() - if name not in self._special_command_names)) - print() - elif command_name in self._commands: - print(FormatOneCmd(command_name, self._commands[command_name], - command_names=[command_name])) - return 0 - - def postcmd(self, stop, line): - return bool(stop) or line == 'EOF' - - -class Repl(NewCmd): - - """Start an interactive session.""" - PROMPT = '> ' - - def __init__(self, name, fv): - super(Repl, self).__init__(name, fv) - self.surface_in_shell = False - flags.DEFINE_string( - 'prompt', '', - 'Prompt to use for interactive shell.', - flag_values=fv) - - def RunWithArgs(self): - """Start an interactive session.""" - prompt = FLAGS.prompt or self.PROMPT - repl = CommandLoop(appcommands.GetCommandList(), prompt=prompt) - print('Welcome! (Type help for more information.)') - while True: - try: - repl.cmdloop() - break - except KeyboardInterrupt: - print() - return repl.last_return_code diff --git a/apitools/base/py/base_cli.py b/apitools/base/py/base_cli.py deleted file mode 100644 index 70515c1a..00000000 --- a/apitools/base/py/base_cli.py +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Base script for generated CLI.""" - -from __future__ import absolute_import - -import atexit -import code -import logging -import os -import readline -import rlcompleter -import sys - -import gflags as flags -from google.apputils import appcommands - -from apitools.base.py import encoding -from apitools.base.py import exceptions - -__all__ = [ - 'ConsoleWithReadline', - 'DeclareBaseFlags', - 'FormatOutput', - 'SetupLogger', - 'run_main', -] - - -# TODO(craigcitro): We should move all the flags for the -# StandardQueryParameters into this file, so that they can be used -# elsewhere easily. - -_BASE_FLAGS_DECLARED = False -_OUTPUT_FORMATTER_MAP = { - 'protorpc': lambda x: x, - 'json': encoding.MessageToJson, -} - - -def DeclareBaseFlags(): - """Declare base flags for all CLIs.""" - # TODO(craigcitro): FlagValidators? - global _BASE_FLAGS_DECLARED # pylint: disable=global-statement - if _BASE_FLAGS_DECLARED: - return - flags.DEFINE_boolean( - 'log_request', False, - 'Log requests.') - flags.DEFINE_boolean( - 'log_response', False, - 'Log responses.') - flags.DEFINE_boolean( - 'log_request_response', False, - 'Log requests and responses.') - flags.DEFINE_enum( - 'output_format', - 'protorpc', - _OUTPUT_FORMATTER_MAP.keys(), - 'Display format for results.') - - _BASE_FLAGS_DECLARED = True - - -FLAGS = flags.FLAGS - - -def SetupLogger(): - if FLAGS.log_request or FLAGS.log_response or FLAGS.log_request_response: - logging.basicConfig() - logging.getLogger().setLevel(logging.INFO) - - -def FormatOutput(message, output_format=None): - """Convert the output to the user-specified format.""" - output_format = output_format or FLAGS.output_format - formatter = _OUTPUT_FORMATTER_MAP.get(FLAGS.output_format) - if formatter is None: - raise exceptions.UserError('Unknown output format: %s' % output_format) - return formatter(message) - - -class _SmartCompleter(rlcompleter.Completer): - - def _callable_postfix(self, val, word): - if ('(' in readline.get_line_buffer() or - not callable(val)): - return word - return word + '(' - - def complete(self, text, state): - if not readline.get_line_buffer().strip(): - if not state: - return ' ' - return None - return rlcompleter.Completer.complete(self, text, state) - - -class ConsoleWithReadline(code.InteractiveConsole): - - """InteractiveConsole with readline, tab completion, and history.""" - - def __init__(self, env, filename='', histfile=None): - new_locals = dict(env) - new_locals.update({ - '_SmartCompleter': _SmartCompleter, - 'readline': readline, - 'rlcompleter': rlcompleter, - }) - code.InteractiveConsole.__init__(self, new_locals, filename) - readline.parse_and_bind('tab: complete') - readline.set_completer(_SmartCompleter(new_locals).complete) - if histfile is not None: - histfile = os.path.expanduser(histfile) - if os.path.exists(histfile): - readline.read_history_file(histfile) - atexit.register(lambda: readline.write_history_file(histfile)) - - -def run_main(): # pylint: disable=invalid-name - """Function to be used as setuptools script entry point. - - Appcommands assumes that it always runs as __main__, but launching - via a setuptools-generated entry_point breaks this rule. We do some - trickery here to make sure that appcommands and flags find their - state where they expect to by faking ourselves as __main__. - """ - - # Put the flags for this module somewhere the flags module will look - # for them. - # pylint: disable=protected-access - new_name = flags._GetMainModule() - sys.modules[new_name] = sys.modules['__main__'] - for flag in FLAGS.FlagsByModuleDict().get(__name__, []): - FLAGS._RegisterFlagByModule(new_name, flag) - for key_flag in FLAGS.KeyFlagsByModuleDict().get(__name__, []): - FLAGS._RegisterKeyFlagForModule(new_name, key_flag) - # pylint: enable=protected-access - - # Now set __main__ appropriately so that appcommands will be - # happy. - sys.modules['__main__'] = sys.modules[__name__] - appcommands.Run() - sys.modules['__main__'] = sys.modules.pop(new_name) - - -if __name__ == '__main__': - appcommands.Run() diff --git a/apitools/base/py/cli.py b/apitools/base/py/cli.py deleted file mode 100644 index 920cfc59..00000000 --- a/apitools/base/py/cli.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Top-level import for all CLI-related functionality in apitools. - -Note that importing this file will ultimately have side-effects, and -may require imports not available in all environments (such as App -Engine). In particular, picking up some readline-related imports can -cause pain. -""" - -# pylint:disable=wildcard-import -# pylint:disable=unused-wildcard-import - -from apitools.base.py.app2 import * -from apitools.base.py.base_cli import * - -try: - # pylint:disable=no-name-in-module - from apitools.base.py.internal.cli import * -except ImportError: - pass diff --git a/apitools/gen/client_generation_test.py b/apitools/gen/client_generation_test.py index 5e7932a5..8a2f8e87 100644 --- a/apitools/gen/client_generation_test.py +++ b/apitools/gen/client_generation_test.py @@ -15,9 +15,11 @@ """Test gen_client against all the APIs we use regularly.""" +import importlib import logging import os import subprocess +import sys import tempfile import unittest2 @@ -27,9 +29,9 @@ _API_LIST = [ - 'drive.v2', 'bigquery.v2', 'compute.v1', + 'drive.v3', 'storage.v1', ] @@ -62,20 +64,7 @@ def testGeneration(self): continue self.assertEqual(0, retcode) - with tempfile.NamedTemporaryFile() as out: - with tempfile.NamedTemporaryFile() as err: - cmdline_args = [ - os.path.join( - 'generated', api.replace('.', '_') + '.py'), - 'help', - ] - retcode = subprocess.call( - cmdline_args, stdout=out, stderr=err) - with open(err.name, 'rb') as f: - err_output = f.read() - # appcommands returns 1 on help - self.assertEqual(1, retcode) - if 'Traceback (most recent call last):' in err_output: - err = '\n======\n%s======\n' % err_output - self.fail( - 'Error raised in generated client:' + err) + sys.path.insert(0, os.path.join(os.getcwd(), 'generated')) + # Ensure we can import the generated client. + importlib.import_module('{}_{}_client'.format( + *api.split('.'))) diff --git a/apitools/gen/command_registry.py b/apitools/gen/command_registry.py deleted file mode 100644 index 486934fa..00000000 --- a/apitools/gen/command_registry.py +++ /dev/null @@ -1,608 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Command registry for apitools.""" - -import logging -import textwrap - -from apitools.base.protorpclite import descriptor -from apitools.base.protorpclite import messages -from apitools.gen import extended_descriptor - -# This is a code generator; we're purposely verbose. -# pylint:disable=too-many-statements - -_VARIANT_TO_FLAG_TYPE_MAP = { - messages.Variant.DOUBLE: 'float', - messages.Variant.FLOAT: 'float', - messages.Variant.INT64: 'string', - messages.Variant.UINT64: 'string', - messages.Variant.INT32: 'integer', - messages.Variant.BOOL: 'boolean', - messages.Variant.STRING: 'string', - messages.Variant.MESSAGE: 'string', - messages.Variant.BYTES: 'string', - messages.Variant.UINT32: 'integer', - messages.Variant.ENUM: 'enum', - messages.Variant.SINT32: 'integer', - messages.Variant.SINT64: 'integer', -} - - -class FlagInfo(messages.Message): - - """Information about a flag and conversion to a message. - - Fields: - name: name of this flag. - type: type of the flag. - description: description of the flag. - default: default value for this flag. - enum_values: if this flag is an enum, the list of possible - values. - required: whether or not this flag is required. - fv: name of the flag_values object where this flag should - be registered. - conversion: template for type conversion. - special: (boolean, default: False) If True, this flag doesn't - correspond to an attribute on the request. - """ - name = messages.StringField(1) - type = messages.StringField(2) - description = messages.StringField(3) - default = messages.StringField(4) - enum_values = messages.StringField(5, repeated=True) - required = messages.BooleanField(6, default=False) - fv = messages.StringField(7) - conversion = messages.StringField(8) - special = messages.BooleanField(9, default=False) - - -class ArgInfo(messages.Message): - - """Information about a single positional command argument. - - Fields: - name: argument name. - description: description of this argument. - conversion: template for type conversion. - """ - name = messages.StringField(1) - description = messages.StringField(2) - conversion = messages.StringField(3) - - -class CommandInfo(messages.Message): - - """Information about a single command. - - Fields: - name: name of this command. - class_name: name of the apitools_base.NewCmd class for this command. - description: description of this command. - flags: list of FlagInfo messages for the command-specific flags. - args: list of ArgInfo messages for the positional args. - request_type: name of the request type for this command. - client_method_path: path from the client object to the method - this command is wrapping. - """ - name = messages.StringField(1) - class_name = messages.StringField(2) - description = messages.StringField(3) - flags = messages.MessageField(FlagInfo, 4, repeated=True) - args = messages.MessageField(ArgInfo, 5, repeated=True) - request_type = messages.StringField(6) - client_method_path = messages.StringField(7) - has_upload = messages.BooleanField(8, default=False) - has_download = messages.BooleanField(9, default=False) - - -class CommandRegistry(object): - - """Registry for CLI commands.""" - - def __init__(self, package, version, client_info, message_registry, - root_package, base_files_package, protorpc_package, names): - self.__package = package - self.__version = version - self.__client_info = client_info - self.__names = names - self.__message_registry = message_registry - self.__root_package = root_package - self.__base_files_package = base_files_package - self.__protorpc_package = protorpc_package - self.__command_list = [] - self.__global_flags = [] - - def Validate(self): - self.__message_registry.Validate() - - def AddGlobalParameters(self, schema): - for field in schema.fields: - self.__global_flags.append(self.__FlagInfoFromField(field, schema)) - - def AddCommandForMethod(self, service_name, method_name, method_info, - request, _): - """Add the given method as a command.""" - command_name = self.__GetCommandName(method_info.method_id) - calling_path = '%s.%s' % (service_name, method_name) - request_type = self.__message_registry.LookupDescriptor(request) - description = method_info.description - if not description: - description = 'Call the %s method.' % method_info.method_id - field_map = dict((f.name, f) for f in request_type.fields) - args = [] - arg_names = [] - for field_name in method_info.ordered_params: - extended_field = field_map[field_name] - name = extended_field.name - args.append(ArgInfo( - name=name, - description=extended_field.description, - conversion=self.__GetConversion(extended_field, request_type), - )) - arg_names.append(name) - flags = [] - for extended_field in sorted(request_type.fields, - key=lambda x: x.name): - field = extended_field.field_descriptor - if extended_field.name in arg_names: - continue - if self.__FieldIsRequired(field): - logging.warning( - 'Required field %s not in ordered_params for command %s', - extended_field.name, command_name) - flags.append(self.__FlagInfoFromField( - extended_field, request_type, fv='fv')) - if method_info.upload_config: - # TODO(craigcitro): Consider adding additional flags to allow - # determining the filename from the object metadata. - upload_flag_info = FlagInfo( - name='upload_filename', type='string', default='', - description='Filename to use for upload.', fv='fv', - special=True) - flags.append(upload_flag_info) - mime_description = ( - 'MIME type to use for the upload. Only needed if ' - 'the extension on --upload_filename does not determine ' - 'the correct (or any) MIME type.') - mime_type_flag_info = FlagInfo( - name='upload_mime_type', type='string', default='', - description=mime_description, fv='fv', special=True) - flags.append(mime_type_flag_info) - if method_info.supports_download: - download_flag_info = FlagInfo( - name='download_filename', type='string', default='', - description='Filename to use for download.', fv='fv', - special=True) - flags.append(download_flag_info) - overwrite_description = ( - 'If True, overwrite the existing file when downloading.') - overwrite_flag_info = FlagInfo( - name='overwrite', type='boolean', default='False', - description=overwrite_description, fv='fv', special=True) - flags.append(overwrite_flag_info) - command_info = CommandInfo( - name=command_name, - class_name=self.__names.ClassName(command_name), - description=description, - flags=flags, - args=args, - request_type=request_type.full_name, - client_method_path=calling_path, - has_upload=bool(method_info.upload_config), - has_download=bool(method_info.supports_download) - ) - self.__command_list.append(command_info) - - def __LookupMessage(self, message, field): - message_type = self.__message_registry.LookupDescriptor( - '%s.%s' % (message.name, field.type_name)) - if message_type is None: - message_type = self.__message_registry.LookupDescriptor( - field.type_name) - return message_type - - def __GetCommandName(self, method_id): - command_name = method_id - prefix = '%s.' % self.__package - if command_name.startswith(prefix): - command_name = command_name[len(prefix):] - command_name = command_name.replace('.', '_') - return command_name - - def __GetConversion(self, extended_field, extended_message): - """Returns a template for field type.""" - field = extended_field.field_descriptor - - type_name = '' - if field.variant in (messages.Variant.MESSAGE, messages.Variant.ENUM): - if field.type_name.startswith('apitools.base.protorpclite.'): - type_name = field.type_name - else: - field_message = self.__LookupMessage(extended_message, field) - if field_message is None: - raise ValueError( - 'Could not find type for field %s' % field.name) - type_name = 'messages.%s' % field_message.full_name - - template = '' - if field.variant in (messages.Variant.INT64, messages.Variant.UINT64): - template = 'int(%s)' - elif field.variant == messages.Variant.MESSAGE: - template = 'apitools_base.JsonToMessage(%s, %%s)' % type_name - elif field.variant == messages.Variant.ENUM: - template = '%s(%%s)' % type_name - elif field.variant == messages.Variant.STRING: - template = "%s.decode('utf8')" - - if self.__FieldIsRepeated(extended_field.field_descriptor): - if template: - template = '[%s for x in %%s]' % (template % 'x') - - return template - - def __FieldIsRequired(self, field): - return field.label == descriptor.FieldDescriptor.Label.REQUIRED - - def __FieldIsRepeated(self, field): - return field.label == descriptor.FieldDescriptor.Label.REPEATED - - def __FlagInfoFromField(self, extended_field, extended_message, fv=''): - """Creates FlagInfo object for given field.""" - field = extended_field.field_descriptor - flag_info = FlagInfo() - flag_info.name = str(field.name) - # TODO(craigcitro): We should key by variant. - flag_info.type = _VARIANT_TO_FLAG_TYPE_MAP[field.variant] - flag_info.description = extended_field.description - if field.default_value: - # TODO(craigcitro): Formatting? - flag_info.default = field.default_value - if flag_info.type == 'enum': - # TODO(craigcitro): Does protorpc do this for us? - enum_type = self.__LookupMessage(extended_message, field) - if enum_type is None: - raise ValueError('Cannot find enum type %s', field.type_name) - flag_info.enum_values = [x.name for x in enum_type.values] - # Note that this choice is completely arbitrary -- but we only - # push the value through if the user specifies it, so this - # doesn't hurt anything. - if flag_info.default is None: - flag_info.default = flag_info.enum_values[0] - if self.__FieldIsRequired(field): - flag_info.required = True - flag_info.fv = fv - flag_info.conversion = self.__GetConversion( - extended_field, extended_message) - return flag_info - - def __PrintFlagDeclarations(self, printer): - """Writes out command line flag declarations.""" - package = self.__client_info.package - function_name = '_Declare%sFlags' % (package[0].upper() + package[1:]) - printer() - printer() - printer('def %s():', function_name) - with printer.Indent(): - printer('"""Declare global flags in an idempotent way."""') - printer("if 'api_endpoint' in flags.FLAGS:") - with printer.Indent(): - printer('return') - printer('flags.DEFINE_string(') - with printer.Indent(' '): - printer("'api_endpoint',") - printer('%r,', self.__client_info.base_url) - printer("'URL of the API endpoint to use.',") - printer("short_name='%s_url')", self.__package) - printer('flags.DEFINE_string(') - with printer.Indent(' '): - printer("'history_file',") - printer('%r,', '~/.%s.%s.history' % - (self.__package, self.__version)) - printer("'File with interactive shell history.')") - printer('flags.DEFINE_multistring(') - with printer.Indent(' '): - printer("'add_header', [],") - printer("'Additional http headers (as key=value strings). '") - printer("'Can be specified multiple times.')") - printer('flags.DEFINE_string(') - with printer.Indent(' '): - printer("'service_account_json_keyfile', '',") - printer("'Filename for a JSON service account key downloaded'") - printer("' from the Developer Console.')") - for flag_info in self.__global_flags: - self.__PrintFlag(printer, flag_info) - printer() - printer() - printer('FLAGS = flags.FLAGS') - printer('apitools_base_cli.DeclareBaseFlags()') - printer('%s()', function_name) - - def __PrintGetGlobalParams(self, printer): - """Writes out GetGlobalParamsFromFlags function.""" - printer('def GetGlobalParamsFromFlags():') - with printer.Indent(): - printer('"""Return a StandardQueryParameters based on flags."""') - printer('result = messages.StandardQueryParameters()') - - for flag_info in self.__global_flags: - rhs = 'FLAGS.%s' % flag_info.name - if flag_info.conversion: - rhs = flag_info.conversion % rhs - printer('if FLAGS[%r].present:', flag_info.name) - with printer.Indent(): - printer('result.%s = %s', flag_info.name, rhs) - printer('return result') - printer() - printer() - - def __PrintGetClient(self, printer): - """Writes out GetClientFromFlags function.""" - printer('def GetClientFromFlags():') - with printer.Indent(): - printer('"""Return a client object, configured from flags."""') - printer('log_request = FLAGS.log_request or ' - 'FLAGS.log_request_response') - printer('log_response = FLAGS.log_response or ' - 'FLAGS.log_request_response') - printer('api_endpoint = apitools_base.NormalizeApiEndpoint(' - 'FLAGS.api_endpoint)') - printer("additional_http_headers = dict(x.split('=', 1) for x in " - "FLAGS.add_header)") - printer('credentials_args = {') - with printer.Indent(' '): - printer("'service_account_json_keyfile': os.path.expanduser(" - 'FLAGS.service_account_json_keyfile)') - printer('}') - printer('try:') - with printer.Indent(): - printer('client = client_lib.%s(', - self.__client_info.client_class_name) - with printer.Indent(indent=' '): - printer('api_endpoint, log_request=log_request,') - printer('log_response=log_response,') - printer('credentials_args=credentials_args,') - printer('additional_http_headers=additional_http_headers)') - printer('except apitools_base.CredentialsError as e:') - with printer.Indent(): - printer("print 'Error creating credentials: %%s' %% e") - printer('sys.exit(1)') - printer('return client') - printer() - printer() - - def __PrintCommandDocstring(self, printer, command_info): - with printer.CommentContext(): - for line in textwrap.wrap('"""%s' % command_info.description, - printer.CalculateWidth()): - printer(line) - extended_descriptor.PrintIndentedDescriptions( - printer, command_info.args, 'Args') - extended_descriptor.PrintIndentedDescriptions( - printer, command_info.flags, 'Flags') - printer('"""') - - def __PrintFlag(self, printer, flag_info): - """Writes out given flag definition.""" - printer('flags.DEFINE_%s(', flag_info.type) - with printer.Indent(indent=' '): - printer('%r,', flag_info.name) - printer('%r,', flag_info.default) - if flag_info.type == 'enum': - printer('%r,', flag_info.enum_values) - - # TODO(craigcitro): Consider using 'drop_whitespace' elsewhere. - description_lines = textwrap.wrap( - flag_info.description, 75 - len(printer.indent), - drop_whitespace=False) - for line in description_lines[:-1]: - printer('%r', line) - last_line = description_lines[-1] if description_lines else '' - printer('%r%s', last_line, ',' if flag_info.fv else ')') - if flag_info.fv: - printer('flag_values=%s)', flag_info.fv) - if flag_info.required: - printer('flags.MarkFlagAsRequired(%r)', flag_info.name) - - def __PrintPyShell(self, printer): - """Writes out PyShell class.""" - printer('class PyShell(appcommands.Cmd):') - printer() - with printer.Indent(): - printer('def Run(self, _):') - with printer.Indent(): - printer( - '"""Run an interactive python shell with the client."""') - printer('client = GetClientFromFlags()') - printer('params = GetGlobalParamsFromFlags()') - printer('for field in params.all_fields():') - with printer.Indent(): - printer('value = params.get_assigned_value(field.name)') - printer('if value != field.default:') - with printer.Indent(): - printer('client.AddGlobalParam(field.name, value)') - printer('banner = """') - printer(' == %s interactive console ==' % ( - self.__client_info.package)) - printer(' client: a %s client' % - self.__client_info.package) - printer(' apitools_base: base apitools module') - printer(' messages: the generated messages module') - printer('"""') - printer('local_vars = {') - with printer.Indent(indent=' '): - printer("'apitools_base': apitools_base,") - printer("'client': client,") - printer("'client_lib': client_lib,") - printer("'messages': messages,") - printer('}') - printer("if platform.system() == 'Linux':") - with printer.Indent(): - printer('console = apitools_base_cli.ConsoleWithReadline(') - with printer.Indent(indent=' '): - printer('local_vars, histfile=FLAGS.history_file)') - printer('else:') - with printer.Indent(): - printer('console = code.InteractiveConsole(local_vars)') - printer('try:') - with printer.Indent(): - printer('console.interact(banner)') - printer('except SystemExit as e:') - with printer.Indent(): - printer('return e.code') - printer() - printer() - - def WriteFile(self, printer): - """Write a simple CLI (currently just a stub).""" - printer('#!/usr/bin/env python') - printer('"""CLI for %s, version %s."""', - self.__package, self.__version) - printer('# NOTE: This file is autogenerated and should not be edited ' - 'by hand.') - # TODO(craigcitro): Add a build stamp, along with some other - # information. - printer() - printer('import code') - printer('import os') - printer('import platform') - printer('import sys') - printer() - printer('from %s import message_types', self.__protorpc_package) - printer('from %s import messages', self.__protorpc_package) - printer() - appcommands_import = 'from google.apputils import appcommands' - printer(appcommands_import) - - flags_import = 'import gflags as flags' - printer(flags_import) - printer() - printer('import %s as apitools_base', self.__base_files_package) - printer('from %s import cli as apitools_base_cli', - self.__base_files_package) - import_prefix = '' - printer('%simport %s as client_lib', - import_prefix, self.__client_info.client_rule_name) - printer('%simport %s as messages', - import_prefix, self.__client_info.messages_rule_name) - self.__PrintFlagDeclarations(printer) - printer() - printer() - self.__PrintGetGlobalParams(printer) - self.__PrintGetClient(printer) - self.__PrintPyShell(printer) - self.__PrintCommands(printer) - printer('def main(_):') - with printer.Indent(): - printer("appcommands.AddCmd('pyshell', PyShell)") - for command_info in self.__command_list: - printer("appcommands.AddCmd('%s', %s)", - command_info.name, command_info.class_name) - printer() - printer('apitools_base_cli.SetupLogger()') - # TODO(craigcitro): Just call SetDefaultCommand as soon as - # another appcommands release happens and this exists - # externally. - printer("if hasattr(appcommands, 'SetDefaultCommand'):") - with printer.Indent(): - printer("appcommands.SetDefaultCommand('pyshell')") - printer() - printer() - printer('run_main = apitools_base_cli.run_main') - printer() - printer("if __name__ == '__main__':") - with printer.Indent(): - printer('appcommands.Run()') - - def __PrintCommands(self, printer): - """Print all commands in this registry using printer.""" - for command_info in self.__command_list: - arg_list = [arg_info.name for arg_info in command_info.args] - printer( - 'class %s(apitools_base_cli.NewCmd):', command_info.class_name) - with printer.Indent(): - printer('"""Command wrapping %s."""', - command_info.client_method_path) - printer() - printer('usage = """%s%s%s"""', - command_info.name, - ' ' if arg_list else '', - ' '.join('<%s>' % argname for argname in arg_list)) - printer() - printer('def __init__(self, name, fv):') - with printer.Indent(): - printer('super(%s, self).__init__(name, fv)', - command_info.class_name) - for flag in command_info.flags: - self.__PrintFlag(printer, flag) - printer() - printer('def RunWithArgs(%s):', ', '.join(['self'] + arg_list)) - with printer.Indent(): - self.__PrintCommandDocstring(printer, command_info) - printer('client = GetClientFromFlags()') - printer('global_params = GetGlobalParamsFromFlags()') - printer( - 'request = messages.%s(', command_info.request_type) - with printer.Indent(indent=' '): - for arg in command_info.args: - rhs = arg.name - if arg.conversion: - rhs = arg.conversion % arg.name - printer('%s=%s,', arg.name, rhs) - printer(')') - for flag_info in command_info.flags: - if flag_info.special: - continue - rhs = 'FLAGS.%s' % flag_info.name - if flag_info.conversion: - rhs = flag_info.conversion % rhs - printer('if FLAGS[%r].present:', flag_info.name) - with printer.Indent(): - printer('request.%s = %s', flag_info.name, rhs) - call_args = ['request', 'global_params=global_params'] - if command_info.has_upload: - call_args.append('upload=upload') - printer('upload = None') - printer('if FLAGS.upload_filename:') - with printer.Indent(): - printer('upload = apitools_base.Upload.FromFile(') - printer(' FLAGS.upload_filename, ' - 'FLAGS.upload_mime_type,') - printer(' progress_callback=' - 'apitools_base.UploadProgressPrinter,') - printer(' finish_callback=' - 'apitools_base.UploadCompletePrinter)') - if command_info.has_download: - call_args.append('download=download') - printer('download = None') - printer('if FLAGS.download_filename:') - with printer.Indent(): - printer('download = apitools_base.Download.' - 'FromFile(FLAGS.download_filename, ' - 'overwrite=FLAGS.overwrite,') - printer(' progress_callback=' - 'apitools_base.DownloadProgressPrinter,') - printer(' finish_callback=' - 'apitools_base.DownloadCompletePrinter)') - printer( - 'result = client.%s(', command_info.client_method_path) - with printer.Indent(indent=' '): - printer('%s)', ', '.join(call_args)) - printer('print apitools_base_cli.FormatOutput(result)') - printer() - printer() diff --git a/apitools/gen/gen_client.py b/apitools/gen/gen_client.py index 462b3470..7027523f 100644 --- a/apitools/gen/gen_client.py +++ b/apitools/gen/gen_client.py @@ -98,7 +98,6 @@ def _GetCodegenFromFlags(args): discovery_doc, client_info, names, args.root_package, outdir, base_package=args.base_package, protorpc_package=args.protorpc_package, - generate_cli=args.generate_cli, init_wildcards_file=(args.init_file == 'wildcards'), use_proto2=args.experimental_proto2_output, unelidable_request_methods=args.unelidable_request_methods, @@ -108,9 +107,7 @@ def _GetCodegenFromFlags(args): # TODO(craigcitro): Delete this if we don't need this functionality. def _WriteBaseFiles(codegen): with util.Chdir(codegen.outdir): - _CopyLocalFile('app2.py') _CopyLocalFile('base_api.py') - _CopyLocalFile('base_cli.py') _CopyLocalFile('credentials_lib.py') _CopyLocalFile('exceptions.py') @@ -136,10 +133,6 @@ def _WriteGeneratedFiles(args, codegen): codegen.WriteMessagesFile(out) with open(codegen.client_info.client_file_name, 'w') as out: codegen.WriteClientLibrary(out) - if args.generate_cli: - with open(codegen.client_info.cli_file_name, 'w') as out: - codegen.WriteCli(out) - os.chmod(codegen.client_info.cli_file_name, 0o755) def _WriteInit(codegen): @@ -176,7 +169,6 @@ def GeneratePipPackage(args): args.outdir = os.path.join( args.outdir, 'apitools/clients/%s' % package) args.root_package = 'apitools.clients.%s' % package - args.generate_cli = False codegen = _GetCodegenFromFlags(args) if codegen is None: logging.error('Failed to create codegen, exiting.') @@ -287,11 +279,10 @@ def main(argv=None): parser.add_argument( '--generate_cli', dest='generate_cli', action='store_true', - help='If specified (default), a CLI is also generated.') + help='Ignored.') parser.add_argument( '--nogenerate_cli', dest='generate_cli', action='store_false', - help='CLI will not be generated.') - parser.set_defaults(generate_cli=True) + help='Ignored.') parser.add_argument( '--init-file', diff --git a/apitools/gen/gen_client_lib.py b/apitools/gen/gen_client_lib.py index b910f0f7..1796762e 100644 --- a/apitools/gen/gen_client_lib.py +++ b/apitools/gen/gen_client_lib.py @@ -22,7 +22,6 @@ import datetime -from apitools.gen import command_registry from apitools.gen import message_registry from apitools.gen import service_registry from apitools.gen import util @@ -63,8 +62,7 @@ class DescriptorGenerator(object): """Code generator for a given discovery document.""" def __init__(self, discovery_doc, client_info, names, root_package, outdir, - base_package, protorpc_package, generate_cli=False, - init_wildcards_file=True, + base_package, protorpc_package, init_wildcards_file=True, use_proto2=False, unelidable_request_methods=None, apitools_version=''): self.__discovery_doc = discovery_doc @@ -76,7 +74,6 @@ def __init__(self, discovery_doc, client_info, names, root_package, outdir, self.__package = self.__client_info.package self.__version = self.__client_info.version self.__revision = discovery_doc.get('revision', '1') - self.__generate_cli = generate_cli self.__init_wildcards_file = init_wildcards_file self.__root_package = root_package self.__base_files_package = base_package @@ -104,19 +101,9 @@ def __init__(self, discovery_doc, client_info, names, root_package, outdir, # fields from MessageFields to EnumFields. self.__message_registry.FixupMessageFields() - self.__command_registry = command_registry.CommandRegistry( - self.__package, self.__version, self.__client_info, - self.__message_registry, self.__root_package, - self.__base_files_package, self.__protorpc_package, - self.__names) - self.__command_registry.AddGlobalParameters( - self.__message_registry.LookupDescriptorOrDie( - 'StandardQueryParameters')) - self.__services_registry = service_registry.ServiceRegistry( self.__client_info, self.__message_registry, - self.__command_registry, self.__names, self.__root_package, self.__base_files_package, @@ -189,9 +176,6 @@ def WriteInit(self, out): import_prefix = '' else: import_prefix = '%s.' % self.__root_package - if self.__generate_cli: - printer('from %s%s import *', - import_prefix, self.__client_info.cli_rule_name) printer('from %s%s import *', import_prefix, self.__client_info.client_rule_name) printer('from %s%s import *', @@ -281,6 +265,3 @@ def WriteServicesProtoFile(self, out): def WriteClientLibrary(self, out): self.__services_registry.WriteFile(self._GetPrinter(out)) - - def WriteCli(self, out): - self.__command_registry.WriteFile(self._GetPrinter(out)) diff --git a/apitools/gen/gen_client_test.py b/apitools/gen/gen_client_test.py index 3be3e7a9..a0dbc9e4 100644 --- a/apitools/gen/gen_client_test.py +++ b/apitools/gen/gen_client_test.py @@ -47,7 +47,6 @@ def testGenClient_SimpleDocNoInit(self): with test_utils.TempDir() as tmp_dir_path: gen_client.main([ gen_client.__file__, - '--generate_cli', '--init-file', 'none', '--infile', GetTestDataPath('dns', 'dns_v1.json'), '--outdir', tmp_dir_path, @@ -56,7 +55,6 @@ def testGenClient_SimpleDocNoInit(self): 'client' ]) expected_files = ( - set(['dns_v1.py']) | # CLI files set(['dns_v1_client.py', 'dns_v1_messages.py'])) self.assertEquals(expected_files, set(os.listdir(tmp_dir_path))) @@ -64,7 +62,6 @@ def testGenClient_SimpleDocEmptyInit(self): with test_utils.TempDir() as tmp_dir_path: gen_client.main([ gen_client.__file__, - '--generate_cli', '--init-file', 'empty', '--infile', GetTestDataPath('dns', 'dns_v1.json'), '--outdir', tmp_dir_path, @@ -73,7 +70,6 @@ def testGenClient_SimpleDocEmptyInit(self): 'client' ]) expected_files = ( - set(['dns_v1.py']) | # CLI files set(['dns_v1_client.py', 'dns_v1_messages.py', '__init__.py'])) self.assertEquals(expected_files, set(os.listdir(tmp_dir_path))) init_file = _GetContent(os.path.join(tmp_dir_path, '__init__.py')) @@ -88,7 +84,6 @@ def testGenClient_SimpleDocWithV4(self): with test_utils.TempDir() as tmp_dir_path: gen_client.main([ gen_client.__file__, - '--nogenerate_cli', '--infile', GetTestDataPath('dns', 'dns_v1.json'), '--outdir', tmp_dir_path, '--overwrite', @@ -104,7 +99,6 @@ def testGenClient_SimpleDocWithV5(self): with test_utils.TempDir() as tmp_dir_path: gen_client.main([ gen_client.__file__, - '--nogenerate_cli', '--infile', GetTestDataPath('dns', 'dns_v1.json'), '--outdir', tmp_dir_path, '--overwrite', @@ -120,7 +114,6 @@ def testGenPipPackage_SimpleDoc(self): with test_utils.TempDir() as tmp_dir_path: gen_client.main([ gen_client.__file__, - '--nogenerate_cli', '--infile', GetTestDataPath('dns', 'dns_v1.json'), '--outdir', tmp_dir_path, '--overwrite', @@ -135,7 +128,6 @@ def testGenProto_SimpleDoc(self): with test_utils.TempDir() as tmp_dir_path: gen_client.main([ gen_client.__file__, - '--nogenerate_cli', '--infile', GetTestDataPath('dns', 'dns_v1.json'), '--outdir', tmp_dir_path, '--overwrite', diff --git a/apitools/gen/service_registry.py b/apitools/gen/service_registry.py index fdcd93eb..66b635ad 100644 --- a/apitools/gen/service_registry.py +++ b/apitools/gen/service_registry.py @@ -34,7 +34,7 @@ class ServiceRegistry(object): """Registry for service types.""" - def __init__(self, client_info, message_registry, command_registry, + def __init__(self, client_info, message_registry, names, root_package, base_files_package, unelidable_request_methods): self.__client_info = client_info @@ -42,7 +42,6 @@ def __init__(self, client_info, message_registry, command_registry, self.__names = names self.__service_method_info_map = collections.OrderedDict() self.__message_registry = message_registry - self.__command_registry = command_registry self.__root_package = root_package self.__base_files_package = base_files_package self.__unelidable_request_methods = unelidable_request_methods @@ -473,9 +472,6 @@ def AddServiceFromResource(self, service_name, methods): method_info_map[method_name] = self.__ComputeMethodInfo( method_description, request, response, request_field) - self.__command_registry.AddCommandForMethod( - service_name, method_name, method_info_map[method_name], - request, response) nested_services = methods.get('resources', {}) services = sorted(nested_services.items()) diff --git a/apitools/gen/util.py b/apitools/gen/util.py index 146b4527..312885f0 100644 --- a/apitools/gen/util.py +++ b/apitools/gen/util.py @@ -222,14 +222,6 @@ def Create(cls, discovery_doc, def default_directory(self): return self.package - @property - def cli_rule_name(self): - return '%s_%s' % (self.package, self.version) - - @property - def cli_file_name(self): - return '%s.py' % self.cli_rule_name - @property def client_rule_name(self): return '%s_%s_client' % (self.package, self.version) diff --git a/samples/bigquery_sample/bigquery_v2/bigquery_v2.py b/samples/bigquery_sample/bigquery_v2/bigquery_v2.py deleted file mode 100644 index 7cd69b5c..00000000 --- a/samples/bigquery_sample/bigquery_v2/bigquery_v2.py +++ /dev/null @@ -1,1096 +0,0 @@ -#!/usr/bin/env python -"""CLI for bigquery, version v2.""" -# NOTE: This file is autogenerated and should not be edited by hand. - -import code -import os -import platform -import sys - -from apitools.base.protorpclite import message_types -from apitools.base.protorpclite import messages - -from google.apputils import appcommands -import gflags as flags - -import apitools.base.py as apitools_base -from apitools.base.py import cli as apitools_base_cli -import bigquery_v2_client as client_lib -import bigquery_v2_messages as messages - - -def _DeclareBigqueryFlags(): - """Declare global flags in an idempotent way.""" - if 'api_endpoint' in flags.FLAGS: - return - flags.DEFINE_string( - 'api_endpoint', - u'https://www.googleapis.com/bigquery/v2/', - 'URL of the API endpoint to use.', - short_name='bigquery_url') - flags.DEFINE_string( - 'history_file', - u'~/.bigquery.v2.history', - 'File with interactive shell history.') - flags.DEFINE_multistring( - 'add_header', [], - 'Additional http headers (as key=value strings). ' - 'Can be specified multiple times.') - flags.DEFINE_string( - 'service_account_json_keyfile', '', - 'Filename for a JSON service account key downloaded' - ' from the Developer Console.') - flags.DEFINE_enum( - 'alt', - u'json', - [u'json'], - u'Data format for the response.') - flags.DEFINE_string( - 'fields', - None, - u'Selector specifying which fields to include in a partial response.') - flags.DEFINE_string( - 'key', - None, - u'API key. Your API key identifies your project and provides you with ' - u'API access, quota, and reports. Required unless you provide an OAuth ' - u'2.0 token.') - flags.DEFINE_string( - 'oauth_token', - None, - u'OAuth 2.0 token for the current user.') - flags.DEFINE_boolean( - 'prettyPrint', - 'True', - u'Returns response with indentations and line breaks.') - flags.DEFINE_string( - 'quotaUser', - None, - u'Available to use for quota purposes for server-side applications. Can' - u' be any arbitrary string assigned to a user, but should not exceed 40' - u' characters. Overrides userIp if both are provided.') - flags.DEFINE_string( - 'trace', - None, - 'A tracing token of the form "token:" to include in api ' - 'requests.') - flags.DEFINE_string( - 'userIp', - None, - u'IP address of the site where the request originates. Use this if you ' - u'want to enforce per-user limits.') - - -FLAGS = flags.FLAGS -apitools_base_cli.DeclareBaseFlags() -_DeclareBigqueryFlags() - - -def GetGlobalParamsFromFlags(): - """Return a StandardQueryParameters based on flags.""" - result = messages.StandardQueryParameters() - if FLAGS['alt'].present: - result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt) - if FLAGS['fields'].present: - result.fields = FLAGS.fields.decode('utf8') - if FLAGS['key'].present: - result.key = FLAGS.key.decode('utf8') - if FLAGS['oauth_token'].present: - result.oauth_token = FLAGS.oauth_token.decode('utf8') - if FLAGS['prettyPrint'].present: - result.prettyPrint = FLAGS.prettyPrint - if FLAGS['quotaUser'].present: - result.quotaUser = FLAGS.quotaUser.decode('utf8') - if FLAGS['trace'].present: - result.trace = FLAGS.trace.decode('utf8') - if FLAGS['userIp'].present: - result.userIp = FLAGS.userIp.decode('utf8') - return result - - -def GetClientFromFlags(): - """Return a client object, configured from flags.""" - log_request = FLAGS.log_request or FLAGS.log_request_response - log_response = FLAGS.log_response or FLAGS.log_request_response - api_endpoint = apitools_base.NormalizeApiEndpoint(FLAGS.api_endpoint) - additional_http_headers = dict(x.split('=', 1) for x in FLAGS.add_header) - credentials_args = { - 'service_account_json_keyfile': os.path.expanduser(FLAGS.service_account_json_keyfile) - } - try: - client = client_lib.BigqueryV2( - api_endpoint, log_request=log_request, - log_response=log_response, - credentials_args=credentials_args, - additional_http_headers=additional_http_headers) - except apitools_base.CredentialsError as e: - print 'Error creating credentials: %s' % e - sys.exit(1) - return client - - -class PyShell(appcommands.Cmd): - - def Run(self, _): - """Run an interactive python shell with the client.""" - client = GetClientFromFlags() - params = GetGlobalParamsFromFlags() - for field in params.all_fields(): - value = params.get_assigned_value(field.name) - if value != field.default: - client.AddGlobalParam(field.name, value) - banner = """ - == bigquery interactive console == - client: a bigquery client - apitools_base: base apitools module - messages: the generated messages module - """ - local_vars = { - 'apitools_base': apitools_base, - 'client': client, - 'client_lib': client_lib, - 'messages': messages, - } - if platform.system() == 'Linux': - console = apitools_base_cli.ConsoleWithReadline( - local_vars, histfile=FLAGS.history_file) - else: - console = code.InteractiveConsole(local_vars) - try: - console.interact(banner) - except SystemExit as e: - return e.code - - -class DatasetsDelete(apitools_base_cli.NewCmd): - """Command wrapping datasets.Delete.""" - - usage = """datasets_delete """ - - def __init__(self, name, fv): - super(DatasetsDelete, self).__init__(name, fv) - flags.DEFINE_boolean( - 'deleteContents', - None, - u'If True, delete all the tables in the dataset. If False and the ' - u'dataset contains tables, the request will fail. Default is False', - flag_values=fv) - - def RunWithArgs(self, projectId, datasetId): - """Deletes the dataset specified by the datasetId value. Before you can - delete a dataset, you must delete all its tables, either manually or by - specifying deleteContents. Immediately after deletion, you can create - another dataset with the same name. - - Args: - projectId: Project ID of the dataset being deleted - datasetId: Dataset ID of dataset being deleted - - Flags: - deleteContents: If True, delete all the tables in the dataset. If False - and the dataset contains tables, the request will fail. Default is - False - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryDatasetsDeleteRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - ) - if FLAGS['deleteContents'].present: - request.deleteContents = FLAGS.deleteContents - result = client.datasets.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DatasetsGet(apitools_base_cli.NewCmd): - """Command wrapping datasets.Get.""" - - usage = """datasets_get """ - - def __init__(self, name, fv): - super(DatasetsGet, self).__init__(name, fv) - - def RunWithArgs(self, projectId, datasetId): - """Returns the dataset specified by datasetID. - - Args: - projectId: Project ID of the requested dataset - datasetId: Dataset ID of the requested dataset - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryDatasetsGetRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - ) - result = client.datasets.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DatasetsInsert(apitools_base_cli.NewCmd): - """Command wrapping datasets.Insert.""" - - usage = """datasets_insert """ - - def __init__(self, name, fv): - super(DatasetsInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'dataset', - None, - u'A Dataset resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, projectId): - """Creates a new empty dataset. - - Args: - projectId: Project ID of the new dataset - - Flags: - dataset: A Dataset resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryDatasetsInsertRequest( - projectId=projectId.decode('utf8'), - ) - if FLAGS['dataset'].present: - request.dataset = apitools_base.JsonToMessage(messages.Dataset, FLAGS.dataset) - result = client.datasets.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DatasetsList(apitools_base_cli.NewCmd): - """Command wrapping datasets.List.""" - - usage = """datasets_list """ - - def __init__(self, name, fv): - super(DatasetsList, self).__init__(name, fv) - flags.DEFINE_boolean( - 'all', - None, - u'Whether to list all datasets, including hidden ones', - flag_values=fv) - flags.DEFINE_string( - 'filter', - None, - u'An expression for filtering the results of the request by label. ' - u'The syntax is "labels.[:]". Multiple filters can be ANDed together ' - u'by connecting with a space. Example: "labels.department:receiving ' - u'labels.active". See https://cloud.google.com/bigquery/docs' - u'/labeling-datasets#filtering_datasets_using_labels for details.', - flag_values=fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'The maximum number of results to return', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Page token, returned by a previous call, to request the next page ' - u'of results', - flag_values=fv) - - def RunWithArgs(self, projectId): - """Lists all datasets in the specified project to which you have been - granted the READER dataset role. - - Args: - projectId: Project ID of the datasets to be listed - - Flags: - all: Whether to list all datasets, including hidden ones - filter: An expression for filtering the results of the request by label. - The syntax is "labels.[:]". Multiple filters can be ANDed together by - connecting with a space. Example: "labels.department:receiving - labels.active". See https://cloud.google.com/bigquery/docs/labeling- - datasets#filtering_datasets_using_labels for details. - maxResults: The maximum number of results to return - pageToken: Page token, returned by a previous call, to request the next - page of results - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryDatasetsListRequest( - projectId=projectId.decode('utf8'), - ) - if FLAGS['all'].present: - request.all = FLAGS.all - if FLAGS['filter'].present: - request.filter = FLAGS.filter.decode('utf8') - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.datasets.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DatasetsPatch(apitools_base_cli.NewCmd): - """Command wrapping datasets.Patch.""" - - usage = """datasets_patch """ - - def __init__(self, name, fv): - super(DatasetsPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'dataset', - None, - u'A Dataset resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, projectId, datasetId): - """Updates information in an existing dataset. The update method replaces - the entire dataset resource, whereas the patch method only replaces fields - that are provided in the submitted dataset resource. This method supports - patch semantics. - - Args: - projectId: Project ID of the dataset being updated - datasetId: Dataset ID of the dataset being updated - - Flags: - dataset: A Dataset resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryDatasetsPatchRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - ) - if FLAGS['dataset'].present: - request.dataset = apitools_base.JsonToMessage(messages.Dataset, FLAGS.dataset) - result = client.datasets.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DatasetsUpdate(apitools_base_cli.NewCmd): - """Command wrapping datasets.Update.""" - - usage = """datasets_update """ - - def __init__(self, name, fv): - super(DatasetsUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'dataset', - None, - u'A Dataset resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, projectId, datasetId): - """Updates information in an existing dataset. The update method replaces - the entire dataset resource, whereas the patch method only replaces fields - that are provided in the submitted dataset resource. - - Args: - projectId: Project ID of the dataset being updated - datasetId: Dataset ID of the dataset being updated - - Flags: - dataset: A Dataset resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryDatasetsUpdateRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - ) - if FLAGS['dataset'].present: - request.dataset = apitools_base.JsonToMessage(messages.Dataset, FLAGS.dataset) - result = client.datasets.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class JobsCancel(apitools_base_cli.NewCmd): - """Command wrapping jobs.Cancel.""" - - usage = """jobs_cancel """ - - def __init__(self, name, fv): - super(JobsCancel, self).__init__(name, fv) - - def RunWithArgs(self, projectId, jobId): - """Requests that a job be cancelled. This call will return immediately, - and the client will need to poll for the job status to see if the cancel - completed successfully. Cancelled jobs may still incur costs. - - Args: - projectId: [Required] Project ID of the job to cancel - jobId: [Required] Job ID of the job to cancel - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryJobsCancelRequest( - projectId=projectId.decode('utf8'), - jobId=jobId.decode('utf8'), - ) - result = client.jobs.Cancel( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class JobsGet(apitools_base_cli.NewCmd): - """Command wrapping jobs.Get.""" - - usage = """jobs_get """ - - def __init__(self, name, fv): - super(JobsGet, self).__init__(name, fv) - - def RunWithArgs(self, projectId, jobId): - """Returns information about a specific job. Job information is available - for a six month period after creation. Requires that you're the person who - ran the job, or have the Is Owner project role. - - Args: - projectId: [Required] Project ID of the requested job - jobId: [Required] Job ID of the requested job - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryJobsGetRequest( - projectId=projectId.decode('utf8'), - jobId=jobId.decode('utf8'), - ) - result = client.jobs.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class JobsGetQueryResults(apitools_base_cli.NewCmd): - """Command wrapping jobs.GetQueryResults.""" - - usage = """jobs_getQueryResults """ - - def __init__(self, name, fv): - super(JobsGetQueryResults, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of results to read', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Page token, returned by a previous call, to request the next page ' - u'of results', - flag_values=fv) - flags.DEFINE_string( - 'startIndex', - None, - u'Zero-based index of the starting row', - flag_values=fv) - flags.DEFINE_integer( - 'timeoutMs', - None, - u'How long to wait for the query to complete, in milliseconds, before' - u' returning. Default is 10 seconds. If the timeout passes before the' - u" job completes, the 'jobComplete' field in the response will be " - u'false', - flag_values=fv) - - def RunWithArgs(self, projectId, jobId): - """Retrieves the results of a query job. - - Args: - projectId: [Required] Project ID of the query job - jobId: [Required] Job ID of the query job - - Flags: - maxResults: Maximum number of results to read - pageToken: Page token, returned by a previous call, to request the next - page of results - startIndex: Zero-based index of the starting row - timeoutMs: How long to wait for the query to complete, in milliseconds, - before returning. Default is 10 seconds. If the timeout passes before - the job completes, the 'jobComplete' field in the response will be - false - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryJobsGetQueryResultsRequest( - projectId=projectId.decode('utf8'), - jobId=jobId.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['startIndex'].present: - request.startIndex = int(FLAGS.startIndex) - if FLAGS['timeoutMs'].present: - request.timeoutMs = FLAGS.timeoutMs - result = client.jobs.GetQueryResults( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class JobsInsert(apitools_base_cli.NewCmd): - """Command wrapping jobs.Insert.""" - - usage = """jobs_insert """ - - def __init__(self, name, fv): - super(JobsInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'job', - None, - u'A Job resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'upload_filename', - '', - 'Filename to use for upload.', - flag_values=fv) - flags.DEFINE_string( - 'upload_mime_type', - '', - 'MIME type to use for the upload. Only needed if the extension on ' - '--upload_filename does not determine the correct (or any) MIME ' - 'type.', - flag_values=fv) - - def RunWithArgs(self, projectId): - """Starts a new asynchronous job. Requires the Can View project role. - - Args: - projectId: Project ID of the project that will be billed for the job - - Flags: - job: A Job resource to be passed as the request body. - upload_filename: Filename to use for upload. - upload_mime_type: MIME type to use for the upload. Only needed if the - extension on --upload_filename does not determine the correct (or any) - MIME type. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryJobsInsertRequest( - projectId=projectId.decode('utf8'), - ) - if FLAGS['job'].present: - request.job = apitools_base.JsonToMessage(messages.Job, FLAGS.job) - upload = None - if FLAGS.upload_filename: - upload = apitools_base.Upload.FromFile( - FLAGS.upload_filename, FLAGS.upload_mime_type, - progress_callback=apitools_base.UploadProgressPrinter, - finish_callback=apitools_base.UploadCompletePrinter) - result = client.jobs.Insert( - request, global_params=global_params, upload=upload) - print apitools_base_cli.FormatOutput(result) - - -class JobsList(apitools_base_cli.NewCmd): - """Command wrapping jobs.List.""" - - usage = """jobs_list """ - - def __init__(self, name, fv): - super(JobsList, self).__init__(name, fv) - flags.DEFINE_boolean( - 'allUsers', - None, - u'Whether to display jobs owned by all users in the project. Default ' - u'false', - flag_values=fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of results to return', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Page token, returned by a previous call, to request the next page ' - u'of results', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'minimal'], - u'Restrict information returned to a set of selected fields', - flag_values=fv) - flags.DEFINE_enum( - 'stateFilter', - u'done', - [u'done', u'pending', u'running'], - u'Filter for job state', - flag_values=fv) - - def RunWithArgs(self, projectId): - """Lists all jobs that you started in the specified project. Job - information is available for a six month period after creation. The job - list is sorted in reverse chronological order, by job creation time. - Requires the Can View project role, or the Is Owner project role if you - set the allUsers property. - - Args: - projectId: Project ID of the jobs to list - - Flags: - allUsers: Whether to display jobs owned by all users in the project. - Default false - maxResults: Maximum number of results to return - pageToken: Page token, returned by a previous call, to request the next - page of results - projection: Restrict information returned to a set of selected fields - stateFilter: Filter for job state - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryJobsListRequest( - projectId=projectId.decode('utf8'), - ) - if FLAGS['allUsers'].present: - request.allUsers = FLAGS.allUsers - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['projection'].present: - request.projection = messages.BigqueryJobsListRequest.ProjectionValueValuesEnum(FLAGS.projection) - if FLAGS['stateFilter'].present: - request.stateFilter = [messages.BigqueryJobsListRequest.StateFilterValueValuesEnum(x) for x in FLAGS.stateFilter] - result = client.jobs.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class JobsQuery(apitools_base_cli.NewCmd): - """Command wrapping jobs.Query.""" - - usage = """jobs_query """ - - def __init__(self, name, fv): - super(JobsQuery, self).__init__(name, fv) - flags.DEFINE_string( - 'queryRequest', - None, - u'A QueryRequest resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, projectId): - """Runs a BigQuery SQL query synchronously and returns query results if - the query completes within a specified timeout. - - Args: - projectId: Project ID of the project billed for the query - - Flags: - queryRequest: A QueryRequest resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryJobsQueryRequest( - projectId=projectId.decode('utf8'), - ) - if FLAGS['queryRequest'].present: - request.queryRequest = apitools_base.JsonToMessage(messages.QueryRequest, FLAGS.queryRequest) - result = client.jobs.Query( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsList(apitools_base_cli.NewCmd): - """Command wrapping projects.List.""" - - usage = """projects_list""" - - def __init__(self, name, fv): - super(ProjectsList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of results to return', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Page token, returned by a previous call, to request the next page ' - u'of results', - flag_values=fv) - - def RunWithArgs(self): - """Lists all projects to which you have been granted any project role. - - Flags: - maxResults: Maximum number of results to return - pageToken: Page token, returned by a previous call, to request the next - page of results - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryProjectsListRequest( - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.projects.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TabledataInsertAll(apitools_base_cli.NewCmd): - """Command wrapping tabledata.InsertAll.""" - - usage = """tabledata_insertAll """ - - def __init__(self, name, fv): - super(TabledataInsertAll, self).__init__(name, fv) - flags.DEFINE_string( - 'tableDataInsertAllRequest', - None, - u'A TableDataInsertAllRequest resource to be passed as the request ' - u'body.', - flag_values=fv) - - def RunWithArgs(self, projectId, datasetId, tableId): - """Streams data into BigQuery one record at a time without needing to run - a load job. Requires the WRITER dataset role. - - Args: - projectId: Project ID of the destination table. - datasetId: Dataset ID of the destination table. - tableId: Table ID of the destination table. - - Flags: - tableDataInsertAllRequest: A TableDataInsertAllRequest resource to be - passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryTabledataInsertAllRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - tableId=tableId.decode('utf8'), - ) - if FLAGS['tableDataInsertAllRequest'].present: - request.tableDataInsertAllRequest = apitools_base.JsonToMessage(messages.TableDataInsertAllRequest, FLAGS.tableDataInsertAllRequest) - result = client.tabledata.InsertAll( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TabledataList(apitools_base_cli.NewCmd): - """Command wrapping tabledata.List.""" - - usage = """tabledata_list """ - - def __init__(self, name, fv): - super(TabledataList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of results to return', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Page token, returned by a previous call, identifying the result set', - flag_values=fv) - flags.DEFINE_string( - 'startIndex', - None, - u'Zero-based index of the starting row to read', - flag_values=fv) - - def RunWithArgs(self, projectId, datasetId, tableId): - """Retrieves table data from a specified set of rows. Requires the READER - dataset role. - - Args: - projectId: Project ID of the table to read - datasetId: Dataset ID of the table to read - tableId: Table ID of the table to read - - Flags: - maxResults: Maximum number of results to return - pageToken: Page token, returned by a previous call, identifying the - result set - startIndex: Zero-based index of the starting row to read - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryTabledataListRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - tableId=tableId.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['startIndex'].present: - request.startIndex = int(FLAGS.startIndex) - result = client.tabledata.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TablesDelete(apitools_base_cli.NewCmd): - """Command wrapping tables.Delete.""" - - usage = """tables_delete """ - - def __init__(self, name, fv): - super(TablesDelete, self).__init__(name, fv) - - def RunWithArgs(self, projectId, datasetId, tableId): - """Deletes the table specified by tableId from the dataset. If the table - contains data, all the data will be deleted. - - Args: - projectId: Project ID of the table to delete - datasetId: Dataset ID of the table to delete - tableId: Table ID of the table to delete - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryTablesDeleteRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - tableId=tableId.decode('utf8'), - ) - result = client.tables.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TablesGet(apitools_base_cli.NewCmd): - """Command wrapping tables.Get.""" - - usage = """tables_get """ - - def __init__(self, name, fv): - super(TablesGet, self).__init__(name, fv) - - def RunWithArgs(self, projectId, datasetId, tableId): - """Gets the specified table resource by table ID. This method does not - return the data in the table, it only returns the table resource, which - describes the structure of this table. - - Args: - projectId: Project ID of the requested table - datasetId: Dataset ID of the requested table - tableId: Table ID of the requested table - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryTablesGetRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - tableId=tableId.decode('utf8'), - ) - result = client.tables.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TablesInsert(apitools_base_cli.NewCmd): - """Command wrapping tables.Insert.""" - - usage = """tables_insert """ - - def __init__(self, name, fv): - super(TablesInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'table', - None, - u'A Table resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, projectId, datasetId): - """Creates a new, empty table in the dataset. - - Args: - projectId: Project ID of the new table - datasetId: Dataset ID of the new table - - Flags: - table: A Table resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryTablesInsertRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - ) - if FLAGS['table'].present: - request.table = apitools_base.JsonToMessage(messages.Table, FLAGS.table) - result = client.tables.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TablesList(apitools_base_cli.NewCmd): - """Command wrapping tables.List.""" - - usage = """tables_list """ - - def __init__(self, name, fv): - super(TablesList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of results to return', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Page token, returned by a previous call, to request the next page ' - u'of results', - flag_values=fv) - - def RunWithArgs(self, projectId, datasetId): - """Lists all tables in the specified dataset. Requires the READER dataset - role. - - Args: - projectId: Project ID of the tables to list - datasetId: Dataset ID of the tables to list - - Flags: - maxResults: Maximum number of results to return - pageToken: Page token, returned by a previous call, to request the next - page of results - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryTablesListRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.tables.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TablesPatch(apitools_base_cli.NewCmd): - """Command wrapping tables.Patch.""" - - usage = """tables_patch """ - - def __init__(self, name, fv): - super(TablesPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'table', - None, - u'A Table resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, projectId, datasetId, tableId): - """Updates information in an existing table. The update method replaces - the entire table resource, whereas the patch method only replaces fields - that are provided in the submitted table resource. This method supports - patch semantics. - - Args: - projectId: Project ID of the table to update - datasetId: Dataset ID of the table to update - tableId: Table ID of the table to update - - Flags: - table: A Table resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryTablesPatchRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - tableId=tableId.decode('utf8'), - ) - if FLAGS['table'].present: - request.table = apitools_base.JsonToMessage(messages.Table, FLAGS.table) - result = client.tables.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TablesUpdate(apitools_base_cli.NewCmd): - """Command wrapping tables.Update.""" - - usage = """tables_update """ - - def __init__(self, name, fv): - super(TablesUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'table', - None, - u'A Table resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, projectId, datasetId, tableId): - """Updates information in an existing table. The update method replaces - the entire table resource, whereas the patch method only replaces fields - that are provided in the submitted table resource. - - Args: - projectId: Project ID of the table to update - datasetId: Dataset ID of the table to update - tableId: Table ID of the table to update - - Flags: - table: A Table resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BigqueryTablesUpdateRequest( - projectId=projectId.decode('utf8'), - datasetId=datasetId.decode('utf8'), - tableId=tableId.decode('utf8'), - ) - if FLAGS['table'].present: - request.table = apitools_base.JsonToMessage(messages.Table, FLAGS.table) - result = client.tables.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -def main(_): - appcommands.AddCmd('pyshell', PyShell) - appcommands.AddCmd('datasets_delete', DatasetsDelete) - appcommands.AddCmd('datasets_get', DatasetsGet) - appcommands.AddCmd('datasets_insert', DatasetsInsert) - appcommands.AddCmd('datasets_list', DatasetsList) - appcommands.AddCmd('datasets_patch', DatasetsPatch) - appcommands.AddCmd('datasets_update', DatasetsUpdate) - appcommands.AddCmd('jobs_cancel', JobsCancel) - appcommands.AddCmd('jobs_get', JobsGet) - appcommands.AddCmd('jobs_getQueryResults', JobsGetQueryResults) - appcommands.AddCmd('jobs_insert', JobsInsert) - appcommands.AddCmd('jobs_list', JobsList) - appcommands.AddCmd('jobs_query', JobsQuery) - appcommands.AddCmd('projects_list', ProjectsList) - appcommands.AddCmd('tabledata_insertAll', TabledataInsertAll) - appcommands.AddCmd('tabledata_list', TabledataList) - appcommands.AddCmd('tables_delete', TablesDelete) - appcommands.AddCmd('tables_get', TablesGet) - appcommands.AddCmd('tables_insert', TablesInsert) - appcommands.AddCmd('tables_list', TablesList) - appcommands.AddCmd('tables_patch', TablesPatch) - appcommands.AddCmd('tables_update', TablesUpdate) - - apitools_base_cli.SetupLogger() - if hasattr(appcommands, 'SetDefaultCommand'): - appcommands.SetDefaultCommand('pyshell') - - -run_main = apitools_base_cli.run_main - -if __name__ == '__main__': - appcommands.Run() diff --git a/samples/dns_sample/dns_v1/dns_v1.py b/samples/dns_sample/dns_v1/dns_v1.py deleted file mode 100644 index 56e54f3e..00000000 --- a/samples/dns_sample/dns_v1/dns_v1.py +++ /dev/null @@ -1,554 +0,0 @@ -#!/usr/bin/env python -"""CLI for dns, version v1.""" -# NOTE: This file is autogenerated and should not be edited by hand. - -import code -import os -import platform -import sys - -from apitools.base.protorpclite import message_types -from apitools.base.protorpclite import messages - -from google.apputils import appcommands -import gflags as flags - -import apitools.base.py as apitools_base -from apitools.base.py import cli as apitools_base_cli -import dns_v1_client as client_lib -import dns_v1_messages as messages - - -def _DeclareDnsFlags(): - """Declare global flags in an idempotent way.""" - if 'api_endpoint' in flags.FLAGS: - return - flags.DEFINE_string( - 'api_endpoint', - u'https://www.googleapis.com/dns/v1/', - 'URL of the API endpoint to use.', - short_name='dns_url') - flags.DEFINE_string( - 'history_file', - u'~/.dns.v1.history', - 'File with interactive shell history.') - flags.DEFINE_multistring( - 'add_header', [], - 'Additional http headers (as key=value strings). ' - 'Can be specified multiple times.') - flags.DEFINE_string( - 'service_account_json_keyfile', '', - 'Filename for a JSON service account key downloaded' - ' from the Developer Console.') - flags.DEFINE_enum( - 'alt', - u'json', - [u'json'], - u'Data format for the response.') - flags.DEFINE_string( - 'fields', - None, - u'Selector specifying which fields to include in a partial response.') - flags.DEFINE_string( - 'key', - None, - u'API key. Your API key identifies your project and provides you with ' - u'API access, quota, and reports. Required unless you provide an OAuth ' - u'2.0 token.') - flags.DEFINE_string( - 'oauth_token', - None, - u'OAuth 2.0 token for the current user.') - flags.DEFINE_boolean( - 'prettyPrint', - 'True', - u'Returns response with indentations and line breaks.') - flags.DEFINE_string( - 'quotaUser', - None, - u'Available to use for quota purposes for server-side applications. Can' - u' be any arbitrary string assigned to a user, but should not exceed 40' - u' characters. Overrides userIp if both are provided.') - flags.DEFINE_string( - 'trace', - None, - 'A tracing token of the form "token:" to include in api ' - 'requests.') - flags.DEFINE_string( - 'userIp', - None, - u'IP address of the site where the request originates. Use this if you ' - u'want to enforce per-user limits.') - - -FLAGS = flags.FLAGS -apitools_base_cli.DeclareBaseFlags() -_DeclareDnsFlags() - - -def GetGlobalParamsFromFlags(): - """Return a StandardQueryParameters based on flags.""" - result = messages.StandardQueryParameters() - if FLAGS['alt'].present: - result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt) - if FLAGS['fields'].present: - result.fields = FLAGS.fields.decode('utf8') - if FLAGS['key'].present: - result.key = FLAGS.key.decode('utf8') - if FLAGS['oauth_token'].present: - result.oauth_token = FLAGS.oauth_token.decode('utf8') - if FLAGS['prettyPrint'].present: - result.prettyPrint = FLAGS.prettyPrint - if FLAGS['quotaUser'].present: - result.quotaUser = FLAGS.quotaUser.decode('utf8') - if FLAGS['trace'].present: - result.trace = FLAGS.trace.decode('utf8') - if FLAGS['userIp'].present: - result.userIp = FLAGS.userIp.decode('utf8') - return result - - -def GetClientFromFlags(): - """Return a client object, configured from flags.""" - log_request = FLAGS.log_request or FLAGS.log_request_response - log_response = FLAGS.log_response or FLAGS.log_request_response - api_endpoint = apitools_base.NormalizeApiEndpoint(FLAGS.api_endpoint) - additional_http_headers = dict(x.split('=', 1) for x in FLAGS.add_header) - credentials_args = { - 'service_account_json_keyfile': os.path.expanduser(FLAGS.service_account_json_keyfile) - } - try: - client = client_lib.DnsV1( - api_endpoint, log_request=log_request, - log_response=log_response, - credentials_args=credentials_args, - additional_http_headers=additional_http_headers) - except apitools_base.CredentialsError as e: - print 'Error creating credentials: %s' % e - sys.exit(1) - return client - - -class PyShell(appcommands.Cmd): - - def Run(self, _): - """Run an interactive python shell with the client.""" - client = GetClientFromFlags() - params = GetGlobalParamsFromFlags() - for field in params.all_fields(): - value = params.get_assigned_value(field.name) - if value != field.default: - client.AddGlobalParam(field.name, value) - banner = """ - == dns interactive console == - client: a dns client - apitools_base: base apitools module - messages: the generated messages module - """ - local_vars = { - 'apitools_base': apitools_base, - 'client': client, - 'client_lib': client_lib, - 'messages': messages, - } - if platform.system() == 'Linux': - console = apitools_base_cli.ConsoleWithReadline( - local_vars, histfile=FLAGS.history_file) - else: - console = code.InteractiveConsole(local_vars) - try: - console.interact(banner) - except SystemExit as e: - return e.code - - -class ChangesCreate(apitools_base_cli.NewCmd): - """Command wrapping changes.Create.""" - - usage = """changes_create """ - - def __init__(self, name, fv): - super(ChangesCreate, self).__init__(name, fv) - flags.DEFINE_string( - 'change', - None, - u'A Change resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, project, managedZone): - """Atomically update the ResourceRecordSet collection. - - Args: - project: Identifies the project addressed by this request. - managedZone: Identifies the managed zone addressed by this request. Can - be the managed zone name or id. - - Flags: - change: A Change resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.DnsChangesCreateRequest( - project=project.decode('utf8'), - managedZone=managedZone.decode('utf8'), - ) - if FLAGS['change'].present: - request.change = apitools_base.JsonToMessage(messages.Change, FLAGS.change) - result = client.changes.Create( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ChangesGet(apitools_base_cli.NewCmd): - """Command wrapping changes.Get.""" - - usage = """changes_get """ - - def __init__(self, name, fv): - super(ChangesGet, self).__init__(name, fv) - - def RunWithArgs(self, project, managedZone, changeId): - """Fetch the representation of an existing Change. - - Args: - project: Identifies the project addressed by this request. - managedZone: Identifies the managed zone addressed by this request. Can - be the managed zone name or id. - changeId: The identifier of the requested change, from a previous - ResourceRecordSetsChangeResponse. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.DnsChangesGetRequest( - project=project.decode('utf8'), - managedZone=managedZone.decode('utf8'), - changeId=changeId.decode('utf8'), - ) - result = client.changes.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ChangesList(apitools_base_cli.NewCmd): - """Command wrapping changes.List.""" - - usage = """changes_list """ - - def __init__(self, name, fv): - super(ChangesList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Optional. Maximum number of results to be returned. If unspecified,' - u' the server will decide how many results to return.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Optional. A tag returned by a previous list request that was ' - u'truncated. Use this parameter to continue a previous list request.', - flag_values=fv) - flags.DEFINE_enum( - 'sortBy', - u'changeSequence', - [u'changeSequence'], - u'Sorting criterion. The only supported value is change sequence.', - flag_values=fv) - flags.DEFINE_string( - 'sortOrder', - None, - u"Sorting order direction: 'ascending' or 'descending'.", - flag_values=fv) - - def RunWithArgs(self, project, managedZone): - """Enumerate Changes to a ResourceRecordSet collection. - - Args: - project: Identifies the project addressed by this request. - managedZone: Identifies the managed zone addressed by this request. Can - be the managed zone name or id. - - Flags: - maxResults: Optional. Maximum number of results to be returned. If - unspecified, the server will decide how many results to return. - pageToken: Optional. A tag returned by a previous list request that was - truncated. Use this parameter to continue a previous list request. - sortBy: Sorting criterion. The only supported value is change sequence. - sortOrder: Sorting order direction: 'ascending' or 'descending'. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.DnsChangesListRequest( - project=project.decode('utf8'), - managedZone=managedZone.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['sortBy'].present: - request.sortBy = messages.DnsChangesListRequest.SortByValueValuesEnum(FLAGS.sortBy) - if FLAGS['sortOrder'].present: - request.sortOrder = FLAGS.sortOrder.decode('utf8') - result = client.changes.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ManagedZonesCreate(apitools_base_cli.NewCmd): - """Command wrapping managedZones.Create.""" - - usage = """managedZones_create """ - - def __init__(self, name, fv): - super(ManagedZonesCreate, self).__init__(name, fv) - flags.DEFINE_string( - 'managedZone', - None, - u'A ManagedZone resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, project): - """Create a new ManagedZone. - - Args: - project: Identifies the project addressed by this request. - - Flags: - managedZone: A ManagedZone resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.DnsManagedZonesCreateRequest( - project=project.decode('utf8'), - ) - if FLAGS['managedZone'].present: - request.managedZone = apitools_base.JsonToMessage(messages.ManagedZone, FLAGS.managedZone) - result = client.managedZones.Create( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ManagedZonesDelete(apitools_base_cli.NewCmd): - """Command wrapping managedZones.Delete.""" - - usage = """managedZones_delete """ - - def __init__(self, name, fv): - super(ManagedZonesDelete, self).__init__(name, fv) - - def RunWithArgs(self, project, managedZone): - """Delete a previously created ManagedZone. - - Args: - project: Identifies the project addressed by this request. - managedZone: Identifies the managed zone addressed by this request. Can - be the managed zone name or id. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.DnsManagedZonesDeleteRequest( - project=project.decode('utf8'), - managedZone=managedZone.decode('utf8'), - ) - result = client.managedZones.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ManagedZonesGet(apitools_base_cli.NewCmd): - """Command wrapping managedZones.Get.""" - - usage = """managedZones_get """ - - def __init__(self, name, fv): - super(ManagedZonesGet, self).__init__(name, fv) - - def RunWithArgs(self, project, managedZone): - """Fetch the representation of an existing ManagedZone. - - Args: - project: Identifies the project addressed by this request. - managedZone: Identifies the managed zone addressed by this request. Can - be the managed zone name or id. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.DnsManagedZonesGetRequest( - project=project.decode('utf8'), - managedZone=managedZone.decode('utf8'), - ) - result = client.managedZones.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ManagedZonesList(apitools_base_cli.NewCmd): - """Command wrapping managedZones.List.""" - - usage = """managedZones_list """ - - def __init__(self, name, fv): - super(ManagedZonesList, self).__init__(name, fv) - flags.DEFINE_string( - 'dnsName', - None, - u'Restricts the list to return only zones with this domain name.', - flag_values=fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Optional. Maximum number of results to be returned. If unspecified,' - u' the server will decide how many results to return.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Optional. A tag returned by a previous list request that was ' - u'truncated. Use this parameter to continue a previous list request.', - flag_values=fv) - - def RunWithArgs(self, project): - """Enumerate ManagedZones that have been created but not yet deleted. - - Args: - project: Identifies the project addressed by this request. - - Flags: - dnsName: Restricts the list to return only zones with this domain name. - maxResults: Optional. Maximum number of results to be returned. If - unspecified, the server will decide how many results to return. - pageToken: Optional. A tag returned by a previous list request that was - truncated. Use this parameter to continue a previous list request. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.DnsManagedZonesListRequest( - project=project.decode('utf8'), - ) - if FLAGS['dnsName'].present: - request.dnsName = FLAGS.dnsName.decode('utf8') - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.managedZones.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsGet(apitools_base_cli.NewCmd): - """Command wrapping projects.Get.""" - - usage = """projects_get """ - - def __init__(self, name, fv): - super(ProjectsGet, self).__init__(name, fv) - - def RunWithArgs(self, project): - """Fetch the representation of an existing Project. - - Args: - project: Identifies the project addressed by this request. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.DnsProjectsGetRequest( - project=project.decode('utf8'), - ) - result = client.projects.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ResourceRecordSetsList(apitools_base_cli.NewCmd): - """Command wrapping resourceRecordSets.List.""" - - usage = """resourceRecordSets_list """ - - def __init__(self, name, fv): - super(ResourceRecordSetsList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Optional. Maximum number of results to be returned. If unspecified,' - u' the server will decide how many results to return.', - flag_values=fv) - flags.DEFINE_string( - 'name', - None, - u'Restricts the list to return only records with this fully qualified' - u' domain name.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Optional. A tag returned by a previous list request that was ' - u'truncated. Use this parameter to continue a previous list request.', - flag_values=fv) - flags.DEFINE_string( - 'type', - None, - u'Restricts the list to return only records of this type. If present,' - u' the "name" parameter must also be present.', - flag_values=fv) - - def RunWithArgs(self, project, managedZone): - """Enumerate ResourceRecordSets that have been created but not yet - deleted. - - Args: - project: Identifies the project addressed by this request. - managedZone: Identifies the managed zone addressed by this request. Can - be the managed zone name or id. - - Flags: - maxResults: Optional. Maximum number of results to be returned. If - unspecified, the server will decide how many results to return. - name: Restricts the list to return only records with this fully - qualified domain name. - pageToken: Optional. A tag returned by a previous list request that was - truncated. Use this parameter to continue a previous list request. - type: Restricts the list to return only records of this type. If - present, the "name" parameter must also be present. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.DnsResourceRecordSetsListRequest( - project=project.decode('utf8'), - managedZone=managedZone.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['name'].present: - request.name = FLAGS.name.decode('utf8') - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['type'].present: - request.type = FLAGS.type.decode('utf8') - result = client.resourceRecordSets.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -def main(_): - appcommands.AddCmd('pyshell', PyShell) - appcommands.AddCmd('changes_create', ChangesCreate) - appcommands.AddCmd('changes_get', ChangesGet) - appcommands.AddCmd('changes_list', ChangesList) - appcommands.AddCmd('managedZones_create', ManagedZonesCreate) - appcommands.AddCmd('managedZones_delete', ManagedZonesDelete) - appcommands.AddCmd('managedZones_get', ManagedZonesGet) - appcommands.AddCmd('managedZones_list', ManagedZonesList) - appcommands.AddCmd('projects_get', ProjectsGet) - appcommands.AddCmd('resourceRecordSets_list', ResourceRecordSetsList) - - apitools_base_cli.SetupLogger() - if hasattr(appcommands, 'SetDefaultCommand'): - appcommands.SetDefaultCommand('pyshell') - - -run_main = apitools_base_cli.run_main - -if __name__ == '__main__': - appcommands.Run() diff --git a/samples/fusiontables_sample/fusiontables_v1/fusiontables_v1.py b/samples/fusiontables_sample/fusiontables_v1/fusiontables_v1.py deleted file mode 100644 index 8bb2c8a4..00000000 --- a/samples/fusiontables_sample/fusiontables_v1/fusiontables_v1.py +++ /dev/null @@ -1,1797 +0,0 @@ -#!/usr/bin/env python -"""CLI for fusiontables, version v1.""" -# NOTE: This file is autogenerated and should not be edited by hand. - -import code -import os -import platform -import sys - -from apitools.base.protorpclite import message_types -from apitools.base.protorpclite import messages - -from google.apputils import appcommands -import gflags as flags - -import apitools.base.py as apitools_base -from apitools.base.py import cli as apitools_base_cli -import fusiontables_v1_client as client_lib -import fusiontables_v1_messages as messages - - -def _DeclareFusiontablesFlags(): - """Declare global flags in an idempotent way.""" - if 'api_endpoint' in flags.FLAGS: - return - flags.DEFINE_string( - 'api_endpoint', - u'https://www.googleapis.com/fusiontables/v1/', - 'URL of the API endpoint to use.', - short_name='fusiontables_url') - flags.DEFINE_string( - 'history_file', - u'~/.fusiontables.v1.history', - 'File with interactive shell history.') - flags.DEFINE_multistring( - 'add_header', [], - 'Additional http headers (as key=value strings). ' - 'Can be specified multiple times.') - flags.DEFINE_string( - 'service_account_json_keyfile', '', - 'Filename for a JSON service account key downloaded' - ' from the Developer Console.') - flags.DEFINE_enum( - 'alt', - u'json', - [u'csv', u'json'], - u'Data format for the response.') - flags.DEFINE_string( - 'fields', - None, - u'Selector specifying which fields to include in a partial response.') - flags.DEFINE_string( - 'key', - None, - u'API key. Your API key identifies your project and provides you with ' - u'API access, quota, and reports. Required unless you provide an OAuth ' - u'2.0 token.') - flags.DEFINE_string( - 'oauth_token', - None, - u'OAuth 2.0 token for the current user.') - flags.DEFINE_boolean( - 'prettyPrint', - 'True', - u'Returns response with indentations and line breaks.') - flags.DEFINE_string( - 'quotaUser', - None, - u'Available to use for quota purposes for server-side applications. Can' - u' be any arbitrary string assigned to a user, but should not exceed 40' - u' characters. Overrides userIp if both are provided.') - flags.DEFINE_string( - 'trace', - None, - 'A tracing token of the form "token:" to include in api ' - 'requests.') - flags.DEFINE_string( - 'userIp', - None, - u'IP address of the site where the request originates. Use this if you ' - u'want to enforce per-user limits.') - - -FLAGS = flags.FLAGS -apitools_base_cli.DeclareBaseFlags() -_DeclareFusiontablesFlags() - - -def GetGlobalParamsFromFlags(): - """Return a StandardQueryParameters based on flags.""" - result = messages.StandardQueryParameters() - if FLAGS['alt'].present: - result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt) - if FLAGS['fields'].present: - result.fields = FLAGS.fields.decode('utf8') - if FLAGS['key'].present: - result.key = FLAGS.key.decode('utf8') - if FLAGS['oauth_token'].present: - result.oauth_token = FLAGS.oauth_token.decode('utf8') - if FLAGS['prettyPrint'].present: - result.prettyPrint = FLAGS.prettyPrint - if FLAGS['quotaUser'].present: - result.quotaUser = FLAGS.quotaUser.decode('utf8') - if FLAGS['trace'].present: - result.trace = FLAGS.trace.decode('utf8') - if FLAGS['userIp'].present: - result.userIp = FLAGS.userIp.decode('utf8') - return result - - -def GetClientFromFlags(): - """Return a client object, configured from flags.""" - log_request = FLAGS.log_request or FLAGS.log_request_response - log_response = FLAGS.log_response or FLAGS.log_request_response - api_endpoint = apitools_base.NormalizeApiEndpoint(FLAGS.api_endpoint) - additional_http_headers = dict(x.split('=', 1) for x in FLAGS.add_header) - credentials_args = { - 'service_account_json_keyfile': os.path.expanduser(FLAGS.service_account_json_keyfile) - } - try: - client = client_lib.FusiontablesV1( - api_endpoint, log_request=log_request, - log_response=log_response, - credentials_args=credentials_args, - additional_http_headers=additional_http_headers) - except apitools_base.CredentialsError as e: - print 'Error creating credentials: %s' % e - sys.exit(1) - return client - - -class PyShell(appcommands.Cmd): - - def Run(self, _): - """Run an interactive python shell with the client.""" - client = GetClientFromFlags() - params = GetGlobalParamsFromFlags() - for field in params.all_fields(): - value = params.get_assigned_value(field.name) - if value != field.default: - client.AddGlobalParam(field.name, value) - banner = """ - == fusiontables interactive console == - client: a fusiontables client - apitools_base: base apitools module - messages: the generated messages module - """ - local_vars = { - 'apitools_base': apitools_base, - 'client': client, - 'client_lib': client_lib, - 'messages': messages, - } - if platform.system() == 'Linux': - console = apitools_base_cli.ConsoleWithReadline( - local_vars, histfile=FLAGS.history_file) - else: - console = code.InteractiveConsole(local_vars) - try: - console.interact(banner) - except SystemExit as e: - return e.code - - -class ColumnDelete(apitools_base_cli.NewCmd): - """Command wrapping column.Delete.""" - - usage = """column_delete """ - - def __init__(self, name, fv): - super(ColumnDelete, self).__init__(name, fv) - - def RunWithArgs(self, tableId, columnId): - """Deletes the column. - - Args: - tableId: Table from which the column is being deleted. - columnId: Name or identifier for the column being deleted. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesColumnDeleteRequest( - tableId=tableId.decode('utf8'), - columnId=columnId.decode('utf8'), - ) - result = client.column.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ColumnGet(apitools_base_cli.NewCmd): - """Command wrapping column.Get.""" - - usage = """column_get """ - - def __init__(self, name, fv): - super(ColumnGet, self).__init__(name, fv) - - def RunWithArgs(self, tableId, columnId): - """Retrieves a specific column by its id. - - Args: - tableId: Table to which the column belongs. - columnId: Name or identifier for the column that is being requested. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesColumnGetRequest( - tableId=tableId.decode('utf8'), - columnId=columnId.decode('utf8'), - ) - result = client.column.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ColumnInsert(apitools_base_cli.NewCmd): - """Command wrapping column.Insert.""" - - usage = """column_insert """ - - def __init__(self, name, fv): - super(ColumnInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'column', - None, - u'A Column resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Adds a new column to the table. - - Args: - tableId: Table for which a new column is being added. - - Flags: - column: A Column resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesColumnInsertRequest( - tableId=tableId.decode('utf8'), - ) - if FLAGS['column'].present: - request.column = apitools_base.JsonToMessage(messages.Column, FLAGS.column) - result = client.column.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ColumnList(apitools_base_cli.NewCmd): - """Command wrapping column.List.""" - - usage = """column_list """ - - def __init__(self, name, fv): - super(ColumnList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of columns to return. Optional. Default is 5.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Continuation token specifying which result page to return. ' - u'Optional.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Retrieves a list of columns. - - Args: - tableId: Table whose columns are being listed. - - Flags: - maxResults: Maximum number of columns to return. Optional. Default is 5. - pageToken: Continuation token specifying which result page to return. - Optional. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesColumnListRequest( - tableId=tableId.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.column.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ColumnPatch(apitools_base_cli.NewCmd): - """Command wrapping column.Patch.""" - - usage = """column_patch """ - - def __init__(self, name, fv): - super(ColumnPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'column', - None, - u'A Column resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, tableId, columnId): - """Updates the name or type of an existing column. This method supports - patch semantics. - - Args: - tableId: Table for which the column is being updated. - columnId: Name or identifier for the column that is being updated. - - Flags: - column: A Column resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesColumnPatchRequest( - tableId=tableId.decode('utf8'), - columnId=columnId.decode('utf8'), - ) - if FLAGS['column'].present: - request.column = apitools_base.JsonToMessage(messages.Column, FLAGS.column) - result = client.column.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ColumnUpdate(apitools_base_cli.NewCmd): - """Command wrapping column.Update.""" - - usage = """column_update """ - - def __init__(self, name, fv): - super(ColumnUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'column', - None, - u'A Column resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, tableId, columnId): - """Updates the name or type of an existing column. - - Args: - tableId: Table for which the column is being updated. - columnId: Name or identifier for the column that is being updated. - - Flags: - column: A Column resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesColumnUpdateRequest( - tableId=tableId.decode('utf8'), - columnId=columnId.decode('utf8'), - ) - if FLAGS['column'].present: - request.column = apitools_base.JsonToMessage(messages.Column, FLAGS.column) - result = client.column.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class QuerySql(apitools_base_cli.NewCmd): - """Command wrapping query.Sql.""" - - usage = """query_sql """ - - def __init__(self, name, fv): - super(QuerySql, self).__init__(name, fv) - flags.DEFINE_boolean( - 'hdrs', - None, - u'Should column names be included (in the first row)?. Default is ' - u'true.', - flag_values=fv) - flags.DEFINE_boolean( - 'typed', - None, - u'Should typed values be returned in the (JSON) response -- numbers ' - u'for numeric values and parsed geometries for KML values? Default is' - u' true.', - flag_values=fv) - flags.DEFINE_string( - 'download_filename', - '', - 'Filename to use for download.', - flag_values=fv) - flags.DEFINE_boolean( - 'overwrite', - 'False', - 'If True, overwrite the existing file when downloading.', - flag_values=fv) - - def RunWithArgs(self, sql): - """Executes an SQL SELECT/INSERT/UPDATE/DELETE/SHOW/DESCRIBE/CREATE - statement. - - Args: - sql: An SQL SELECT/SHOW/DESCRIBE/INSERT/UPDATE/DELETE/CREATE statement. - - Flags: - hdrs: Should column names be included (in the first row)?. Default is - true. - typed: Should typed values be returned in the (JSON) response -- numbers - for numeric values and parsed geometries for KML values? Default is - true. - download_filename: Filename to use for download. - overwrite: If True, overwrite the existing file when downloading. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesQuerySqlRequest( - sql=sql.decode('utf8'), - ) - if FLAGS['hdrs'].present: - request.hdrs = FLAGS.hdrs - if FLAGS['typed'].present: - request.typed = FLAGS.typed - download = None - if FLAGS.download_filename: - download = apitools_base.Download.FromFile(FLAGS.download_filename, overwrite=FLAGS.overwrite, - progress_callback=apitools_base.DownloadProgressPrinter, - finish_callback=apitools_base.DownloadCompletePrinter) - result = client.query.Sql( - request, global_params=global_params, download=download) - print apitools_base_cli.FormatOutput(result) - - -class QuerySqlGet(apitools_base_cli.NewCmd): - """Command wrapping query.SqlGet.""" - - usage = """query_sqlGet """ - - def __init__(self, name, fv): - super(QuerySqlGet, self).__init__(name, fv) - flags.DEFINE_boolean( - 'hdrs', - None, - u'Should column names be included (in the first row)?. Default is ' - u'true.', - flag_values=fv) - flags.DEFINE_boolean( - 'typed', - None, - u'Should typed values be returned in the (JSON) response -- numbers ' - u'for numeric values and parsed geometries for KML values? Default is' - u' true.', - flag_values=fv) - flags.DEFINE_string( - 'download_filename', - '', - 'Filename to use for download.', - flag_values=fv) - flags.DEFINE_boolean( - 'overwrite', - 'False', - 'If True, overwrite the existing file when downloading.', - flag_values=fv) - - def RunWithArgs(self, sql): - """Executes an SQL SELECT/SHOW/DESCRIBE statement. - - Args: - sql: An SQL SELECT/SHOW/DESCRIBE statement. - - Flags: - hdrs: Should column names be included (in the first row)?. Default is - true. - typed: Should typed values be returned in the (JSON) response -- numbers - for numeric values and parsed geometries for KML values? Default is - true. - download_filename: Filename to use for download. - overwrite: If True, overwrite the existing file when downloading. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesQuerySqlGetRequest( - sql=sql.decode('utf8'), - ) - if FLAGS['hdrs'].present: - request.hdrs = FLAGS.hdrs - if FLAGS['typed'].present: - request.typed = FLAGS.typed - download = None - if FLAGS.download_filename: - download = apitools_base.Download.FromFile(FLAGS.download_filename, overwrite=FLAGS.overwrite, - progress_callback=apitools_base.DownloadProgressPrinter, - finish_callback=apitools_base.DownloadCompletePrinter) - result = client.query.SqlGet( - request, global_params=global_params, download=download) - print apitools_base_cli.FormatOutput(result) - - -class StyleDelete(apitools_base_cli.NewCmd): - """Command wrapping style.Delete.""" - - usage = """style_delete """ - - def __init__(self, name, fv): - super(StyleDelete, self).__init__(name, fv) - - def RunWithArgs(self, tableId, styleId): - """Deletes a style. - - Args: - tableId: Table from which the style is being deleted - styleId: Identifier (within a table) for the style being deleted - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesStyleDeleteRequest( - tableId=tableId.decode('utf8'), - styleId=styleId, - ) - result = client.style.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class StyleGet(apitools_base_cli.NewCmd): - """Command wrapping style.Get.""" - - usage = """style_get """ - - def __init__(self, name, fv): - super(StyleGet, self).__init__(name, fv) - - def RunWithArgs(self, tableId, styleId): - """Gets a specific style. - - Args: - tableId: Table to which the requested style belongs - styleId: Identifier (integer) for a specific style in a table - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesStyleGetRequest( - tableId=tableId.decode('utf8'), - styleId=styleId, - ) - result = client.style.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class StyleInsert(apitools_base_cli.NewCmd): - """Command wrapping style.Insert.""" - - usage = """style_insert """ - - def __init__(self, name, fv): - super(StyleInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'kind', - u'fusiontables#styleSetting', - u'Type name: an individual style setting. A StyleSetting contains the' - u' style defintions for points, lines, and polygons in a table. Since' - u' a table can have any one or all of them, a style definition can ' - u'have point, line and polygon style definitions.', - flag_values=fv) - flags.DEFINE_string( - 'markerOptions', - None, - u'Style definition for points in the table.', - flag_values=fv) - flags.DEFINE_string( - 'name', - None, - u'Optional name for the style setting.', - flag_values=fv) - flags.DEFINE_string( - 'polygonOptions', - None, - u'Style definition for polygons in the table.', - flag_values=fv) - flags.DEFINE_string( - 'polylineOptions', - None, - u'Style definition for lines in the table.', - flag_values=fv) - flags.DEFINE_integer( - 'styleId', - None, - u'Identifier for the style setting (unique only within tables).', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Adds a new style for the table. - - Args: - tableId: Identifier for the table. - - Flags: - kind: Type name: an individual style setting. A StyleSetting contains - the style defintions for points, lines, and polygons in a table. Since - a table can have any one or all of them, a style definition can have - point, line and polygon style definitions. - markerOptions: Style definition for points in the table. - name: Optional name for the style setting. - polygonOptions: Style definition for polygons in the table. - polylineOptions: Style definition for lines in the table. - styleId: Identifier for the style setting (unique only within tables). - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StyleSetting( - tableId=tableId.decode('utf8'), - ) - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['markerOptions'].present: - request.markerOptions = apitools_base.JsonToMessage(messages.PointStyle, FLAGS.markerOptions) - if FLAGS['name'].present: - request.name = FLAGS.name.decode('utf8') - if FLAGS['polygonOptions'].present: - request.polygonOptions = apitools_base.JsonToMessage(messages.PolygonStyle, FLAGS.polygonOptions) - if FLAGS['polylineOptions'].present: - request.polylineOptions = apitools_base.JsonToMessage(messages.LineStyle, FLAGS.polylineOptions) - if FLAGS['styleId'].present: - request.styleId = FLAGS.styleId - result = client.style.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class StyleList(apitools_base_cli.NewCmd): - """Command wrapping style.List.""" - - usage = """style_list """ - - def __init__(self, name, fv): - super(StyleList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of styles to return. Optional. Default is 5.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Continuation token specifying which result page to return. ' - u'Optional.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Retrieves a list of styles. - - Args: - tableId: Table whose styles are being listed - - Flags: - maxResults: Maximum number of styles to return. Optional. Default is 5. - pageToken: Continuation token specifying which result page to return. - Optional. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesStyleListRequest( - tableId=tableId.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.style.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class StylePatch(apitools_base_cli.NewCmd): - """Command wrapping style.Patch.""" - - usage = """style_patch """ - - def __init__(self, name, fv): - super(StylePatch, self).__init__(name, fv) - flags.DEFINE_string( - 'kind', - u'fusiontables#styleSetting', - u'Type name: an individual style setting. A StyleSetting contains the' - u' style defintions for points, lines, and polygons in a table. Since' - u' a table can have any one or all of them, a style definition can ' - u'have point, line and polygon style definitions.', - flag_values=fv) - flags.DEFINE_string( - 'markerOptions', - None, - u'Style definition for points in the table.', - flag_values=fv) - flags.DEFINE_string( - 'name', - None, - u'Optional name for the style setting.', - flag_values=fv) - flags.DEFINE_string( - 'polygonOptions', - None, - u'Style definition for polygons in the table.', - flag_values=fv) - flags.DEFINE_string( - 'polylineOptions', - None, - u'Style definition for lines in the table.', - flag_values=fv) - - def RunWithArgs(self, tableId, styleId): - """Updates an existing style. This method supports patch semantics. - - Args: - tableId: Identifier for the table. - styleId: Identifier for the style setting (unique only within tables). - - Flags: - kind: Type name: an individual style setting. A StyleSetting contains - the style defintions for points, lines, and polygons in a table. Since - a table can have any one or all of them, a style definition can have - point, line and polygon style definitions. - markerOptions: Style definition for points in the table. - name: Optional name for the style setting. - polygonOptions: Style definition for polygons in the table. - polylineOptions: Style definition for lines in the table. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StyleSetting( - tableId=tableId.decode('utf8'), - styleId=styleId, - ) - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['markerOptions'].present: - request.markerOptions = apitools_base.JsonToMessage(messages.PointStyle, FLAGS.markerOptions) - if FLAGS['name'].present: - request.name = FLAGS.name.decode('utf8') - if FLAGS['polygonOptions'].present: - request.polygonOptions = apitools_base.JsonToMessage(messages.PolygonStyle, FLAGS.polygonOptions) - if FLAGS['polylineOptions'].present: - request.polylineOptions = apitools_base.JsonToMessage(messages.LineStyle, FLAGS.polylineOptions) - result = client.style.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class StyleUpdate(apitools_base_cli.NewCmd): - """Command wrapping style.Update.""" - - usage = """style_update """ - - def __init__(self, name, fv): - super(StyleUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'kind', - u'fusiontables#styleSetting', - u'Type name: an individual style setting. A StyleSetting contains the' - u' style defintions for points, lines, and polygons in a table. Since' - u' a table can have any one or all of them, a style definition can ' - u'have point, line and polygon style definitions.', - flag_values=fv) - flags.DEFINE_string( - 'markerOptions', - None, - u'Style definition for points in the table.', - flag_values=fv) - flags.DEFINE_string( - 'name', - None, - u'Optional name for the style setting.', - flag_values=fv) - flags.DEFINE_string( - 'polygonOptions', - None, - u'Style definition for polygons in the table.', - flag_values=fv) - flags.DEFINE_string( - 'polylineOptions', - None, - u'Style definition for lines in the table.', - flag_values=fv) - - def RunWithArgs(self, tableId, styleId): - """Updates an existing style. - - Args: - tableId: Identifier for the table. - styleId: Identifier for the style setting (unique only within tables). - - Flags: - kind: Type name: an individual style setting. A StyleSetting contains - the style defintions for points, lines, and polygons in a table. Since - a table can have any one or all of them, a style definition can have - point, line and polygon style definitions. - markerOptions: Style definition for points in the table. - name: Optional name for the style setting. - polygonOptions: Style definition for polygons in the table. - polylineOptions: Style definition for lines in the table. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StyleSetting( - tableId=tableId.decode('utf8'), - styleId=styleId, - ) - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['markerOptions'].present: - request.markerOptions = apitools_base.JsonToMessage(messages.PointStyle, FLAGS.markerOptions) - if FLAGS['name'].present: - request.name = FLAGS.name.decode('utf8') - if FLAGS['polygonOptions'].present: - request.polygonOptions = apitools_base.JsonToMessage(messages.PolygonStyle, FLAGS.polygonOptions) - if FLAGS['polylineOptions'].present: - request.polylineOptions = apitools_base.JsonToMessage(messages.LineStyle, FLAGS.polylineOptions) - result = client.style.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TableCopy(apitools_base_cli.NewCmd): - """Command wrapping table.Copy.""" - - usage = """table_copy """ - - def __init__(self, name, fv): - super(TableCopy, self).__init__(name, fv) - flags.DEFINE_boolean( - 'copyPresentation', - None, - u'Whether to also copy tabs, styles, and templates. Default is false.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Copies a table. - - Args: - tableId: ID of the table that is being copied. - - Flags: - copyPresentation: Whether to also copy tabs, styles, and templates. - Default is false. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTableCopyRequest( - tableId=tableId.decode('utf8'), - ) - if FLAGS['copyPresentation'].present: - request.copyPresentation = FLAGS.copyPresentation - result = client.table.Copy( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TableDelete(apitools_base_cli.NewCmd): - """Command wrapping table.Delete.""" - - usage = """table_delete """ - - def __init__(self, name, fv): - super(TableDelete, self).__init__(name, fv) - - def RunWithArgs(self, tableId): - """Deletes a table. - - Args: - tableId: ID of the table that is being deleted. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTableDeleteRequest( - tableId=tableId.decode('utf8'), - ) - result = client.table.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TableGet(apitools_base_cli.NewCmd): - """Command wrapping table.Get.""" - - usage = """table_get """ - - def __init__(self, name, fv): - super(TableGet, self).__init__(name, fv) - - def RunWithArgs(self, tableId): - """Retrieves a specific table by its id. - - Args: - tableId: Identifier(ID) for the table being requested. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTableGetRequest( - tableId=tableId.decode('utf8'), - ) - result = client.table.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TableImportRows(apitools_base_cli.NewCmd): - """Command wrapping table.ImportRows.""" - - usage = """table_importRows """ - - def __init__(self, name, fv): - super(TableImportRows, self).__init__(name, fv) - flags.DEFINE_string( - 'delimiter', - None, - u'The delimiter used to separate cell values. This can only consist ' - u"of a single character. Default is ','.", - flag_values=fv) - flags.DEFINE_string( - 'encoding', - None, - u"The encoding of the content. Default is UTF-8. Use 'auto-detect' if" - u' you are unsure of the encoding.', - flag_values=fv) - flags.DEFINE_integer( - 'endLine', - None, - u'The index of the last line from which to start importing, ' - u'exclusive. Thus, the number of imported lines is endLine - ' - u'startLine. If this parameter is not provided, the file will be ' - u'imported until the last line of the file. If endLine is negative, ' - u'then the imported content will exclude the last endLine lines. That' - u' is, if endline is negative, no line will be imported whose index ' - u'is greater than N + endLine where N is the number of lines in the ' - u'file, and the number of imported lines will be N + endLine - ' - u'startLine.', - flag_values=fv) - flags.DEFINE_boolean( - 'isStrict', - None, - u'Whether the CSV must have the same number of values for each row. ' - u'If false, rows with fewer values will be padded with empty values. ' - u'Default is true.', - flag_values=fv) - flags.DEFINE_integer( - 'startLine', - None, - u'The index of the first line from which to start importing, ' - u'inclusive. Default is 0.', - flag_values=fv) - flags.DEFINE_string( - 'upload_filename', - '', - 'Filename to use for upload.', - flag_values=fv) - flags.DEFINE_string( - 'upload_mime_type', - '', - 'MIME type to use for the upload. Only needed if the extension on ' - '--upload_filename does not determine the correct (or any) MIME ' - 'type.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Import more rows into a table. - - Args: - tableId: The table into which new rows are being imported. - - Flags: - delimiter: The delimiter used to separate cell values. This can only - consist of a single character. Default is ','. - encoding: The encoding of the content. Default is UTF-8. Use 'auto- - detect' if you are unsure of the encoding. - endLine: The index of the last line from which to start importing, - exclusive. Thus, the number of imported lines is endLine - startLine. - If this parameter is not provided, the file will be imported until the - last line of the file. If endLine is negative, then the imported - content will exclude the last endLine lines. That is, if endline is - negative, no line will be imported whose index is greater than N + - endLine where N is the number of lines in the file, and the number of - imported lines will be N + endLine - startLine. - isStrict: Whether the CSV must have the same number of values for each - row. If false, rows with fewer values will be padded with empty - values. Default is true. - startLine: The index of the first line from which to start importing, - inclusive. Default is 0. - upload_filename: Filename to use for upload. - upload_mime_type: MIME type to use for the upload. Only needed if the - extension on --upload_filename does not determine the correct (or any) - MIME type. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTableImportRowsRequest( - tableId=tableId.decode('utf8'), - ) - if FLAGS['delimiter'].present: - request.delimiter = FLAGS.delimiter.decode('utf8') - if FLAGS['encoding'].present: - request.encoding = FLAGS.encoding.decode('utf8') - if FLAGS['endLine'].present: - request.endLine = FLAGS.endLine - if FLAGS['isStrict'].present: - request.isStrict = FLAGS.isStrict - if FLAGS['startLine'].present: - request.startLine = FLAGS.startLine - upload = None - if FLAGS.upload_filename: - upload = apitools_base.Upload.FromFile( - FLAGS.upload_filename, FLAGS.upload_mime_type, - progress_callback=apitools_base.UploadProgressPrinter, - finish_callback=apitools_base.UploadCompletePrinter) - result = client.table.ImportRows( - request, global_params=global_params, upload=upload) - print apitools_base_cli.FormatOutput(result) - - -class TableImportTable(apitools_base_cli.NewCmd): - """Command wrapping table.ImportTable.""" - - usage = """table_importTable """ - - def __init__(self, name, fv): - super(TableImportTable, self).__init__(name, fv) - flags.DEFINE_string( - 'delimiter', - None, - u'The delimiter used to separate cell values. This can only consist ' - u"of a single character. Default is ','.", - flag_values=fv) - flags.DEFINE_string( - 'encoding', - None, - u"The encoding of the content. Default is UTF-8. Use 'auto-detect' if" - u' you are unsure of the encoding.', - flag_values=fv) - flags.DEFINE_string( - 'upload_filename', - '', - 'Filename to use for upload.', - flag_values=fv) - flags.DEFINE_string( - 'upload_mime_type', - '', - 'MIME type to use for the upload. Only needed if the extension on ' - '--upload_filename does not determine the correct (or any) MIME ' - 'type.', - flag_values=fv) - - def RunWithArgs(self, name): - """Import a new table. - - Args: - name: The name to be assigned to the new table. - - Flags: - delimiter: The delimiter used to separate cell values. This can only - consist of a single character. Default is ','. - encoding: The encoding of the content. Default is UTF-8. Use 'auto- - detect' if you are unsure of the encoding. - upload_filename: Filename to use for upload. - upload_mime_type: MIME type to use for the upload. Only needed if the - extension on --upload_filename does not determine the correct (or any) - MIME type. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTableImportTableRequest( - name=name.decode('utf8'), - ) - if FLAGS['delimiter'].present: - request.delimiter = FLAGS.delimiter.decode('utf8') - if FLAGS['encoding'].present: - request.encoding = FLAGS.encoding.decode('utf8') - upload = None - if FLAGS.upload_filename: - upload = apitools_base.Upload.FromFile( - FLAGS.upload_filename, FLAGS.upload_mime_type, - progress_callback=apitools_base.UploadProgressPrinter, - finish_callback=apitools_base.UploadCompletePrinter) - result = client.table.ImportTable( - request, global_params=global_params, upload=upload) - print apitools_base_cli.FormatOutput(result) - - -class TableInsert(apitools_base_cli.NewCmd): - """Command wrapping table.Insert.""" - - usage = """table_insert""" - - def __init__(self, name, fv): - super(TableInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'attribution', - None, - u'Optional attribution assigned to the table.', - flag_values=fv) - flags.DEFINE_string( - 'attributionLink', - None, - u'Optional link for attribution.', - flag_values=fv) - flags.DEFINE_string( - 'baseTableIds', - None, - u'Optional base table identifier if this table is a view or merged ' - u'table.', - flag_values=fv) - flags.DEFINE_string( - 'columns', - None, - u'Columns in the table.', - flag_values=fv) - flags.DEFINE_string( - 'description', - None, - u'Optional description assigned to the table.', - flag_values=fv) - flags.DEFINE_boolean( - 'isExportable', - None, - u'Variable for whether table is exportable.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'fusiontables#table', - u'Type name: a template for an individual table.', - flag_values=fv) - flags.DEFINE_string( - 'name', - None, - u'Name assigned to a table.', - flag_values=fv) - flags.DEFINE_string( - 'sql', - None, - u'Optional sql that encodes the table definition for derived tables.', - flag_values=fv) - flags.DEFINE_string( - 'tableId', - None, - u'Encrypted unique alphanumeric identifier for the table.', - flag_values=fv) - - def RunWithArgs(self): - """Creates a new table. - - Flags: - attribution: Optional attribution assigned to the table. - attributionLink: Optional link for attribution. - baseTableIds: Optional base table identifier if this table is a view or - merged table. - columns: Columns in the table. - description: Optional description assigned to the table. - isExportable: Variable for whether table is exportable. - kind: Type name: a template for an individual table. - name: Name assigned to a table. - sql: Optional sql that encodes the table definition for derived tables. - tableId: Encrypted unique alphanumeric identifier for the table. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.Table( - ) - if FLAGS['attribution'].present: - request.attribution = FLAGS.attribution.decode('utf8') - if FLAGS['attributionLink'].present: - request.attributionLink = FLAGS.attributionLink.decode('utf8') - if FLAGS['baseTableIds'].present: - request.baseTableIds = [x.decode('utf8') for x in FLAGS.baseTableIds] - if FLAGS['columns'].present: - request.columns = [apitools_base.JsonToMessage(messages.Column, x) for x in FLAGS.columns] - if FLAGS['description'].present: - request.description = FLAGS.description.decode('utf8') - if FLAGS['isExportable'].present: - request.isExportable = FLAGS.isExportable - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['name'].present: - request.name = FLAGS.name.decode('utf8') - if FLAGS['sql'].present: - request.sql = FLAGS.sql.decode('utf8') - if FLAGS['tableId'].present: - request.tableId = FLAGS.tableId.decode('utf8') - result = client.table.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TableList(apitools_base_cli.NewCmd): - """Command wrapping table.List.""" - - usage = """table_list""" - - def __init__(self, name, fv): - super(TableList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of styles to return. Optional. Default is 5.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Continuation token specifying which result page to return. ' - u'Optional.', - flag_values=fv) - - def RunWithArgs(self): - """Retrieves a list of tables a user owns. - - Flags: - maxResults: Maximum number of styles to return. Optional. Default is 5. - pageToken: Continuation token specifying which result page to return. - Optional. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTableListRequest( - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.table.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TablePatch(apitools_base_cli.NewCmd): - """Command wrapping table.Patch.""" - - usage = """table_patch """ - - def __init__(self, name, fv): - super(TablePatch, self).__init__(name, fv) - flags.DEFINE_boolean( - 'replaceViewDefinition', - None, - u'Should the view definition also be updated? The specified view ' - u'definition replaces the existing one. Only a view can be updated ' - u'with a new definition.', - flag_values=fv) - flags.DEFINE_string( - 'table', - None, - u'A Table resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Updates an existing table. Unless explicitly requested, only the name, - description, and attribution will be updated. This method supports patch - semantics. - - Args: - tableId: ID of the table that is being updated. - - Flags: - replaceViewDefinition: Should the view definition also be updated? The - specified view definition replaces the existing one. Only a view can - be updated with a new definition. - table: A Table resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTablePatchRequest( - tableId=tableId.decode('utf8'), - ) - if FLAGS['replaceViewDefinition'].present: - request.replaceViewDefinition = FLAGS.replaceViewDefinition - if FLAGS['table'].present: - request.table = apitools_base.JsonToMessage(messages.Table, FLAGS.table) - result = client.table.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TableUpdate(apitools_base_cli.NewCmd): - """Command wrapping table.Update.""" - - usage = """table_update """ - - def __init__(self, name, fv): - super(TableUpdate, self).__init__(name, fv) - flags.DEFINE_boolean( - 'replaceViewDefinition', - None, - u'Should the view definition also be updated? The specified view ' - u'definition replaces the existing one. Only a view can be updated ' - u'with a new definition.', - flag_values=fv) - flags.DEFINE_string( - 'table', - None, - u'A Table resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Updates an existing table. Unless explicitly requested, only the name, - description, and attribution will be updated. - - Args: - tableId: ID of the table that is being updated. - - Flags: - replaceViewDefinition: Should the view definition also be updated? The - specified view definition replaces the existing one. Only a view can - be updated with a new definition. - table: A Table resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTableUpdateRequest( - tableId=tableId.decode('utf8'), - ) - if FLAGS['replaceViewDefinition'].present: - request.replaceViewDefinition = FLAGS.replaceViewDefinition - if FLAGS['table'].present: - request.table = apitools_base.JsonToMessage(messages.Table, FLAGS.table) - result = client.table.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TaskDelete(apitools_base_cli.NewCmd): - """Command wrapping task.Delete.""" - - usage = """task_delete """ - - def __init__(self, name, fv): - super(TaskDelete, self).__init__(name, fv) - - def RunWithArgs(self, tableId, taskId): - """Deletes the task, unless already started. - - Args: - tableId: Table from which the task is being deleted. - taskId: A string attribute. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTaskDeleteRequest( - tableId=tableId.decode('utf8'), - taskId=taskId.decode('utf8'), - ) - result = client.task.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TaskGet(apitools_base_cli.NewCmd): - """Command wrapping task.Get.""" - - usage = """task_get """ - - def __init__(self, name, fv): - super(TaskGet, self).__init__(name, fv) - - def RunWithArgs(self, tableId, taskId): - """Retrieves a specific task by its id. - - Args: - tableId: Table to which the task belongs. - taskId: A string attribute. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTaskGetRequest( - tableId=tableId.decode('utf8'), - taskId=taskId.decode('utf8'), - ) - result = client.task.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TaskList(apitools_base_cli.NewCmd): - """Command wrapping task.List.""" - - usage = """task_list """ - - def __init__(self, name, fv): - super(TaskList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of columns to return. Optional. Default is 5.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - 'A string attribute.', - flag_values=fv) - flags.DEFINE_integer( - 'startIndex', - None, - 'A integer attribute.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Retrieves a list of tasks. - - Args: - tableId: Table whose tasks are being listed. - - Flags: - maxResults: Maximum number of columns to return. Optional. Default is 5. - pageToken: A string attribute. - startIndex: A integer attribute. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTaskListRequest( - tableId=tableId.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['startIndex'].present: - request.startIndex = FLAGS.startIndex - result = client.task.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TemplateDelete(apitools_base_cli.NewCmd): - """Command wrapping template.Delete.""" - - usage = """template_delete """ - - def __init__(self, name, fv): - super(TemplateDelete, self).__init__(name, fv) - - def RunWithArgs(self, tableId, templateId): - """Deletes a template - - Args: - tableId: Table from which the template is being deleted - templateId: Identifier for the template which is being deleted - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTemplateDeleteRequest( - tableId=tableId.decode('utf8'), - templateId=templateId, - ) - result = client.template.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TemplateGet(apitools_base_cli.NewCmd): - """Command wrapping template.Get.""" - - usage = """template_get """ - - def __init__(self, name, fv): - super(TemplateGet, self).__init__(name, fv) - - def RunWithArgs(self, tableId, templateId): - """Retrieves a specific template by its id - - Args: - tableId: Table to which the template belongs - templateId: Identifier for the template that is being requested - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTemplateGetRequest( - tableId=tableId.decode('utf8'), - templateId=templateId, - ) - result = client.template.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TemplateInsert(apitools_base_cli.NewCmd): - """Command wrapping template.Insert.""" - - usage = """template_insert """ - - def __init__(self, name, fv): - super(TemplateInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'automaticColumnNames', - None, - u'List of columns from which the template is to be automatically ' - u'constructed. Only one of body or automaticColumns can be specified.', - flag_values=fv) - flags.DEFINE_string( - 'body', - None, - u'Body of the template. It contains HTML with {column_name} to insert' - u' values from a particular column. The body is sanitized to remove ' - u'certain tags, e.g., script. Only one of body or automaticColumns ' - u'can be specified.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'fusiontables#template', - u'Type name: a template for the info window contents. The template ' - u'can either include an HTML body or a list of columns from which the' - u' template is computed automatically.', - flag_values=fv) - flags.DEFINE_string( - 'name', - None, - u'Optional name assigned to a template.', - flag_values=fv) - flags.DEFINE_integer( - 'templateId', - None, - u'Identifier for the template, unique within the context of a ' - u'particular table.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Creates a new template for the table. - - Args: - tableId: Identifier for the table for which the template is defined. - - Flags: - automaticColumnNames: List of columns from which the template is to be - automatically constructed. Only one of body or automaticColumns can be - specified. - body: Body of the template. It contains HTML with {column_name} to - insert values from a particular column. The body is sanitized to - remove certain tags, e.g., script. Only one of body or - automaticColumns can be specified. - kind: Type name: a template for the info window contents. The template - can either include an HTML body or a list of columns from which the - template is computed automatically. - name: Optional name assigned to a template. - templateId: Identifier for the template, unique within the context of a - particular table. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.Template( - tableId=tableId.decode('utf8'), - ) - if FLAGS['automaticColumnNames'].present: - request.automaticColumnNames = [x.decode('utf8') for x in FLAGS.automaticColumnNames] - if FLAGS['body'].present: - request.body = FLAGS.body.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['name'].present: - request.name = FLAGS.name.decode('utf8') - if FLAGS['templateId'].present: - request.templateId = FLAGS.templateId - result = client.template.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TemplateList(apitools_base_cli.NewCmd): - """Command wrapping template.List.""" - - usage = """template_list """ - - def __init__(self, name, fv): - super(TemplateList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of templates to return. Optional. Default is 5.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Continuation token specifying which results page to return. ' - u'Optional.', - flag_values=fv) - - def RunWithArgs(self, tableId): - """Retrieves a list of templates. - - Args: - tableId: Identifier for the table whose templates are being requested - - Flags: - maxResults: Maximum number of templates to return. Optional. Default is - 5. - pageToken: Continuation token specifying which results page to return. - Optional. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.FusiontablesTemplateListRequest( - tableId=tableId.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.template.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TemplatePatch(apitools_base_cli.NewCmd): - """Command wrapping template.Patch.""" - - usage = """template_patch """ - - def __init__(self, name, fv): - super(TemplatePatch, self).__init__(name, fv) - flags.DEFINE_string( - 'automaticColumnNames', - None, - u'List of columns from which the template is to be automatically ' - u'constructed. Only one of body or automaticColumns can be specified.', - flag_values=fv) - flags.DEFINE_string( - 'body', - None, - u'Body of the template. It contains HTML with {column_name} to insert' - u' values from a particular column. The body is sanitized to remove ' - u'certain tags, e.g., script. Only one of body or automaticColumns ' - u'can be specified.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'fusiontables#template', - u'Type name: a template for the info window contents. The template ' - u'can either include an HTML body or a list of columns from which the' - u' template is computed automatically.', - flag_values=fv) - flags.DEFINE_string( - 'name', - None, - u'Optional name assigned to a template.', - flag_values=fv) - - def RunWithArgs(self, tableId, templateId): - """Updates an existing template. This method supports patch semantics. - - Args: - tableId: Identifier for the table for which the template is defined. - templateId: Identifier for the template, unique within the context of a - particular table. - - Flags: - automaticColumnNames: List of columns from which the template is to be - automatically constructed. Only one of body or automaticColumns can be - specified. - body: Body of the template. It contains HTML with {column_name} to - insert values from a particular column. The body is sanitized to - remove certain tags, e.g., script. Only one of body or - automaticColumns can be specified. - kind: Type name: a template for the info window contents. The template - can either include an HTML body or a list of columns from which the - template is computed automatically. - name: Optional name assigned to a template. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.Template( - tableId=tableId.decode('utf8'), - templateId=templateId, - ) - if FLAGS['automaticColumnNames'].present: - request.automaticColumnNames = [x.decode('utf8') for x in FLAGS.automaticColumnNames] - if FLAGS['body'].present: - request.body = FLAGS.body.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['name'].present: - request.name = FLAGS.name.decode('utf8') - result = client.template.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class TemplateUpdate(apitools_base_cli.NewCmd): - """Command wrapping template.Update.""" - - usage = """template_update """ - - def __init__(self, name, fv): - super(TemplateUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'automaticColumnNames', - None, - u'List of columns from which the template is to be automatically ' - u'constructed. Only one of body or automaticColumns can be specified.', - flag_values=fv) - flags.DEFINE_string( - 'body', - None, - u'Body of the template. It contains HTML with {column_name} to insert' - u' values from a particular column. The body is sanitized to remove ' - u'certain tags, e.g., script. Only one of body or automaticColumns ' - u'can be specified.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'fusiontables#template', - u'Type name: a template for the info window contents. The template ' - u'can either include an HTML body or a list of columns from which the' - u' template is computed automatically.', - flag_values=fv) - flags.DEFINE_string( - 'name', - None, - u'Optional name assigned to a template.', - flag_values=fv) - - def RunWithArgs(self, tableId, templateId): - """Updates an existing template - - Args: - tableId: Identifier for the table for which the template is defined. - templateId: Identifier for the template, unique within the context of a - particular table. - - Flags: - automaticColumnNames: List of columns from which the template is to be - automatically constructed. Only one of body or automaticColumns can be - specified. - body: Body of the template. It contains HTML with {column_name} to - insert values from a particular column. The body is sanitized to - remove certain tags, e.g., script. Only one of body or - automaticColumns can be specified. - kind: Type name: a template for the info window contents. The template - can either include an HTML body or a list of columns from which the - template is computed automatically. - name: Optional name assigned to a template. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.Template( - tableId=tableId.decode('utf8'), - templateId=templateId, - ) - if FLAGS['automaticColumnNames'].present: - request.automaticColumnNames = [x.decode('utf8') for x in FLAGS.automaticColumnNames] - if FLAGS['body'].present: - request.body = FLAGS.body.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['name'].present: - request.name = FLAGS.name.decode('utf8') - result = client.template.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -def main(_): - appcommands.AddCmd('pyshell', PyShell) - appcommands.AddCmd('column_delete', ColumnDelete) - appcommands.AddCmd('column_get', ColumnGet) - appcommands.AddCmd('column_insert', ColumnInsert) - appcommands.AddCmd('column_list', ColumnList) - appcommands.AddCmd('column_patch', ColumnPatch) - appcommands.AddCmd('column_update', ColumnUpdate) - appcommands.AddCmd('query_sql', QuerySql) - appcommands.AddCmd('query_sqlGet', QuerySqlGet) - appcommands.AddCmd('style_delete', StyleDelete) - appcommands.AddCmd('style_get', StyleGet) - appcommands.AddCmd('style_insert', StyleInsert) - appcommands.AddCmd('style_list', StyleList) - appcommands.AddCmd('style_patch', StylePatch) - appcommands.AddCmd('style_update', StyleUpdate) - appcommands.AddCmd('table_copy', TableCopy) - appcommands.AddCmd('table_delete', TableDelete) - appcommands.AddCmd('table_get', TableGet) - appcommands.AddCmd('table_importRows', TableImportRows) - appcommands.AddCmd('table_importTable', TableImportTable) - appcommands.AddCmd('table_insert', TableInsert) - appcommands.AddCmd('table_list', TableList) - appcommands.AddCmd('table_patch', TablePatch) - appcommands.AddCmd('table_update', TableUpdate) - appcommands.AddCmd('task_delete', TaskDelete) - appcommands.AddCmd('task_get', TaskGet) - appcommands.AddCmd('task_list', TaskList) - appcommands.AddCmd('template_delete', TemplateDelete) - appcommands.AddCmd('template_get', TemplateGet) - appcommands.AddCmd('template_insert', TemplateInsert) - appcommands.AddCmd('template_list', TemplateList) - appcommands.AddCmd('template_patch', TemplatePatch) - appcommands.AddCmd('template_update', TemplateUpdate) - - apitools_base_cli.SetupLogger() - if hasattr(appcommands, 'SetDefaultCommand'): - appcommands.SetDefaultCommand('pyshell') - - -run_main = apitools_base_cli.run_main - -if __name__ == '__main__': - appcommands.Run() diff --git a/samples/iam_sample/iam_v1/iam_v1.py b/samples/iam_sample/iam_v1/iam_v1.py deleted file mode 100644 index da9750e9..00000000 --- a/samples/iam_sample/iam_v1/iam_v1.py +++ /dev/null @@ -1,921 +0,0 @@ -#!/usr/bin/env python -"""CLI for iam, version v1.""" -# NOTE: This file is autogenerated and should not be edited by hand. - -import code -import os -import platform -import sys - -from apitools.base.protorpclite import message_types -from apitools.base.protorpclite import messages - -from google.apputils import appcommands -import gflags as flags - -import apitools.base.py as apitools_base -from apitools.base.py import cli as apitools_base_cli -import iam_v1_client as client_lib -import iam_v1_messages as messages - - -def _DeclareIamFlags(): - """Declare global flags in an idempotent way.""" - if 'api_endpoint' in flags.FLAGS: - return - flags.DEFINE_string( - 'api_endpoint', - u'https://iam.googleapis.com/', - 'URL of the API endpoint to use.', - short_name='iam_url') - flags.DEFINE_string( - 'history_file', - u'~/.iam.v1.history', - 'File with interactive shell history.') - flags.DEFINE_multistring( - 'add_header', [], - 'Additional http headers (as key=value strings). ' - 'Can be specified multiple times.') - flags.DEFINE_string( - 'service_account_json_keyfile', '', - 'Filename for a JSON service account key downloaded' - ' from the Developer Console.') - flags.DEFINE_enum( - 'f__xgafv', - u'_1', - [u'_1', u'_2'], - u'V1 error format.') - flags.DEFINE_string( - 'access_token', - None, - u'OAuth access token.') - flags.DEFINE_enum( - 'alt', - u'json', - [u'json', u'media', u'proto'], - u'Data format for response.') - flags.DEFINE_string( - 'bearer_token', - None, - u'OAuth bearer token.') - flags.DEFINE_string( - 'callback', - None, - u'JSONP') - flags.DEFINE_string( - 'fields', - None, - u'Selector specifying which fields to include in a partial response.') - flags.DEFINE_string( - 'key', - None, - u'API key. Your API key identifies your project and provides you with ' - u'API access, quota, and reports. Required unless you provide an OAuth ' - u'2.0 token.') - flags.DEFINE_string( - 'oauth_token', - None, - u'OAuth 2.0 token for the current user.') - flags.DEFINE_boolean( - 'pp', - 'True', - u'Pretty-print response.') - flags.DEFINE_boolean( - 'prettyPrint', - 'True', - u'Returns response with indentations and line breaks.') - flags.DEFINE_string( - 'quotaUser', - None, - u'Available to use for quota purposes for server-side applications. Can' - u' be any arbitrary string assigned to a user, but should not exceed 40' - u' characters.') - flags.DEFINE_string( - 'trace', - None, - 'A tracing token of the form "token:" to include in api ' - 'requests.') - flags.DEFINE_string( - 'uploadType', - None, - u'Legacy upload protocol for media (e.g. "media", "multipart").') - flags.DEFINE_string( - 'upload_protocol', - None, - u'Upload protocol for media (e.g. "raw", "multipart").') - - -FLAGS = flags.FLAGS -apitools_base_cli.DeclareBaseFlags() -_DeclareIamFlags() - - -def GetGlobalParamsFromFlags(): - """Return a StandardQueryParameters based on flags.""" - result = messages.StandardQueryParameters() - if FLAGS['f__xgafv'].present: - result.f__xgafv = messages.StandardQueryParameters.FXgafvValueValuesEnum(FLAGS.f__xgafv) - if FLAGS['access_token'].present: - result.access_token = FLAGS.access_token.decode('utf8') - if FLAGS['alt'].present: - result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt) - if FLAGS['bearer_token'].present: - result.bearer_token = FLAGS.bearer_token.decode('utf8') - if FLAGS['callback'].present: - result.callback = FLAGS.callback.decode('utf8') - if FLAGS['fields'].present: - result.fields = FLAGS.fields.decode('utf8') - if FLAGS['key'].present: - result.key = FLAGS.key.decode('utf8') - if FLAGS['oauth_token'].present: - result.oauth_token = FLAGS.oauth_token.decode('utf8') - if FLAGS['pp'].present: - result.pp = FLAGS.pp - if FLAGS['prettyPrint'].present: - result.prettyPrint = FLAGS.prettyPrint - if FLAGS['quotaUser'].present: - result.quotaUser = FLAGS.quotaUser.decode('utf8') - if FLAGS['trace'].present: - result.trace = FLAGS.trace.decode('utf8') - if FLAGS['uploadType'].present: - result.uploadType = FLAGS.uploadType.decode('utf8') - if FLAGS['upload_protocol'].present: - result.upload_protocol = FLAGS.upload_protocol.decode('utf8') - return result - - -def GetClientFromFlags(): - """Return a client object, configured from flags.""" - log_request = FLAGS.log_request or FLAGS.log_request_response - log_response = FLAGS.log_response or FLAGS.log_request_response - api_endpoint = apitools_base.NormalizeApiEndpoint(FLAGS.api_endpoint) - additional_http_headers = dict(x.split('=', 1) for x in FLAGS.add_header) - credentials_args = { - 'service_account_json_keyfile': os.path.expanduser(FLAGS.service_account_json_keyfile) - } - try: - client = client_lib.IamV1( - api_endpoint, log_request=log_request, - log_response=log_response, - credentials_args=credentials_args, - additional_http_headers=additional_http_headers) - except apitools_base.CredentialsError as e: - print 'Error creating credentials: %s' % e - sys.exit(1) - return client - - -class PyShell(appcommands.Cmd): - - def Run(self, _): - """Run an interactive python shell with the client.""" - client = GetClientFromFlags() - params = GetGlobalParamsFromFlags() - for field in params.all_fields(): - value = params.get_assigned_value(field.name) - if value != field.default: - client.AddGlobalParam(field.name, value) - banner = """ - == iam interactive console == - client: a iam client - apitools_base: base apitools module - messages: the generated messages module - """ - local_vars = { - 'apitools_base': apitools_base, - 'client': client, - 'client_lib': client_lib, - 'messages': messages, - } - if platform.system() == 'Linux': - console = apitools_base_cli.ConsoleWithReadline( - local_vars, histfile=FLAGS.history_file) - else: - console = code.InteractiveConsole(local_vars) - try: - console.interact(banner) - except SystemExit as e: - return e.code - - -class IamPoliciesGetPolicyDetails(apitools_base_cli.NewCmd): - """Command wrapping iamPolicies.GetPolicyDetails.""" - - usage = """iamPolicies_getPolicyDetails""" - - def __init__(self, name, fv): - super(IamPoliciesGetPolicyDetails, self).__init__(name, fv) - flags.DEFINE_string( - 'fullResourcePath', - None, - u'REQUIRED: The full resource path of the current policy being ' - u'requested, e.g., `//dataflow.googleapis.com/projects/../jobs/..`.', - flag_values=fv) - flags.DEFINE_integer( - 'pageSize', - None, - u'Limit on the number of policies to include in the response. Further' - u' accounts can subsequently be obtained by including the ' - u'GetPolicyDetailsResponse.next_page_token in a subsequent request. ' - u'If zero, the default page size 20 will be used. Must be given a ' - u'value in range [0, 100], otherwise an invalid argument error will ' - u'be returned.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Optional pagination token returned in an earlier ' - u'GetPolicyDetailsResponse.next_page_token response.', - flag_values=fv) - - def RunWithArgs(self): - """Returns the current IAM policy and the policies on the inherited - resources that the user has access to. - - Flags: - fullResourcePath: REQUIRED: The full resource path of the current policy - being requested, e.g., - `//dataflow.googleapis.com/projects/../jobs/..`. - pageSize: Limit on the number of policies to include in the response. - Further accounts can subsequently be obtained by including the - GetPolicyDetailsResponse.next_page_token in a subsequent request. If - zero, the default page size 20 will be used. Must be given a value in - range [0, 100], otherwise an invalid argument error will be returned. - pageToken: Optional pagination token returned in an earlier - GetPolicyDetailsResponse.next_page_token response. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.GetPolicyDetailsRequest( - ) - if FLAGS['fullResourcePath'].present: - request.fullResourcePath = FLAGS.fullResourcePath.decode('utf8') - if FLAGS['pageSize'].present: - request.pageSize = FLAGS.pageSize - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.iamPolicies.GetPolicyDetails( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsCreate(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.Create.""" - - usage = """projects_serviceAccounts_create """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsCreate, self).__init__(name, fv) - flags.DEFINE_string( - 'createServiceAccountRequest', - None, - u'A CreateServiceAccountRequest resource to be passed as the request ' - u'body.', - flag_values=fv) - - def RunWithArgs(self, name): - """Creates a ServiceAccount and returns it. - - Args: - name: Required. The resource name of the project associated with the - service accounts, such as `projects/my-project-123`. - - Flags: - createServiceAccountRequest: A CreateServiceAccountRequest resource to - be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsCreateRequest( - name=name.decode('utf8'), - ) - if FLAGS['createServiceAccountRequest'].present: - request.createServiceAccountRequest = apitools_base.JsonToMessage(messages.CreateServiceAccountRequest, FLAGS.createServiceAccountRequest) - result = client.projects_serviceAccounts.Create( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsDelete(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.Delete.""" - - usage = """projects_serviceAccounts_delete """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsDelete, self).__init__(name, fv) - - def RunWithArgs(self, name): - """Deletes a ServiceAccount. - - Args: - name: The resource name of the service account in the following format: - `projects/{project}/serviceAccounts/{account}`. Using `-` as a - wildcard for the project will infer the project from the account. The - `account` value can be the `email` address or the `unique_id` of the - service account. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsDeleteRequest( - name=name.decode('utf8'), - ) - result = client.projects_serviceAccounts.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsGet(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.Get.""" - - usage = """projects_serviceAccounts_get """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsGet, self).__init__(name, fv) - - def RunWithArgs(self, name): - """Gets a ServiceAccount. - - Args: - name: The resource name of the service account in the following format: - `projects/{project}/serviceAccounts/{account}`. Using `-` as a - wildcard for the project will infer the project from the account. The - `account` value can be the `email` address or the `unique_id` of the - service account. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsGetRequest( - name=name.decode('utf8'), - ) - result = client.projects_serviceAccounts.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsGetIamPolicy(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.GetIamPolicy.""" - - usage = """projects_serviceAccounts_getIamPolicy """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsGetIamPolicy, self).__init__(name, fv) - - def RunWithArgs(self, resource): - """Returns the IAM access control policy for specified IAM resource. - - Args: - resource: REQUIRED: The resource for which the policy is being - requested. `resource` is usually specified as a path, such as - `projects/*project*/zones/*zone*/disks/*disk*`. The format for the - path specified in this value is resource specific and is specified in - the `getIamPolicy` documentation. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsGetIamPolicyRequest( - resource=resource.decode('utf8'), - ) - result = client.projects_serviceAccounts.GetIamPolicy( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsList(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.List.""" - - usage = """projects_serviceAccounts_list """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsList, self).__init__(name, fv) - flags.DEFINE_integer( - 'pageSize', - None, - u'Optional limit on the number of service accounts to include in the ' - u'response. Further accounts can subsequently be obtained by ' - u'including the ListServiceAccountsResponse.next_page_token in a ' - u'subsequent request.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Optional pagination token returned in an earlier ' - u'ListServiceAccountsResponse.next_page_token.', - flag_values=fv) - flags.DEFINE_boolean( - 'removeDeletedServiceAccounts', - None, - u'Do not list service accounts deleted from Gaia. DO NOT INCLUDE IN EXTERNAL DOCUMENTATION.', - flag_values=fv) - - def RunWithArgs(self, name): - """Lists ServiceAccounts for a project. - - Args: - name: Required. The resource name of the project associated with the - service accounts, such as `projects/my-project-123`. - - Flags: - pageSize: Optional limit on the number of service accounts to include in - the response. Further accounts can subsequently be obtained by - including the ListServiceAccountsResponse.next_page_token in a - subsequent request. - pageToken: Optional pagination token returned in an earlier - ListServiceAccountsResponse.next_page_token. - removeDeletedServiceAccounts: Do not list service accounts deleted from - Gaia. DO NOT INCLUDE IN EXTERNAL - DOCUMENTATION. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsListRequest( - name=name.decode('utf8'), - ) - if FLAGS['pageSize'].present: - request.pageSize = FLAGS.pageSize - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['removeDeletedServiceAccounts'].present: - request.removeDeletedServiceAccounts = FLAGS.removeDeletedServiceAccounts - result = client.projects_serviceAccounts.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsSetIamPolicy(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.SetIamPolicy.""" - - usage = """projects_serviceAccounts_setIamPolicy """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsSetIamPolicy, self).__init__(name, fv) - flags.DEFINE_string( - 'setIamPolicyRequest', - None, - u'A SetIamPolicyRequest resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, resource): - """Sets the IAM access control policy for the specified IAM resource. - - Args: - resource: REQUIRED: The resource for which the policy is being - specified. `resource` is usually specified as a path, such as - `projects/*project*/zones/*zone*/disks/*disk*`. The format for the - path specified in this value is resource specific and is specified in - the `setIamPolicy` documentation. - - Flags: - setIamPolicyRequest: A SetIamPolicyRequest resource to be passed as the - request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsSetIamPolicyRequest( - resource=resource.decode('utf8'), - ) - if FLAGS['setIamPolicyRequest'].present: - request.setIamPolicyRequest = apitools_base.JsonToMessage(messages.SetIamPolicyRequest, FLAGS.setIamPolicyRequest) - result = client.projects_serviceAccounts.SetIamPolicy( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsSignBlob(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.SignBlob.""" - - usage = """projects_serviceAccounts_signBlob """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsSignBlob, self).__init__(name, fv) - flags.DEFINE_string( - 'signBlobRequest', - None, - u'A SignBlobRequest resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, name): - """Signs a blob using a service account's system-managed private key. - - Args: - name: The resource name of the service account in the following format: - `projects/{project}/serviceAccounts/{account}`. Using `-` as a - wildcard for the project will infer the project from the account. The - `account` value can be the `email` address or the `unique_id` of the - service account. - - Flags: - signBlobRequest: A SignBlobRequest resource to be passed as the request - body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsSignBlobRequest( - name=name.decode('utf8'), - ) - if FLAGS['signBlobRequest'].present: - request.signBlobRequest = apitools_base.JsonToMessage(messages.SignBlobRequest, FLAGS.signBlobRequest) - result = client.projects_serviceAccounts.SignBlob( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsSignJwt(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.SignJwt.""" - - usage = """projects_serviceAccounts_signJwt """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsSignJwt, self).__init__(name, fv) - flags.DEFINE_string( - 'signJwtRequest', - None, - u'A SignJwtRequest resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, name): - """Signs a JWT using a service account's system-managed private key. If - no `exp` (expiry) time is contained in the claims, we will provide an - expiry of one hour in the future. If an expiry of more than one hour in - the future is requested, the request will fail. - - Args: - name: The resource name of the service account in the following format: - `projects/{project}/serviceAccounts/{account}`. Using `-` as a - wildcard for the project will infer the project from the account. The - `account` value can be the `email` address or the `unique_id` of the - service account. - - Flags: - signJwtRequest: A SignJwtRequest resource to be passed as the request - body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsSignJwtRequest( - name=name.decode('utf8'), - ) - if FLAGS['signJwtRequest'].present: - request.signJwtRequest = apitools_base.JsonToMessage(messages.SignJwtRequest, FLAGS.signJwtRequest) - result = client.projects_serviceAccounts.SignJwt( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsTestIamPermissions(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.TestIamPermissions.""" - - usage = """projects_serviceAccounts_testIamPermissions """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsTestIamPermissions, self).__init__(name, fv) - flags.DEFINE_string( - 'testIamPermissionsRequest', - None, - u'A TestIamPermissionsRequest resource to be passed as the request ' - u'body.', - flag_values=fv) - - def RunWithArgs(self, resource): - """Tests the specified permissions against the IAM access control policy - for the specified IAM resource. - - Args: - resource: REQUIRED: The resource for which the policy detail is being - requested. `resource` is usually specified as a path, such as - `projects/*project*/zones/*zone*/disks/*disk*`. The format for the - path specified in this value is resource specific and is specified in - the `testIamPermissions` documentation. - - Flags: - testIamPermissionsRequest: A TestIamPermissionsRequest resource to be - passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsTestIamPermissionsRequest( - resource=resource.decode('utf8'), - ) - if FLAGS['testIamPermissionsRequest'].present: - request.testIamPermissionsRequest = apitools_base.JsonToMessage(messages.TestIamPermissionsRequest, FLAGS.testIamPermissionsRequest) - result = client.projects_serviceAccounts.TestIamPermissions( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsUpdate(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts.Update.""" - - usage = """projects_serviceAccounts_update """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'description', - None, - u'Optional. A user-specified opaque description of the service ' - u'account.', - flag_values=fv) - flags.DEFINE_string( - 'displayName', - None, - u'Optional. A user-specified description of the service account. ' - u'Must be fewer than 100 UTF-8 bytes.', - flag_values=fv) - flags.DEFINE_string( - 'email', - None, - u'@OutputOnly The email address of the service account.', - flag_values=fv) - flags.DEFINE_string( - 'etag', - None, - u'Used to perform a consistent read-modify-write.', - flag_values=fv) - flags.DEFINE_string( - 'oauth2ClientId', - None, - u'@OutputOnly. The OAuth2 client id for the service account. This is ' - u'used in conjunction with the OAuth2 clientconfig API to make three ' - u'legged OAuth2 (3LO) flows to access the data of Google users.', - flag_values=fv) - flags.DEFINE_string( - 'projectId', - None, - u'@OutputOnly The id of the project that owns the service account.', - flag_values=fv) - flags.DEFINE_string( - 'uniqueId', - None, - u'@OutputOnly The unique and stable id of the service account.', - flag_values=fv) - - def RunWithArgs(self, name): - """Updates a ServiceAccount. Currently, only the following fields are - updatable: `display_name` . The `etag` is mandatory. - - Args: - name: The resource name of the service account in the following format: - `projects/{project}/serviceAccounts/{account}`. Requests using `-` as - a wildcard for the project will infer the project from the `account` - and the `account` value can be the `email` address or the `unique_id` - of the service account. In responses the resource name will always be - in the format `projects/{project}/serviceAccounts/{email}`. - - Flags: - description: Optional. A user-specified opaque description of the - service account. - displayName: Optional. A user-specified description of the service - account. Must be fewer than 100 UTF-8 bytes. - email: @OutputOnly The email address of the service account. - etag: Used to perform a consistent read-modify-write. - oauth2ClientId: @OutputOnly. The OAuth2 client id for the service - account. This is used in conjunction with the OAuth2 clientconfig API - to make three legged OAuth2 (3LO) flows to access the data of Google - users. - projectId: @OutputOnly The id of the project that owns the service - account. - uniqueId: @OutputOnly The unique and stable id of the service account. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServiceAccount( - name=name.decode('utf8'), - ) - if FLAGS['description'].present: - request.description = FLAGS.description.decode('utf8') - if FLAGS['displayName'].present: - request.displayName = FLAGS.displayName.decode('utf8') - if FLAGS['email'].present: - request.email = FLAGS.email.decode('utf8') - if FLAGS['etag'].present: - request.etag = FLAGS.etag - if FLAGS['oauth2ClientId'].present: - request.oauth2ClientId = FLAGS.oauth2ClientId.decode('utf8') - if FLAGS['projectId'].present: - request.projectId = FLAGS.projectId.decode('utf8') - if FLAGS['uniqueId'].present: - request.uniqueId = FLAGS.uniqueId.decode('utf8') - result = client.projects_serviceAccounts.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsKeysCreate(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts_keys.Create.""" - - usage = """projects_serviceAccounts_keys_create """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsKeysCreate, self).__init__(name, fv) - flags.DEFINE_string( - 'createServiceAccountKeyRequest', - None, - u'A CreateServiceAccountKeyRequest resource to be passed as the ' - u'request body.', - flag_values=fv) - - def RunWithArgs(self, name): - """Creates a ServiceAccountKey and returns it. - - Args: - name: The resource name of the service account in the following format: - `projects/{project}/serviceAccounts/{account}`. Using `-` as a - wildcard for the project will infer the project from the account. The - `account` value can be the `email` address or the `unique_id` of the - service account. - - Flags: - createServiceAccountKeyRequest: A CreateServiceAccountKeyRequest - resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsKeysCreateRequest( - name=name.decode('utf8'), - ) - if FLAGS['createServiceAccountKeyRequest'].present: - request.createServiceAccountKeyRequest = apitools_base.JsonToMessage(messages.CreateServiceAccountKeyRequest, FLAGS.createServiceAccountKeyRequest) - result = client.projects_serviceAccounts_keys.Create( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsKeysDelete(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts_keys.Delete.""" - - usage = """projects_serviceAccounts_keys_delete """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsKeysDelete, self).__init__(name, fv) - - def RunWithArgs(self, name): - """Deletes a ServiceAccountKey. - - Args: - name: The resource name of the service account key in the following - format: `projects/{project}/serviceAccounts/{account}/keys/{key}`. - Using `-` as a wildcard for the project will infer the project from - the account. The `account` value can be the `email` address or the - `unique_id` of the service account. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsKeysDeleteRequest( - name=name.decode('utf8'), - ) - result = client.projects_serviceAccounts_keys.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsKeysGet(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts_keys.Get.""" - - usage = """projects_serviceAccounts_keys_get """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsKeysGet, self).__init__(name, fv) - flags.DEFINE_enum( - 'publicKeyType', - u'TYPE_NONE', - [u'TYPE_NONE', u'TYPE_X509_PEM_FILE', u'TYPE_RAW_PUBLIC_KEY'], - u'The output format of the public key requested. X509_PEM is the ' - u'default output format.', - flag_values=fv) - - def RunWithArgs(self, name): - """Gets the ServiceAccountKey by key id. - - Args: - name: The resource name of the service account key in the following - format: `projects/{project}/serviceAccounts/{account}/keys/{key}`. - Using `-` as a wildcard for the project will infer the project from - the account. The `account` value can be the `email` address or the - `unique_id` of the service account. - - Flags: - publicKeyType: The output format of the public key requested. X509_PEM - is the default output format. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsKeysGetRequest( - name=name.decode('utf8'), - ) - if FLAGS['publicKeyType'].present: - request.publicKeyType = messages.IamProjectsServiceAccountsKeysGetRequest.PublicKeyTypeValueValuesEnum(FLAGS.publicKeyType) - result = client.projects_serviceAccounts_keys.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ProjectsServiceAccountsKeysList(apitools_base_cli.NewCmd): - """Command wrapping projects_serviceAccounts_keys.List.""" - - usage = """projects_serviceAccounts_keys_list """ - - def __init__(self, name, fv): - super(ProjectsServiceAccountsKeysList, self).__init__(name, fv) - flags.DEFINE_enum( - 'keyTypes', - u'KEY_TYPE_UNSPECIFIED', - [u'KEY_TYPE_UNSPECIFIED', u'USER_MANAGED', u'SYSTEM_MANAGED'], - u'Filters the types of keys the user wants to include in the list ' - u'response. Duplicate key types are not allowed. If no key type is ' - u'provided, all keys are returned.', - flag_values=fv) - - def RunWithArgs(self, name): - """Lists ServiceAccountKeys. - - Args: - name: The resource name of the service account in the following format: - `projects/{project}/serviceAccounts/{account}`. Using `-` as a - wildcard for the project, will infer the project from the account. The - `account` value can be the `email` address or the `unique_id` of the - service account. - - Flags: - keyTypes: Filters the types of keys the user wants to include in the - list response. Duplicate key types are not allowed. If no key type is - provided, all keys are returned. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.IamProjectsServiceAccountsKeysListRequest( - name=name.decode('utf8'), - ) - if FLAGS['keyTypes'].present: - request.keyTypes = [messages.IamProjectsServiceAccountsKeysListRequest.KeyTypesValueValuesEnum(x) for x in FLAGS.keyTypes] - result = client.projects_serviceAccounts_keys.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class RolesQueryGrantableRoles(apitools_base_cli.NewCmd): - """Command wrapping roles.QueryGrantableRoles.""" - - usage = """roles_queryGrantableRoles""" - - def __init__(self, name, fv): - super(RolesQueryGrantableRoles, self).__init__(name, fv) - flags.DEFINE_string( - 'fullResourceName', - None, - u'Required. The full resource name to query from the list of ' - u'grantable roles. The name follows the Google Cloud Platform ' - u'resource format. For example, a Cloud Platform project with id `my-' - u'project` will be named ' - u'`//cloudresourcemanager.googleapis.com/projects/my-project`.', - flag_values=fv) - - def RunWithArgs(self): - """Queries roles that can be granted on a particular resource. - - Flags: - fullResourceName: Required. The full resource name to query from the - list of grantable roles. The name follows the Google Cloud Platform - resource format. For example, a Cloud Platform project with id `my- - project` will be named `//cloudresourcemanager.googleapis.com/projects - /my-project`. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.QueryGrantableRolesRequest( - ) - if FLAGS['fullResourceName'].present: - request.fullResourceName = FLAGS.fullResourceName.decode('utf8') - result = client.roles.QueryGrantableRoles( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -def main(_): - appcommands.AddCmd('pyshell', PyShell) - appcommands.AddCmd('iamPolicies_getPolicyDetails', IamPoliciesGetPolicyDetails) - appcommands.AddCmd('projects_serviceAccounts_create', ProjectsServiceAccountsCreate) - appcommands.AddCmd('projects_serviceAccounts_delete', ProjectsServiceAccountsDelete) - appcommands.AddCmd('projects_serviceAccounts_get', ProjectsServiceAccountsGet) - appcommands.AddCmd('projects_serviceAccounts_getIamPolicy', ProjectsServiceAccountsGetIamPolicy) - appcommands.AddCmd('projects_serviceAccounts_list', ProjectsServiceAccountsList) - appcommands.AddCmd('projects_serviceAccounts_setIamPolicy', ProjectsServiceAccountsSetIamPolicy) - appcommands.AddCmd('projects_serviceAccounts_signBlob', ProjectsServiceAccountsSignBlob) - appcommands.AddCmd('projects_serviceAccounts_signJwt', ProjectsServiceAccountsSignJwt) - appcommands.AddCmd('projects_serviceAccounts_testIamPermissions', ProjectsServiceAccountsTestIamPermissions) - appcommands.AddCmd('projects_serviceAccounts_update', ProjectsServiceAccountsUpdate) - appcommands.AddCmd('projects_serviceAccounts_keys_create', ProjectsServiceAccountsKeysCreate) - appcommands.AddCmd('projects_serviceAccounts_keys_delete', ProjectsServiceAccountsKeysDelete) - appcommands.AddCmd('projects_serviceAccounts_keys_get', ProjectsServiceAccountsKeysGet) - appcommands.AddCmd('projects_serviceAccounts_keys_list', ProjectsServiceAccountsKeysList) - appcommands.AddCmd('roles_queryGrantableRoles', RolesQueryGrantableRoles) - - apitools_base_cli.SetupLogger() - if hasattr(appcommands, 'SetDefaultCommand'): - appcommands.SetDefaultCommand('pyshell') - - -run_main = apitools_base_cli.run_main - -if __name__ == '__main__': - appcommands.Run() diff --git a/samples/servicemanagement_sample/servicemanagement_v1/servicemanagement_v1.py b/samples/servicemanagement_sample/servicemanagement_v1/servicemanagement_v1.py deleted file mode 100644 index d1a4ab82..00000000 --- a/samples/servicemanagement_sample/servicemanagement_v1/servicemanagement_v1.py +++ /dev/null @@ -1,1520 +0,0 @@ -#!/usr/bin/env python -"""CLI for servicemanagement, version v1.""" -# NOTE: This file is autogenerated and should not be edited by hand. - -import code -import os -import platform -import sys - -from apitools.base.protorpclite import message_types -from apitools.base.protorpclite import messages - -from google.apputils import appcommands -import gflags as flags - -import apitools.base.py as apitools_base -from apitools.base.py import cli as apitools_base_cli -import servicemanagement_v1_client as client_lib -import servicemanagement_v1_messages as messages - - -def _DeclareServicemanagementFlags(): - """Declare global flags in an idempotent way.""" - if 'api_endpoint' in flags.FLAGS: - return - flags.DEFINE_string( - 'api_endpoint', - u'https://servicemanagement.googleapis.com/', - 'URL of the API endpoint to use.', - short_name='servicemanagement_url') - flags.DEFINE_string( - 'history_file', - u'~/.servicemanagement.v1.history', - 'File with interactive shell history.') - flags.DEFINE_multistring( - 'add_header', [], - 'Additional http headers (as key=value strings). ' - 'Can be specified multiple times.') - flags.DEFINE_string( - 'service_account_json_keyfile', '', - 'Filename for a JSON service account key downloaded' - ' from the Developer Console.') - flags.DEFINE_enum( - 'f__xgafv', - u'_1', - [u'_1', u'_2'], - u'V1 error format.') - flags.DEFINE_string( - 'access_token', - None, - u'OAuth access token.') - flags.DEFINE_enum( - 'alt', - u'json', - [u'json', u'media', u'proto'], - u'Data format for response.') - flags.DEFINE_string( - 'bearer_token', - None, - u'OAuth bearer token.') - flags.DEFINE_string( - 'callback', - None, - u'JSONP') - flags.DEFINE_string( - 'fields', - None, - u'Selector specifying which fields to include in a partial response.') - flags.DEFINE_string( - 'key', - None, - u'API key. Your API key identifies your project and provides you with ' - u'API access, quota, and reports. Required unless you provide an OAuth ' - u'2.0 token.') - flags.DEFINE_string( - 'oauth_token', - None, - u'OAuth 2.0 token for the current user.') - flags.DEFINE_boolean( - 'pp', - 'True', - u'Pretty-print response.') - flags.DEFINE_boolean( - 'prettyPrint', - 'True', - u'Returns response with indentations and line breaks.') - flags.DEFINE_string( - 'quotaUser', - None, - u'Available to use for quota purposes for server-side applications. Can' - u' be any arbitrary string assigned to a user, but should not exceed 40' - u' characters.') - flags.DEFINE_string( - 'trace', - None, - 'A tracing token of the form "token:" to include in api ' - 'requests.') - flags.DEFINE_string( - 'uploadType', - None, - u'Legacy upload protocol for media (e.g. "media", "multipart").') - flags.DEFINE_string( - 'upload_protocol', - None, - u'Upload protocol for media (e.g. "raw", "multipart").') - - -FLAGS = flags.FLAGS -apitools_base_cli.DeclareBaseFlags() -_DeclareServicemanagementFlags() - - -def GetGlobalParamsFromFlags(): - """Return a StandardQueryParameters based on flags.""" - result = messages.StandardQueryParameters() - if FLAGS['f__xgafv'].present: - result.f__xgafv = messages.StandardQueryParameters.FXgafvValueValuesEnum(FLAGS.f__xgafv) - if FLAGS['access_token'].present: - result.access_token = FLAGS.access_token.decode('utf8') - if FLAGS['alt'].present: - result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt) - if FLAGS['bearer_token'].present: - result.bearer_token = FLAGS.bearer_token.decode('utf8') - if FLAGS['callback'].present: - result.callback = FLAGS.callback.decode('utf8') - if FLAGS['fields'].present: - result.fields = FLAGS.fields.decode('utf8') - if FLAGS['key'].present: - result.key = FLAGS.key.decode('utf8') - if FLAGS['oauth_token'].present: - result.oauth_token = FLAGS.oauth_token.decode('utf8') - if FLAGS['pp'].present: - result.pp = FLAGS.pp - if FLAGS['prettyPrint'].present: - result.prettyPrint = FLAGS.prettyPrint - if FLAGS['quotaUser'].present: - result.quotaUser = FLAGS.quotaUser.decode('utf8') - if FLAGS['trace'].present: - result.trace = FLAGS.trace.decode('utf8') - if FLAGS['uploadType'].present: - result.uploadType = FLAGS.uploadType.decode('utf8') - if FLAGS['upload_protocol'].present: - result.upload_protocol = FLAGS.upload_protocol.decode('utf8') - return result - - -def GetClientFromFlags(): - """Return a client object, configured from flags.""" - log_request = FLAGS.log_request or FLAGS.log_request_response - log_response = FLAGS.log_response or FLAGS.log_request_response - api_endpoint = apitools_base.NormalizeApiEndpoint(FLAGS.api_endpoint) - additional_http_headers = dict(x.split('=', 1) for x in FLAGS.add_header) - credentials_args = { - 'service_account_json_keyfile': os.path.expanduser(FLAGS.service_account_json_keyfile) - } - try: - client = client_lib.ServicemanagementV1( - api_endpoint, log_request=log_request, - log_response=log_response, - credentials_args=credentials_args, - additional_http_headers=additional_http_headers) - except apitools_base.CredentialsError as e: - print 'Error creating credentials: %s' % e - sys.exit(1) - return client - - -class PyShell(appcommands.Cmd): - - def Run(self, _): - """Run an interactive python shell with the client.""" - client = GetClientFromFlags() - params = GetGlobalParamsFromFlags() - for field in params.all_fields(): - value = params.get_assigned_value(field.name) - if value != field.default: - client.AddGlobalParam(field.name, value) - banner = """ - == servicemanagement interactive console == - client: a servicemanagement client - apitools_base: base apitools module - messages: the generated messages module - """ - local_vars = { - 'apitools_base': apitools_base, - 'client': client, - 'client_lib': client_lib, - 'messages': messages, - } - if platform.system() == 'Linux': - console = apitools_base_cli.ConsoleWithReadline( - local_vars, histfile=FLAGS.history_file) - else: - console = code.InteractiveConsole(local_vars) - try: - console.interact(banner) - except SystemExit as e: - return e.code - - -class OperationsGet(apitools_base_cli.NewCmd): - """Command wrapping operations.Get.""" - - usage = """operations_get """ - - def __init__(self, name, fv): - super(OperationsGet, self).__init__(name, fv) - - def RunWithArgs(self, operationsId): - """Gets the latest state of a long-running operation. Clients can use - this method to poll the operation result at intervals as recommended by - the API service. - - Args: - operationsId: Part of `name`. The name of the operation resource. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementOperationsGetRequest( - operationsId=operationsId.decode('utf8'), - ) - result = client.operations.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesConvertConfig(apitools_base_cli.NewCmd): - """Command wrapping services.ConvertConfig.""" - - usage = """services_convertConfig""" - - def __init__(self, name, fv): - super(ServicesConvertConfig, self).__init__(name, fv) - flags.DEFINE_string( - 'configSpec', - None, - u'Input configuration For this version of API, the supported type is ' - u'OpenApiSpec', - flag_values=fv) - flags.DEFINE_string( - 'openApiSpec', - None, - u'The OpenAPI specification for an API.', - flag_values=fv) - flags.DEFINE_string( - 'serviceName', - None, - u'The service name to use for constructing the normalized service ' - u'configuration equivalent of the provided configuration ' - u'specification.', - flag_values=fv) - flags.DEFINE_string( - 'swaggerSpec', - None, - u'The swagger specification for an API.', - flag_values=fv) - - def RunWithArgs(self): - """DEPRECATED. `SubmitConfigSource` with `validate_only=true` will provide - config conversion moving forward. Converts an API specification (e.g. - Swagger spec) to an equivalent `google.api.Service`. - - Flags: - configSpec: Input configuration For this version of API, the supported - type is OpenApiSpec - openApiSpec: The OpenAPI specification for an API. - serviceName: The service name to use for constructing the normalized - service configuration equivalent of the provided configuration - specification. - swaggerSpec: The swagger specification for an API. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ConvertConfigRequest( - ) - if FLAGS['configSpec'].present: - request.configSpec = apitools_base.JsonToMessage(messages.ConvertConfigRequest.ConfigSpecValue, FLAGS.configSpec) - if FLAGS['openApiSpec'].present: - request.openApiSpec = apitools_base.JsonToMessage(messages.OpenApiSpec, FLAGS.openApiSpec) - if FLAGS['serviceName'].present: - request.serviceName = FLAGS.serviceName.decode('utf8') - if FLAGS['swaggerSpec'].present: - request.swaggerSpec = apitools_base.JsonToMessage(messages.SwaggerSpec, FLAGS.swaggerSpec) - result = client.services.ConvertConfig( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesCreate(apitools_base_cli.NewCmd): - """Command wrapping services.Create.""" - - usage = """services_create""" - - def __init__(self, name, fv): - super(ServicesCreate, self).__init__(name, fv) - flags.DEFINE_string( - 'configSource', - None, - u'User-supplied source configuration for the service. This is ' - u'distinct from the generated configuration provided in ' - u'`google.api.Service`. This is NOT populated on GetService calls at ' - u'the moment. NOTE: Any upsert operation that contains both a ' - u'service_config and a config_source is considered invalid and will ' - u'result in an error being returned.', - flag_values=fv) - flags.DEFINE_string( - 'generation', - None, - u'A server-assigned monotonically increasing number that changes ' - u'whenever a mutation is made to the `ManagedService` or any of its ' - u'components via the `ServiceManager` API.', - flag_values=fv) - flags.DEFINE_string( - 'operations', - None, - u'Read-only view of pending operations affecting this resource, if ' - u'requested.', - flag_values=fv) - flags.DEFINE_string( - 'producerProjectId', - None, - u'ID of the project that produces and owns this service.', - flag_values=fv) - flags.DEFINE_string( - 'projectSettings', - None, - u'Read-only view of settings for a particular consumer project, if ' - u'requested.', - flag_values=fv) - flags.DEFINE_string( - 'serviceConfig', - None, - u"The service's generated configuration.", - flag_values=fv) - flags.DEFINE_string( - 'serviceName', - None, - u'The name of the service. See the `ServiceManager` overview for ' - u'naming requirements. This name must match ' - u'`google.api.Service.name` in the `service_config` field.', - flag_values=fv) - - def RunWithArgs(self): - """Creates a new managed service. Operation - - Flags: - configSource: User-supplied source configuration for the service. This - is distinct from the generated configuration provided in - `google.api.Service`. This is NOT populated on GetService calls at the - moment. NOTE: Any upsert operation that contains both a service_config - and a config_source is considered invalid and will result in an error - being returned. - generation: A server-assigned monotonically increasing number that - changes whenever a mutation is made to the `ManagedService` or any of - its components via the `ServiceManager` API. - operations: Read-only view of pending operations affecting this - resource, if requested. - producerProjectId: ID of the project that produces and owns this - service. - projectSettings: Read-only view of settings for a particular consumer - project, if requested. - serviceConfig: The service's generated configuration. - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. This name must match - `google.api.Service.name` in the `service_config` field. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ManagedService( - ) - if FLAGS['configSource'].present: - request.configSource = apitools_base.JsonToMessage(messages.ConfigSource, FLAGS.configSource) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['operations'].present: - request.operations = [apitools_base.JsonToMessage(messages.Operation, x) for x in FLAGS.operations] - if FLAGS['producerProjectId'].present: - request.producerProjectId = FLAGS.producerProjectId.decode('utf8') - if FLAGS['projectSettings'].present: - request.projectSettings = apitools_base.JsonToMessage(messages.ProjectSettings, FLAGS.projectSettings) - if FLAGS['serviceConfig'].present: - request.serviceConfig = apitools_base.JsonToMessage(messages.Service, FLAGS.serviceConfig) - if FLAGS['serviceName'].present: - request.serviceName = FLAGS.serviceName.decode('utf8') - result = client.services.Create( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesDelete(apitools_base_cli.NewCmd): - """Command wrapping services.Delete.""" - - usage = """services_delete """ - - def __init__(self, name, fv): - super(ServicesDelete, self).__init__(name, fv) - - def RunWithArgs(self, serviceName): - """Deletes a managed service. Operation - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesDeleteRequest( - serviceName=serviceName.decode('utf8'), - ) - result = client.services.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesDisable(apitools_base_cli.NewCmd): - """Command wrapping services.Disable.""" - - usage = """services_disable """ - - def __init__(self, name, fv): - super(ServicesDisable, self).__init__(name, fv) - flags.DEFINE_string( - 'disableServiceRequest', - None, - u'A DisableServiceRequest resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Disable a managed service for a project. Google Service Management will - only disable the managed service even if there are other services depend - on the managed service. Operation - - Args: - serviceName: Name of the service to disable. Specifying an unknown - service name will cause the request to fail. - - Flags: - disableServiceRequest: A DisableServiceRequest resource to be passed as - the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesDisableRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['disableServiceRequest'].present: - request.disableServiceRequest = apitools_base.JsonToMessage(messages.DisableServiceRequest, FLAGS.disableServiceRequest) - result = client.services.Disable( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesEnable(apitools_base_cli.NewCmd): - """Command wrapping services.Enable.""" - - usage = """services_enable """ - - def __init__(self, name, fv): - super(ServicesEnable, self).__init__(name, fv) - flags.DEFINE_string( - 'enableServiceRequest', - None, - u'A EnableServiceRequest resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Enable a managed service for a project with default setting. If the - managed service has dependencies, they will be enabled as well. - Operation - - Args: - serviceName: Name of the service to enable. Specifying an unknown - service name will cause the request to fail. - - Flags: - enableServiceRequest: A EnableServiceRequest resource to be passed as - the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesEnableRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['enableServiceRequest'].present: - request.enableServiceRequest = apitools_base.JsonToMessage(messages.EnableServiceRequest, FLAGS.enableServiceRequest) - result = client.services.Enable( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesGet(apitools_base_cli.NewCmd): - """Command wrapping services.Get.""" - - usage = """services_get """ - - def __init__(self, name, fv): - super(ServicesGet, self).__init__(name, fv) - flags.DEFINE_string( - 'consumerProjectId', - None, - u'If project_settings is expanded, return settings for the specified ' - u'consumer project.', - flag_values=fv) - flags.DEFINE_string( - 'expand', - None, - u'Fields to expand in any results. By default, the following fields ' - u'are not present in the result: - `operations` - `project_settings` ' - u'- `project_settings.operations` - `quota_usage` (It requires ' - u'`project_settings`) - `historical_quota_usage` (It requires ' - u'`project_settings`)', - flag_values=fv) - flags.DEFINE_enum( - 'view', - u'PROJECT_SETTINGS_VIEW_UNSPECIFIED', - [u'PROJECT_SETTINGS_VIEW_UNSPECIFIED', u'CONSUMER_VIEW', u'PRODUCER_VIEW', u'ALL'], - u'If project_settings is expanded, request only fields for the ' - u'specified view.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Gets a managed service. If the `consumer_project_id` is specified, the - project's settings for the specified service are also returned. - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - - Flags: - consumerProjectId: If project_settings is expanded, return settings for - the specified consumer project. - expand: Fields to expand in any results. By default, the following - fields are not present in the result: - `operations` - - `project_settings` - `project_settings.operations` - `quota_usage` (It - requires `project_settings`) - `historical_quota_usage` (It requires - `project_settings`) - view: If project_settings is expanded, request only fields for the - specified view. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesGetRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['consumerProjectId'].present: - request.consumerProjectId = FLAGS.consumerProjectId.decode('utf8') - if FLAGS['expand'].present: - request.expand = FLAGS.expand.decode('utf8') - if FLAGS['view'].present: - request.view = messages.ServicemanagementServicesGetRequest.ViewValueValuesEnum(FLAGS.view) - result = client.services.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesGetAccessPolicy(apitools_base_cli.NewCmd): - """Command wrapping services.GetAccessPolicy.""" - - usage = """services_getAccessPolicy """ - - def __init__(self, name, fv): - super(ServicesGetAccessPolicy, self).__init__(name, fv) - - def RunWithArgs(self, serviceName): - """Producer method to retrieve current policy. - - Args: - serviceName: The name of the service. For example: - `example.googleapis.com`. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesGetAccessPolicyRequest( - serviceName=serviceName.decode('utf8'), - ) - result = client.services.GetAccessPolicy( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesGetConfig(apitools_base_cli.NewCmd): - """Command wrapping services.GetConfig.""" - - usage = """services_getConfig """ - - def __init__(self, name, fv): - super(ServicesGetConfig, self).__init__(name, fv) - flags.DEFINE_string( - 'configId', - None, - u'The id of the service config resource. Optional. If it is not ' - u'specified, the latest version of config will be returned.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Gets a service config (version) for a managed service. If `config_id` - is not specified, the latest service config will be returned. - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - - Flags: - configId: The id of the service config resource. Optional. If it is not - specified, the latest version of config will be returned. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesGetConfigRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['configId'].present: - request.configId = FLAGS.configId.decode('utf8') - result = client.services.GetConfig( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesList(apitools_base_cli.NewCmd): - """Command wrapping services.List.""" - - usage = """services_list""" - - def __init__(self, name, fv): - super(ServicesList, self).__init__(name, fv) - flags.DEFINE_string( - 'category', - None, - u'Include services only in the specified category. Supported ' - u'categories are servicemanagement.googleapis.com/categories/google-' - u'services or servicemanagement.googleapis.com/categories/play-games.', - flag_values=fv) - flags.DEFINE_string( - 'consumerProjectId', - None, - u'Include services consumed by the specified project. If ' - u'project_settings is expanded, then this field controls which ' - u'project project_settings is populated for.', - flag_values=fv) - flags.DEFINE_string( - 'expand', - None, - u'Fields to expand in any results. By default, the following fields ' - u'are not fully included in list results: - `operations` - ' - u'`project_settings` - `project_settings.operations` - `quota_usage` ' - u'(It requires `project_settings`)', - flag_values=fv) - flags.DEFINE_integer( - 'pageSize', - None, - u'Requested size of the next page of data.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'Token identifying which result to start with; returned by a ' - u'previous list call.', - flag_values=fv) - flags.DEFINE_string( - 'producerProjectId', - None, - u'Include services produced by the specified project.', - flag_values=fv) - - def RunWithArgs(self): - """Lists all managed services. If the `consumer_project_id` is specified, - the project's settings for the specified service are also returned. - - Flags: - category: Include services only in the specified category. Supported - categories are servicemanagement.googleapis.com/categories/google- - services or servicemanagement.googleapis.com/categories/play-games. - consumerProjectId: Include services consumed by the specified project. - If project_settings is expanded, then this field controls which - project project_settings is populated for. - expand: Fields to expand in any results. By default, the following - fields are not fully included in list results: - `operations` - - `project_settings` - `project_settings.operations` - `quota_usage` (It - requires `project_settings`) - pageSize: Requested size of the next page of data. - pageToken: Token identifying which result to start with; returned by a - previous list call. - producerProjectId: Include services produced by the specified project. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesListRequest( - ) - if FLAGS['category'].present: - request.category = FLAGS.category.decode('utf8') - if FLAGS['consumerProjectId'].present: - request.consumerProjectId = FLAGS.consumerProjectId.decode('utf8') - if FLAGS['expand'].present: - request.expand = FLAGS.expand.decode('utf8') - if FLAGS['pageSize'].present: - request.pageSize = FLAGS.pageSize - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['producerProjectId'].present: - request.producerProjectId = FLAGS.producerProjectId.decode('utf8') - result = client.services.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesPatch(apitools_base_cli.NewCmd): - """Command wrapping services.Patch.""" - - usage = """services_patch """ - - def __init__(self, name, fv): - super(ServicesPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'managedService', - None, - u'A ManagedService resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'updateMask', - None, - u'A mask specifying which fields to update.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Updates the specified subset of the configuration. If the specified - service does not exists the patch operation fails. Operation - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - - Flags: - managedService: A ManagedService resource to be passed as the request - body. - updateMask: A mask specifying which fields to update. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesPatchRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['managedService'].present: - request.managedService = apitools_base.JsonToMessage(messages.ManagedService, FLAGS.managedService) - if FLAGS['updateMask'].present: - request.updateMask = FLAGS.updateMask.decode('utf8') - result = client.services.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesPatchConfig(apitools_base_cli.NewCmd): - """Command wrapping services.PatchConfig.""" - - usage = """services_patchConfig """ - - def __init__(self, name, fv): - super(ServicesPatchConfig, self).__init__(name, fv) - flags.DEFINE_string( - 'service', - None, - u'A Service resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'updateMask', - None, - u'A mask specifying which fields to update.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Updates the specified subset of the service resource. Equivalent to - calling `PatchService` with only the `service_config` field updated. - Operation - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - - Flags: - service: A Service resource to be passed as the request body. - updateMask: A mask specifying which fields to update. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesPatchConfigRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['service'].present: - request.service = apitools_base.JsonToMessage(messages.Service, FLAGS.service) - if FLAGS['updateMask'].present: - request.updateMask = FLAGS.updateMask.decode('utf8') - result = client.services.PatchConfig( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesUpdate(apitools_base_cli.NewCmd): - """Command wrapping services.Update.""" - - usage = """services_update """ - - def __init__(self, name, fv): - super(ServicesUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'managedService', - None, - u'A ManagedService resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'updateMask', - None, - u'A mask specifying which fields to update. Update mask has been ' - u'deprecated on UpdateService service method. Please use PatchService' - u' method instead to do partial updates.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Updates the configuration of a service. If the specified service does - not already exist, then it is created. Operation - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - - Flags: - managedService: A ManagedService resource to be passed as the request - body. - updateMask: A mask specifying which fields to update. Update mask has - been deprecated on UpdateService service method. Please use - PatchService method instead to do partial updates. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesUpdateRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['managedService'].present: - request.managedService = apitools_base.JsonToMessage(messages.ManagedService, FLAGS.managedService) - if FLAGS['updateMask'].present: - request.updateMask = FLAGS.updateMask.decode('utf8') - result = client.services.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesUpdateAccessPolicy(apitools_base_cli.NewCmd): - """Command wrapping services.UpdateAccessPolicy.""" - - usage = """services_updateAccessPolicy """ - - def __init__(self, name, fv): - super(ServicesUpdateAccessPolicy, self).__init__(name, fv) - flags.DEFINE_string( - 'accessList', - None, - u'ACL for access to the unrestricted surface of the service.', - flag_values=fv) - flags.DEFINE_string( - 'visibilityLabelAccessLists', - None, - u'ACLs for access to restricted parts of the service. The map key is' - u' the visibility label that is being controlled. Note that access ' - u'to any label also implies access to the unrestricted surface.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Producer method to update the current policy. This method will return - an error if the policy is too large (more than 50 entries across all - lists). - - Args: - serviceName: The service protected by this policy. - - Flags: - accessList: ACL for access to the unrestricted surface of the service. - visibilityLabelAccessLists: ACLs for access to restricted parts of the - service. The map key is the visibility label that is being - controlled. Note that access to any label also implies access to the - unrestricted surface. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServiceAccessPolicy( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['accessList'].present: - request.accessList = apitools_base.JsonToMessage(messages.ServiceAccessList, FLAGS.accessList) - if FLAGS['visibilityLabelAccessLists'].present: - request.visibilityLabelAccessLists = apitools_base.JsonToMessage(messages.ServiceAccessPolicy.VisibilityLabelAccessListsValue, FLAGS.visibilityLabelAccessLists) - result = client.services.UpdateAccessPolicy( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesUpdateConfig(apitools_base_cli.NewCmd): - """Command wrapping services.UpdateConfig.""" - - usage = """services_updateConfig """ - - def __init__(self, name, fv): - super(ServicesUpdateConfig, self).__init__(name, fv) - flags.DEFINE_string( - 'service', - None, - u'A Service resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'updateMask', - None, - u'A mask specifying which fields to update. Update mask has been ' - u'deprecated on UpdateServiceConfig service method. Please use ' - u'PatchServiceConfig method instead to do partial updates.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Updates the specified subset of the service resource. Equivalent to - calling `UpdateService` with only the `service_config` field updated. - Operation - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - - Flags: - service: A Service resource to be passed as the request body. - updateMask: A mask specifying which fields to update. Update mask has - been deprecated on UpdateServiceConfig service method. Please use - PatchServiceConfig method instead to do partial updates. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesUpdateConfigRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['service'].present: - request.service = apitools_base.JsonToMessage(messages.Service, FLAGS.service) - if FLAGS['updateMask'].present: - request.updateMask = FLAGS.updateMask.decode('utf8') - result = client.services.UpdateConfig( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesAccessPolicyQuery(apitools_base_cli.NewCmd): - """Command wrapping services_accessPolicy.Query.""" - - usage = """services_accessPolicy_query """ - - def __init__(self, name, fv): - super(ServicesAccessPolicyQuery, self).__init__(name, fv) - flags.DEFINE_string( - 'userEmail', - None, - u'The user to query access for.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Method to query the accessibility of a service and any associated - visibility labels for a specified user. Members of the producer project - may call this method and specify any user. Any user may call this method, - but must specify their own email address. In this case the method will - return NOT_FOUND if the user has no access to the service. - - Args: - serviceName: The service to query access for. - - Flags: - userEmail: The user to query access for. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesAccessPolicyQueryRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['userEmail'].present: - request.userEmail = FLAGS.userEmail.decode('utf8') - result = client.services_accessPolicy.Query( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesConfigsCreate(apitools_base_cli.NewCmd): - """Command wrapping services_configs.Create.""" - - usage = """services_configs_create """ - - def __init__(self, name, fv): - super(ServicesConfigsCreate, self).__init__(name, fv) - flags.DEFINE_string( - 'service', - None, - u'A Service resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Creates a new service config (version) for a managed service. This - method only stores the service config, but does not apply the service - config to any backend services. - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - - Flags: - service: A Service resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesConfigsCreateRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['service'].present: - request.service = apitools_base.JsonToMessage(messages.Service, FLAGS.service) - result = client.services_configs.Create( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesConfigsGet(apitools_base_cli.NewCmd): - """Command wrapping services_configs.Get.""" - - usage = """services_configs_get """ - - def __init__(self, name, fv): - super(ServicesConfigsGet, self).__init__(name, fv) - - def RunWithArgs(self, serviceName, configId): - """Gets a service config (version) for a managed service. If `config_id` - is not specified, the latest service config will be returned. - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - configId: The id of the service config resource. Optional. If it is not - specified, the latest version of config will be returned. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesConfigsGetRequest( - serviceName=serviceName.decode('utf8'), - configId=configId.decode('utf8'), - ) - result = client.services_configs.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesConfigsList(apitools_base_cli.NewCmd): - """Command wrapping services_configs.List.""" - - usage = """services_configs_list """ - - def __init__(self, name, fv): - super(ServicesConfigsList, self).__init__(name, fv) - flags.DEFINE_integer( - 'pageSize', - None, - u'The max number of items to include in the response list.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'The token of the page to retrieve.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Lists the history of the service config for a managed service, from the - newest to the oldest. - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - - Flags: - pageSize: The max number of items to include in the response list. - pageToken: The token of the page to retrieve. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesConfigsListRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['pageSize'].present: - request.pageSize = FLAGS.pageSize - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - result = client.services_configs.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesConfigsSubmit(apitools_base_cli.NewCmd): - """Command wrapping services_configs.Submit.""" - - usage = """services_configs_submit """ - - def __init__(self, name, fv): - super(ServicesConfigsSubmit, self).__init__(name, fv) - flags.DEFINE_string( - 'submitConfigSourceRequest', - None, - u'A SubmitConfigSourceRequest resource to be passed as the request ' - u'body.', - flag_values=fv) - - def RunWithArgs(self, serviceName): - """Creates a new service config (version) for a managed service based on - user-supplied configuration sources files (for example: OpenAPI - Specification). This method stores the source configurations as well as - the generated service config. It does NOT apply the service config to any - backend services. Operation - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - - Flags: - submitConfigSourceRequest: A SubmitConfigSourceRequest resource to be - passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesConfigsSubmitRequest( - serviceName=serviceName.decode('utf8'), - ) - if FLAGS['submitConfigSourceRequest'].present: - request.submitConfigSourceRequest = apitools_base.JsonToMessage(messages.SubmitConfigSourceRequest, FLAGS.submitConfigSourceRequest) - result = client.services_configs.Submit( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesCustomerSettingsGet(apitools_base_cli.NewCmd): - """Command wrapping services_customerSettings.Get.""" - - usage = """services_customerSettings_get """ - - def __init__(self, name, fv): - super(ServicesCustomerSettingsGet, self).__init__(name, fv) - flags.DEFINE_string( - 'expand', - None, - u'Fields to expand in any results.', - flag_values=fv) - flags.DEFINE_enum( - 'view', - u'PROJECT_SETTINGS_VIEW_UNSPECIFIED', - [u'PROJECT_SETTINGS_VIEW_UNSPECIFIED', u'CONSUMER_VIEW', u'PRODUCER_VIEW', u'ALL'], - u'Request only fields for the specified view.', - flag_values=fv) - - def RunWithArgs(self, serviceName, customerId): - """Retrieves the settings that control the specified customer's usage of - the service. - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. This - field is required. - customerId: ID for the customer. See the comment for - `CustomerSettings.customer_id` field of message for its format. This - field is required. - - Flags: - expand: Fields to expand in any results. - view: Request only fields for the specified view. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesCustomerSettingsGetRequest( - serviceName=serviceName.decode('utf8'), - customerId=customerId.decode('utf8'), - ) - if FLAGS['expand'].present: - request.expand = FLAGS.expand.decode('utf8') - if FLAGS['view'].present: - request.view = messages.ServicemanagementServicesCustomerSettingsGetRequest.ViewValueValuesEnum(FLAGS.view) - result = client.services_customerSettings.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesCustomerSettingsPatch(apitools_base_cli.NewCmd): - """Command wrapping services_customerSettings.Patch.""" - - usage = """services_customerSettings_patch """ - - def __init__(self, name, fv): - super(ServicesCustomerSettingsPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'customerSettings', - None, - u'A CustomerSettings resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'updateMask', - None, - u'The field mask specifying which fields are to be updated.', - flag_values=fv) - - def RunWithArgs(self, serviceName, customerId): - """Updates specified subset of the settings that control the specified - customer's usage of the service. Attempts to update a field not - controlled by the caller will result in an access denied error. - Operation - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. This - field is required. - customerId: ID for the customer. See the comment for - `CustomerSettings.customer_id` field of message for its format. This - field is required. - - Flags: - customerSettings: A CustomerSettings resource to be passed as the - request body. - updateMask: The field mask specifying which fields are to be updated. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesCustomerSettingsPatchRequest( - serviceName=serviceName.decode('utf8'), - customerId=customerId.decode('utf8'), - ) - if FLAGS['customerSettings'].present: - request.customerSettings = apitools_base.JsonToMessage(messages.CustomerSettings, FLAGS.customerSettings) - if FLAGS['updateMask'].present: - request.updateMask = FLAGS.updateMask.decode('utf8') - result = client.services_customerSettings.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesProjectSettingsGet(apitools_base_cli.NewCmd): - """Command wrapping services_projectSettings.Get.""" - - usage = """services_projectSettings_get """ - - def __init__(self, name, fv): - super(ServicesProjectSettingsGet, self).__init__(name, fv) - flags.DEFINE_string( - 'expand', - None, - u'Fields to expand in any results. By default, the following fields ' - u'are not present in the result: - `operations` - `quota_usage`', - flag_values=fv) - flags.DEFINE_enum( - 'view', - u'PROJECT_SETTINGS_VIEW_UNSPECIFIED', - [u'PROJECT_SETTINGS_VIEW_UNSPECIFIED', u'CONSUMER_VIEW', u'PRODUCER_VIEW', u'ALL'], - u'Request only the fields for the specified view.', - flag_values=fv) - - def RunWithArgs(self, serviceName, consumerProjectId): - """Retrieves the settings that control the specified consumer project's - usage of the service. - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - consumerProjectId: The project ID of the consumer. - - Flags: - expand: Fields to expand in any results. By default, the following - fields are not present in the result: - `operations` - `quota_usage` - view: Request only the fields for the specified view. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesProjectSettingsGetRequest( - serviceName=serviceName.decode('utf8'), - consumerProjectId=consumerProjectId.decode('utf8'), - ) - if FLAGS['expand'].present: - request.expand = FLAGS.expand.decode('utf8') - if FLAGS['view'].present: - request.view = messages.ServicemanagementServicesProjectSettingsGetRequest.ViewValueValuesEnum(FLAGS.view) - result = client.services_projectSettings.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesProjectSettingsPatch(apitools_base_cli.NewCmd): - """Command wrapping services_projectSettings.Patch.""" - - usage = """services_projectSettings_patch """ - - def __init__(self, name, fv): - super(ServicesProjectSettingsPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'projectSettings', - None, - u'A ProjectSettings resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'updateMask', - None, - u'The field mask specifying which fields are to be updated.', - flag_values=fv) - - def RunWithArgs(self, serviceName, consumerProjectId): - """Updates specified subset of the settings that control the specified - consumer project's usage of the service. Attempts to update a field not - controlled by the caller will result in an access denied error. - Operation - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. For example: `example.googleapis.com`. - consumerProjectId: The project ID of the consumer. - - Flags: - projectSettings: A ProjectSettings resource to be passed as the request - body. - updateMask: The field mask specifying which fields are to be updated. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ServicemanagementServicesProjectSettingsPatchRequest( - serviceName=serviceName.decode('utf8'), - consumerProjectId=consumerProjectId.decode('utf8'), - ) - if FLAGS['projectSettings'].present: - request.projectSettings = apitools_base.JsonToMessage(messages.ProjectSettings, FLAGS.projectSettings) - if FLAGS['updateMask'].present: - request.updateMask = FLAGS.updateMask.decode('utf8') - result = client.services_projectSettings.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ServicesProjectSettingsUpdate(apitools_base_cli.NewCmd): - """Command wrapping services_projectSettings.Update.""" - - usage = """services_projectSettings_update """ - - def __init__(self, name, fv): - super(ServicesProjectSettingsUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'operations', - None, - u'Read-only view of pending operations affecting this resource, if ' - u'requested.', - flag_values=fv) - flags.DEFINE_string( - 'properties', - None, - u'Service-defined per-consumer properties. A key-value mapping a ' - u'string key to a google.protobuf.ListValue proto. Values in the list' - u" are typed as defined in the Service configuration's " - u'consumer.properties field.', - flag_values=fv) - flags.DEFINE_string( - 'quotaSettings', - None, - u'Settings that control how much or how fast the service can be used ' - u'by the consumer project.', - flag_values=fv) - flags.DEFINE_string( - 'usageSettings', - None, - u'Settings that control whether this service is usable by the ' - u'consumer project.', - flag_values=fv) - flags.DEFINE_string( - 'visibilitySettings', - None, - u'Settings that control which features of the service are visible to ' - u'the consumer project.', - flag_values=fv) - - def RunWithArgs(self, serviceName, consumerProjectId): - """NOTE: Currently unsupported. Use PatchProjectSettings instead. - Updates the settings that control the specified consumer project's usage - of the service. Attempts to update a field not controlled by the caller - will result in an access denied error. Operation - - Args: - serviceName: The name of the service. See the `ServiceManager` overview - for naming requirements. - consumerProjectId: ID for the project consuming this service. - - Flags: - operations: Read-only view of pending operations affecting this - resource, if requested. - properties: Service-defined per-consumer properties. A key-value - mapping a string key to a google.protobuf.ListValue proto. Values in - the list are typed as defined in the Service configuration's - consumer.properties field. - quotaSettings: Settings that control how much or how fast the service - can be used by the consumer project. - usageSettings: Settings that control whether this service is usable by - the consumer project. - visibilitySettings: Settings that control which features of the service - are visible to the consumer project. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ProjectSettings( - serviceName=serviceName.decode('utf8'), - consumerProjectId=consumerProjectId.decode('utf8'), - ) - if FLAGS['operations'].present: - request.operations = [apitools_base.JsonToMessage(messages.Operation, x) for x in FLAGS.operations] - if FLAGS['properties'].present: - request.properties = apitools_base.JsonToMessage(messages.ProjectSettings.PropertiesValue, FLAGS.properties) - if FLAGS['quotaSettings'].present: - request.quotaSettings = apitools_base.JsonToMessage(messages.QuotaSettings, FLAGS.quotaSettings) - if FLAGS['usageSettings'].present: - request.usageSettings = apitools_base.JsonToMessage(messages.UsageSettings, FLAGS.usageSettings) - if FLAGS['visibilitySettings'].present: - request.visibilitySettings = apitools_base.JsonToMessage(messages.VisibilitySettings, FLAGS.visibilitySettings) - result = client.services_projectSettings.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ConvertConfig(apitools_base_cli.NewCmd): - """Command wrapping v1.ConvertConfig.""" - - usage = """convertConfig""" - - def __init__(self, name, fv): - super(ConvertConfig, self).__init__(name, fv) - flags.DEFINE_string( - 'configSpec', - None, - u'Input configuration For this version of API, the supported type is ' - u'OpenApiSpec', - flag_values=fv) - flags.DEFINE_string( - 'openApiSpec', - None, - u'The OpenAPI specification for an API.', - flag_values=fv) - flags.DEFINE_string( - 'serviceName', - None, - u'The service name to use for constructing the normalized service ' - u'configuration equivalent of the provided configuration ' - u'specification.', - flag_values=fv) - flags.DEFINE_string( - 'swaggerSpec', - None, - u'The swagger specification for an API.', - flag_values=fv) - - def RunWithArgs(self): - """DEPRECATED. `SubmitConfigSource` with `validate_only=true` will provide - config conversion moving forward. Converts an API specification (e.g. - Swagger spec) to an equivalent `google.api.Service`. - - Flags: - configSpec: Input configuration For this version of API, the supported - type is OpenApiSpec - openApiSpec: The OpenAPI specification for an API. - serviceName: The service name to use for constructing the normalized - service configuration equivalent of the provided configuration - specification. - swaggerSpec: The swagger specification for an API. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ConvertConfigRequest( - ) - if FLAGS['configSpec'].present: - request.configSpec = apitools_base.JsonToMessage(messages.ConvertConfigRequest.ConfigSpecValue, FLAGS.configSpec) - if FLAGS['openApiSpec'].present: - request.openApiSpec = apitools_base.JsonToMessage(messages.OpenApiSpec, FLAGS.openApiSpec) - if FLAGS['serviceName'].present: - request.serviceName = FLAGS.serviceName.decode('utf8') - if FLAGS['swaggerSpec'].present: - request.swaggerSpec = apitools_base.JsonToMessage(messages.SwaggerSpec, FLAGS.swaggerSpec) - result = client.v1.ConvertConfig( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -def main(_): - appcommands.AddCmd('pyshell', PyShell) - appcommands.AddCmd('operations_get', OperationsGet) - appcommands.AddCmd('services_convertConfig', ServicesConvertConfig) - appcommands.AddCmd('services_create', ServicesCreate) - appcommands.AddCmd('services_delete', ServicesDelete) - appcommands.AddCmd('services_disable', ServicesDisable) - appcommands.AddCmd('services_enable', ServicesEnable) - appcommands.AddCmd('services_get', ServicesGet) - appcommands.AddCmd('services_getAccessPolicy', ServicesGetAccessPolicy) - appcommands.AddCmd('services_getConfig', ServicesGetConfig) - appcommands.AddCmd('services_list', ServicesList) - appcommands.AddCmd('services_patch', ServicesPatch) - appcommands.AddCmd('services_patchConfig', ServicesPatchConfig) - appcommands.AddCmd('services_update', ServicesUpdate) - appcommands.AddCmd('services_updateAccessPolicy', ServicesUpdateAccessPolicy) - appcommands.AddCmd('services_updateConfig', ServicesUpdateConfig) - appcommands.AddCmd('services_accessPolicy_query', ServicesAccessPolicyQuery) - appcommands.AddCmd('services_configs_create', ServicesConfigsCreate) - appcommands.AddCmd('services_configs_get', ServicesConfigsGet) - appcommands.AddCmd('services_configs_list', ServicesConfigsList) - appcommands.AddCmd('services_configs_submit', ServicesConfigsSubmit) - appcommands.AddCmd('services_customerSettings_get', ServicesCustomerSettingsGet) - appcommands.AddCmd('services_customerSettings_patch', ServicesCustomerSettingsPatch) - appcommands.AddCmd('services_projectSettings_get', ServicesProjectSettingsGet) - appcommands.AddCmd('services_projectSettings_patch', ServicesProjectSettingsPatch) - appcommands.AddCmd('services_projectSettings_update', ServicesProjectSettingsUpdate) - appcommands.AddCmd('convertConfig', ConvertConfig) - - apitools_base_cli.SetupLogger() - if hasattr(appcommands, 'SetDefaultCommand'): - appcommands.SetDefaultCommand('pyshell') - - -run_main = apitools_base_cli.run_main - -if __name__ == '__main__': - appcommands.Run() diff --git a/samples/storage_sample/storage_v1/storage_v1.py b/samples/storage_sample/storage_v1/storage_v1.py deleted file mode 100644 index d7cff48a..00000000 --- a/samples/storage_sample/storage_v1/storage_v1.py +++ /dev/null @@ -1,3578 +0,0 @@ -#!/usr/bin/env python -"""CLI for storage, version v1.""" -# NOTE: This file is autogenerated and should not be edited by hand. - -import code -import os -import platform -import sys - -from apitools.base.protorpclite import message_types -from apitools.base.protorpclite import messages - -from google.apputils import appcommands -import gflags as flags - -import apitools.base.py as apitools_base -from apitools.base.py import cli as apitools_base_cli -import storage_v1_client as client_lib -import storage_v1_messages as messages - - -def _DeclareStorageFlags(): - """Declare global flags in an idempotent way.""" - if 'api_endpoint' in flags.FLAGS: - return - flags.DEFINE_string( - 'api_endpoint', - u'https://www.googleapis.com/storage/v1/', - 'URL of the API endpoint to use.', - short_name='storage_url') - flags.DEFINE_string( - 'history_file', - u'~/.storage.v1.history', - 'File with interactive shell history.') - flags.DEFINE_multistring( - 'add_header', [], - 'Additional http headers (as key=value strings). ' - 'Can be specified multiple times.') - flags.DEFINE_string( - 'service_account_json_keyfile', '', - 'Filename for a JSON service account key downloaded' - ' from the Developer Console.') - flags.DEFINE_enum( - 'alt', - u'json', - [u'json'], - u'Data format for the response.') - flags.DEFINE_string( - 'fields', - None, - u'Selector specifying which fields to include in a partial response.') - flags.DEFINE_string( - 'key', - None, - u'API key. Your API key identifies your project and provides you with ' - u'API access, quota, and reports. Required unless you provide an OAuth ' - u'2.0 token.') - flags.DEFINE_string( - 'oauth_token', - None, - u'OAuth 2.0 token for the current user.') - flags.DEFINE_boolean( - 'prettyPrint', - 'True', - u'Returns response with indentations and line breaks.') - flags.DEFINE_string( - 'quotaUser', - None, - u'Available to use for quota purposes for server-side applications. Can' - u' be any arbitrary string assigned to a user, but should not exceed 40' - u' characters. Overrides userIp if both are provided.') - flags.DEFINE_string( - 'trace', - None, - 'A tracing token of the form "token:" to include in api ' - 'requests.') - flags.DEFINE_string( - 'userIp', - None, - u'IP address of the site where the request originates. Use this if you ' - u'want to enforce per-user limits.') - - -FLAGS = flags.FLAGS -apitools_base_cli.DeclareBaseFlags() -_DeclareStorageFlags() - - -def GetGlobalParamsFromFlags(): - """Return a StandardQueryParameters based on flags.""" - result = messages.StandardQueryParameters() - if FLAGS['alt'].present: - result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt) - if FLAGS['fields'].present: - result.fields = FLAGS.fields.decode('utf8') - if FLAGS['key'].present: - result.key = FLAGS.key.decode('utf8') - if FLAGS['oauth_token'].present: - result.oauth_token = FLAGS.oauth_token.decode('utf8') - if FLAGS['prettyPrint'].present: - result.prettyPrint = FLAGS.prettyPrint - if FLAGS['quotaUser'].present: - result.quotaUser = FLAGS.quotaUser.decode('utf8') - if FLAGS['trace'].present: - result.trace = FLAGS.trace.decode('utf8') - if FLAGS['userIp'].present: - result.userIp = FLAGS.userIp.decode('utf8') - return result - - -def GetClientFromFlags(): - """Return a client object, configured from flags.""" - log_request = FLAGS.log_request or FLAGS.log_request_response - log_response = FLAGS.log_response or FLAGS.log_request_response - api_endpoint = apitools_base.NormalizeApiEndpoint(FLAGS.api_endpoint) - additional_http_headers = dict(x.split('=', 1) for x in FLAGS.add_header) - credentials_args = { - 'service_account_json_keyfile': os.path.expanduser(FLAGS.service_account_json_keyfile) - } - try: - client = client_lib.StorageV1( - api_endpoint, log_request=log_request, - log_response=log_response, - credentials_args=credentials_args, - additional_http_headers=additional_http_headers) - except apitools_base.CredentialsError as e: - print 'Error creating credentials: %s' % e - sys.exit(1) - return client - - -class PyShell(appcommands.Cmd): - - def Run(self, _): - """Run an interactive python shell with the client.""" - client = GetClientFromFlags() - params = GetGlobalParamsFromFlags() - for field in params.all_fields(): - value = params.get_assigned_value(field.name) - if value != field.default: - client.AddGlobalParam(field.name, value) - banner = """ - == storage interactive console == - client: a storage client - apitools_base: base apitools module - messages: the generated messages module - """ - local_vars = { - 'apitools_base': apitools_base, - 'client': client, - 'client_lib': client_lib, - 'messages': messages, - } - if platform.system() == 'Linux': - console = apitools_base_cli.ConsoleWithReadline( - local_vars, histfile=FLAGS.history_file) - else: - console = code.InteractiveConsole(local_vars) - try: - console.interact(banner) - except SystemExit as e: - return e.code - - -class BucketAccessControlsDelete(apitools_base_cli.NewCmd): - """Command wrapping bucketAccessControls.Delete.""" - - usage = """bucketAccessControls_delete """ - - def __init__(self, name, fv): - super(BucketAccessControlsDelete, self).__init__(name, fv) - - def RunWithArgs(self, bucket, entity): - """Permanently deletes the ACL entry for the specified entity on the - specified bucket. - - Args: - bucket: Name of a bucket. - entity: The entity holding the permission. Can be user-userId, user- - emailAddress, group-groupId, group-emailAddress, allUsers, or - allAuthenticatedUsers. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketAccessControlsDeleteRequest( - bucket=bucket.decode('utf8'), - entity=entity.decode('utf8'), - ) - result = client.bucketAccessControls.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketAccessControlsGet(apitools_base_cli.NewCmd): - """Command wrapping bucketAccessControls.Get.""" - - usage = """bucketAccessControls_get """ - - def __init__(self, name, fv): - super(BucketAccessControlsGet, self).__init__(name, fv) - - def RunWithArgs(self, bucket, entity): - """Returns the ACL entry for the specified entity on the specified bucket. - - Args: - bucket: Name of a bucket. - entity: The entity holding the permission. Can be user-userId, user- - emailAddress, group-groupId, group-emailAddress, allUsers, or - allAuthenticatedUsers. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketAccessControlsGetRequest( - bucket=bucket.decode('utf8'), - entity=entity.decode('utf8'), - ) - result = client.bucketAccessControls.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketAccessControlsInsert(apitools_base_cli.NewCmd): - """Command wrapping bucketAccessControls.Insert.""" - - usage = """bucketAccessControls_insert """ - - def __init__(self, name, fv): - super(BucketAccessControlsInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'domain', - None, - u'The domain associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'email', - None, - u'The email address associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'entity', - None, - u'The entity holding the permission, in one of the following forms: ' - u'- user-userId - user-email - group-groupId - group-email - ' - u'domain-domain - project-team-projectId - allUsers - ' - u'allAuthenticatedUsers Examples: - The user liz@example.com would ' - u'be user-liz@example.com. - The group example@googlegroups.com ' - u'would be group-example@googlegroups.com. - To refer to all members' - u' of the Google Apps for Business domain example.com, the entity ' - u'would be domain-example.com.', - flag_values=fv) - flags.DEFINE_string( - 'entityId', - None, - u'The ID for the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'etag', - None, - u'HTTP 1.1 Entity tag for the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'id', - None, - u'The ID of the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'storage#bucketAccessControl', - u'The kind of item this is. For bucket access control entries, this ' - u'is always storage#bucketAccessControl.', - flag_values=fv) - flags.DEFINE_string( - 'projectTeam', - None, - u'The project team associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'role', - None, - u'The access permission for the entity. Can be READER, WRITER, or ' - u'OWNER.', - flag_values=fv) - flags.DEFINE_string( - 'selfLink', - None, - u'The link to this access-control entry.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Creates a new ACL entry on the specified bucket. - - Args: - bucket: The name of the bucket. - - Flags: - domain: The domain associated with the entity, if any. - email: The email address associated with the entity, if any. - entity: The entity holding the permission, in one of the following - forms: - user-userId - user-email - group-groupId - group-email - - domain-domain - project-team-projectId - allUsers - - allAuthenticatedUsers Examples: - The user liz@example.com would be - user-liz@example.com. - The group example@googlegroups.com would be - group-example@googlegroups.com. - To refer to all members of the - Google Apps for Business domain example.com, the entity would be - domain-example.com. - entityId: The ID for the entity, if any. - etag: HTTP 1.1 Entity tag for the access-control entry. - id: The ID of the access-control entry. - kind: The kind of item this is. For bucket access control entries, this - is always storage#bucketAccessControl. - projectTeam: The project team associated with the entity, if any. - role: The access permission for the entity. Can be READER, WRITER, or - OWNER. - selfLink: The link to this access-control entry. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BucketAccessControl( - bucket=bucket.decode('utf8'), - ) - if FLAGS['domain'].present: - request.domain = FLAGS.domain.decode('utf8') - if FLAGS['email'].present: - request.email = FLAGS.email.decode('utf8') - if FLAGS['entity'].present: - request.entity = FLAGS.entity.decode('utf8') - if FLAGS['entityId'].present: - request.entityId = FLAGS.entityId.decode('utf8') - if FLAGS['etag'].present: - request.etag = FLAGS.etag.decode('utf8') - if FLAGS['id'].present: - request.id = FLAGS.id.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['projectTeam'].present: - request.projectTeam = apitools_base.JsonToMessage(messages.BucketAccessControl.ProjectTeamValue, FLAGS.projectTeam) - if FLAGS['role'].present: - request.role = FLAGS.role.decode('utf8') - if FLAGS['selfLink'].present: - request.selfLink = FLAGS.selfLink.decode('utf8') - result = client.bucketAccessControls.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketAccessControlsList(apitools_base_cli.NewCmd): - """Command wrapping bucketAccessControls.List.""" - - usage = """bucketAccessControls_list """ - - def __init__(self, name, fv): - super(BucketAccessControlsList, self).__init__(name, fv) - - def RunWithArgs(self, bucket): - """Retrieves ACL entries on the specified bucket. - - Args: - bucket: Name of a bucket. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketAccessControlsListRequest( - bucket=bucket.decode('utf8'), - ) - result = client.bucketAccessControls.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketAccessControlsPatch(apitools_base_cli.NewCmd): - """Command wrapping bucketAccessControls.Patch.""" - - usage = """bucketAccessControls_patch """ - - def __init__(self, name, fv): - super(BucketAccessControlsPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'domain', - None, - u'The domain associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'email', - None, - u'The email address associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'entityId', - None, - u'The ID for the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'etag', - None, - u'HTTP 1.1 Entity tag for the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'id', - None, - u'The ID of the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'storage#bucketAccessControl', - u'The kind of item this is. For bucket access control entries, this ' - u'is always storage#bucketAccessControl.', - flag_values=fv) - flags.DEFINE_string( - 'projectTeam', - None, - u'The project team associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'role', - None, - u'The access permission for the entity. Can be READER, WRITER, or ' - u'OWNER.', - flag_values=fv) - flags.DEFINE_string( - 'selfLink', - None, - u'The link to this access-control entry.', - flag_values=fv) - - def RunWithArgs(self, bucket, entity): - """Updates an ACL entry on the specified bucket. This method supports - patch semantics. - - Args: - bucket: The name of the bucket. - entity: The entity holding the permission, in one of the following - forms: - user-userId - user-email - group-groupId - group-email - - domain-domain - project-team-projectId - allUsers - - allAuthenticatedUsers Examples: - The user liz@example.com would be - user-liz@example.com. - The group example@googlegroups.com would be - group-example@googlegroups.com. - To refer to all members of the - Google Apps for Business domain example.com, the entity would be - domain-example.com. - - Flags: - domain: The domain associated with the entity, if any. - email: The email address associated with the entity, if any. - entityId: The ID for the entity, if any. - etag: HTTP 1.1 Entity tag for the access-control entry. - id: The ID of the access-control entry. - kind: The kind of item this is. For bucket access control entries, this - is always storage#bucketAccessControl. - projectTeam: The project team associated with the entity, if any. - role: The access permission for the entity. Can be READER, WRITER, or - OWNER. - selfLink: The link to this access-control entry. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BucketAccessControl( - bucket=bucket.decode('utf8'), - entity=entity.decode('utf8'), - ) - if FLAGS['domain'].present: - request.domain = FLAGS.domain.decode('utf8') - if FLAGS['email'].present: - request.email = FLAGS.email.decode('utf8') - if FLAGS['entityId'].present: - request.entityId = FLAGS.entityId.decode('utf8') - if FLAGS['etag'].present: - request.etag = FLAGS.etag.decode('utf8') - if FLAGS['id'].present: - request.id = FLAGS.id.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['projectTeam'].present: - request.projectTeam = apitools_base.JsonToMessage(messages.BucketAccessControl.ProjectTeamValue, FLAGS.projectTeam) - if FLAGS['role'].present: - request.role = FLAGS.role.decode('utf8') - if FLAGS['selfLink'].present: - request.selfLink = FLAGS.selfLink.decode('utf8') - result = client.bucketAccessControls.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketAccessControlsUpdate(apitools_base_cli.NewCmd): - """Command wrapping bucketAccessControls.Update.""" - - usage = """bucketAccessControls_update """ - - def __init__(self, name, fv): - super(BucketAccessControlsUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'domain', - None, - u'The domain associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'email', - None, - u'The email address associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'entityId', - None, - u'The ID for the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'etag', - None, - u'HTTP 1.1 Entity tag for the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'id', - None, - u'The ID of the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'storage#bucketAccessControl', - u'The kind of item this is. For bucket access control entries, this ' - u'is always storage#bucketAccessControl.', - flag_values=fv) - flags.DEFINE_string( - 'projectTeam', - None, - u'The project team associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'role', - None, - u'The access permission for the entity. Can be READER, WRITER, or ' - u'OWNER.', - flag_values=fv) - flags.DEFINE_string( - 'selfLink', - None, - u'The link to this access-control entry.', - flag_values=fv) - - def RunWithArgs(self, bucket, entity): - """Updates an ACL entry on the specified bucket. - - Args: - bucket: The name of the bucket. - entity: The entity holding the permission, in one of the following - forms: - user-userId - user-email - group-groupId - group-email - - domain-domain - project-team-projectId - allUsers - - allAuthenticatedUsers Examples: - The user liz@example.com would be - user-liz@example.com. - The group example@googlegroups.com would be - group-example@googlegroups.com. - To refer to all members of the - Google Apps for Business domain example.com, the entity would be - domain-example.com. - - Flags: - domain: The domain associated with the entity, if any. - email: The email address associated with the entity, if any. - entityId: The ID for the entity, if any. - etag: HTTP 1.1 Entity tag for the access-control entry. - id: The ID of the access-control entry. - kind: The kind of item this is. For bucket access control entries, this - is always storage#bucketAccessControl. - projectTeam: The project team associated with the entity, if any. - role: The access permission for the entity. Can be READER, WRITER, or - OWNER. - selfLink: The link to this access-control entry. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.BucketAccessControl( - bucket=bucket.decode('utf8'), - entity=entity.decode('utf8'), - ) - if FLAGS['domain'].present: - request.domain = FLAGS.domain.decode('utf8') - if FLAGS['email'].present: - request.email = FLAGS.email.decode('utf8') - if FLAGS['entityId'].present: - request.entityId = FLAGS.entityId.decode('utf8') - if FLAGS['etag'].present: - request.etag = FLAGS.etag.decode('utf8') - if FLAGS['id'].present: - request.id = FLAGS.id.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['projectTeam'].present: - request.projectTeam = apitools_base.JsonToMessage(messages.BucketAccessControl.ProjectTeamValue, FLAGS.projectTeam) - if FLAGS['role'].present: - request.role = FLAGS.role.decode('utf8') - if FLAGS['selfLink'].present: - request.selfLink = FLAGS.selfLink.decode('utf8') - result = client.bucketAccessControls.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketsDelete(apitools_base_cli.NewCmd): - """Command wrapping buckets.Delete.""" - - usage = """buckets_delete """ - - def __init__(self, name, fv): - super(BucketsDelete, self).__init__(name, fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u'If set, only deletes the bucket if its metageneration matches this ' - u'value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u'If set, only deletes the bucket if its metageneration does not ' - u'match this value.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Permanently deletes an empty bucket. - - Args: - bucket: Name of a bucket. - - Flags: - ifMetagenerationMatch: If set, only deletes the bucket if its - metageneration matches this value. - ifMetagenerationNotMatch: If set, only deletes the bucket if its - metageneration does not match this value. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketsDeleteRequest( - bucket=bucket.decode('utf8'), - ) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - result = client.buckets.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketsGet(apitools_base_cli.NewCmd): - """Command wrapping buckets.Get.""" - - usage = """buckets_get """ - - def __init__(self, name, fv): - super(BucketsGet, self).__init__(name, fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u'Makes the return of the bucket metadata conditional on whether the ' - u"bucket's current metageneration matches the given value.", - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u'Makes the return of the bucket metadata conditional on whether the ' - u"bucket's current metageneration does not match the given value.", - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to noAcl.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Returns metadata for the specified bucket. - - Args: - bucket: Name of a bucket. - - Flags: - ifMetagenerationMatch: Makes the return of the bucket metadata - conditional on whether the bucket's current metageneration matches the - given value. - ifMetagenerationNotMatch: Makes the return of the bucket metadata - conditional on whether the bucket's current metageneration does not - match the given value. - projection: Set of properties to return. Defaults to noAcl. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketsGetRequest( - bucket=bucket.decode('utf8'), - ) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - if FLAGS['projection'].present: - request.projection = messages.StorageBucketsGetRequest.ProjectionValueValuesEnum(FLAGS.projection) - result = client.buckets.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketsGetIamPolicy(apitools_base_cli.NewCmd): - """Command wrapping buckets.GetIamPolicy.""" - - usage = """buckets_getIamPolicy """ - - def __init__(self, name, fv): - super(BucketsGetIamPolicy, self).__init__(name, fv) - - def RunWithArgs(self, bucket): - """Returns an IAM policy for the specified bucket. - - Args: - bucket: Name of a bucket. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketsGetIamPolicyRequest( - bucket=bucket.decode('utf8'), - ) - result = client.buckets.GetIamPolicy( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketsInsert(apitools_base_cli.NewCmd): - """Command wrapping buckets.Insert.""" - - usage = """buckets_insert """ - - def __init__(self, name, fv): - super(BucketsInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'bucket', - None, - u'A Bucket resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_enum( - 'predefinedAcl', - u'authenticatedRead', - [u'authenticatedRead', u'private', u'projectPrivate', u'publicRead', u'publicReadWrite'], - u'Apply a predefined set of access controls to this bucket.', - flag_values=fv) - flags.DEFINE_enum( - 'predefinedDefaultObjectAcl', - u'authenticatedRead', - [u'authenticatedRead', u'bucketOwnerFullControl', u'bucketOwnerRead', u'private', u'projectPrivate', u'publicRead'], - u'Apply a predefined set of default object access controls to this ' - u'bucket.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to noAcl, unless the bucket ' - u'resource specifies acl or defaultObjectAcl properties, when it ' - u'defaults to full.', - flag_values=fv) - - def RunWithArgs(self, project): - """Creates a new bucket. - - Args: - project: A valid API project identifier. - - Flags: - bucket: A Bucket resource to be passed as the request body. - predefinedAcl: Apply a predefined set of access controls to this bucket. - predefinedDefaultObjectAcl: Apply a predefined set of default object - access controls to this bucket. - projection: Set of properties to return. Defaults to noAcl, unless the - bucket resource specifies acl or defaultObjectAcl properties, when it - defaults to full. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketsInsertRequest( - project=project.decode('utf8'), - ) - if FLAGS['bucket'].present: - request.bucket = apitools_base.JsonToMessage(messages.Bucket, FLAGS.bucket) - if FLAGS['predefinedAcl'].present: - request.predefinedAcl = messages.StorageBucketsInsertRequest.PredefinedAclValueValuesEnum(FLAGS.predefinedAcl) - if FLAGS['predefinedDefaultObjectAcl'].present: - request.predefinedDefaultObjectAcl = messages.StorageBucketsInsertRequest.PredefinedDefaultObjectAclValueValuesEnum(FLAGS.predefinedDefaultObjectAcl) - if FLAGS['projection'].present: - request.projection = messages.StorageBucketsInsertRequest.ProjectionValueValuesEnum(FLAGS.projection) - result = client.buckets.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketsList(apitools_base_cli.NewCmd): - """Command wrapping buckets.List.""" - - usage = """buckets_list """ - - def __init__(self, name, fv): - super(BucketsList, self).__init__(name, fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of buckets to return.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'A previously-returned page token representing part of the larger ' - u'set of results to view.', - flag_values=fv) - flags.DEFINE_string( - 'prefix', - None, - u'Filter results to buckets whose names begin with this prefix.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to noAcl.', - flag_values=fv) - - def RunWithArgs(self, project): - """Retrieves a list of buckets for a given project. - - Args: - project: A valid API project identifier. - - Flags: - maxResults: Maximum number of buckets to return. - pageToken: A previously-returned page token representing part of the - larger set of results to view. - prefix: Filter results to buckets whose names begin with this prefix. - projection: Set of properties to return. Defaults to noAcl. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketsListRequest( - project=project.decode('utf8'), - ) - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['prefix'].present: - request.prefix = FLAGS.prefix.decode('utf8') - if FLAGS['projection'].present: - request.projection = messages.StorageBucketsListRequest.ProjectionValueValuesEnum(FLAGS.projection) - result = client.buckets.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketsPatch(apitools_base_cli.NewCmd): - """Command wrapping buckets.Patch.""" - - usage = """buckets_patch """ - - def __init__(self, name, fv): - super(BucketsPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'bucketResource', - None, - u'A Bucket resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u'Makes the return of the bucket metadata conditional on whether the ' - u"bucket's current metageneration matches the given value.", - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u'Makes the return of the bucket metadata conditional on whether the ' - u"bucket's current metageneration does not match the given value.", - flag_values=fv) - flags.DEFINE_enum( - 'predefinedAcl', - u'authenticatedRead', - [u'authenticatedRead', u'private', u'projectPrivate', u'publicRead', u'publicReadWrite'], - u'Apply a predefined set of access controls to this bucket.', - flag_values=fv) - flags.DEFINE_enum( - 'predefinedDefaultObjectAcl', - u'authenticatedRead', - [u'authenticatedRead', u'bucketOwnerFullControl', u'bucketOwnerRead', u'private', u'projectPrivate', u'publicRead'], - u'Apply a predefined set of default object access controls to this ' - u'bucket.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to full.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Updates a bucket. This method supports patch semantics. - - Args: - bucket: Name of a bucket. - - Flags: - bucketResource: A Bucket resource to be passed as the request body. - ifMetagenerationMatch: Makes the return of the bucket metadata - conditional on whether the bucket's current metageneration matches the - given value. - ifMetagenerationNotMatch: Makes the return of the bucket metadata - conditional on whether the bucket's current metageneration does not - match the given value. - predefinedAcl: Apply a predefined set of access controls to this bucket. - predefinedDefaultObjectAcl: Apply a predefined set of default object - access controls to this bucket. - projection: Set of properties to return. Defaults to full. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketsPatchRequest( - bucket=bucket.decode('utf8'), - ) - if FLAGS['bucketResource'].present: - request.bucketResource = apitools_base.JsonToMessage(messages.Bucket, FLAGS.bucketResource) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - if FLAGS['predefinedAcl'].present: - request.predefinedAcl = messages.StorageBucketsPatchRequest.PredefinedAclValueValuesEnum(FLAGS.predefinedAcl) - if FLAGS['predefinedDefaultObjectAcl'].present: - request.predefinedDefaultObjectAcl = messages.StorageBucketsPatchRequest.PredefinedDefaultObjectAclValueValuesEnum(FLAGS.predefinedDefaultObjectAcl) - if FLAGS['projection'].present: - request.projection = messages.StorageBucketsPatchRequest.ProjectionValueValuesEnum(FLAGS.projection) - result = client.buckets.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketsSetIamPolicy(apitools_base_cli.NewCmd): - """Command wrapping buckets.SetIamPolicy.""" - - usage = """buckets_setIamPolicy """ - - def __init__(self, name, fv): - super(BucketsSetIamPolicy, self).__init__(name, fv) - flags.DEFINE_string( - 'policy', - None, - u'A Policy resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Updates an IAM policy for the specified bucket. - - Args: - bucket: Name of a bucket. - - Flags: - policy: A Policy resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketsSetIamPolicyRequest( - bucket=bucket.decode('utf8'), - ) - if FLAGS['policy'].present: - request.policy = apitools_base.JsonToMessage(messages.Policy, FLAGS.policy) - result = client.buckets.SetIamPolicy( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketsTestIamPermissions(apitools_base_cli.NewCmd): - """Command wrapping buckets.TestIamPermissions.""" - - usage = """buckets_testIamPermissions """ - - def __init__(self, name, fv): - super(BucketsTestIamPermissions, self).__init__(name, fv) - - def RunWithArgs(self, bucket, permissions): - """Tests a set of permissions on the given bucket to see which, if any, - are held by the caller. - - Args: - bucket: Name of a bucket. - permissions: Permissions to test. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketsTestIamPermissionsRequest( - bucket=bucket.decode('utf8'), - permissions=permissions.decode('utf8'), - ) - result = client.buckets.TestIamPermissions( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class BucketsUpdate(apitools_base_cli.NewCmd): - """Command wrapping buckets.Update.""" - - usage = """buckets_update """ - - def __init__(self, name, fv): - super(BucketsUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'bucketResource', - None, - u'A Bucket resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u'Makes the return of the bucket metadata conditional on whether the ' - u"bucket's current metageneration matches the given value.", - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u'Makes the return of the bucket metadata conditional on whether the ' - u"bucket's current metageneration does not match the given value.", - flag_values=fv) - flags.DEFINE_enum( - 'predefinedAcl', - u'authenticatedRead', - [u'authenticatedRead', u'private', u'projectPrivate', u'publicRead', u'publicReadWrite'], - u'Apply a predefined set of access controls to this bucket.', - flag_values=fv) - flags.DEFINE_enum( - 'predefinedDefaultObjectAcl', - u'authenticatedRead', - [u'authenticatedRead', u'bucketOwnerFullControl', u'bucketOwnerRead', u'private', u'projectPrivate', u'publicRead'], - u'Apply a predefined set of default object access controls to this ' - u'bucket.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to full.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Updates a bucket. - - Args: - bucket: Name of a bucket. - - Flags: - bucketResource: A Bucket resource to be passed as the request body. - ifMetagenerationMatch: Makes the return of the bucket metadata - conditional on whether the bucket's current metageneration matches the - given value. - ifMetagenerationNotMatch: Makes the return of the bucket metadata - conditional on whether the bucket's current metageneration does not - match the given value. - predefinedAcl: Apply a predefined set of access controls to this bucket. - predefinedDefaultObjectAcl: Apply a predefined set of default object - access controls to this bucket. - projection: Set of properties to return. Defaults to full. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageBucketsUpdateRequest( - bucket=bucket.decode('utf8'), - ) - if FLAGS['bucketResource'].present: - request.bucketResource = apitools_base.JsonToMessage(messages.Bucket, FLAGS.bucketResource) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - if FLAGS['predefinedAcl'].present: - request.predefinedAcl = messages.StorageBucketsUpdateRequest.PredefinedAclValueValuesEnum(FLAGS.predefinedAcl) - if FLAGS['predefinedDefaultObjectAcl'].present: - request.predefinedDefaultObjectAcl = messages.StorageBucketsUpdateRequest.PredefinedDefaultObjectAclValueValuesEnum(FLAGS.predefinedDefaultObjectAcl) - if FLAGS['projection'].present: - request.projection = messages.StorageBucketsUpdateRequest.ProjectionValueValuesEnum(FLAGS.projection) - result = client.buckets.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ChannelsStop(apitools_base_cli.NewCmd): - """Command wrapping channels.Stop.""" - - usage = """channels_stop""" - - def __init__(self, name, fv): - super(ChannelsStop, self).__init__(name, fv) - flags.DEFINE_string( - 'address', - None, - u'The address where notifications are delivered for this channel.', - flag_values=fv) - flags.DEFINE_string( - 'expiration', - None, - u'Date and time of notification channel expiration, expressed as a ' - u'Unix timestamp, in milliseconds. Optional.', - flag_values=fv) - flags.DEFINE_string( - 'id', - None, - u'A UUID or similar unique string that identifies this channel.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'api#channel', - u'Identifies this as a notification channel used to watch for changes' - u' to a resource. Value: the fixed string "api#channel".', - flag_values=fv) - flags.DEFINE_string( - 'params', - None, - u'Additional parameters controlling delivery channel behavior. ' - u'Optional.', - flag_values=fv) - flags.DEFINE_boolean( - 'payload', - None, - u'A Boolean value to indicate whether payload is wanted. Optional.', - flag_values=fv) - flags.DEFINE_string( - 'resourceId', - None, - u'An opaque ID that identifies the resource being watched on this ' - u'channel. Stable across different API versions.', - flag_values=fv) - flags.DEFINE_string( - 'resourceUri', - None, - u'A version-specific identifier for the watched resource.', - flag_values=fv) - flags.DEFINE_string( - 'token', - None, - u'An arbitrary string delivered to the target address with each ' - u'notification delivered over this channel. Optional.', - flag_values=fv) - flags.DEFINE_string( - 'type', - None, - u'The type of delivery mechanism used for this channel.', - flag_values=fv) - - def RunWithArgs(self): - """Stop watching resources through this channel - - Flags: - address: The address where notifications are delivered for this channel. - expiration: Date and time of notification channel expiration, expressed - as a Unix timestamp, in milliseconds. Optional. - id: A UUID or similar unique string that identifies this channel. - kind: Identifies this as a notification channel used to watch for - changes to a resource. Value: the fixed string "api#channel". - params: Additional parameters controlling delivery channel behavior. - Optional. - payload: A Boolean value to indicate whether payload is wanted. - Optional. - resourceId: An opaque ID that identifies the resource being watched on - this channel. Stable across different API versions. - resourceUri: A version-specific identifier for the watched resource. - token: An arbitrary string delivered to the target address with each - notification delivered over this channel. Optional. - type: The type of delivery mechanism used for this channel. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.Channel( - ) - if FLAGS['address'].present: - request.address = FLAGS.address.decode('utf8') - if FLAGS['expiration'].present: - request.expiration = int(FLAGS.expiration) - if FLAGS['id'].present: - request.id = FLAGS.id.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['params'].present: - request.params = apitools_base.JsonToMessage(messages.Channel.ParamsValue, FLAGS.params) - if FLAGS['payload'].present: - request.payload = FLAGS.payload - if FLAGS['resourceId'].present: - request.resourceId = FLAGS.resourceId.decode('utf8') - if FLAGS['resourceUri'].present: - request.resourceUri = FLAGS.resourceUri.decode('utf8') - if FLAGS['token'].present: - request.token = FLAGS.token.decode('utf8') - if FLAGS['type'].present: - request.type = FLAGS.type.decode('utf8') - result = client.channels.Stop( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DefaultObjectAccessControlsDelete(apitools_base_cli.NewCmd): - """Command wrapping defaultObjectAccessControls.Delete.""" - - usage = """defaultObjectAccessControls_delete """ - - def __init__(self, name, fv): - super(DefaultObjectAccessControlsDelete, self).__init__(name, fv) - - def RunWithArgs(self, bucket, entity): - """Permanently deletes the default object ACL entry for the specified - entity on the specified bucket. - - Args: - bucket: Name of a bucket. - entity: The entity holding the permission. Can be user-userId, user- - emailAddress, group-groupId, group-emailAddress, allUsers, or - allAuthenticatedUsers. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageDefaultObjectAccessControlsDeleteRequest( - bucket=bucket.decode('utf8'), - entity=entity.decode('utf8'), - ) - result = client.defaultObjectAccessControls.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DefaultObjectAccessControlsGet(apitools_base_cli.NewCmd): - """Command wrapping defaultObjectAccessControls.Get.""" - - usage = """defaultObjectAccessControls_get """ - - def __init__(self, name, fv): - super(DefaultObjectAccessControlsGet, self).__init__(name, fv) - - def RunWithArgs(self, bucket, entity): - """Returns the default object ACL entry for the specified entity on the - specified bucket. - - Args: - bucket: Name of a bucket. - entity: The entity holding the permission. Can be user-userId, user- - emailAddress, group-groupId, group-emailAddress, allUsers, or - allAuthenticatedUsers. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageDefaultObjectAccessControlsGetRequest( - bucket=bucket.decode('utf8'), - entity=entity.decode('utf8'), - ) - result = client.defaultObjectAccessControls.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DefaultObjectAccessControlsInsert(apitools_base_cli.NewCmd): - """Command wrapping defaultObjectAccessControls.Insert.""" - - usage = """defaultObjectAccessControls_insert """ - - def __init__(self, name, fv): - super(DefaultObjectAccessControlsInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'domain', - None, - u'The domain associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'email', - None, - u'The email address associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'entity', - None, - u'The entity holding the permission, in one of the following forms: ' - u'- user-userId - user-email - group-groupId - group-email - ' - u'domain-domain - project-team-projectId - allUsers - ' - u'allAuthenticatedUsers Examples: - The user liz@example.com would ' - u'be user-liz@example.com. - The group example@googlegroups.com ' - u'would be group-example@googlegroups.com. - To refer to all members' - u' of the Google Apps for Business domain example.com, the entity ' - u'would be domain-example.com.', - flag_values=fv) - flags.DEFINE_string( - 'entityId', - None, - u'The ID for the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'etag', - None, - u'HTTP 1.1 Entity tag for the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'generation', - None, - u'The content generation of the object.', - flag_values=fv) - flags.DEFINE_string( - 'id', - None, - u'The ID of the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'storage#objectAccessControl', - u'The kind of item this is. For object access control entries, this ' - u'is always storage#objectAccessControl.', - flag_values=fv) - flags.DEFINE_string( - 'object', - None, - u'The name of the object.', - flag_values=fv) - flags.DEFINE_string( - 'projectTeam', - None, - u'The project team associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'role', - None, - u'The access permission for the entity. Can be READER or OWNER.', - flag_values=fv) - flags.DEFINE_string( - 'selfLink', - None, - u'The link to this access-control entry.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Creates a new default object ACL entry on the specified bucket. - - Args: - bucket: The name of the bucket. - - Flags: - domain: The domain associated with the entity, if any. - email: The email address associated with the entity, if any. - entity: The entity holding the permission, in one of the following - forms: - user-userId - user-email - group-groupId - group-email - - domain-domain - project-team-projectId - allUsers - - allAuthenticatedUsers Examples: - The user liz@example.com would be - user-liz@example.com. - The group example@googlegroups.com would be - group-example@googlegroups.com. - To refer to all members of the - Google Apps for Business domain example.com, the entity would be - domain-example.com. - entityId: The ID for the entity, if any. - etag: HTTP 1.1 Entity tag for the access-control entry. - generation: The content generation of the object. - id: The ID of the access-control entry. - kind: The kind of item this is. For object access control entries, this - is always storage#objectAccessControl. - object: The name of the object. - projectTeam: The project team associated with the entity, if any. - role: The access permission for the entity. Can be READER or OWNER. - selfLink: The link to this access-control entry. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ObjectAccessControl( - bucket=bucket.decode('utf8'), - ) - if FLAGS['domain'].present: - request.domain = FLAGS.domain.decode('utf8') - if FLAGS['email'].present: - request.email = FLAGS.email.decode('utf8') - if FLAGS['entity'].present: - request.entity = FLAGS.entity.decode('utf8') - if FLAGS['entityId'].present: - request.entityId = FLAGS.entityId.decode('utf8') - if FLAGS['etag'].present: - request.etag = FLAGS.etag.decode('utf8') - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['id'].present: - request.id = FLAGS.id.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['object'].present: - request.object = FLAGS.object.decode('utf8') - if FLAGS['projectTeam'].present: - request.projectTeam = apitools_base.JsonToMessage(messages.ObjectAccessControl.ProjectTeamValue, FLAGS.projectTeam) - if FLAGS['role'].present: - request.role = FLAGS.role.decode('utf8') - if FLAGS['selfLink'].present: - request.selfLink = FLAGS.selfLink.decode('utf8') - result = client.defaultObjectAccessControls.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DefaultObjectAccessControlsList(apitools_base_cli.NewCmd): - """Command wrapping defaultObjectAccessControls.List.""" - - usage = """defaultObjectAccessControls_list """ - - def __init__(self, name, fv): - super(DefaultObjectAccessControlsList, self).__init__(name, fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u"If present, only return default ACL listing if the bucket's current" - u' metageneration matches this value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u"If present, only return default ACL listing if the bucket's current" - u' metageneration does not match the given value.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Retrieves default object ACL entries on the specified bucket. - - Args: - bucket: Name of a bucket. - - Flags: - ifMetagenerationMatch: If present, only return default ACL listing if - the bucket's current metageneration matches this value. - ifMetagenerationNotMatch: If present, only return default ACL listing if - the bucket's current metageneration does not match the given value. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageDefaultObjectAccessControlsListRequest( - bucket=bucket.decode('utf8'), - ) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - result = client.defaultObjectAccessControls.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DefaultObjectAccessControlsPatch(apitools_base_cli.NewCmd): - """Command wrapping defaultObjectAccessControls.Patch.""" - - usage = """defaultObjectAccessControls_patch """ - - def __init__(self, name, fv): - super(DefaultObjectAccessControlsPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'domain', - None, - u'The domain associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'email', - None, - u'The email address associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'entityId', - None, - u'The ID for the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'etag', - None, - u'HTTP 1.1 Entity tag for the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'generation', - None, - u'The content generation of the object.', - flag_values=fv) - flags.DEFINE_string( - 'id', - None, - u'The ID of the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'storage#objectAccessControl', - u'The kind of item this is. For object access control entries, this ' - u'is always storage#objectAccessControl.', - flag_values=fv) - flags.DEFINE_string( - 'object', - None, - u'The name of the object.', - flag_values=fv) - flags.DEFINE_string( - 'projectTeam', - None, - u'The project team associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'role', - None, - u'The access permission for the entity. Can be READER or OWNER.', - flag_values=fv) - flags.DEFINE_string( - 'selfLink', - None, - u'The link to this access-control entry.', - flag_values=fv) - - def RunWithArgs(self, bucket, entity): - """Updates a default object ACL entry on the specified bucket. This method - supports patch semantics. - - Args: - bucket: The name of the bucket. - entity: The entity holding the permission, in one of the following - forms: - user-userId - user-email - group-groupId - group-email - - domain-domain - project-team-projectId - allUsers - - allAuthenticatedUsers Examples: - The user liz@example.com would be - user-liz@example.com. - The group example@googlegroups.com would be - group-example@googlegroups.com. - To refer to all members of the - Google Apps for Business domain example.com, the entity would be - domain-example.com. - - Flags: - domain: The domain associated with the entity, if any. - email: The email address associated with the entity, if any. - entityId: The ID for the entity, if any. - etag: HTTP 1.1 Entity tag for the access-control entry. - generation: The content generation of the object. - id: The ID of the access-control entry. - kind: The kind of item this is. For object access control entries, this - is always storage#objectAccessControl. - object: The name of the object. - projectTeam: The project team associated with the entity, if any. - role: The access permission for the entity. Can be READER or OWNER. - selfLink: The link to this access-control entry. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ObjectAccessControl( - bucket=bucket.decode('utf8'), - entity=entity.decode('utf8'), - ) - if FLAGS['domain'].present: - request.domain = FLAGS.domain.decode('utf8') - if FLAGS['email'].present: - request.email = FLAGS.email.decode('utf8') - if FLAGS['entityId'].present: - request.entityId = FLAGS.entityId.decode('utf8') - if FLAGS['etag'].present: - request.etag = FLAGS.etag.decode('utf8') - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['id'].present: - request.id = FLAGS.id.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['object'].present: - request.object = FLAGS.object.decode('utf8') - if FLAGS['projectTeam'].present: - request.projectTeam = apitools_base.JsonToMessage(messages.ObjectAccessControl.ProjectTeamValue, FLAGS.projectTeam) - if FLAGS['role'].present: - request.role = FLAGS.role.decode('utf8') - if FLAGS['selfLink'].present: - request.selfLink = FLAGS.selfLink.decode('utf8') - result = client.defaultObjectAccessControls.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class DefaultObjectAccessControlsUpdate(apitools_base_cli.NewCmd): - """Command wrapping defaultObjectAccessControls.Update.""" - - usage = """defaultObjectAccessControls_update """ - - def __init__(self, name, fv): - super(DefaultObjectAccessControlsUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'domain', - None, - u'The domain associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'email', - None, - u'The email address associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'entityId', - None, - u'The ID for the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'etag', - None, - u'HTTP 1.1 Entity tag for the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'generation', - None, - u'The content generation of the object.', - flag_values=fv) - flags.DEFINE_string( - 'id', - None, - u'The ID of the access-control entry.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'storage#objectAccessControl', - u'The kind of item this is. For object access control entries, this ' - u'is always storage#objectAccessControl.', - flag_values=fv) - flags.DEFINE_string( - 'object', - None, - u'The name of the object.', - flag_values=fv) - flags.DEFINE_string( - 'projectTeam', - None, - u'The project team associated with the entity, if any.', - flag_values=fv) - flags.DEFINE_string( - 'role', - None, - u'The access permission for the entity. Can be READER or OWNER.', - flag_values=fv) - flags.DEFINE_string( - 'selfLink', - None, - u'The link to this access-control entry.', - flag_values=fv) - - def RunWithArgs(self, bucket, entity): - """Updates a default object ACL entry on the specified bucket. - - Args: - bucket: The name of the bucket. - entity: The entity holding the permission, in one of the following - forms: - user-userId - user-email - group-groupId - group-email - - domain-domain - project-team-projectId - allUsers - - allAuthenticatedUsers Examples: - The user liz@example.com would be - user-liz@example.com. - The group example@googlegroups.com would be - group-example@googlegroups.com. - To refer to all members of the - Google Apps for Business domain example.com, the entity would be - domain-example.com. - - Flags: - domain: The domain associated with the entity, if any. - email: The email address associated with the entity, if any. - entityId: The ID for the entity, if any. - etag: HTTP 1.1 Entity tag for the access-control entry. - generation: The content generation of the object. - id: The ID of the access-control entry. - kind: The kind of item this is. For object access control entries, this - is always storage#objectAccessControl. - object: The name of the object. - projectTeam: The project team associated with the entity, if any. - role: The access permission for the entity. Can be READER or OWNER. - selfLink: The link to this access-control entry. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.ObjectAccessControl( - bucket=bucket.decode('utf8'), - entity=entity.decode('utf8'), - ) - if FLAGS['domain'].present: - request.domain = FLAGS.domain.decode('utf8') - if FLAGS['email'].present: - request.email = FLAGS.email.decode('utf8') - if FLAGS['entityId'].present: - request.entityId = FLAGS.entityId.decode('utf8') - if FLAGS['etag'].present: - request.etag = FLAGS.etag.decode('utf8') - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['id'].present: - request.id = FLAGS.id.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['object'].present: - request.object = FLAGS.object.decode('utf8') - if FLAGS['projectTeam'].present: - request.projectTeam = apitools_base.JsonToMessage(messages.ObjectAccessControl.ProjectTeamValue, FLAGS.projectTeam) - if FLAGS['role'].present: - request.role = FLAGS.role.decode('utf8') - if FLAGS['selfLink'].present: - request.selfLink = FLAGS.selfLink.decode('utf8') - result = client.defaultObjectAccessControls.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class NotificationsDelete(apitools_base_cli.NewCmd): - """Command wrapping notifications.Delete.""" - - usage = """notifications_delete """ - - def __init__(self, name, fv): - super(NotificationsDelete, self).__init__(name, fv) - - def RunWithArgs(self, notification): - """Permanently deletes a notification subscription. - - Args: - notification: ID of the notification to delete. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageNotificationsDeleteRequest( - notification=notification.decode('utf8'), - ) - result = client.notifications.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class NotificationsGet(apitools_base_cli.NewCmd): - """Command wrapping notifications.Get.""" - - usage = """notifications_get """ - - def __init__(self, name, fv): - super(NotificationsGet, self).__init__(name, fv) - - def RunWithArgs(self, notification): - """View a notification configuration. - - Args: - notification: Notification ID - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageNotificationsGetRequest( - notification=notification.decode('utf8'), - ) - result = client.notifications.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class NotificationsInsert(apitools_base_cli.NewCmd): - """Command wrapping notifications.Insert.""" - - usage = """notifications_insert""" - - def __init__(self, name, fv): - super(NotificationsInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'bucket', - None, - u'The name of the bucket this subscription is particular to.', - flag_values=fv) - flags.DEFINE_string( - 'custom_attributes', - None, - u'An optional list of additional attributes to attach to each Cloud ' - u'PubSub message published for this notification subscription.', - flag_values=fv) - flags.DEFINE_string( - 'etag', - None, - u'HTTP 1.1 Entity tag for this subscription notification.', - flag_values=fv) - flags.DEFINE_string( - 'event_types', - None, - u'If present, only send notifications about listed event types. If ' - u'empty, sent notifications for all event types.', - flag_values=fv) - flags.DEFINE_string( - 'id', - None, - u'The ID of the notification.', - flag_values=fv) - flags.DEFINE_string( - 'kind', - u'storage#notification', - u'The kind of item this is. For notifications, this is always ' - u'storage#notification.', - flag_values=fv) - flags.DEFINE_string( - 'object_metadata_format', - u'JSON_API_V1', - u'If payload_content is OBJECT_METADATA, controls the format of that ' - u'metadata. Otherwise, must not be set.', - flag_values=fv) - flags.DEFINE_string( - 'object_name_prefix', - None, - u'If present, only apply this notification configuration to object ' - u'names that begin with this prefix.', - flag_values=fv) - flags.DEFINE_string( - 'payload_content', - u'OBJECT_METADATA', - u'The desired content of the Payload. Defaults to OBJECT_METADATA.', - flag_values=fv) - flags.DEFINE_string( - 'selfLink', - None, - u'The canonical URL of this notification.', - flag_values=fv) - flags.DEFINE_string( - 'topic', - None, - u'The Cloud PubSub topic to which this subscription publishes. ' - u"Formatted as: '//pubsub.googleapis.com/projects/{project-" - u"identifier}/topics/{my-topic}'", - flag_values=fv) - - def RunWithArgs(self): - """Creates a notification subscription for a given bucket. - - Flags: - bucket: The name of the bucket this subscription is particular to. - custom_attributes: An optional list of additional attributes to attach - to each Cloud PubSub message published for this notification - subscription. - etag: HTTP 1.1 Entity tag for this subscription notification. - event_types: If present, only send notifications about listed event - types. If empty, sent notifications for all event types. - id: The ID of the notification. - kind: The kind of item this is. For notifications, this is always - storage#notification. - object_metadata_format: If payload_content is OBJECT_METADATA, controls - the format of that metadata. Otherwise, must not be set. - object_name_prefix: If present, only apply this notification - configuration to object names that begin with this prefix. - payload_content: The desired content of the Payload. Defaults to - OBJECT_METADATA. - selfLink: The canonical URL of this notification. - topic: The Cloud PubSub topic to which this subscription publishes. - Formatted as: '//pubsub.googleapis.com/projects/{project- - identifier}/topics/{my-topic}' - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.Notification( - ) - if FLAGS['bucket'].present: - request.bucket = FLAGS.bucket.decode('utf8') - if FLAGS['custom_attributes'].present: - request.custom_attributes = apitools_base.JsonToMessage(messages.Notification.CustomAttributesValue, FLAGS.custom_attributes) - if FLAGS['etag'].present: - request.etag = FLAGS.etag.decode('utf8') - if FLAGS['event_types'].present: - request.event_types = [x.decode('utf8') for x in FLAGS.event_types] - if FLAGS['id'].present: - request.id = FLAGS.id.decode('utf8') - if FLAGS['kind'].present: - request.kind = FLAGS.kind.decode('utf8') - if FLAGS['object_metadata_format'].present: - request.object_metadata_format = FLAGS.object_metadata_format.decode('utf8') - if FLAGS['object_name_prefix'].present: - request.object_name_prefix = FLAGS.object_name_prefix.decode('utf8') - if FLAGS['payload_content'].present: - request.payload_content = FLAGS.payload_content.decode('utf8') - if FLAGS['selfLink'].present: - request.selfLink = FLAGS.selfLink.decode('utf8') - if FLAGS['topic'].present: - request.topic = FLAGS.topic.decode('utf8') - result = client.notifications.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class NotificationsList(apitools_base_cli.NewCmd): - """Command wrapping notifications.List.""" - - usage = """notifications_list """ - - def __init__(self, name, fv): - super(NotificationsList, self).__init__(name, fv) - - def RunWithArgs(self, bucket): - """Retrieves a list of notification subscriptions for a given bucket. - - Args: - bucket: Name of a GCS bucket. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageNotificationsListRequest( - bucket=bucket.decode('utf8'), - ) - result = client.notifications.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectAccessControlsDelete(apitools_base_cli.NewCmd): - """Command wrapping objectAccessControls.Delete.""" - - usage = """objectAccessControls_delete """ - - def __init__(self, name, fv): - super(ObjectAccessControlsDelete, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - - def RunWithArgs(self, bucket, object, entity): - """Permanently deletes the ACL entry for the specified entity on the - specified object. - - Args: - bucket: Name of a bucket. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - entity: The entity holding the permission. Can be user-userId, user- - emailAddress, group-groupId, group-emailAddress, allUsers, or - allAuthenticatedUsers. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectAccessControlsDeleteRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - entity=entity.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - result = client.objectAccessControls.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectAccessControlsGet(apitools_base_cli.NewCmd): - """Command wrapping objectAccessControls.Get.""" - - usage = """objectAccessControls_get """ - - def __init__(self, name, fv): - super(ObjectAccessControlsGet, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - - def RunWithArgs(self, bucket, object, entity): - """Returns the ACL entry for the specified entity on the specified object. - - Args: - bucket: Name of a bucket. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - entity: The entity holding the permission. Can be user-userId, user- - emailAddress, group-groupId, group-emailAddress, allUsers, or - allAuthenticatedUsers. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectAccessControlsGetRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - entity=entity.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - result = client.objectAccessControls.Get( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectAccessControlsInsert(apitools_base_cli.NewCmd): - """Command wrapping objectAccessControls.Insert.""" - - usage = """objectAccessControls_insert """ - - def __init__(self, name, fv): - super(ObjectAccessControlsInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - flags.DEFINE_string( - 'objectAccessControl', - None, - u'A ObjectAccessControl resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, bucket, object): - """Creates a new ACL entry on the specified object. - - Args: - bucket: Name of a bucket. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - objectAccessControl: A ObjectAccessControl resource to be passed as the - request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectAccessControlsInsertRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['objectAccessControl'].present: - request.objectAccessControl = apitools_base.JsonToMessage(messages.ObjectAccessControl, FLAGS.objectAccessControl) - result = client.objectAccessControls.Insert( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectAccessControlsList(apitools_base_cli.NewCmd): - """Command wrapping objectAccessControls.List.""" - - usage = """objectAccessControls_list """ - - def __init__(self, name, fv): - super(ObjectAccessControlsList, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - - def RunWithArgs(self, bucket, object): - """Retrieves ACL entries on the specified object. - - Args: - bucket: Name of a bucket. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectAccessControlsListRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - result = client.objectAccessControls.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectAccessControlsPatch(apitools_base_cli.NewCmd): - """Command wrapping objectAccessControls.Patch.""" - - usage = """objectAccessControls_patch """ - - def __init__(self, name, fv): - super(ObjectAccessControlsPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - flags.DEFINE_string( - 'objectAccessControl', - None, - u'A ObjectAccessControl resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, bucket, object, entity): - """Updates an ACL entry on the specified object. This method supports - patch semantics. - - Args: - bucket: Name of a bucket. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - entity: The entity holding the permission. Can be user-userId, user- - emailAddress, group-groupId, group-emailAddress, allUsers, or - allAuthenticatedUsers. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - objectAccessControl: A ObjectAccessControl resource to be passed as the - request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectAccessControlsPatchRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - entity=entity.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['objectAccessControl'].present: - request.objectAccessControl = apitools_base.JsonToMessage(messages.ObjectAccessControl, FLAGS.objectAccessControl) - result = client.objectAccessControls.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectAccessControlsUpdate(apitools_base_cli.NewCmd): - """Command wrapping objectAccessControls.Update.""" - - usage = """objectAccessControls_update """ - - def __init__(self, name, fv): - super(ObjectAccessControlsUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - flags.DEFINE_string( - 'objectAccessControl', - None, - u'A ObjectAccessControl resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, bucket, object, entity): - """Updates an ACL entry on the specified object. - - Args: - bucket: Name of a bucket. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - entity: The entity holding the permission. Can be user-userId, user- - emailAddress, group-groupId, group-emailAddress, allUsers, or - allAuthenticatedUsers. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - objectAccessControl: A ObjectAccessControl resource to be passed as the - request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectAccessControlsUpdateRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - entity=entity.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['objectAccessControl'].present: - request.objectAccessControl = apitools_base.JsonToMessage(messages.ObjectAccessControl, FLAGS.objectAccessControl) - result = client.objectAccessControls.Update( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsCompose(apitools_base_cli.NewCmd): - """Command wrapping objects.Compose.""" - - usage = """objects_compose """ - - def __init__(self, name, fv): - super(ObjectsCompose, self).__init__(name, fv) - flags.DEFINE_string( - 'composeRequest', - None, - u'A ComposeRequest resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_enum( - 'destinationPredefinedAcl', - u'authenticatedRead', - [u'authenticatedRead', u'bucketOwnerFullControl', u'bucketOwnerRead', u'private', u'projectPrivate', u'publicRead'], - u'Apply a predefined set of access controls to the destination ' - u'object.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'generation matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'download_filename', - '', - 'Filename to use for download.', - flag_values=fv) - flags.DEFINE_boolean( - 'overwrite', - 'False', - 'If True, overwrite the existing file when downloading.', - flag_values=fv) - - def RunWithArgs(self, destinationBucket, destinationObject): - """Concatenates a list of existing objects into a new object in the same - bucket. - - Args: - destinationBucket: Name of the bucket in which to store the new object. - destinationObject: Name of the new object. For information about how to - URL encode object names to be path safe, see Encoding URI Path Parts. - - Flags: - composeRequest: A ComposeRequest resource to be passed as the request - body. - destinationPredefinedAcl: Apply a predefined set of access controls to - the destination object. - ifGenerationMatch: Makes the operation conditional on whether the - object's current generation matches the given value. - ifMetagenerationMatch: Makes the operation conditional on whether the - object's current metageneration matches the given value. - download_filename: Filename to use for download. - overwrite: If True, overwrite the existing file when downloading. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsComposeRequest( - destinationBucket=destinationBucket.decode('utf8'), - destinationObject=destinationObject.decode('utf8'), - ) - if FLAGS['composeRequest'].present: - request.composeRequest = apitools_base.JsonToMessage(messages.ComposeRequest, FLAGS.composeRequest) - if FLAGS['destinationPredefinedAcl'].present: - request.destinationPredefinedAcl = messages.StorageObjectsComposeRequest.DestinationPredefinedAclValueValuesEnum(FLAGS.destinationPredefinedAcl) - if FLAGS['ifGenerationMatch'].present: - request.ifGenerationMatch = int(FLAGS.ifGenerationMatch) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - download = None - if FLAGS.download_filename: - download = apitools_base.Download.FromFile(FLAGS.download_filename, overwrite=FLAGS.overwrite, - progress_callback=apitools_base.DownloadProgressPrinter, - finish_callback=apitools_base.DownloadCompletePrinter) - result = client.objects.Compose( - request, global_params=global_params, download=download) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsCopy(apitools_base_cli.NewCmd): - """Command wrapping objects.Copy.""" - - usage = """objects_copy """ - - def __init__(self, name, fv): - super(ObjectsCopy, self).__init__(name, fv) - flags.DEFINE_enum( - 'destinationPredefinedAcl', - u'authenticatedRead', - [u'authenticatedRead', u'bucketOwnerFullControl', u'bucketOwnerRead', u'private', u'projectPrivate', u'publicRead'], - u'Apply a predefined set of access controls to the destination ' - u'object.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationMatch', - None, - u"Makes the operation conditional on whether the destination object's" - u' current generation matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationNotMatch', - None, - u"Makes the operation conditional on whether the destination object's" - u' current generation does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u"Makes the operation conditional on whether the destination object's" - u' current metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u"Makes the operation conditional on whether the destination object's" - u' current metageneration does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifSourceGenerationMatch', - None, - u"Makes the operation conditional on whether the source object's " - u'generation matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifSourceGenerationNotMatch', - None, - u"Makes the operation conditional on whether the source object's " - u'generation does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifSourceMetagenerationMatch', - None, - u"Makes the operation conditional on whether the source object's " - u'current metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifSourceMetagenerationNotMatch', - None, - u"Makes the operation conditional on whether the source object's " - u'current metageneration does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'object', - None, - u'A Object resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to noAcl, unless the object ' - u'resource specifies the acl property, when it defaults to full.', - flag_values=fv) - flags.DEFINE_string( - 'sourceGeneration', - None, - u'If present, selects a specific revision of the source object (as ' - u'opposed to the latest version, the default).', - flag_values=fv) - flags.DEFINE_string( - 'download_filename', - '', - 'Filename to use for download.', - flag_values=fv) - flags.DEFINE_boolean( - 'overwrite', - 'False', - 'If True, overwrite the existing file when downloading.', - flag_values=fv) - - def RunWithArgs(self, sourceBucket, sourceObject, destinationBucket, destinationObject): - """Copies a source object to a destination object. Optionally overrides - metadata. - - Args: - sourceBucket: Name of the bucket in which to find the source object. - sourceObject: Name of the source object. For information about how to - URL encode object names to be path safe, see Encoding URI Path Parts. - destinationBucket: Name of the bucket in which to store the new object. - Overrides the provided object metadata's bucket value, if any.For - information about how to URL encode object names to be path safe, see - Encoding URI Path Parts. - destinationObject: Name of the new object. Required when the object - metadata is not otherwise provided. Overrides the object metadata's - name value, if any. - - Flags: - destinationPredefinedAcl: Apply a predefined set of access controls to - the destination object. - ifGenerationMatch: Makes the operation conditional on whether the - destination object's current generation matches the given value. - ifGenerationNotMatch: Makes the operation conditional on whether the - destination object's current generation does not match the given - value. - ifMetagenerationMatch: Makes the operation conditional on whether the - destination object's current metageneration matches the given value. - ifMetagenerationNotMatch: Makes the operation conditional on whether the - destination object's current metageneration does not match the given - value. - ifSourceGenerationMatch: Makes the operation conditional on whether the - source object's generation matches the given value. - ifSourceGenerationNotMatch: Makes the operation conditional on whether - the source object's generation does not match the given value. - ifSourceMetagenerationMatch: Makes the operation conditional on whether - the source object's current metageneration matches the given value. - ifSourceMetagenerationNotMatch: Makes the operation conditional on - whether the source object's current metageneration does not match the - given value. - object: A Object resource to be passed as the request body. - projection: Set of properties to return. Defaults to noAcl, unless the - object resource specifies the acl property, when it defaults to full. - sourceGeneration: If present, selects a specific revision of the source - object (as opposed to the latest version, the default). - download_filename: Filename to use for download. - overwrite: If True, overwrite the existing file when downloading. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsCopyRequest( - sourceBucket=sourceBucket.decode('utf8'), - sourceObject=sourceObject.decode('utf8'), - destinationBucket=destinationBucket.decode('utf8'), - destinationObject=destinationObject.decode('utf8'), - ) - if FLAGS['destinationPredefinedAcl'].present: - request.destinationPredefinedAcl = messages.StorageObjectsCopyRequest.DestinationPredefinedAclValueValuesEnum(FLAGS.destinationPredefinedAcl) - if FLAGS['ifGenerationMatch'].present: - request.ifGenerationMatch = int(FLAGS.ifGenerationMatch) - if FLAGS['ifGenerationNotMatch'].present: - request.ifGenerationNotMatch = int(FLAGS.ifGenerationNotMatch) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - if FLAGS['ifSourceGenerationMatch'].present: - request.ifSourceGenerationMatch = int(FLAGS.ifSourceGenerationMatch) - if FLAGS['ifSourceGenerationNotMatch'].present: - request.ifSourceGenerationNotMatch = int(FLAGS.ifSourceGenerationNotMatch) - if FLAGS['ifSourceMetagenerationMatch'].present: - request.ifSourceMetagenerationMatch = int(FLAGS.ifSourceMetagenerationMatch) - if FLAGS['ifSourceMetagenerationNotMatch'].present: - request.ifSourceMetagenerationNotMatch = int(FLAGS.ifSourceMetagenerationNotMatch) - if FLAGS['object'].present: - request.object = apitools_base.JsonToMessage(messages.Object, FLAGS.object) - if FLAGS['projection'].present: - request.projection = messages.StorageObjectsCopyRequest.ProjectionValueValuesEnum(FLAGS.projection) - if FLAGS['sourceGeneration'].present: - request.sourceGeneration = int(FLAGS.sourceGeneration) - download = None - if FLAGS.download_filename: - download = apitools_base.Download.FromFile(FLAGS.download_filename, overwrite=FLAGS.overwrite, - progress_callback=apitools_base.DownloadProgressPrinter, - finish_callback=apitools_base.DownloadCompletePrinter) - result = client.objects.Copy( - request, global_params=global_params, download=download) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsDelete(apitools_base_cli.NewCmd): - """Command wrapping objects.Delete.""" - - usage = """objects_delete """ - - def __init__(self, name, fv): - super(ObjectsDelete, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, permanently deletes a specific revision of this object ' - u'(as opposed to the latest version, the default).', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'generation matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'generation does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration does not match the given value.', - flag_values=fv) - - def RunWithArgs(self, bucket, object): - """Deletes an object and its metadata. Deletions are permanent if - versioning is not enabled for the bucket, or if the generation parameter - is used. - - Args: - bucket: Name of the bucket in which the object resides. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - - Flags: - generation: If present, permanently deletes a specific revision of this - object (as opposed to the latest version, the default). - ifGenerationMatch: Makes the operation conditional on whether the - object's current generation matches the given value. - ifGenerationNotMatch: Makes the operation conditional on whether the - object's current generation does not match the given value. - ifMetagenerationMatch: Makes the operation conditional on whether the - object's current metageneration matches the given value. - ifMetagenerationNotMatch: Makes the operation conditional on whether the - object's current metageneration does not match the given value. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsDeleteRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['ifGenerationMatch'].present: - request.ifGenerationMatch = int(FLAGS.ifGenerationMatch) - if FLAGS['ifGenerationNotMatch'].present: - request.ifGenerationNotMatch = int(FLAGS.ifGenerationNotMatch) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - result = client.objects.Delete( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsGet(apitools_base_cli.NewCmd): - """Command wrapping objects.Get.""" - - usage = """objects_get """ - - def __init__(self, name, fv): - super(ObjectsGet, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationMatch', - None, - u"Makes the operation conditional on whether the object's generation " - u'matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's generation " - u'does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration does not match the given value.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to noAcl.', - flag_values=fv) - flags.DEFINE_string( - 'download_filename', - '', - 'Filename to use for download.', - flag_values=fv) - flags.DEFINE_boolean( - 'overwrite', - 'False', - 'If True, overwrite the existing file when downloading.', - flag_values=fv) - - def RunWithArgs(self, bucket, object): - """Retrieves an object or its metadata. - - Args: - bucket: Name of the bucket in which the object resides. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - ifGenerationMatch: Makes the operation conditional on whether the - object's generation matches the given value. - ifGenerationNotMatch: Makes the operation conditional on whether the - object's generation does not match the given value. - ifMetagenerationMatch: Makes the operation conditional on whether the - object's current metageneration matches the given value. - ifMetagenerationNotMatch: Makes the operation conditional on whether the - object's current metageneration does not match the given value. - projection: Set of properties to return. Defaults to noAcl. - download_filename: Filename to use for download. - overwrite: If True, overwrite the existing file when downloading. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsGetRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['ifGenerationMatch'].present: - request.ifGenerationMatch = int(FLAGS.ifGenerationMatch) - if FLAGS['ifGenerationNotMatch'].present: - request.ifGenerationNotMatch = int(FLAGS.ifGenerationNotMatch) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - if FLAGS['projection'].present: - request.projection = messages.StorageObjectsGetRequest.ProjectionValueValuesEnum(FLAGS.projection) - download = None - if FLAGS.download_filename: - download = apitools_base.Download.FromFile(FLAGS.download_filename, overwrite=FLAGS.overwrite, - progress_callback=apitools_base.DownloadProgressPrinter, - finish_callback=apitools_base.DownloadCompletePrinter) - result = client.objects.Get( - request, global_params=global_params, download=download) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsGetIamPolicy(apitools_base_cli.NewCmd): - """Command wrapping objects.GetIamPolicy.""" - - usage = """objects_getIamPolicy """ - - def __init__(self, name, fv): - super(ObjectsGetIamPolicy, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - - def RunWithArgs(self, bucket, object): - """Returns an IAM policy for the specified object. - - Args: - bucket: Name of the bucket in which the object resides. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsGetIamPolicyRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - result = client.objects.GetIamPolicy( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsInsert(apitools_base_cli.NewCmd): - """Command wrapping objects.Insert.""" - - usage = """objects_insert """ - - def __init__(self, name, fv): - super(ObjectsInsert, self).__init__(name, fv) - flags.DEFINE_string( - 'contentEncoding', - None, - u'If set, sets the contentEncoding property of the final object to ' - u'this value. Setting this parameter is equivalent to setting the ' - u'contentEncoding metadata property. This can be useful when ' - u'uploading an object with uploadType=media to indicate the encoding ' - u'of the content being uploaded.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'generation matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'generation does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'name', - None, - u'Name of the object. Required when the object metadata is not ' - u"otherwise provided. Overrides the object metadata's name value, if " - u'any. For information about how to URL encode object names to be ' - u'path safe, see Encoding URI Path Parts.', - flag_values=fv) - flags.DEFINE_string( - 'object', - None, - u'A Object resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_enum( - 'predefinedAcl', - u'authenticatedRead', - [u'authenticatedRead', u'bucketOwnerFullControl', u'bucketOwnerRead', u'private', u'projectPrivate', u'publicRead'], - u'Apply a predefined set of access controls to this object.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to noAcl, unless the object ' - u'resource specifies the acl property, when it defaults to full.', - flag_values=fv) - flags.DEFINE_string( - 'upload_filename', - '', - 'Filename to use for upload.', - flag_values=fv) - flags.DEFINE_string( - 'upload_mime_type', - '', - 'MIME type to use for the upload. Only needed if the extension on ' - '--upload_filename does not determine the correct (or any) MIME ' - 'type.', - flag_values=fv) - flags.DEFINE_string( - 'download_filename', - '', - 'Filename to use for download.', - flag_values=fv) - flags.DEFINE_boolean( - 'overwrite', - 'False', - 'If True, overwrite the existing file when downloading.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Stores a new object and metadata. - - Args: - bucket: Name of the bucket in which to store the new object. Overrides - the provided object metadata's bucket value, if any. - - Flags: - contentEncoding: If set, sets the contentEncoding property of the final - object to this value. Setting this parameter is equivalent to setting - the contentEncoding metadata property. This can be useful when - uploading an object with uploadType=media to indicate the encoding of - the content being uploaded. - ifGenerationMatch: Makes the operation conditional on whether the - object's current generation matches the given value. - ifGenerationNotMatch: Makes the operation conditional on whether the - object's current generation does not match the given value. - ifMetagenerationMatch: Makes the operation conditional on whether the - object's current metageneration matches the given value. - ifMetagenerationNotMatch: Makes the operation conditional on whether the - object's current metageneration does not match the given value. - name: Name of the object. Required when the object metadata is not - otherwise provided. Overrides the object metadata's name value, if - any. For information about how to URL encode object names to be path - safe, see Encoding URI Path Parts. - object: A Object resource to be passed as the request body. - predefinedAcl: Apply a predefined set of access controls to this object. - projection: Set of properties to return. Defaults to noAcl, unless the - object resource specifies the acl property, when it defaults to full. - upload_filename: Filename to use for upload. - upload_mime_type: MIME type to use for the upload. Only needed if the - extension on --upload_filename does not determine the correct (or any) - MIME type. - download_filename: Filename to use for download. - overwrite: If True, overwrite the existing file when downloading. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsInsertRequest( - bucket=bucket.decode('utf8'), - ) - if FLAGS['contentEncoding'].present: - request.contentEncoding = FLAGS.contentEncoding.decode('utf8') - if FLAGS['ifGenerationMatch'].present: - request.ifGenerationMatch = int(FLAGS.ifGenerationMatch) - if FLAGS['ifGenerationNotMatch'].present: - request.ifGenerationNotMatch = int(FLAGS.ifGenerationNotMatch) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - if FLAGS['name'].present: - request.name = FLAGS.name.decode('utf8') - if FLAGS['object'].present: - request.object = apitools_base.JsonToMessage(messages.Object, FLAGS.object) - if FLAGS['predefinedAcl'].present: - request.predefinedAcl = messages.StorageObjectsInsertRequest.PredefinedAclValueValuesEnum(FLAGS.predefinedAcl) - if FLAGS['projection'].present: - request.projection = messages.StorageObjectsInsertRequest.ProjectionValueValuesEnum(FLAGS.projection) - upload = None - if FLAGS.upload_filename: - upload = apitools_base.Upload.FromFile( - FLAGS.upload_filename, FLAGS.upload_mime_type, - progress_callback=apitools_base.UploadProgressPrinter, - finish_callback=apitools_base.UploadCompletePrinter) - download = None - if FLAGS.download_filename: - download = apitools_base.Download.FromFile(FLAGS.download_filename, overwrite=FLAGS.overwrite, - progress_callback=apitools_base.DownloadProgressPrinter, - finish_callback=apitools_base.DownloadCompletePrinter) - result = client.objects.Insert( - request, global_params=global_params, upload=upload, download=download) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsList(apitools_base_cli.NewCmd): - """Command wrapping objects.List.""" - - usage = """objects_list """ - - def __init__(self, name, fv): - super(ObjectsList, self).__init__(name, fv) - flags.DEFINE_string( - 'delimiter', - None, - u'Returns results in a directory-like mode. items will contain only ' - u'objects whose names, aside from the prefix, do not contain ' - u'delimiter. Objects whose names, aside from the prefix, contain ' - u'delimiter will have their name, truncated after the delimiter, ' - u'returned in prefixes. Duplicate prefixes are omitted.', - flag_values=fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of items plus prefixes to return. As duplicate ' - u'prefixes are omitted, fewer total results may be returned than ' - u'requested. The default value of this parameter is 1,000 items.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'A previously-returned page token representing part of the larger ' - u'set of results to view.', - flag_values=fv) - flags.DEFINE_string( - 'prefix', - None, - u'Filter results to objects whose names begin with this prefix.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to noAcl.', - flag_values=fv) - flags.DEFINE_boolean( - 'versions', - None, - u'If true, lists all versions of an object as distinct results. The ' - u'default is false. For more information, see Object Versioning.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Retrieves a list of objects matching the criteria. - - Args: - bucket: Name of the bucket in which to look for objects. - - Flags: - delimiter: Returns results in a directory-like mode. items will contain - only objects whose names, aside from the prefix, do not contain - delimiter. Objects whose names, aside from the prefix, contain - delimiter will have their name, truncated after the delimiter, - returned in prefixes. Duplicate prefixes are omitted. - maxResults: Maximum number of items plus prefixes to return. As - duplicate prefixes are omitted, fewer total results may be returned - than requested. The default value of this parameter is 1,000 items. - pageToken: A previously-returned page token representing part of the - larger set of results to view. - prefix: Filter results to objects whose names begin with this prefix. - projection: Set of properties to return. Defaults to noAcl. - versions: If true, lists all versions of an object as distinct results. - The default is false. For more information, see Object Versioning. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsListRequest( - bucket=bucket.decode('utf8'), - ) - if FLAGS['delimiter'].present: - request.delimiter = FLAGS.delimiter.decode('utf8') - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['prefix'].present: - request.prefix = FLAGS.prefix.decode('utf8') - if FLAGS['projection'].present: - request.projection = messages.StorageObjectsListRequest.ProjectionValueValuesEnum(FLAGS.projection) - if FLAGS['versions'].present: - request.versions = FLAGS.versions - result = client.objects.List( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsPatch(apitools_base_cli.NewCmd): - """Command wrapping objects.Patch.""" - - usage = """objects_patch """ - - def __init__(self, name, fv): - super(ObjectsPatch, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'generation matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'generation does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'objectResource', - None, - u'A Object resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_enum( - 'predefinedAcl', - u'authenticatedRead', - [u'authenticatedRead', u'bucketOwnerFullControl', u'bucketOwnerRead', u'private', u'projectPrivate', u'publicRead'], - u'Apply a predefined set of access controls to this object.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to full.', - flag_values=fv) - - def RunWithArgs(self, bucket, object): - """Updates an object's metadata. This method supports patch semantics. - - Args: - bucket: Name of the bucket in which the object resides. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - ifGenerationMatch: Makes the operation conditional on whether the - object's current generation matches the given value. - ifGenerationNotMatch: Makes the operation conditional on whether the - object's current generation does not match the given value. - ifMetagenerationMatch: Makes the operation conditional on whether the - object's current metageneration matches the given value. - ifMetagenerationNotMatch: Makes the operation conditional on whether the - object's current metageneration does not match the given value. - objectResource: A Object resource to be passed as the request body. - predefinedAcl: Apply a predefined set of access controls to this object. - projection: Set of properties to return. Defaults to full. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsPatchRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['ifGenerationMatch'].present: - request.ifGenerationMatch = int(FLAGS.ifGenerationMatch) - if FLAGS['ifGenerationNotMatch'].present: - request.ifGenerationNotMatch = int(FLAGS.ifGenerationNotMatch) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - if FLAGS['objectResource'].present: - request.objectResource = apitools_base.JsonToMessage(messages.Object, FLAGS.objectResource) - if FLAGS['predefinedAcl'].present: - request.predefinedAcl = messages.StorageObjectsPatchRequest.PredefinedAclValueValuesEnum(FLAGS.predefinedAcl) - if FLAGS['projection'].present: - request.projection = messages.StorageObjectsPatchRequest.ProjectionValueValuesEnum(FLAGS.projection) - result = client.objects.Patch( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsRewrite(apitools_base_cli.NewCmd): - """Command wrapping objects.Rewrite.""" - - usage = """objects_rewrite """ - - def __init__(self, name, fv): - super(ObjectsRewrite, self).__init__(name, fv) - flags.DEFINE_enum( - 'destinationPredefinedAcl', - u'authenticatedRead', - [u'authenticatedRead', u'bucketOwnerFullControl', u'bucketOwnerRead', u'private', u'projectPrivate', u'publicRead'], - u'Apply a predefined set of access controls to the destination ' - u'object.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationMatch', - None, - u"Makes the operation conditional on whether the destination object's" - u' current generation matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationNotMatch', - None, - u"Makes the operation conditional on whether the destination object's" - u' current generation does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u"Makes the operation conditional on whether the destination object's" - u' current metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u"Makes the operation conditional on whether the destination object's" - u' current metageneration does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifSourceGenerationMatch', - None, - u"Makes the operation conditional on whether the source object's " - u'generation matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifSourceGenerationNotMatch', - None, - u"Makes the operation conditional on whether the source object's " - u'generation does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifSourceMetagenerationMatch', - None, - u"Makes the operation conditional on whether the source object's " - u'current metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifSourceMetagenerationNotMatch', - None, - u"Makes the operation conditional on whether the source object's " - u'current metageneration does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'maxBytesRewrittenPerCall', - None, - u'The maximum number of bytes that will be rewritten per rewrite ' - u"request. Most callers shouldn't need to specify this parameter - it" - u' is primarily in place to support testing. If specified the value ' - u'must be an integral multiple of 1 MiB (1048576). Also, this only ' - u'applies to requests where the source and destination span locations' - u' and/or storage classes. Finally, this value must not change across' - u" rewrite calls else you'll get an error that the rewriteToken is " - u'invalid.', - flag_values=fv) - flags.DEFINE_string( - 'object', - None, - u'A Object resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to noAcl, unless the object ' - u'resource specifies the acl property, when it defaults to full.', - flag_values=fv) - flags.DEFINE_string( - 'rewriteToken', - None, - u'Include this field (from the previous rewrite response) on each ' - u'rewrite request after the first one, until the rewrite response ' - u"'done' flag is true. Calls that provide a rewriteToken can omit all" - u' other request fields, but if included those fields must match the ' - u'values provided in the first rewrite request.', - flag_values=fv) - flags.DEFINE_string( - 'sourceGeneration', - None, - u'If present, selects a specific revision of the source object (as ' - u'opposed to the latest version, the default).', - flag_values=fv) - - def RunWithArgs(self, sourceBucket, sourceObject, destinationBucket, destinationObject): - """Rewrites a source object to a destination object. Optionally overrides - metadata. - - Args: - sourceBucket: Name of the bucket in which to find the source object. - sourceObject: Name of the source object. For information about how to - URL encode object names to be path safe, see Encoding URI Path Parts. - destinationBucket: Name of the bucket in which to store the new object. - Overrides the provided object metadata's bucket value, if any. - destinationObject: Name of the new object. Required when the object - metadata is not otherwise provided. Overrides the object metadata's - name value, if any. For information about how to URL encode object - names to be path safe, see Encoding URI Path Parts. - - Flags: - destinationPredefinedAcl: Apply a predefined set of access controls to - the destination object. - ifGenerationMatch: Makes the operation conditional on whether the - destination object's current generation matches the given value. - ifGenerationNotMatch: Makes the operation conditional on whether the - destination object's current generation does not match the given - value. - ifMetagenerationMatch: Makes the operation conditional on whether the - destination object's current metageneration matches the given value. - ifMetagenerationNotMatch: Makes the operation conditional on whether the - destination object's current metageneration does not match the given - value. - ifSourceGenerationMatch: Makes the operation conditional on whether the - source object's generation matches the given value. - ifSourceGenerationNotMatch: Makes the operation conditional on whether - the source object's generation does not match the given value. - ifSourceMetagenerationMatch: Makes the operation conditional on whether - the source object's current metageneration matches the given value. - ifSourceMetagenerationNotMatch: Makes the operation conditional on - whether the source object's current metageneration does not match the - given value. - maxBytesRewrittenPerCall: The maximum number of bytes that will be - rewritten per rewrite request. Most callers shouldn't need to specify - this parameter - it is primarily in place to support testing. If - specified the value must be an integral multiple of 1 MiB (1048576). - Also, this only applies to requests where the source and destination - span locations and/or storage classes. Finally, this value must not - change across rewrite calls else you'll get an error that the - rewriteToken is invalid. - object: A Object resource to be passed as the request body. - projection: Set of properties to return. Defaults to noAcl, unless the - object resource specifies the acl property, when it defaults to full. - rewriteToken: Include this field (from the previous rewrite response) on - each rewrite request after the first one, until the rewrite response - 'done' flag is true. Calls that provide a rewriteToken can omit all - other request fields, but if included those fields must match the - values provided in the first rewrite request. - sourceGeneration: If present, selects a specific revision of the source - object (as opposed to the latest version, the default). - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsRewriteRequest( - sourceBucket=sourceBucket.decode('utf8'), - sourceObject=sourceObject.decode('utf8'), - destinationBucket=destinationBucket.decode('utf8'), - destinationObject=destinationObject.decode('utf8'), - ) - if FLAGS['destinationPredefinedAcl'].present: - request.destinationPredefinedAcl = messages.StorageObjectsRewriteRequest.DestinationPredefinedAclValueValuesEnum(FLAGS.destinationPredefinedAcl) - if FLAGS['ifGenerationMatch'].present: - request.ifGenerationMatch = int(FLAGS.ifGenerationMatch) - if FLAGS['ifGenerationNotMatch'].present: - request.ifGenerationNotMatch = int(FLAGS.ifGenerationNotMatch) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - if FLAGS['ifSourceGenerationMatch'].present: - request.ifSourceGenerationMatch = int(FLAGS.ifSourceGenerationMatch) - if FLAGS['ifSourceGenerationNotMatch'].present: - request.ifSourceGenerationNotMatch = int(FLAGS.ifSourceGenerationNotMatch) - if FLAGS['ifSourceMetagenerationMatch'].present: - request.ifSourceMetagenerationMatch = int(FLAGS.ifSourceMetagenerationMatch) - if FLAGS['ifSourceMetagenerationNotMatch'].present: - request.ifSourceMetagenerationNotMatch = int(FLAGS.ifSourceMetagenerationNotMatch) - if FLAGS['maxBytesRewrittenPerCall'].present: - request.maxBytesRewrittenPerCall = int(FLAGS.maxBytesRewrittenPerCall) - if FLAGS['object'].present: - request.object = apitools_base.JsonToMessage(messages.Object, FLAGS.object) - if FLAGS['projection'].present: - request.projection = messages.StorageObjectsRewriteRequest.ProjectionValueValuesEnum(FLAGS.projection) - if FLAGS['rewriteToken'].present: - request.rewriteToken = FLAGS.rewriteToken.decode('utf8') - if FLAGS['sourceGeneration'].present: - request.sourceGeneration = int(FLAGS.sourceGeneration) - result = client.objects.Rewrite( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsSetIamPolicy(apitools_base_cli.NewCmd): - """Command wrapping objects.SetIamPolicy.""" - - usage = """objects_setIamPolicy """ - - def __init__(self, name, fv): - super(ObjectsSetIamPolicy, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - flags.DEFINE_string( - 'policy', - None, - u'A Policy resource to be passed as the request body.', - flag_values=fv) - - def RunWithArgs(self, bucket, object): - """Updates an IAM policy for the specified object. - - Args: - bucket: Name of the bucket in which the object resides. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - policy: A Policy resource to be passed as the request body. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsSetIamPolicyRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['policy'].present: - request.policy = apitools_base.JsonToMessage(messages.Policy, FLAGS.policy) - result = client.objects.SetIamPolicy( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsTestIamPermissions(apitools_base_cli.NewCmd): - """Command wrapping objects.TestIamPermissions.""" - - usage = """objects_testIamPermissions """ - - def __init__(self, name, fv): - super(ObjectsTestIamPermissions, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - - def RunWithArgs(self, bucket, object, permissions): - """Tests a set of permissions on the given object to see which, if any, - are held by the caller. - - Args: - bucket: Name of the bucket in which the object resides. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - permissions: Permissions to test. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsTestIamPermissionsRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - permissions=permissions.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - result = client.objects.TestIamPermissions( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsUpdate(apitools_base_cli.NewCmd): - """Command wrapping objects.Update.""" - - usage = """objects_update """ - - def __init__(self, name, fv): - super(ObjectsUpdate, self).__init__(name, fv) - flags.DEFINE_string( - 'generation', - None, - u'If present, selects a specific revision of this object (as opposed ' - u'to the latest version, the default).', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'generation matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifGenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'generation does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration matches the given value.', - flag_values=fv) - flags.DEFINE_string( - 'ifMetagenerationNotMatch', - None, - u"Makes the operation conditional on whether the object's current " - u'metageneration does not match the given value.', - flag_values=fv) - flags.DEFINE_string( - 'objectResource', - None, - u'A Object resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_enum( - 'predefinedAcl', - u'authenticatedRead', - [u'authenticatedRead', u'bucketOwnerFullControl', u'bucketOwnerRead', u'private', u'projectPrivate', u'publicRead'], - u'Apply a predefined set of access controls to this object.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to full.', - flag_values=fv) - flags.DEFINE_string( - 'download_filename', - '', - 'Filename to use for download.', - flag_values=fv) - flags.DEFINE_boolean( - 'overwrite', - 'False', - 'If True, overwrite the existing file when downloading.', - flag_values=fv) - - def RunWithArgs(self, bucket, object): - """Updates an object's metadata. - - Args: - bucket: Name of the bucket in which the object resides. - object: Name of the object. For information about how to URL encode - object names to be path safe, see Encoding URI Path Parts. - - Flags: - generation: If present, selects a specific revision of this object (as - opposed to the latest version, the default). - ifGenerationMatch: Makes the operation conditional on whether the - object's current generation matches the given value. - ifGenerationNotMatch: Makes the operation conditional on whether the - object's current generation does not match the given value. - ifMetagenerationMatch: Makes the operation conditional on whether the - object's current metageneration matches the given value. - ifMetagenerationNotMatch: Makes the operation conditional on whether the - object's current metageneration does not match the given value. - objectResource: A Object resource to be passed as the request body. - predefinedAcl: Apply a predefined set of access controls to this object. - projection: Set of properties to return. Defaults to full. - download_filename: Filename to use for download. - overwrite: If True, overwrite the existing file when downloading. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsUpdateRequest( - bucket=bucket.decode('utf8'), - object=object.decode('utf8'), - ) - if FLAGS['generation'].present: - request.generation = int(FLAGS.generation) - if FLAGS['ifGenerationMatch'].present: - request.ifGenerationMatch = int(FLAGS.ifGenerationMatch) - if FLAGS['ifGenerationNotMatch'].present: - request.ifGenerationNotMatch = int(FLAGS.ifGenerationNotMatch) - if FLAGS['ifMetagenerationMatch'].present: - request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch) - if FLAGS['ifMetagenerationNotMatch'].present: - request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch) - if FLAGS['objectResource'].present: - request.objectResource = apitools_base.JsonToMessage(messages.Object, FLAGS.objectResource) - if FLAGS['predefinedAcl'].present: - request.predefinedAcl = messages.StorageObjectsUpdateRequest.PredefinedAclValueValuesEnum(FLAGS.predefinedAcl) - if FLAGS['projection'].present: - request.projection = messages.StorageObjectsUpdateRequest.ProjectionValueValuesEnum(FLAGS.projection) - download = None - if FLAGS.download_filename: - download = apitools_base.Download.FromFile(FLAGS.download_filename, overwrite=FLAGS.overwrite, - progress_callback=apitools_base.DownloadProgressPrinter, - finish_callback=apitools_base.DownloadCompletePrinter) - result = client.objects.Update( - request, global_params=global_params, download=download) - print apitools_base_cli.FormatOutput(result) - - -class ObjectsWatchAll(apitools_base_cli.NewCmd): - """Command wrapping objects.WatchAll.""" - - usage = """objects_watchAll """ - - def __init__(self, name, fv): - super(ObjectsWatchAll, self).__init__(name, fv) - flags.DEFINE_string( - 'channel', - None, - u'A Channel resource to be passed as the request body.', - flag_values=fv) - flags.DEFINE_string( - 'delimiter', - None, - u'Returns results in a directory-like mode. items will contain only ' - u'objects whose names, aside from the prefix, do not contain ' - u'delimiter. Objects whose names, aside from the prefix, contain ' - u'delimiter will have their name, truncated after the delimiter, ' - u'returned in prefixes. Duplicate prefixes are omitted.', - flag_values=fv) - flags.DEFINE_integer( - 'maxResults', - None, - u'Maximum number of items plus prefixes to return. As duplicate ' - u'prefixes are omitted, fewer total results may be returned than ' - u'requested. The default value of this parameter is 1,000 items.', - flag_values=fv) - flags.DEFINE_string( - 'pageToken', - None, - u'A previously-returned page token representing part of the larger ' - u'set of results to view.', - flag_values=fv) - flags.DEFINE_string( - 'prefix', - None, - u'Filter results to objects whose names begin with this prefix.', - flag_values=fv) - flags.DEFINE_enum( - 'projection', - u'full', - [u'full', u'noAcl'], - u'Set of properties to return. Defaults to noAcl.', - flag_values=fv) - flags.DEFINE_boolean( - 'versions', - None, - u'If true, lists all versions of an object as distinct results. The ' - u'default is false. For more information, see Object Versioning.', - flag_values=fv) - - def RunWithArgs(self, bucket): - """Watch for changes on all objects in a bucket. - - Args: - bucket: Name of the bucket in which to look for objects. - - Flags: - channel: A Channel resource to be passed as the request body. - delimiter: Returns results in a directory-like mode. items will contain - only objects whose names, aside from the prefix, do not contain - delimiter. Objects whose names, aside from the prefix, contain - delimiter will have their name, truncated after the delimiter, - returned in prefixes. Duplicate prefixes are omitted. - maxResults: Maximum number of items plus prefixes to return. As - duplicate prefixes are omitted, fewer total results may be returned - than requested. The default value of this parameter is 1,000 items. - pageToken: A previously-returned page token representing part of the - larger set of results to view. - prefix: Filter results to objects whose names begin with this prefix. - projection: Set of properties to return. Defaults to noAcl. - versions: If true, lists all versions of an object as distinct results. - The default is false. For more information, see Object Versioning. - """ - client = GetClientFromFlags() - global_params = GetGlobalParamsFromFlags() - request = messages.StorageObjectsWatchAllRequest( - bucket=bucket.decode('utf8'), - ) - if FLAGS['channel'].present: - request.channel = apitools_base.JsonToMessage(messages.Channel, FLAGS.channel) - if FLAGS['delimiter'].present: - request.delimiter = FLAGS.delimiter.decode('utf8') - if FLAGS['maxResults'].present: - request.maxResults = FLAGS.maxResults - if FLAGS['pageToken'].present: - request.pageToken = FLAGS.pageToken.decode('utf8') - if FLAGS['prefix'].present: - request.prefix = FLAGS.prefix.decode('utf8') - if FLAGS['projection'].present: - request.projection = messages.StorageObjectsWatchAllRequest.ProjectionValueValuesEnum(FLAGS.projection) - if FLAGS['versions'].present: - request.versions = FLAGS.versions - result = client.objects.WatchAll( - request, global_params=global_params) - print apitools_base_cli.FormatOutput(result) - - -def main(_): - appcommands.AddCmd('pyshell', PyShell) - appcommands.AddCmd('bucketAccessControls_delete', BucketAccessControlsDelete) - appcommands.AddCmd('bucketAccessControls_get', BucketAccessControlsGet) - appcommands.AddCmd('bucketAccessControls_insert', BucketAccessControlsInsert) - appcommands.AddCmd('bucketAccessControls_list', BucketAccessControlsList) - appcommands.AddCmd('bucketAccessControls_patch', BucketAccessControlsPatch) - appcommands.AddCmd('bucketAccessControls_update', BucketAccessControlsUpdate) - appcommands.AddCmd('buckets_delete', BucketsDelete) - appcommands.AddCmd('buckets_get', BucketsGet) - appcommands.AddCmd('buckets_getIamPolicy', BucketsGetIamPolicy) - appcommands.AddCmd('buckets_insert', BucketsInsert) - appcommands.AddCmd('buckets_list', BucketsList) - appcommands.AddCmd('buckets_patch', BucketsPatch) - appcommands.AddCmd('buckets_setIamPolicy', BucketsSetIamPolicy) - appcommands.AddCmd('buckets_testIamPermissions', BucketsTestIamPermissions) - appcommands.AddCmd('buckets_update', BucketsUpdate) - appcommands.AddCmd('channels_stop', ChannelsStop) - appcommands.AddCmd('defaultObjectAccessControls_delete', DefaultObjectAccessControlsDelete) - appcommands.AddCmd('defaultObjectAccessControls_get', DefaultObjectAccessControlsGet) - appcommands.AddCmd('defaultObjectAccessControls_insert', DefaultObjectAccessControlsInsert) - appcommands.AddCmd('defaultObjectAccessControls_list', DefaultObjectAccessControlsList) - appcommands.AddCmd('defaultObjectAccessControls_patch', DefaultObjectAccessControlsPatch) - appcommands.AddCmd('defaultObjectAccessControls_update', DefaultObjectAccessControlsUpdate) - appcommands.AddCmd('notifications_delete', NotificationsDelete) - appcommands.AddCmd('notifications_get', NotificationsGet) - appcommands.AddCmd('notifications_insert', NotificationsInsert) - appcommands.AddCmd('notifications_list', NotificationsList) - appcommands.AddCmd('objectAccessControls_delete', ObjectAccessControlsDelete) - appcommands.AddCmd('objectAccessControls_get', ObjectAccessControlsGet) - appcommands.AddCmd('objectAccessControls_insert', ObjectAccessControlsInsert) - appcommands.AddCmd('objectAccessControls_list', ObjectAccessControlsList) - appcommands.AddCmd('objectAccessControls_patch', ObjectAccessControlsPatch) - appcommands.AddCmd('objectAccessControls_update', ObjectAccessControlsUpdate) - appcommands.AddCmd('objects_compose', ObjectsCompose) - appcommands.AddCmd('objects_copy', ObjectsCopy) - appcommands.AddCmd('objects_delete', ObjectsDelete) - appcommands.AddCmd('objects_get', ObjectsGet) - appcommands.AddCmd('objects_getIamPolicy', ObjectsGetIamPolicy) - appcommands.AddCmd('objects_insert', ObjectsInsert) - appcommands.AddCmd('objects_list', ObjectsList) - appcommands.AddCmd('objects_patch', ObjectsPatch) - appcommands.AddCmd('objects_rewrite', ObjectsRewrite) - appcommands.AddCmd('objects_setIamPolicy', ObjectsSetIamPolicy) - appcommands.AddCmd('objects_testIamPermissions', ObjectsTestIamPermissions) - appcommands.AddCmd('objects_update', ObjectsUpdate) - appcommands.AddCmd('objects_watchAll', ObjectsWatchAll) - - apitools_base_cli.SetupLogger() - if hasattr(appcommands, 'SetDefaultCommand'): - appcommands.SetDefaultCommand('pyshell') - - -run_main = apitools_base_cli.run_main - -if __name__ == '__main__': - appcommands.Run() diff --git a/samples/uptodate_check_test.py b/samples/uptodate_check_test.py index 6fbea9c0..ec262a44 100644 --- a/samples/uptodate_check_test.py +++ b/samples/uptodate_check_test.py @@ -45,7 +45,6 @@ def _CheckGeneratedFiles(self, api_name, api_version): with test_utils.TempDir() as tmp_dir_path: gen_client.main([ gen_client.__file__, - '--generate_cli', '--init-file', 'empty', '--infile', GetSampleClientPath(api_name, prefix + '.json'), @@ -56,7 +55,6 @@ def _CheckGeneratedFiles(self, api_name, api_version): 'client' ]) expected_files = ( - set([prefix + '.py']) | # CLI files set([prefix + '_client.py', prefix + '_messages.py', '__init__.py'])) diff --git a/setup.py b/setup.py index c0ab0b84..88ab29a1 100644 --- a/setup.py +++ b/setup.py @@ -35,12 +35,10 @@ ] CLI_PACKAGES = [ - 'google-apputils>=0.4.0', - 'python-gflags==3.0.6', # Starting version 3.0.7 py26 is not supported. + 'python-gflags>=3.0.6', ] TESTING_PACKAGES = [ - 'google-apputils>=0.4.0', 'unittest2>=0.5.1', 'mock>=1.0.1', ] @@ -51,9 +49,6 @@ py_version = platform.python_version() -if py_version < '2.7': - REQUIRED_PACKAGES.append('argparse>=1.2.1') - _APITOOLS_VERSION = '0.5.22' with open('README.rst') as fileobj: diff --git a/tox.ini b/tox.ini index c81e32ab..dfee48bc 100644 --- a/tox.ini +++ b/tox.ini @@ -9,7 +9,7 @@ envlist = [testenv] deps = nose - python-gflags==3.0.6 + python-gflags oauth2client1: oauth2client<1.5dev oauth2client2: oauth2client>=2,<=3dev oauth2client3: oauth2client>=3,<=4dev @@ -36,8 +36,7 @@ basepython = commands = nosetests --with-xunit --with-xcoverage --cover-package=apitools --nocapture --cover-erase --cover-tests --cover-branches [] deps = - google-apputils - python-gflags==3.0.6 + python-gflags mock nose unittest2 From d475ca9112baa451da2ba9fb8712e88bf260f4f0 Mon Sep 17 00:00:00 2001 From: Craig Citro Date: Wed, 28 Mar 2018 23:11:59 -0700 Subject: [PATCH 2/2] Ensure client generation works smoothly in py3. It turns out that generated clients had a few issues in python3: * the discovery doc was returned as bytes, but `json.loads` wanted a string * in python3, source files should be strings, not bytes * \N, \u, and \U have special interpretations in python3 strings, which makes them invalid bare sequences in a docstring. This commit updates these and re-enables tests for python3. The only remaining py2-only check is the "did we generate the exact same source file" check, which fails for trivial reasons (eg u'foo' vs. 'foo') for python3. Since there are no more python27-only tests, I removed the "disable test in 2.7" helper. --- apitools/gen/client_generation_test.py | 10 ++++++---- apitools/gen/gen_client_test.py | 1 - apitools/gen/test_utils.py | 5 +---- apitools/gen/util.py | 13 +++++++++++-- samples/uptodate_check_test.py | 6 +++++- 5 files changed, 23 insertions(+), 12 deletions(-) diff --git a/apitools/gen/client_generation_test.py b/apitools/gen/client_generation_test.py index 8a2f8e87..91465014 100644 --- a/apitools/gen/client_generation_test.py +++ b/apitools/gen/client_generation_test.py @@ -18,15 +18,18 @@ import importlib import logging import os +import six import subprocess import sys import tempfile -import unittest2 - from apitools.gen import gen_client from apitools.gen import test_utils +if six.PY2: + import unittest2 as unittest +else: + import unittest _API_LIST = [ 'bigquery.v2', @@ -36,14 +39,13 @@ ] -class ClientGenerationTest(unittest2.TestCase): +class ClientGenerationTest(unittest.TestCase): def setUp(self): super(ClientGenerationTest, self).setUp() self.gen_client_binary = 'gen_client' @test_utils.SkipOnWindows - @test_utils.RunOnlyOnPython27 def testGeneration(self): for api in _API_LIST: with test_utils.TempDir(change_to=True): diff --git a/apitools/gen/gen_client_test.py b/apitools/gen/gen_client_test.py index a0dbc9e4..6c4e9b10 100644 --- a/apitools/gen/gen_client_test.py +++ b/apitools/gen/gen_client_test.py @@ -32,7 +32,6 @@ def _GetContent(file_path): return f.read() -@test_utils.RunOnlyOnPython27 class ClientGenCliTest(unittest2.TestCase): def testHelp_NotEnoughArguments(self): diff --git a/apitools/gen/test_utils.py b/apitools/gen/test_utils.py index 59eea51c..484dcbc0 100644 --- a/apitools/gen/test_utils.py +++ b/apitools/gen/test_utils.py @@ -17,17 +17,14 @@ import contextlib import os -import tempfile import shutil import sys +import tempfile import six import unittest2 -RunOnlyOnPython27 = unittest2.skipUnless( - sys.version_info[:2] == (2, 7), 'Only runs in Python 2.7') - SkipOnWindows = unittest2.skipIf( os.name == 'nt', 'Does not run on windows') diff --git a/apitools/gen/util.py b/apitools/gen/util.py index 312885f0..caf08542 100644 --- a/apitools/gen/util.py +++ b/apitools/gen/util.py @@ -255,6 +255,11 @@ def CleanDescription(description): """Return a version of description safe for printing in a docstring.""" if not isinstance(description, six.string_types): return description + if six.PY3: + # https://docs.python.org/3/reference/lexical_analysis.html#index-18 + description = description.replace('\\N', '\\\\N') + description = description.replace('\\u', '\\\\u') + description = description.replace('\\U', '\\\\U') return description.replace('"""', '" " "') @@ -298,7 +303,8 @@ def __call__(self, *args): line = (args[0] % args[1:]).rstrip() else: line = args[0].rstrip() - line = line.encode('ascii', 'backslashreplace') + if six.PY2: + line = line.encode('ascii', 'backslashreplace') print('%s%s' % (self.__indent, line), file=self.__out) else: print('', file=self.__out) @@ -327,7 +333,10 @@ def FetchDiscoveryDoc(discovery_url, retries=5): for url in discovery_urls: for _ in range(retries): try: - discovery_doc = json.loads(urllib_request.urlopen(url).read()) + content = urllib_request.urlopen(url).read() + if isinstance(content, bytes): + content = content.decode('utf8') + discovery_doc = json.loads(content) break except (urllib_error.HTTPError, urllib_error.URLError) as e: logging.info( diff --git a/samples/uptodate_check_test.py b/samples/uptodate_check_test.py index ec262a44..3871695c 100644 --- a/samples/uptodate_check_test.py +++ b/samples/uptodate_check_test.py @@ -15,6 +15,7 @@ import os import difflib +import six import unittest2 from apitools.gen import gen_client @@ -30,7 +31,6 @@ def _GetContent(file_path): return f.read() -@test_utils.RunOnlyOnPython27 class ClientGenCliTest(unittest2.TestCase): def AssertDiffEqual(self, expected, actual): @@ -59,6 +59,10 @@ def _CheckGeneratedFiles(self, api_name, api_version): prefix + '_messages.py', '__init__.py'])) self.assertEquals(expected_files, set(os.listdir(tmp_dir_path))) + if six.PY3: + # The source files won't be identical under python3, + # so we exit early. + return for expected_file in expected_files: self.AssertDiffEqual( _GetContent(GetSampleClientPath(