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