d5ad2d45851feb7e7c0f767c0819cf87f08b5fad
[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(hrn).get_leaf()
8 def get_authority(hrn): return Xrn(hrn).get_authority_hrn()
9 def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type)
10 def hrn_to_urn(hrn,type): return Xrn(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, type=None):
64         if not xrn: xrn = ""
65         # user has specified xrn : guess if urn or hrn
66         if xrn.startswith(Xrn.URN_PREFIX):
67             self.hrn=None
68             self.urn=xrn
69             self.urn_to_hrn()
70         else:
71             self.urn=None
72             self.hrn=xrn
73             self.type=type
74             self.hrn_to_urn()
75 # happens all the time ..
76 #        if not type:
77 #            sfa_logger().debug("type-less Xrn's are not safe")
78
79     def get_urn(self): return self.urn
80     def get_hrn(self): return self.hrn
81     def get_type(self): return self.type
82     def get_hrn_type(self): return (self.hrn, self.type)
83
84     def _normalize(self):
85         if self.hrn is None: raise SfaAPIError, "Xrn._normalize"
86         if not hasattr(self,'leaf'): 
87             self.leaf=Xrn.hrn_split(self.hrn)[-1]
88         # self.authority keeps a list
89         if not hasattr(self,'authority'): 
90             self.authority=Xrn.hrn_auth_list(self.hrn)
91
92     def get_leaf(self):
93         self._normalize()
94         return self.leaf
95
96     def get_authority_hrn(self): 
97         self._normalize()
98         return '.'.join( self.authority )
99     
100     def get_authority_urn(self): 
101         self._normalize()
102         return ':'.join( [Xrn.unescape(x) for x in self.authority] )
103     
104     def urn_to_hrn(self):
105         """
106         compute tuple (hrn, type) from urn
107         """
108         
109 #        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
110         if not self.urn.startswith(Xrn.URN_PREFIX):
111             raise SfaAPIError, "Xrn.urn_to_hrn"
112
113         parts = Xrn.urn_split(self.urn)
114         type=parts.pop(2)
115         # Remove the authority name (e.g. '.sa')
116         if type == 'authority':
117             name = parts.pop()
118             # Drop the sa. This is a bad hack, but its either this
119             # or completely change how record types are generated/stored   
120             if name != 'sa':
121                 type = type + "+" + name
122
123         # convert parts (list) into hrn (str) by doing the following
124         # 1. remove blank parts
125         # 2. escape dots inside parts
126         # 3. replace ':' with '.' inside parts
127         # 3. join parts using '.' 
128         hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part]) 
129
130         self.hrn=str(hrn)
131         self.type=str(type)
132     
133     def hrn_to_urn(self):
134         """
135         compute urn from (hrn, type)
136         """
137
138 #        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
139         if self.hrn.startswith(Xrn.URN_PREFIX):
140             raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn
141
142         if self.type and self.type.startswith('authority'):
143             self.authority = Xrn.hrn_split(self.hrn)
144             type_parts = self.type.split("+")
145             self.type = type_parts[0]
146             name = 'sa'
147             if len(type_parts) > 1:
148                 name = type_parts[1]
149         else:
150             self.authority = Xrn.hrn_auth_list(self.hrn)
151             name = Xrn.hrn_leaf(self.hrn)
152
153         authority_string = self.get_authority_urn()
154
155         if self.type == None:
156             urn = "+".join(['',authority_string,Xrn.unescape(name)])
157         else:
158             urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)])
159         
160         self.urn = Xrn.URN_PREFIX + urn
161
162     def dump_string(self):
163         result="-------------------- XRN\n"
164         result += "URN=%s\n"%self.urn
165         result += "HRN=%s\n"%self.hrn
166         result += "TYPE=%s\n"%self.type
167         result += "LEAF=%s\n"%self.get_leaf()
168         result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()
169         result += "AUTH(urn format)=%s\n"%self.get_authority_urn()
170         return result
171