def ToClassName(self, s, element, element_type=None): """Convert a discovery name to a suitable C++ class name. In C++, nested class names cannot share the same name as the outer class name. Overrides the default. Args: s: (str) A rosy name of data element. element: (object) The object we need a class name for. element_type: (str) The kind of object we need a class name for. Returns: A name suitable for use as a class in the generator's target language. """ s = utilities.CamelCase(s) if s in CppLanguageModel.RESERVED_CLASS_NAMES: s = '%s%s' % (utilities.CamelCase(self.values['name']), s) decorator = '' if isinstance(element, api.Method): resource = element.parent while isinstance(resource, api.Resource): s = '%s_%s' % (resource.values['className'], s) resource = resource.parent decorator = 'Method' elif isinstance(element, api.Resource): decorator = 'Resource' elif isinstance(element, api.Api): if not s.endswith('Service'): decorator = 'Service' else: return s return '%s%s' % (s, decorator)
def ToClassName(self, s, element_type=None): """Convert a discovery name to a suitable Java class name. In Java, nested class names cannot share the same name as the outer class name. Overrides the default. Args: s: (str) A rosy name of data element. element_type: (str) The kind of object we need a class name for. Returns: A name suitable for use as a class in the generator's target language. """ if s.lower() in JavaLanguageModel.RESERVED_CLASS_NAMES: # Prepend the service name return '%s%s' % (utilities.CamelCase( self.values['name']), utilities.CamelCase(s)) name = utilities.CamelCase(s) if name == self.values.get('className'): if 'resource' == element_type: name += 'Operations' elif 'method' == element_type: name += 'Operation' return name
def ToClassName(self, s, element, element_type=None): """Convert a discovery name to a suitable Java class name. In Java, nested class names cannot share the same name as the outer class name. Overrides the default. Args: s: (str) A rosy name of data element. element: (object) The object we need a class name for. element_type: (str) The kind of object we need a class name for. Returns: A name suitable for use as a class in the generator's target language. """ # Camelcase what we have and account for spaces in canonical names name = utilities.CamelCase(s).replace(' ', '') if name.lower() in JavaLanguageModel.RESERVED_CLASS_NAMES: # Prepend the service name service = self._class_name or utilities.CamelCase( self.values['name']) return service + name if name == self.values.get('className'): if 'resource' == element_type: name += 'Operations' elif 'method' == element_type: name += 'Operation' return name
def ToSafeClassName(self, s, the_api, parent=None): """Convert a name to a suitable class name in Java. Subclasses should override as appropriate. Args: s: (str) A canonical name for data element. (Usually the API wire format) the_api: (Api) The API this element is part of. For use as a hint when the name cannot be used directly. parent: (schema) The parent we use to get a safe class name. Returns: A name suitable for use as an element in Java. """ safe_class_name = utilities.CamelCase(s) if parent: for ancestor in parent.full_path: if ancestor.safeClassName == safe_class_name: safe_class_name = '%s%s' % (parent.class_name, safe_class_name) if safe_class_name.lower() in JavaLanguageModel.RESERVED_CLASS_NAMES: api_name = utilities.CamelCase(the_api.values['name']) if utilities.CamelCase(the_api.values['canonicalName']): # Use canonical name if specified. api_name = utilities.CamelCase( the_api.values['canonicalName']).replace(' ', '') # Prepend the API name safe_class_name = '%s%s' % (api_name, utilities.CamelCase(s)) return safe_class_name
def ToMemberName(self, s, the_api): """CamelCase a wire format name into a suitable Go variable name.""" if s.lower() in GoLanguageModel.RESERVED_NAMES: # Prepend the service name return '%s%s' % (utilities.CamelCase(the_api.values['name']), utilities.CamelCase(s)) return utilities.CamelCase(s)
def ToClassName(self, s, element_type=None): """Convert a discovery name to a suitable PHP class name. Overrides the default. Args: s: (string) The wire format name of a class. element_type: (string) The kind of object we need a class name for. Returns: A name suitable for use as a class in PHP. """ if s.lower() in PhpLanguageModel.RESERVED_CLASS_NAMES: # Prepend the service name. return utilities.CamelCase( self.values['name']) + utilities.CamelCase(s) return utilities.CamelCase(s)
def NestedClassNameForProperty(self, name, schema): """Returns the class name of an object nested in a property.""" # TODO(user): This functionality belongs in the language model, but # because of the way the api is bootstrapped, that isn't available when we # need it. When language model is available from the start, this should be # moved. return '%s%s' % (schema.class_name, utilities.CamelCase(name))
def _GetTypeInfo(self, def_dict): """Returns a tuple of type information for a json schema data dict. For the dictionary containing {type, [format]}, return the tuple of the form (Java class name, ImportDefinition, Java primitive data type) describing the appropriate Java data type. Args: def_dict: (dict) JSON schema data definition. Returns: tuple of (class name, ImportDefinition, primitive data type). """ json_type = def_dict.get('type', 'string') json_format = def_dict.get('format') result = self.type_map.get((json_type, json_format)) if result: return result # TODO(user): Uncomment this and update golden files. # result = self.type_map.get((json_type, None)) # if result: # return result # # raise ValueError('Unknown type: %s format: %s' % (json_type, json_format)) return (utilities.CamelCase(json_type), None, None)
def ToMemberName(self, s, the_api): """CamelCase a wire format name into a suitable Java variable name.""" camel_s = utilities.CamelCase(s) if s.lower() in JavaLanguageModel.RESERVED_CLASS_NAMES: # Prepend the service name return '%s%s' % (the_api.values['name'], camel_s) return camel_s[0].lower() + camel_s[1:]
def ToMemberName(self, s, unused_the_api): """CamelCase a wire format name into a suitable Dart variable name.""" candidate = utilities.CamelCase(s) candidate = candidate[0].lower() + candidate[1:] while candidate in self.RESERVED_CLASS_NAMES: candidate += '_' return candidate
def ToMemberName(self, s, unused_api): """Convert a wire format name into a suitable ObjC variable name.""" camel_s = utilities.CamelCase(s) ret = camel_s[0].lower() + camel_s[1:] if s.lower() in ObjCLanguageModel.RESERVED_MEMBER_NAMES: ret = '%sProperty' % ret return ret
def AnnotateMethod(self, the_api, method, unused_rsrc): """Override the default.""" super(CppGenerator, self).AnnotateMethod(the_api, method, unused_rsrc) import_manager = cpp_import_manager.CppImportManager.ForElement( the_api) request_type = method.values.get('requestType') response_type = method.values.get('responseType') if request_type: self._HandleImports(request_type, import_manager) if method.values.get('mediaUpload'): media_upload_h = '"googleapis/client/service/media_uploader.h"' import_manager.AddImport(media_upload_h) if response_type != the_api.void_type: request_pager_h = '"googleapis/client/service/service_request_pager.h"' self._HandleImports(method.values['responseType'], import_manager) if (method.values.get('isPageable') and method.values['isPagingStyleStandard']): import_manager.AddImport(request_pager_h) method.SetTemplateValue( 'undecoratedClassName', '%sMethod' % utilities.CamelCase(method.values['wireName'])) self.AnnotateDocumentation(method)
def ToClassName(self, s, element, element_type=None): """Convert a discovery name to a suitable C# class name. Overrides the default. Args: s: (str) A rosy name of data element. element: (object) The object we need a class name for. element_type: (str) The kind of element (resource|method) to name. Returns: A name suitable for use as a class in the generator's target language. """ if s in CSharpLanguageModel.RESERVED_CLASS_NAMES: # Prepend the service name return '%s%s' % (utilities.CamelCase(self.values['name']), utilities.CamelCase(s)) return '.'.join([utilities.CamelCase(x) for x in s.split('.')])
def render(self, context): # pylint: disable=g-bad-name try: text = django_template.resolve_variable(self._variable_name, context) if text: return utilities.CamelCase(text) except django_template.base.VariableDoesNotExist: pass return ''
def ToClassName(self, s, element_type=None): # pylint: disable-msg=W0613 """Convert a discovery name to a suitable C# class name. Overrides the default. Args: s: (str) A rosy name of data element. element_type: (str) The kind of element (resource|method) to name. Returns: A name suitable for use as a class in the generator's target language. """ if s.lower() in CSharpLanguageModel.RESERVED_CLASS_NAMES: # Prepend the service name return '%s%s' % (utilities.CamelCase( self.values['name']), utilities.CamelCase(s)) return utilities.CamelCase(s)
def testCamelCase(self): """Basic CamelCase functionality.""" self.assertEquals('HelloWorld', utilities.CamelCase('hello_world')) self.assertEquals('HelloWorld', utilities.CamelCase('hello-world')) self.assertEquals('HelloWorld', utilities.CamelCase('helloWorld')) self.assertEquals('HelloWorld', utilities.CamelCase('Hello_world')) self.assertEquals('HelloWorld', utilities.CamelCase('_hello_world')) self.assertEquals('HelloWorld', utilities.CamelCase('helloWorld')) self.assertEquals('HelloWorld', utilities.CamelCase('hello.world')) self.assertEquals('HELLOWORLD', utilities.CamelCase('HELLO_WORLD'))
def ToSafeClassName(self, name, the_api, parent): # pylint:disable=unused-argument # Retrieve the object in question. if parent: for child in parent.children: if child.get('wireName') == name: return child.className.split('.')[-1] # Fall through if it cannot be found if parent: name += '_data' return utilities.CamelCase(name)
def NestedClassNameForProperty(self, name, owning_schema): # Nested classes are only used within the class that contains # them, so it's fine to just return the class name as a simple-name, # without any qualification. We detect collisions with the parent # name, but that's the only use of the parent name. parent_name = owning_schema.class_name.split('.')[-1] class_name = utilities.CamelCase(name) + 'Data' if parent_name == class_name: class_name += 'Schema' return class_name
def ToClassName(self, s, element_type=None): # pylint: disable-msg=W0613 """Convert a discovery name to a suitable Go type name. Overrides the default. Args: s: (str) A rosy name of data element. element_type: (str) The kind of object we need a class name for. Returns: A name suitable for use as a class in the generator's target language. """ if s.lower() in GoLanguageModel.RESERVED_NAMES: class_name = '%s%s' % (utilities.CamelCase(self.values['name']), utilities.CamelCase(s)) else: class_name = utilities.CamelCase(s) if element_type == 'resource': class_name = '%sResource' % class_name return class_name
def ToPropertyGetterMethodWithDelim(self, prop_name): """Convert a property name to the name of the getter method that returns it. Args: prop_name: (str) The name of a property. Returns: A Java specific name of the getter method that returns the specified property. Eg: returns .getXyz for a property called xyz. """ return '%sget%s()' % (self._class_name_delimiter, utilities.CamelCase(prop_name))
def ToClassName(self, s, element_type=None): """Convert a discovery name to a suitable ObjC class name. Overrides the default. Args: s: (str) A rosy name of data element. element_type: (str) The kind of element to name. Returns: A name suitable for use as a class in the generator's target language. """ if ((s.lower() in ObjCLanguageModel.RESERVED_CLASS_NAMES) or (element_type == 'schema')): # Prepend the service name s = '%s%s' % (utilities.CamelCase( self.values['name']), utilities.CamelCase(s)) else: s = utilities.CamelCase(s) if not s.startswith('GTL'): return 'GTL' + s return s
def __init__(self, discovery, options=dict()): super(GoGenerator, self).__init__(GoApi, discovery, language='go', language_model=GoLanguageModel(), options=options) # Main class name is package (and file) name in Go. Make it lower character self._api.values['className'] = self._api.values['className'].lower() # Annotate resources with field name for resource in self._api.values['resources']: resource.values['accessorName'] = utilities.CamelCase( resource.values['wireName'])
def ToSafeClassName(self, s, api): # pylint: disable-msg=W0613 """Convert a name to a suitable class name in the target language. Subclasses should override as appropriate. Args: s: (str) A canonical name for data element. (Usually the API wire format) api: (Api) The API this element is part of. For use as a hint when the name cannot be used directly. Returns: A name suitable for use as an element in the generator's target language. """ return utilities.CamelCase(s)
def ToClassName(self, s, element_type=None): # pylint: disable-msg=W0613 """Convert a name to a suitable member name in the target language. This default implementation camel cases the string, which is appropriate for Java and C++. Subclasses may override as appropriate. Args: s: (str) A rosy name of data element. element_type: (str) The kind of object we are making a class name for. E.g. resource, method, schema. Returns: A name suitable for use as a class in the generator's target language. """ return utilities.CamelCase(s)
def __init__(self, api, schema, name, def_dict): """Construct a Property. A Property requires several elements in its template value dictionary which all computed here: wireName: the string which labels this Property in the wire protocol dataType: the DataType of this property Args: api: (Api) The Api which owns this Property schema: (Schema) the schema this Property is part of name: (string) the name for this Property def_dict: (dict) the JSON schema dictionary Raises: ApiException: If we have an array type without object definitions. """ super(Property, self).__init__(def_dict, api) self.ValidateName(name) self.requires_imports = [] self.schema = schema self.SetTemplateValue('wireName', name) # If the schema value for this property defines a new object directly, # rather than refering to another schema, we will have to create a class # name for it. We create a unique name by prepending the schema we are # in to the object name. tentative_class_name = '%s%s' % (schema.class_name, utilities.CamelCase(name)) if '$ref' in self.values: element_type = 'object' self.SetTemplateValue('type', 'object') else: element_type = self.values.get('type', 'string') self.format_type = self.values.get('format') self.object_type = None self.requires_imports = [] if element_type == 'array': self._data_type = api.DataTypeFromJson(def_dict, tentative_class_name, parent=schema, wire_name=name) elif element_type == 'object': self._data_type = api.DataTypeFromJson(def_dict, tentative_class_name, parent=schema, wire_name=name) else: self._data_type = data_types.BuiltInDataType(def_dict, api, parent=schema)
def ToClassName(self, s, element, element_type=None): """Convert a discovery name to a suitable ObjC class name. Overrides the default. Args: s: (str) A rosy name of data element. element: (object) The object we need a class name for. element_type: (str) The kind of element to name. Returns: A name suitable for use as a class in the generator's target language. """ if ((s.lower() in ObjCLanguageModel.RESERVED_CLASS_NAMES) or isinstance(element, api.Schema)): # Prepend the service name name = self.values['canonicalName'] s = '%s%s' % (utilities.CamelCase(name).replace( ' ', ''), utilities.CamelCase(s)) else: s = utilities.CamelCase(s).replace(' ', '') if not s.startswith('GTL'): return 'GTL' + s return s
def ToClassName(self, s, element, element_type=None): """Convert a name to a suitable class name in the target language. This default implementation camel cases the string, which is appropriate for some languages. Subclasses are encouraged to override this. Args: s: (str) A rosy name of data element. element: (object) The object we are making a class name for. element_type: (str) Deprecated. The kind of object we are making a class name for. E.g. resource, method, schema. TODO(user): replace type in favor of class of element, but that will require changing the place where we call ToClassName with no element. Returns: A name suitable for use as a class in the generator's target language. """ return utilities.CamelCase(s).replace(' ', '')
def __init__(self, discovery_doc, language=None): super(Api, self).__init__(discovery_doc, self) name = self.values['name'] self._validator.ValidateApiName(name) self._validator.ValidateApiVersion(self.values['version']) self._class_name = utilities.CamelCase(name) self._language = language self._template_dir = None self._surface_features = {} self._schemas = {} self.void_type = data_types.Void(self) self.SetTemplateValue('className', self._class_name) self.SetTemplateValue('versionNoDots', self.values['version'].replace('.', '_')) self.SetTemplateValue( 'dataWrapper', 'dataWrapper' in discovery_doc.get('features', [])) self._BuildSchemaDefinitions() self._BuildResourceDefinitions() self.SetTemplateValue('resources', self._resources) # Make data models part of the api dictionary self.SetTemplateValue('models', self.ModelClasses()) # Replace methods dict with Methods self._methods = [] for name, method_dict in self.values.get('methods', {}).iteritems(): self._methods.append(Method(self, name, method_dict)) self.SetTemplateValue('methods', self._methods) # Global parameters self._parameters = [] for name, param_dict in self.values.get('parameters', {}).iteritems(): self._parameters.append(Parameter(self, name, param_dict, self)) self.SetTemplateValue('parameters', self._parameters) # Auth scopes self._authscopes = [] if (self.values.get('auth') and self.values['auth'].get('oauth2') and self.values['auth']['oauth2'].get('scopes')): for value, auth_dict in sorted( self.values['auth']['oauth2']['scopes'].iteritems()): self._authscopes.append(AuthScope(self, value, auth_dict)) self.SetTemplateValue('authscopes', self._authscopes)
def ToClassName(self, s, element, element_type=None): """Convert a discovery name to a suitable Dart class name. Overrides the default. Args: s: (str) A rosy name of data element. element: (object) The object we need a class name for. element_type: (str) The kind of element (resource|method) to name. Returns: A name suitable for use as a class in the generator's target language. """ candidate = utilities.CamelCase(s) if isinstance(element, api.Api): candidate += 'Api' while candidate in DartLanguageModel.RESERVED_CLASS_NAMES: candidate += '_' return candidate
def GetCodeTypeFromDictionary(self, def_dict): """Convert a json schema type to a suitable C++ type name. Overrides the default. Args: def_dict: (dict) A dictionary describing Json schema for this Property. Returns: A name suitable for use as a class in the generator's target language. """ json_type = def_dict.get('type', 'string') json_format = def_dict.get('format') datatype_and_imports = self.type_map.get((json_type, json_format)) if datatype_and_imports: # If there is an entry in the type format to datatype and imports # dictionary set it as the native format. native_format = datatype_and_imports[0] else: # Could not find it in the dictionary, set it to the json type. native_format = utilities.CamelCase(json_type) return native_format