Add function to parse scp / ssh style URLs.
[htsworkflow.git] / htsworkflow / util / url.py
1 """
2 Utilities to help handle urls
3 """
4 import collections
5
6 def normalize_url(url, scheme='http'):
7     """
8     Make sure there is a http at the head of what should be a url
9     """
10     # not much to do with None except avoid an exception
11     if url is None:
12         return None
13     
14     scheme_sep = '://'
15     if url.find(scheme_sep) != -1:
16         return url
17     else:
18         return scheme + scheme_sep + url
19
20 SSHURL = collections.namedtuple("SSHURL", "user host path")
21
22 def parse_ssh_url(url):
23     """Parse scp-style username, host and path.
24     """
25     # simple initialization
26     user = None
27     host = None
28     path = None
29     
30     colon = url.find(':')
31     if colon == -1:
32         raise ValueError("Invalid SSH URL: need <host>:<path>")
33     
34     path = url[colon+1:]
35     
36     user_host = url[:colon]
37     atsign = user_host.find('@')
38     if atsign != -1:
39         user = user_host[:atsign]
40         host = user_host[atsign+1:]
41     else:
42         host = user_host
43
44     return SSHURL(user, host, path)
45