Fix version output when missing.
[plcapi.git] / PLC / Namespace.py
1 ### $Id: Namespace.py
2 ### $URL:
3
4 URN_PREFIX = "urn:publicid:IDN"
5
6 def get_leaf(hrn):
7     parts = hrn.split(".")
8     return ".".join(parts[-1:])
9
10 def get_authority(hrn):
11     parts = hrn.split(".")
12     return ".".join(parts[:-1])
13
14 def hrn_to_pl_slicename(hrn):
15     parts = hrn.split(".")
16     return parts[-2] + "_" + parts[-1]
17
18 # assuming hrn is the hrn of an authority, return the plc authority name
19 def hrn_to_pl_authname(hrn):
20     parts = hrn.split(".")
21     return parts[-1]
22
23 # assuming hrn is the hrn of an authority, return the plc login_base
24 def hrn_to_pl_login_base(hrn):
25     return hrn_to_pl_authname(hrn)
26
27 def hostname_to_hrn(auth_hrn, login_base, hostname):
28     """
29     Convert hrn to plantelab name.
30     """
31     sfa_hostname = ".".join([auth_hrn, login_base, hostname.split(".")[0]])
32     return sfa_hostname
33
34 def slicename_to_hrn(auth_hrn, slicename):
35     """
36     Convert hrn to planetlab name.
37     """
38     parts = slicename.split("_")
39     slice_hrn = ".".join([auth_hrn, parts[0]]) + "." + "_".join(parts[1:])
40
41     return slice_hrn
42
43 def email_to_hrn(auth_hrn, email):
44     parts = email.split("@")
45     username = parts[0]
46     username = username.replace(".", "_")
47     person_hrn = ".".join([auth_hrn, username])
48
49     return person_hrn
50
51 def urn_to_hrn(urn):
52     """
53     convert a urn to hrn
54     return a tuple (hrn, type)
55     """
56
57     # if this is already a hrn dont do anything
58     if not urn or not urn.startswith(URN_PREFIX):
59         return urn, None
60
61     name = urn[len(URN_PREFIX):]
62     hrn_parts = name.split("+")
63
64     # type is always the second to last element in the list
65     type = hrn_parts.pop(-2)
66
67     # convert hrn_parts (list) into hrn (str) by doing the following
68     # remove blank elements
69     # replace ':' with '.'
70     # join list elements using '.'
71     hrn = '.'.join([part.replace(':', '.') for part in hrn_parts if part])
72
73     return str(hrn), str(type)
74
75
76 def hrn_to_urn(hrn, type=None):
77     """
78     convert an hrn and type to a urn string
79     """
80     # if  this is already a urn dont do anything
81     if not hrn or hrn.startswith(URN_PREFIX):
82         return hrn
83
84     authority = get_authority(hrn)
85     name = get_leaf(hrn)
86     urn = "+".join([unicode(part).replace('.', ':') \
87                     for part in ['',authority,type,name]])
88
89     return URN_PREFIX + urn