2 from sfa.util.faults import InvalidRSpec, InvalidRSpecVersion
3 from sfa.rspecs.baseversion import BaseVersion
4 from sfa.util.sfalogging import logger
8 default_version_num = '1'
14 def load_versions(self):
15 path = os.path.dirname(os.path.abspath( __file__ ))
16 versions_path = path + os.sep + 'versions'
17 versions_module_path = 'sfa.rspecs.versions'
18 valid_module = lambda x: os.path.isfile(os.sep.join([versions_path, x])) \
19 and not x.endswith('.pyc') and x not in ['__init__.py']
20 files = [f for f in os.listdir(versions_path) if valid_module(f)]
21 for filename in files:
22 basename = filename.split('.')[0]
23 module_path = versions_module_path +'.'+basename
24 module = __import__(module_path, fromlist=module_path)
25 for attr_name in dir(module):
26 attr = getattr(module, attr_name)
27 if hasattr(attr, 'version') and hasattr(attr, 'enabled') and attr.enabled == True:
28 self.versions.append(attr())
30 def _get_version(self, type, version_num=None, content_type=None):
32 for version in self.versions:
33 if type is None or type.lower() == version.type.lower():
34 if version_num is None or str(version_num) == version.version:
35 if content_type is None or content_type.lower() == version.content_type.lower() \
36 or version.content_type == '*':
39 raise InvalidRSpecVersion("No such version format: %s version: %s type:%s "% (type, version_num, content_type))
42 def get_version(self, version=None):
44 if isinstance(version, dict):
45 retval = self._get_version(version.get('type'), version.get('version'), version.get('content_type'))
46 elif isinstance(version, basestring):
47 version_parts = version.split(' ')
48 num_parts = len(version_parts)
49 type = version_parts[0]
53 version_num = version_parts[1]
55 content_type = version_parts[2]
56 retval = self._get_version(type, version_num, content_type)
57 elif isinstance(version, BaseVersion):
60 retval = self._get_version(self.default_type, self.default_version_num)
64 def get_version_by_schema(self, schema):
66 for version in self.versions:
67 if schema == version.schema:
70 raise InvalidRSpec("Unkwnown RSpec schema: %s" % schema)
73 if __name__ == '__main__':
76 print v.get_version('sfa 1')
77 print v.get_version('protogeni 2')
78 print v.get_version('protogeni 2 advertisement')
79 print v.get_version_by_schema('http://www.protogeni.net/resources/rspec/2/ad.xsd')