1 from __future__ import print_function
4 from sfa.util.faults import InvalidRSpec, UnsupportedRSpecVersion
5 from sfa.rspecs.version import RSpecVersion
6 from sfa.util.sfalogging import logger
7 from sfa.util.py23 import StringType
15 return "<VersionManager with {} flavours: [{}]>"\
16 .format(len(self.versions),
17 ", ".join( [ str(x) for x in self.versions ]))
19 def load_versions(self):
20 path = os.path.dirname(os.path.abspath( __file__ ))
21 versions_path = path + os.sep + 'versions'
22 versions_module_path = 'sfa.rspecs.versions'
23 valid_module = lambda x: os.path.isfile(os.sep.join([versions_path, x])) \
24 and x.endswith('.py') and x != '__init__.py'
25 files = [f for f in os.listdir(versions_path) if valid_module(f)]
26 for filename in files:
27 basename = filename.split('.')[0]
28 module_path = versions_module_path +'.'+basename
29 module = __import__(module_path, fromlist=module_path)
30 for attr_name in dir(module):
31 attr = getattr(module, attr_name)
32 if hasattr(attr, 'version') and hasattr(attr, 'enabled') and attr.enabled == True:
33 self.versions.append(attr())
35 def _get_version(self, type, version_num=None, content_type=None):
37 for version in self.versions:
38 if type is None or type.lower() == version.type.lower():
39 if version_num is None or str(float(version_num)) == str(float(version.version)):
40 if content_type is None or content_type.lower() == version.content_type.lower() \
41 or version.content_type == '*':
43 ### sounds like we should be glad with the first match, not the last one
46 raise UnsupportedRSpecVersion("[%s %s %s] is not suported here"% (type, version_num, content_type))
49 def get_version(self, version=None):
51 if isinstance(version, dict):
52 retval = self._get_version(version.get('type'), version.get('version'), version.get('content_type'))
53 elif isinstance(version, StringType):
54 version_parts = version.split(' ')
55 num_parts = len(version_parts)
56 type = version_parts[0]
60 version_num = version_parts[1]
62 content_type = version_parts[2]
63 retval = self._get_version(type, version_num, content_type)
64 elif isinstance(version, RSpecVersion):
67 retval = self.versions[0]
69 raise UnsupportedRSpecVersion("No such version: %s "% str(version))
73 def get_version_by_schema(self, schema):
75 for version in self.versions:
76 if schema == version.schema:
79 raise InvalidRSpec("Unkwnown RSpec schema: %s" % schema)
82 def show_by_string(self, string):
84 print(self.get_version(string))
85 except Exception as e:
88 def show_by_schema(self, string):
90 print(self.get_version_by_schema(string))
91 except Exception as e:
94 if __name__ == '__main__':
95 manager = VersionManager()
97 manager.show_by_string('sfa 1')
98 manager.show_by_string('protogeni 2')
99 manager.show_by_string('protogeni 2 advertisement')
100 manager.show_by_schema('http://www.protogeni.net/resources/rspec/2/ad.xsd')
101 manager.show_by_schema('http://sorch.netmode.ntua.gr/ws/RSpec/ad.xsd')