[asterisk-commits] dlee: branch dlee/stasis-http r382381 - in /team/dlee/stasis-http: build_tool...

SVN commits to the Asterisk project asterisk-commits at lists.digium.com
Mon Mar 4 11:26:42 CST 2013


Author: dlee
Date: Mon Mar  4 11:26:39 2013
New Revision: 382381

URL: http://svnview.digium.com/svn/asterisk?view=rev&rev=382381
Log:
PEP8; svn:ignore and svn:executable flags

Modified:
    team/dlee/stasis-http/build_tools/make_stasis_http_stubs   (props changed)
    team/dlee/stasis-http/cog/   (props changed)
    team/dlee/stasis-http/cog/stasis_cog.py

Propchange: team/dlee/stasis-http/build_tools/make_stasis_http_stubs
------------------------------------------------------------------------------
    svn:executable = *

Propchange: team/dlee/stasis-http/cog/
------------------------------------------------------------------------------
--- svn:ignore (added)
+++ svn:ignore Mon Mar  4 11:26:39 2013
@@ -1,0 +1,1 @@
+*.pyc

Modified: team/dlee/stasis-http/cog/stasis_cog.py
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/cog/stasis_cog.py?view=diff&rev=382381&r1=382380&r2=382381
==============================================================================
--- team/dlee/stasis-http/cog/stasis_cog.py (original)
+++ team/dlee/stasis-http/cog/stasis_cog.py Mon Mar  4 11:26:39 2013
@@ -32,160 +32,181 @@
 import textwrap
 from collections import OrderedDict
 
-SWAGGER_VERSION="1.1"
+SWAGGER_VERSION = "1.1"
+
 
 class ResourceListingSourceWriter(object):
     """Writes the resources.c file from Swagger API docs.
     """
 
     def __init__(self, root):
-	self.root = root
+        self.root = root
 
     def write(self):
-	"""Write source code for this resource, and all decendants.
-	"""
-	self.write_includes()
-	# Callbacks are referenced by handlers, so write them first
-	self.write_callbacks(self.root)
-	self.write_handlers(self.root)
+        """Write source code for this resource, and all decendants.
+        """
+        self.write_includes()
+        # Callbacks are referenced by handlers, so write them first
+        self.write_callbacks(self.root)
+        self.write_handlers(self.root)
 
     def write_includes(self):
-	"""Write the #includes for resources.c
-	"""
-	for include in self.root.includes:
-	    cog.outl('#include "%s"' % include)
-	cog.outl("#include <inttypes.h>")
-	cog.outl("#include <strings.h>")
-	cog.outl()
+        """Write the #includes for resources.c
+        """
+        for include in self.root.includes:
+            cog.outl('#include "%s"' % include)
+        cog.outl("#include <inttypes.h>")
+        cog.outl("#include <strings.h>")
+        cog.outl()
 
     def write_callbacks(self, resource):
-	"""Write the callback functions for the resource
-	"""
-	# Children first, for consistency with handler order
-	for child in resource.children.itervalues():
-	    self.write_callbacks(child)
-
- 	for operation in resource.operations.itervalues():
-	    self.write_callback(operation)
+        """Write the callback functions for the resource
+        """
+        # Children first, for consistency with handler order
+        for child in resource.children.itervalues():
+            self.write_callbacks(child)
+
+        for operation in resource.operations.itervalues():
+            self.write_callback(operation)
 
     def write_callback(self, operation):
-	"""Writes the Operations's callback function definition
-	"""
-	cog.outl('static void %s(struct ast_variable *get_params, struct ast_variable *path_vars, struct ast_variable *headers, struct stasis_http_response *response)' % operation.get_callback_name())
-	cog.outl('{')
-	if operation.path_parameters or operation.query_parameters:
-	    cog.outl('\tstruct ast_variable *i;');
-	cog.outl('\t%s args = {};' % operation.get_args_name())
-	cog.outl('')
-	if operation.path_parameters:
-	    cog.outl('\tfor (i = path_vars; i; i = i->next) {')
-	    for param in operation.path_parameters.itervalues():
-		cog.outl('\t\tif (strcmp(i->name, "%s") == 0) {' % param.name)
-		cog.outl('\t\t\targs.%s = i->value;' % param.c_name)
-		cog.outl('\t\t}')
-	    cog.outl('\t}')
-	if operation.query_parameters:
-	    cog.outl('\tfor (i = get_params; i; i = i->next) {')
-	    for param in operation.query_parameters.itervalues():
-		cog.outl('\t\tif (strcmp(i->name, "%s") == 0) {' % param.name)
-		cog.outl('\t\t\targs.%s = %s;' % (param.c_name, param.decoder("i->value")))
-		cog.outl('\t\t}')
-	    cog.outl('\t}')
-	cog.outl('\t%s(headers, &args, response);' % operation.get_impl_name())
-	cog.outl('}')
-	cog.outl()
+        """Writes the Operations's callback function definition
+        """
+        cog.outl('static void %s(struct ast_variable *get_params, '
+                 'struct ast_variable *path_vars, '
+                 'struct ast_variable *headers, '
+                 'struct stasis_http_response *response)' %
+                 operation.get_callback_name())
+        cog.outl('{')
+        if operation.path_parameters or operation.query_parameters:
+            cog.outl('\tstruct ast_variable *i;')
+        cog.outl('\t%s args = {};' % operation.get_args_name())
+        cog.outl('')
+        if operation.path_parameters:
+            cog.outl('\tfor (i = path_vars; i; i = i->next) {')
+            for param in operation.path_parameters.itervalues():
+                cog.outl('\t\tif (strcmp(i->name, "%s") == 0) {' % param.name)
+                cog.outl('\t\t\targs.%s = i->value;' % param.c_name)
+                cog.outl('\t\t}')
+            cog.outl('\t}')
+        if operation.query_parameters:
+            cog.outl('\tfor (i = get_params; i; i = i->next) {')
+            for param in operation.query_parameters.itervalues():
+                cog.outl('\t\tif (strcmp(i->name, "%s") == 0) {' % param.name)
+                cog.outl('\t\t\targs.%s = %s;' %
+                         (param.c_name, param.decoder("i->value")))
+                cog.outl('\t\t}')
+            cog.outl('\t}')
+        cog.outl('\t%s(headers, &args, response);' % operation.get_impl_name())
+        cog.outl('}')
+        cog.outl()
 
     def write_handlers(self, resource):
-	"""Write the stasis_rest_handlers for the resource
-	"""
-	# Children are referred to by handler, so write them first
-	for child in resource.children.itervalues():
-	    self.write_handlers(child)
-
-	cog.outl('static struct stasis_rest_handlers %s = {' % resource.get_name())
-	cog.outl('\t.path_segment = "%s",' % resource.path_element)
-	if resource.is_wildcard:
-	    cog.outl('\t.is_wildcard = 1,')
-	cog.outl('\t.callbacks = {')
-	for operation in resource.operations.itervalues():
-	    cog.outl('\t\t[AST_HTTP_%s] = %s,' % (operation.http_method, operation.get_callback_name()))
-	cog.outl('\t},')
-	cog.outl('\t.num_children = %d,' % len(resource.children))
-	cog.out('\t.children = { ')
-	for child in resource.children.itervalues():
-	    cog.out('&%s, ' % child.get_name())
-	cog.outl('},')
-	cog.outl('};')
-	cog.outl()
+        """Write the stasis_rest_handlers for the resource
+        """
+        # Children are referred to by handler, so write them first
+        for child in resource.children.itervalues():
+            self.write_handlers(child)
+
+        cog.outl('static struct stasis_rest_handlers %s = {' %
+                 resource.get_name())
+        cog.outl('\t.path_segment = "%s",' % resource.path_element)
+        if resource.is_wildcard:
+            cog.outl('\t.is_wildcard = 1,')
+        cog.outl('\t.callbacks = {')
+        for operation in resource.operations.itervalues():
+            cog.outl('\t\t[AST_HTTP_%s] = %s,' %
+                     (operation.http_method, operation.get_callback_name()))
+        cog.outl('\t},')
+        cog.outl('\t.num_children = %d,' % len(resource.children))
+        cog.out('\t.children = { ')
+        for child in resource.children.itervalues():
+            cog.out('&%s, ' % child.get_name())
+        cog.outl('},')
+        cog.outl('};')
+        cog.outl()
+
 
 class ApiDeclarationHeaderWriter(object):
     """Writes the .h for for a Swagger API Declaration file.
     """
 
     def __init__(self, root):
-	self.root = root
+        self.root = root
 
     def write(self):
-	"""Writes the corresponding header file for this resource's operations.
-	"""
-	(name, ext) = os.path.splitext(os.path.basename(cog.outFile))
-	incl_guard = '_ASTERISK_%s_H' % name.upper()
-	cog.outl('#ifndef %s' % incl_guard)
-	cog.outl('#define %s' % incl_guard)
-	# args structures first, so the prototypes can easily be copy/pasted in one blob
-	self.write_structs(self.root)
-	self.write_impl_prototypes(self.root)
-	cog.outl('#endif /* %s */' % incl_guard)
+        """Writes the corresponding header file for this resource's operations.
+        """
+        (name, ext) = os.path.splitext(os.path.basename(cog.outFile))
+        incl_guard = '_ASTERISK_%s_H' % name.upper()
+        cog.outl('#ifndef %s' % incl_guard)
+        cog.outl('#define %s' % incl_guard)
+        # args structures first, so the prototypes can easily be copy/pasted in
+        # one blob
+        self.write_structs(self.root)
+        self.write_impl_prototypes(self.root)
+        cog.outl('#endif /* %s */' % incl_guard)
 
     def write_structs(self, resource):
-	"""Write the args structs for the resource's operations.
-	"""
-	# Children first, so we're in the same order as resources.c
-	for child in resource.children.itervalues():
-	    self.write_structs(child)
-
-	for operation in resource.operations.itervalues():
-	    cog.outl('%s {' % operation.get_args_name())
-	    for param in operation.get_all_parameters().itervalues():
-		if param.description:
-		    cog.outl('\t/*! %s */' % (param.description))
-		cog.out('\t%s' % param.c_type)
-		if not param.c_type.endswith('*'):
-		    cog.out(' ')
-		cog.outl('%s;' % param.c_name)
-	    cog.outl('};')
+        """Write the args structs for the resource's operations.
+        """
+        # Children first, so we're in the same order as resources.c
+        for child in resource.children.itervalues():
+            self.write_structs(child)
+
+        for operation in resource.operations.itervalues():
+            cog.outl('%s {' % operation.get_args_name())
+            for param in operation.get_all_parameters().itervalues():
+                if param.description:
+                    cog.outl('\t/*! %s */' % (param.description))
+                cog.out('\t%s' % param.c_type)
+                if not param.c_type.endswith('*'):
+                    cog.out(' ')
+                cog.outl('%s;' % param.c_name)
+            cog.outl('};')
 
     def write_impl_prototypes(self, resource):
-	"""Write the prototypes for all the implementation functions in the given resource's operations.
-	"""
-	# Children first, so we're in the same order as resources.c
-	for child in resource.children.itervalues():
-	    self.write_impl_prototypes(child)
-
- 	for operation in resource.operations.itervalues():
-	    cog.outl('/*!')
-	    if operation.summary.endswith('.'):
-		raise ValueError("Operation summary should not end with a period (%s)" % operation.summary)
-
-	    # swagger spec recommends no more than 60 chars in the summary
-	    # See https://github.com/wordnik/swagger-core/wiki/API-Declaration
-	    if len(operation.summary) > 60:
-		raise ValueError("Operaiton summary too long (%s)" % operation.summary)
-	    cog.outl(' * \\brief %s.' % operation.summary)
-	    if operation.notes:
-		cog.outl(' *')
-		for line in textwrap.wrap(operation.notes, 79, initial_indent = ' * ', subsequent_indent = ' * '):
-		    cog.outl(line)
-		cog.outl(' *')
-	    cog.outl(' * \param headers HTTP headers')
-	    cog.outl(' * \param args Swagger parameters')
-	    cog.outl(' * \param[out] response HTTP response')
-	    cog.outl(' */')
-	    cog.outl('void %s(struct ast_variable *headers, %s *args, struct stasis_http_response *response);' % (operation.get_impl_name(), operation.get_args_name()))
+        """Write the prototypes for all the implementation functions in the
+        given resource's operations.
+        """
+        # Children first, so we're in the same order as resources.c
+        for child in resource.children.itervalues():
+            self.write_impl_prototypes(child)
+
+        for operation in resource.operations.itervalues():
+            cog.outl('/*!')
+            if operation.summary.endswith('.'):
+                raise ValueError(
+                    "Operation summary should not end with a period (%s)" %
+                    operation.summary)
+
+            # swagger spec recommends no more than 60 chars in the summary
+            # See https://github.com/wordnik/swagger-core/wiki/API-Declaration
+            if len(operation.summary) > 60:
+                raise ValueError("Operaiton summary too long (%s)" %
+                                 operation.summary)
+            cog.outl(' * \\brief %s.' % operation.summary)
+            if operation.notes:
+                cog.outl(' *')
+                for line in textwrap.wrap(operation.notes, 79,
+                                          initial_indent=' * ',
+                                          subsequent_indent=' * '):
+                    cog.outl(line)
+                cog.outl(' *')
+            cog.outl(' * \param headers HTTP headers')
+            cog.outl(' * \param args Swagger parameters')
+            cog.outl(' * \param[out] response HTTP response')
+            cog.outl(' */')
+            cog.outl('void %s(struct ast_variable *headers, %s *args, '
+                     'struct stasis_http_response *response);' %
+                     (operation.get_impl_name(), operation.get_args_name()))
+
 
 def write_operation_declaration(operation):
-    """Common code for writing an operation handler's doc comment and prototype.
-    """
+    """Common code for writing an operation handler's doc comment and
+    prototype.
+    """
+
 
 class ApiDeclarationSourceWriter(object):
     """Writes the .c for for a Swagger API Declaration file.
@@ -195,28 +216,34 @@
     """
 
     def __init__(self, root):
-	self.root = root
+        self.root = root
 
     def write(self):
-	"""Writes the corresponding source stubs file for this resource's operations.
-	"""
-	(name, ext) = os.path.splitext(os.path.basename(cog.outFile))
-	cog.outl('#include "asterisk/%s.h"' % name)
-	cog.outl()
-	self.write_impl_stubs(self.root)
+        """Writes the corresponding source stubs file for this resource's
+        operations.
+        """
+        (name, ext) = os.path.splitext(os.path.basename(cog.outFile))
+        cog.outl('#include "asterisk/%s.h"' % name)
+        cog.outl()
+        self.write_impl_stubs(self.root)
 
     def write_impl_stubs(self, resource):
-	"""Write the stubs for all the implementation functions in the given resource's operations.
-	"""
-	# Children first, so we're in the same order as the header file
-	for child in resource.children.itervalues():
-	    self.write_impl_stubs(child)
-
- 	for operation in resource.operations.itervalues():
-	    cog.outl('void %s(struct ast_variable *headers, %s *args, struct stasis_http_response *response)' % (operation.get_impl_name(), operation.get_args_name()))
-	    cog.outl('{')
-	    cog.outl('\tast_log(LOG_ERROR, "TODO: %s\\n");' % operation.get_impl_name())
-	    cog.outl('}')
+        """Write the stubs for all the implementation functions in the given
+        resource's operations.
+        """
+        # Children first, so we're in the same order as the header file
+        for child in resource.children.itervalues():
+            self.write_impl_stubs(child)
+
+        for operation in resource.operations.itervalues():
+            cog.outl('void %s(struct ast_variable *headers, %s *args, '
+                     'struct stasis_http_response *response)' %
+                     (operation.get_impl_name(), operation.get_args_name()))
+            cog.outl('{')
+            cog.outl('\tast_log(LOG_ERROR, "TODO: %s\\n");' %
+                     operation.get_impl_name())
+            cog.outl('}')
+
 
 class Resource(object):
     """Resource from a Swagger API declaration.
@@ -230,216 +257,236 @@
     """
 
     def __init__(self, parent_name, path_element):
-	self.parent_name = parent_name
-	if path_element.startswith('{') and path_element.endswith('}'):
-	    self.is_wildcard = True
-	    self.path_element = path_element[1:-1]
-	else:
-	    self.is_wildcard = False
-	    self.path_element = path_element
-	# It's important to maintain order of the children
-	# Otherwise, search order won't match the .json files
-	self.children = OrderedDict()
-	self.operations = OrderedDict()
-	self.includes = []
-	self.author = None
-	self.copyright = None
-	self.basePath = None
-
-	if not is_identifier(self.get_name()):
-	    raise ValueError("Invalid path name: %s" % path_element)
+        self.parent_name = parent_name
+        if path_element.startswith('{') and path_element.endswith('}'):
+            self.is_wildcard = True
+            self.path_element = path_element[1:-1]
+        else:
+            self.is_wildcard = False
+            self.path_element = path_element
+        # It's important to maintain order of the children
+        # Otherwise, search order won't match the .json files
+        self.children = OrderedDict()
+        self.operations = OrderedDict()
+        self.includes = []
+        self.author = None
+        self.copyright = None
+        self.basePath = None
+
+        if not is_identifier(self.get_name()):
+            raise ValueError("Invalid path name: %s" % path_element)
 
     def load_resource_listing(self, resource_listing_file):
-	"""Loads resource_listing from a Swagger resources.json file.
-	"""
-	assert not self.children, "Should not reload existing resource"
-	assert not self.operations, "Should not reload existing resource"
-
-	resource_listing_dir = os.path.dirname(resource_listing_file)
-	with open(resource_listing_file) as fp:
-	    resource_listing = json.load(fp)
-
-	self.author = resource_listing.get('_author')
-	self.copyright = resource_listing.get('_copyright')
-
-	swagger_version = resource_listing.get('swaggerVersion')
-	if not swagger_version == SWAGGER_VERSION:
-	    raise ValueError("Unsupported Swagger version %s" % swagger_version)
-
-	self.basePath = resource_listing.get('basePath')
-	if self.basePath is None:
-	    raise ValueError("basePath missing from %s" % resource_listing_file)
-
-	for api in resource_listing['apis']:
-	    # Path in json is URI relative, so we need to drop the initial /api/
-	    path = api['path'].replace('/', '', 1)
-	    api_declaration_file = os.path.abspath(os.path.join(resource_listing_dir, path)).format(format = 'json')
-	    (basename, ext) = os.path.splitext(os.path.basename(api_declaration_file))
-	    self.includes.append('asterisk/stasis_http_%s.h' % basename)
-	    self.load_api_declaration(api_declaration_file)
+        """Loads resource_listing from a Swagger resources.json file.
+        """
+        assert not self.children, "Should not reload existing resource"
+        assert not self.operations, "Should not reload existing resource"
+
+        resource_listing_dir = os.path.dirname(resource_listing_file)
+        with open(resource_listing_file) as fp:
+            resource_listing = json.load(fp)
+
+        self.author = resource_listing.get('_author')
+        self.copyright = resource_listing.get('_copyright')
+
+        swagger_version = resource_listing.get('swaggerVersion')
+        if not swagger_version == SWAGGER_VERSION:
+            raise ValueError("Unsupported Swagger version %s" %
+                             swagger_version)
+
+        self.basePath = resource_listing.get('basePath')
+        if self.basePath is None:
+            raise ValueError("basePath missing from %s" %
+                             resource_listing_file)
+
+        for api in resource_listing['apis']:
+            # Path in json is URI relative, so we need to drop the initial /
+            path = api['path'].replace('/', '', 1)
+            api_declaration_file = os.path.abspath(
+                os.path.join(resource_listing_dir, path)).format(format='json')
+            (basename, ext) = os.path.splitext(
+                os.path.basename(api_declaration_file))
+            self.includes.append('asterisk/stasis_http_%s.h' % basename)
+            self.load_api_declaration(api_declaration_file)
 
     def load_api_declaration(self, api_declaration_file):
-	"""Loads a resource from a single Swagger resource.json file.
-	"""
-	with open(api_declaration_file) as fp:
-	    api_declaration = json.load(fp)
-
-	self.author = self.author or api_declaration.get('_author')
-	self.copyright = self.copyright or api_declaration.get('_copyright')
-
-	swagger_version = api_declaration.get('swaggerVersion')
-	if swagger_version != SWAGGER_VERSION:
-	    raise ValueError("Unsupported Swagger version %s" % swagger_version)
-
-	if self.basePath and api_declaration.get('basePath') != self.basePath:
-	    raise ValueError("invalid basePath in %s" % api_declaration_file)
-
-	for api in api_declaration['apis']:
-	    resource_path = api['path'].split('/')
-	    # remove empty strings from resource_path
-	    resource_path = filter(lambda x: x, resource_path)
-	    resource = self.get_child(resource_path)
-	    for operation in api['operations']:
-		op = resource.add_operation(operation['httpMethod'], operation['nickname'])
-		op.summary = operation.get('summary')
-		op.notes = operation.get('notes')
-		for param in operation.get('parameters') or []:
-		    op.add_parameter(name = param['name'],
-				     description = param['description'],
-				     param_type = param['paramType'],
-				     required = param.get('required'),
-				     allowMultiple = param.get('allowMultiple'),
-				     dataType = param.get('dataType'),
-				     defaultValue = param.get('defaultValue'))
+        """Loads a resource from a single Swagger resource.json file.
+        """
+        with open(api_declaration_file) as fp:
+            api_declaration = json.load(fp)
+
+        self.author = self.author or api_declaration.get('_author')
+        self.copyright = self.copyright or api_declaration.get('_copyright')
+
+        swagger_version = api_declaration.get('swaggerVersion')
+        if swagger_version != SWAGGER_VERSION:
+            raise ValueError("Unsupported Swagger version %s" %
+                             swagger_version)
+
+        if self.basePath and api_declaration.get('basePath') != self.basePath:
+            raise ValueError("invalid basePath in %s" % api_declaration_file)
+
+        for api in api_declaration['apis']:
+            resource_path = api['path'].split('/')
+            # remove empty strings from resource_path
+            resource_path = filter(lambda x: x, resource_path)
+            resource = self.get_child(resource_path)
+            for operation in api['operations']:
+                op = resource.add_operation(operation['httpMethod'],
+                                            operation['nickname'])
+                op.summary = operation.get('summary')
+                op.notes = operation.get('notes')
+                for param in operation.get('parameters') or []:
+                    op.add_parameter(name=param['name'],
+                                     description=param['description'],
+                                     param_type=param['paramType'],
+                                     required=param.get('required'),
+                                     allowMultiple=param.get('allowMultiple'),
+                                     dataType=param.get('dataType'),
+                                     defaultValue=param.get('defaultValue'))
 
     def get_name(self):
-	"""Returns the fully qualified name of this Resource.
-	"""
-	if self.parent_name:
-	    return '%s_%s' % (self.parent_name, self.path_element)
-	else:
-	    return self.path_element
+        """Returns the fully qualified name of this Resource.
+        """
+        if self.parent_name:
+            return '%s_%s' % (self.parent_name, self.path_element)
+        else:
+            return self.path_element
 
     def get_child(self, path_list):
-	"""Finds the decendent specified by path_list.
-
-	This method will create any missing decendants along the way, if needed.
-	"""
-	if not path_list:
-	    return self
-
-	path_element = path_list[0]
-	r = self.children.get(path_element)
-	if r is None:
-	    r = Resource(self.get_name(), path_element)
-	    self.children[path_element] = r
-	return r.get_child(path_list[1:])
+        """Finds the decendent specified by path_list.
+
+        This method will create any missing decendants along the way, if
+        needed.
+        """
+        if not path_list:
+            return self
+
+        path_element = path_list[0]
+        r = self.children.get(path_element)
+        if r is None:
+            r = Resource(self.get_name(), path_element)
+            self.children[path_element] = r
+        return r.get_child(path_list[1:])
 
     def add_operation(self, http_method, nickname):
-	"""Add an operation to this resource.
-	"""
-	op = Operation(http_method, nickname)
-	self.operations[http_method] = op
-	return op
+        """Add an operation to this resource.
+        """
+        op = Operation(http_method, nickname)
+        self.operations[http_method] = op
+        return op
+
 
 class Operation(object):
     """Swagger operation
     """
     def __init__(self, http_method, nickname):
-	self.http_method = http_method
-	self.nickname = snakify(nickname)
-	self.query_parameters = OrderedDict()
-	self.path_parameters = OrderedDict()
-	self.summary = None
-	self.notes = None
-
-	if not is_identifier(self.get_callback_name()) or not is_identifier(self.nickname):
-	    raise ValueError("Invalid operation nickname: %s" % nickname)
-
-    def add_parameter(self, name, description, param_type, required, allowMultiple, dataType, defaultValue):
-	if param_type == 'path':
-	    p = self.path_parameters
-	elif param_type == 'query':
-	    p = self.query_parameters
-	else:
-	    raise ValueError("Invalid param_type: %s" % param_type)
-	p[name] = Parameter(name = name, description = description, required = required, allowMultiple = allowMultiple, dataType = dataType, defaultValue = defaultValue)
+        self.http_method = http_method
+        self.nickname = snakify(nickname)
+        self.query_parameters = OrderedDict()
+        self.path_parameters = OrderedDict()
+        self.summary = None
+        self.notes = None
+
+        cb_is_valid = is_identifier(self.get_callback_name())
+        nick_is_valid = is_identifier(self.nickname)
+        if not cb_is_valid or not nick_is_valid:
+            raise ValueError("Invalid operation nickname: %s" % nickname)
+
+    def add_parameter(self, name, description, param_type, required,
+                      allowMultiple, dataType, defaultValue):
+        if param_type == 'path':
+            p = self.path_parameters
+        elif param_type == 'query':
+            p = self.query_parameters
+        else:
+            raise ValueError("Invalid param_type: %s" % param_type)
+        p[name] = Parameter(name=name, description=description,
+                            required=required, allowMultiple=allowMultiple,
+                            dataType=dataType, defaultValue=defaultValue)
 
     def get_all_parameters(self):
-	return OrderedDict(self.path_parameters.items() + self.query_parameters.items())
+        return OrderedDict(self.path_parameters.items() +
+                           self.query_parameters.items())
 
     def get_callback_name(self):
-	"""Returns the name of this Operation's callback function.
-	"""
-	return "%s_cb" % self.get_impl_name()
+        """Returns the name of this Operation's callback function.
+        """
+        return "%s_cb" % self.get_impl_name()
 
     def get_impl_name(self):
-	"""Returns the name of this Operation's callback function.
-	"""
-	return "stasis_http_%s" % self.nickname
+        """Returns the name of this Operation's callback function.
+        """
+        return "stasis_http_%s" % self.nickname
 
     def get_args_name(self):
-	"""Returns the name of impl's args struct.
-	"""
-	return "struct ast_%s_args" % self.nickname
+        """Returns the name of impl's args struct.
+        """
+        return "struct ast_%s_args" % self.nickname
+
 
 class Parameter(object):
     """Swagger operation parameter.
     """
-    def __init__(self, name, description, required, allowMultiple, dataType, defaultValue):
-	self.name = name
-	self.description = description
-	self.required = required
-	self.allowMultiple = allowMultiple
-	self.dataType = dataType
-	self.defaultValue = defaultValue
-	self.c_name = snakify(self.name)
-
-	if dataType == 'string':
-	    self.c_type = 'const char *'
-	elif dataType == 'boolean':
-	    self.c_type = 'int'
-	elif dataType == 'number':
-	    self.c_type = 'int'
-	else:
-	    raise ValueError("Invalid dataType: %s" % dataType)
-
-	if not is_identifier(self.c_name):
-	    raise ValueError("Invalid paramater name: %s" % name)
+    def __init__(self, name, description, required, allowMultiple, dataType,
+                 defaultValue):
+        self.name = name
+        self.description = description
+        self.required = required
+        self.allowMultiple = allowMultiple
+        self.dataType = dataType
+        self.defaultValue = defaultValue
+        self.c_name = snakify(self.name)
+
+        if dataType == 'string':
+            self.c_type = 'const char *'
+        elif dataType == 'boolean':
+            self.c_type = 'int'
+        elif dataType == 'number':
+            self.c_type = 'int'
+        else:
+            raise ValueError("Invalid dataType: %s" % dataType)
+
+        if not is_identifier(self.c_name):
+            raise ValueError("Invalid paramater name: %s" % name)
 
     def decoder(self, char_pointer):
-	"""Returns the C code for decoding this param from a string.
-	"""
-	if self.dataType == 'string':
-	    return char_pointer
-	elif self.dataType == 'boolean':
-	    return 'ast_true(%s)' % char_pointer
-	elif self.dataType == 'number':
-	    return 'strtol(%s, NULL, 0)' % char_pointer
-	else:
-	    assert False, "Someone forgot to update the decoder"
-	    return char_pointer
+        """Returns the C code for decoding this param from a string.
+        """
+        if self.dataType == 'string':
+            return char_pointer
+        elif self.dataType == 'boolean':
+            return 'ast_true(%s)' % char_pointer
+        elif self.dataType == 'number':
+            return 'strtol(%s, NULL, 0)' % char_pointer
+        else:
+            assert False, "Someone forgot to update the decoder"
+            return char_pointer
+
 
 def snakify(name):
-    """Helper to take a camelCase or dash-seperated name and make it snake_case.
+    """Helper to take a camelCase or dash-seperated name and make it
+    snake_case.
     """
     r = ''
     prior_lower = False
     for c in name:
-	if c.isupper() and prior_lower:
-	    r += "_"
-	if c is '-':
-	    c = '_'
-	prior_lower = c.islower()
-	r += c.lower()
+        if c.isupper() and prior_lower:
+            r += "_"
+        if c is '-':
+            c = '_'
+        prior_lower = c.islower()
+        r += c.lower()
     return r
+
 
 def is_identifier(str):
     """Returns True if given string is a valid C identifier; False otherwise
     """
     return re.match('^[_A-Za-z][_A-Za-z0-9]*$', str) is not None
 
-def do_not_edit(comment_style = 'C'):
+
+def do_not_edit(comment_style='C'):
     """Write the do not edit warning.
 
     Note that this doesn't apply to this file, just the generated output. But I
@@ -453,14 +500,15 @@
 ~ at %s
 ~""" % cog.inFile
     if comment_style == 'C':
-	msg = msg.replace('~', '/*', 1)
-	msg = msg.replace('~', ' *')
-	msg += '/'
+        msg = msg.replace('~', '/*', 1)
+        msg = msg.replace('~', ' *')
+        msg += '/'
     elif comment_style == '#':
-	msg = msg.replace('~', '#')
+        msg = msg.replace('~', '#')
     else:
-	raise ValueError("Invalid comment style: %s" % comment_style)
+        raise ValueError("Invalid comment style: %s" % comment_style)
     cog.outl(msg)
+
 
 def write_resource_copyright(prefix, resource):
     """Write the copyright statement for the given resource.
@@ -468,9 +516,10 @@
     root = Resource('', 'stasis')
     root.load_api_declaration(resource)
     if root.copyright is None:
-	raise ValueError("Missing copyright statement in %s" % resource)
+        raise ValueError("Missing copyright statement in %s" % resource)
     cog.out(prefix)
     cog.out(root.copyright)
+
 
 def write_resource_author(prefix, resource):
     """Write the author name for the given resource.
@@ -478,9 +527,10 @@
     root = Resource('', 'stasis')
     root.load_api_declaration(resource)
     if root.author is None:
-	raise ValueError("Missing author statement in %s" % resource)
+        raise ValueError("Missing author statement in %s" % resource)
     cog.out(prefix)
     cog.out(root.author)
+
 
 def write_resources_copyright(prefix, resources):
     """Write the copyright statement for the given resources.
@@ -488,9 +538,10 @@
     root = Resource('', 'stasis')
     root.load_resource_listing(resources)
     if root.copyright is None:
-	raise ValueError("Missing copyright statement in %s" % resources)
+        raise ValueError("Missing copyright statement in %s" % resources)
     cog.out(prefix)
     cog.out(root.copyright)
+
 
 def write_resources_author(prefix, resources):
     """Write the author name for the given resources.
@@ -498,6 +549,6 @@
     root = Resource('', 'stasis')
     root.load_resource_listing(resources)
     if root.author is None:
-	raise ValueError("Missing author statement in %s" % resources)
+        raise ValueError("Missing author statement in %s" % resources)
     cog.out(prefix)
     cog.out(root.author)




More information about the asterisk-commits mailing list