namespace module is gone, plxrn provides PL-specific translations
[sfa.git] / sfa / util / xrn.py
1 import re
2
3 from sfa.util.faults import *
4 from sfa.util.sfalogging import sfa_logger
5
6 # for convenience and smoother translation - we should get rid of these functions eventually 
7 def get_leaf(hrn): return Xrn(xrn=hrn).get_leaf()
8 def get_authority(hrn): return Xrn(xrn=hrn).get_authority_hrn()
9 def urn_to_hrn(urn): xrn=Xrn(xrn=urn); return (xrn.hrn, xrn.type)
10 def hrn_to_urn(hrn,type): return Xrn(hrn=hrn, type=type).urn
11
12 class Xrn:
13
14     ########## basic tools on HRNs
15     # split a HRN-like string into pieces
16     # this is like split('.') except for escaped (backslashed) dots
17     # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']
18     @staticmethod
19     def hrn_split(hrn):
20         return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ]
21
22     # e.g. hrn_leaf ('a\.b.c.d') -> 'd'
23     @staticmethod
24     def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1]
25
26     # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']
27     @staticmethod
28     def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1]
29     
30     # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'
31     @staticmethod
32     def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn))
33     
34     # e.g. escape ('a.b') -> 'a\.b'
35     @staticmethod
36     def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token)
37     # e.g. unescape ('a\.b') -> 'a.b'
38     @staticmethod
39     def unescape(token): return token.replace('\\.','.')
40         
41     URN_PREFIX = "urn:publicid:IDN"
42
43     ########## basic tools on URNs
44     @staticmethod
45     def urn_full (urn):
46         if urn.startswith(Xrn.URN_PREFIX): return urn
47         else: return Xrn.URN_PREFIX+URN
48     @staticmethod
49     def urn_meaningful (urn):
50         if urn.startswith(Xrn.URN_PREFIX): return urn[len(Xrn.URN_PREFIX):]
51         else: return urn
52     @staticmethod
53     def urn_split (urn):
54         return Xrn.urn_meaningful(urn).split('+')
55
56     ####################
57     # the local fields that are kept consistent
58     # self.urn
59     # self.hrn
60     # self.type
61     # self.path
62     # provide either urn, or (hrn + type)
63     def __init__ (self, xrn=None, urn=None, hrn=None, type=None):
64         if xrn is not None:
65             if xrn.startswith(Xrn.URN_PREFIX):
66                 self.urn=xrn
67                 self.urn_to_hrn()
68             else:
69                 self.hrn=xrn
70                 self.type=type
71                 self.hrn_to_urn()
72         elif urn is not None: 
73             self.urn=urn
74             self.urn_to_hrn()
75         elif hrn is not None and type is not None: 
76             self.hrn=hrn
77             self.type=type
78             self.hrn_to_urn()
79         else:
80             raise SfaAPIError,"Xrn.__init__"
81 # happens all the time ..
82 #        if not type:
83 #            sfa_logger().debug("type-less Xrn's are not safe")
84
85     def get_urn(self): return self.urn
86     def get_hrn(self): return self.hrn
87     def get_type(self): return self.type
88     def get_hrn_type(self): return (self.hrn, self.type)
89
90     def _normalize(self):
91         if self.hrn is None: raise SfaAPIError, "Xrn._normalize"
92         if not hasattr(self,'leaf'): 
93             self.leaf=Xrn.hrn_split(self.hrn)[-1]
94         # self.authority keeps a list
95         if not hasattr(self,'authority'): 
96             self.authority=Xrn.hrn_auth_list(self.hrn)
97
98     def get_leaf(self):
99         self._normalize()
100         return self.leaf
101
102     def get_authority_hrn(self): 
103         self._normalize()
104         return '.'.join( self.authority )
105     
106     def get_authority_urn(self): 
107         self._normalize()
108         return ':'.join( [Xrn.unescape(x) for x in self.authority] )
109     
110     def urn_to_hrn(self):
111         """
112         compute tuple (hrn, type) from urn
113         """
114         
115 #        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
116         if not self.urn.startswith(Xrn.URN_PREFIX):
117             raise SfaAPIError, "Xrn.urn_to_hrn"
118
119         parts = Xrn.urn_split(self.urn)
120         type=parts.pop(2)
121         # Remove the authority name (e.g. '.sa')
122         if type == 'authority': parts.pop()
123
124         # convert parts (list) into hrn (str) by doing the following
125         # 1. remove blank parts
126         # 2. escape dots inside parts
127         # 3. replace ':' with '.' inside parts
128         # 3. join parts using '.' 
129         hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part]) 
130
131         self.hrn=str(hrn)
132         self.type=str(type)
133     
134     def hrn_to_urn(self):
135         """
136         compute urn from (hrn, type)
137         """
138
139 #        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
140         if self.hrn.startswith(Xrn.URN_PREFIX):
141             raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn
142
143         if self.type == 'authority':
144             self.authority = Xrn.hrn_split(self.hrn)
145             name = 'sa'   
146         else:
147             self.authority = Xrn.hrn_auth_list(self.hrn)
148             name = Xrn.hrn_leaf(self.hrn)
149
150         authority_string = self.get_authority_urn()
151
152         if self.type == None:
153             urn = "+".join(['',authority_string,name])
154         else:
155             urn = "+".join(['',authority_string,self.type,name])
156         
157         self.urn = Xrn.URN_PREFIX + urn
158
159     def dump_string(self):
160         result="-------------------- XRN\n"
161         result += "URN=%s\n"%self.urn
162         result += "HRN=%s\n"%self.hrn
163         result += "TYPE=%s\n"%self.type
164         result += "LEAF=%s\n"%self.get_leaf()
165         result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()
166         result += "AUTH(urn format)=%s\n"%self.get_authority_urn()
167         return result
168