1
# Copyright (C) 2006-2010 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
from __future__ import absolute_import
19
"""A collection of function for handling URL operations."""
25
from bzrlib.lazy_import import lazy_import
26
lazy_import(globals(), """
27
from posixpath import split as _posix_split
38
def basename(url, exclude_trailing_slash=True):
39
"""Return the last component of a URL.
41
:param url: The URL in question
42
:param exclude_trailing_slash: If the url looks like "path/to/foo/"
43
ignore the final slash and return 'foo' rather than ''
44
:return: Just the final component of the URL. This can return ''
45
if you don't exclude_trailing_slash, or if you are at the
48
return split(url, exclude_trailing_slash=exclude_trailing_slash)[1]
51
def dirname(url, exclude_trailing_slash=True):
52
"""Return the parent directory of the given path.
54
:param url: Relative or absolute URL
55
:param exclude_trailing_slash: Remove a final slash
56
(treat http://host/foo/ as http://host/foo, but
57
http://host/ stays http://host/)
58
:return: Everything in the URL except the last path chunk
60
# TODO: jam 20060502 This was named dirname to be consistent
61
# with the os functions, but maybe "parent" would be better
62
return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
66
"""Escape relpath to be a valid url."""
67
if isinstance(relpath, unicode):
68
relpath = relpath.encode('utf-8')
69
# After quoting and encoding, the path should be perfectly
70
# safe as a plain ASCII string, str() just enforces this
71
return str(urllib.quote(relpath, safe='/~'))
74
def file_relpath(base, path):
75
"""Compute just the relative sub-portion of a url
77
This assumes that both paths are already fully specified file:// URLs.
79
if len(base) < MIN_ABS_FILEURL_LENGTH:
80
raise ValueError('Length of base (%r) must equal or'
81
' exceed the platform minimum url length (which is %d)' %
82
(base, MIN_ABS_FILEURL_LENGTH))
83
base = osutils.normpath(local_path_from_url(base))
84
path = osutils.normpath(local_path_from_url(path))
85
return escape(osutils.relpath(base, path))
88
def _find_scheme_and_separator(url):
89
"""Find the scheme separator (://) and the first path separator
91
This is just a helper functions for other path utilities.
92
It could probably be replaced by urlparse
94
m = _url_scheme_re.match(url)
98
scheme = m.group('scheme')
99
path = m.group('path')
101
# Find the path separating slash
102
# (first slash after the ://)
103
first_path_slash = path.find('/')
104
if first_path_slash == -1:
105
return len(scheme), None
106
return len(scheme), first_path_slash+m.start('path')
110
"""Tests whether a URL is in actual fact a URL."""
111
return _url_scheme_re.match(url) is not None
114
def join(base, *args):
115
"""Create a URL by joining sections.
117
This will normalize '..', assuming that paths are absolute
118
(it assumes no symlinks in either path)
120
If any of *args is an absolute URL, it will be treated correctly.
122
join('http://foo', 'http://bar') => 'http://bar'
123
join('http://foo', 'bar') => 'http://foo/bar'
124
join('http://foo', 'bar', '../baz') => 'http://foo/baz'
128
scheme_end, path_start = _find_scheme_and_separator(base)
129
if scheme_end is None and path_start is None:
131
elif path_start is None:
132
path_start = len(base)
133
path = base[path_start:]
135
arg_scheme_end, arg_path_start = _find_scheme_and_separator(arg)
136
if arg_scheme_end is None and arg_path_start is None:
138
elif arg_path_start is None:
139
arg_path_start = len(arg)
140
if arg_scheme_end is not None:
142
path = arg[arg_path_start:]
143
scheme_end = arg_scheme_end
144
path_start = arg_path_start
146
path = joinpath(path, arg)
147
return base[:path_start] + path
150
def joinpath(base, *args):
151
"""Join URL path segments to a URL path segment.
153
This is somewhat like osutils.joinpath, but intended for URLs.
155
XXX: this duplicates some normalisation logic, and also duplicates a lot of
156
path handling logic that already exists in some Transport implementations.
157
We really should try to have exactly one place in the code base responsible
158
for combining paths of URLs.
160
path = base.split('/')
161
if len(path) > 1 and path[-1] == '':
162
#If the path ends in a trailing /, remove it.
165
if arg.startswith('/'):
167
for chunk in arg.split('/'):
172
raise errors.InvalidURLJoin('Cannot go above root',
180
return '/'.join(path)
183
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
184
def _posix_local_path_from_url(url):
185
"""Convert a url like file:///path/to/foo into /path/to/foo"""
186
url = split_segment_parameters_raw(url)[0]
187
file_localhost_prefix = 'file://localhost/'
188
if url.startswith(file_localhost_prefix):
189
path = url[len(file_localhost_prefix) - 1:]
190
elif not url.startswith('file:///'):
191
raise errors.InvalidURL(
192
url, 'local urls must start with file:/// or file://localhost/')
194
path = url[len('file://'):]
195
# We only strip off 2 slashes
196
return unescape(path)
199
def _posix_local_path_to_url(path):
200
"""Convert a local path like ./foo into a URL like file:///path/to/foo
202
This also handles transforming escaping unicode characters, etc.
204
# importing directly from posixpath allows us to test this
205
# on non-posix platforms
206
return 'file://' + escape(osutils._posix_abspath(path))
209
def _win32_local_path_from_url(url):
210
"""Convert a url like file:///C:/path/to/foo into C:/path/to/foo"""
211
if not url.startswith('file://'):
212
raise errors.InvalidURL(url, 'local urls must start with file:///, '
213
'UNC path urls must start with file://')
214
url = split_segment_parameters_raw(url)[0]
215
# We strip off all 3 slashes
216
win32_url = url[len('file:'):]
217
# check for UNC path: //HOST/path
218
if not win32_url.startswith('///'):
219
if (win32_url[2] == '/'
220
or win32_url[3] in '|:'):
221
raise errors.InvalidURL(url, 'Win32 UNC path urls'
222
' have form file://HOST/path')
223
return unescape(win32_url)
225
# allow empty paths so we can serve all roots
226
if win32_url == '///':
229
# usual local path with drive letter
230
if (len(win32_url) < 6
231
or win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
232
'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
233
or win32_url[4] not in '|:'
234
or win32_url[5] != '/'):
235
raise errors.InvalidURL(url, 'Win32 file urls start with'
236
' file:///x:/, where x is a valid drive letter')
237
return win32_url[3].upper() + u':' + unescape(win32_url[5:])
240
def _win32_local_path_to_url(path):
241
"""Convert a local path like ./foo into a URL like file:///C:/path/to/foo
243
This also handles transforming escaping unicode characters, etc.
245
# importing directly from ntpath allows us to test this
246
# on non-win32 platform
247
# FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
248
# which actually strips trailing space characters.
249
# The worst part is that on linux ntpath.abspath has different
250
# semantics, since 'nt' is not an available module.
254
win32_path = osutils._win32_abspath(path)
255
# check for UNC path \\HOST\path
256
if win32_path.startswith('//'):
257
return 'file:' + escape(win32_path)
258
return ('file:///' + str(win32_path[0].upper()) + ':' +
259
escape(win32_path[2:]))
262
local_path_to_url = _posix_local_path_to_url
263
local_path_from_url = _posix_local_path_from_url
264
MIN_ABS_FILEURL_LENGTH = len('file:///')
265
WIN32_MIN_ABS_FILEURL_LENGTH = len('file:///C:/')
267
if sys.platform == 'win32':
268
local_path_to_url = _win32_local_path_to_url
269
local_path_from_url = _win32_local_path_from_url
271
MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
274
_url_scheme_re = re.compile(r'^(?P<scheme>[^:/]{2,}):(//)?(?P<path>.*)$')
275
_url_hex_escapes_re = re.compile(r'(%[0-9a-fA-F]{2})')
278
def _unescape_safe_chars(matchobj):
279
"""re.sub callback to convert hex-escapes to plain characters (if safe).
281
e.g. '%7E' will be converted to '~'.
283
hex_digits = matchobj.group(0)[1:]
284
char = chr(int(hex_digits, 16))
285
if char in _url_dont_escape_characters:
288
return matchobj.group(0).upper()
291
def normalize_url(url):
292
"""Make sure that a path string is in fully normalized URL form.
294
This handles URLs which have unicode characters, spaces,
295
special characters, etc.
297
It has two basic modes of operation, depending on whether the
298
supplied string starts with a url specifier (scheme://) or not.
299
If it does not have a specifier it is considered a local path,
300
and will be converted into a file:/// url. Non-ascii characters
301
will be encoded using utf-8.
302
If it does have a url specifier, it will be treated as a "hybrid"
303
URL. Basically, a URL that should have URL special characters already
304
escaped (like +?&# etc), but may have unicode characters, etc
305
which would not be valid in a real URL.
307
:param url: Either a hybrid URL or a local path
308
:return: A normalized URL which only includes 7-bit ASCII characters.
310
scheme_end, path_start = _find_scheme_and_separator(url)
311
if scheme_end is None:
312
return local_path_to_url(url)
313
prefix = url[:path_start]
314
path = url[path_start:]
315
if not isinstance(url, unicode):
317
if c not in _url_safe_characters:
318
raise errors.InvalidURL(url, 'URLs can only contain specific'
319
' safe characters (not %r)' % c)
320
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
321
return str(prefix + ''.join(path))
323
# We have a unicode (hybrid) url
324
path_chars = list(path)
326
for i in xrange(len(path_chars)):
327
if path_chars[i] not in _url_safe_characters:
328
chars = path_chars[i].encode('utf-8')
329
path_chars[i] = ''.join(
330
['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
331
path = ''.join(path_chars)
332
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
333
return str(prefix + path)
336
def relative_url(base, other):
337
"""Return a path to other from base.
339
If other is unrelated to base, return other. Else return a relative path.
340
This assumes no symlinks as part of the url.
342
dummy, base_first_slash = _find_scheme_and_separator(base)
343
if base_first_slash is None:
346
dummy, other_first_slash = _find_scheme_and_separator(other)
347
if other_first_slash is None:
350
# this takes care of differing schemes or hosts
351
base_scheme = base[:base_first_slash]
352
other_scheme = other[:other_first_slash]
353
if base_scheme != other_scheme:
355
elif sys.platform == 'win32' and base_scheme == 'file://':
356
base_drive = base[base_first_slash+1:base_first_slash+3]
357
other_drive = other[other_first_slash+1:other_first_slash+3]
358
if base_drive != other_drive:
361
base_path = base[base_first_slash+1:]
362
other_path = other[other_first_slash+1:]
364
if base_path.endswith('/'):
365
base_path = base_path[:-1]
367
base_sections = base_path.split('/')
368
other_sections = other_path.split('/')
370
if base_sections == ['']:
372
if other_sections == ['']:
376
for b, o in zip(base_sections, other_sections):
379
output_sections.append(b)
381
match_len = len(output_sections)
382
output_sections = ['..' for x in base_sections[match_len:]]
383
output_sections.extend(other_sections[match_len:])
385
return "/".join(output_sections) or "."
388
def _win32_extract_drive_letter(url_base, path):
389
"""On win32 the drive letter needs to be added to the url base."""
390
# Strip off the drive letter
391
# path is currently /C:/foo
392
if len(path) < 4 or path[2] not in ':|' or path[3] != '/':
393
raise errors.InvalidURL(url_base + path,
394
'win32 file:/// paths need a drive letter')
395
url_base += path[0:3] # file:// + /C:
396
path = path[3:] # /foo
397
return url_base, path
400
def split(url, exclude_trailing_slash=True):
401
"""Split a URL into its parent directory and a child directory.
403
:param url: A relative or absolute URL
404
:param exclude_trailing_slash: Strip off a final '/' if it is part
405
of the path (but not if it is part of the protocol specification)
407
:return: (parent_url, child_dir). child_dir may be the empty string if we're at
410
scheme_loc, first_path_slash = _find_scheme_and_separator(url)
412
if first_path_slash is None:
413
# We have either a relative path, or no separating slash
414
if scheme_loc is None:
416
if exclude_trailing_slash and url.endswith('/'):
418
return _posix_split(url)
420
# Scheme with no path
423
# We have a fully defined path
424
url_base = url[:first_path_slash] # http://host, file://
425
path = url[first_path_slash:] # /file/foo
427
if sys.platform == 'win32' and url.startswith('file:///'):
428
# Strip off the drive letter
429
# url_base is currently file://
430
# path is currently /C:/foo
431
url_base, path = _win32_extract_drive_letter(url_base, path)
432
# now it should be file:///C: and /foo
434
if exclude_trailing_slash and len(path) > 1 and path.endswith('/'):
436
head, tail = _posix_split(path)
437
return url_base + head, tail
440
def split_segment_parameters_raw(url):
441
"""Split the subsegment of the last segment of a URL.
443
:param url: A relative or absolute URL
444
:return: (url, subsegments)
446
# GZ 2011-11-18: Dodgy removing the terminal slash like this, function
447
# operates on urls not url+segments, and Transport classes
448
# should not be blindly adding slashes in the first place.
449
lurl = strip_trailing_slash(url)
450
# Segments begin at first comma after last forward slash, if one exists
451
segment_start = lurl.find(",", lurl.rfind("/")+1)
452
if segment_start == -1:
454
return (lurl[:segment_start], lurl[segment_start+1:].split(","))
457
def split_segment_parameters(url):
458
"""Split the segment parameters of the last segment of a URL.
460
:param url: A relative or absolute URL
461
:return: (url, segment_parameters)
463
(base_url, subsegments) = split_segment_parameters_raw(url)
465
for subsegment in subsegments:
466
(key, value) = subsegment.split("=", 1)
467
parameters[key] = value
468
return (base_url, parameters)
471
def join_segment_parameters_raw(base, *subsegments):
472
"""Create a new URL by adding subsegments to an existing one.
474
This adds the specified subsegments to the last path in the specified
475
base URL. The subsegments should be bytestrings.
477
:note: You probably want to use join_segment_parameters instead.
481
for subsegment in subsegments:
482
if type(subsegment) is not str:
483
raise TypeError("Subsegment %r is not a bytestring" % subsegment)
484
if "," in subsegment:
485
raise errors.InvalidURLJoin(", exists in subsegments",
487
return ",".join((base,) + subsegments)
490
def join_segment_parameters(url, parameters):
491
"""Create a new URL by adding segment parameters to an existing one.
493
The parameters of the last segment in the URL will be updated; if a
494
parameter with the same key already exists it will be overwritten.
496
:param url: A URL, as string
497
:param parameters: Dictionary of parameters, keys and values as bytestrings
499
(base, existing_parameters) = split_segment_parameters(url)
501
new_parameters.update(existing_parameters)
502
for key, value in parameters.iteritems():
503
if type(key) is not str:
504
raise TypeError("parameter key %r is not a bytestring" % key)
505
if type(value) is not str:
506
raise TypeError("parameter value %r for %s is not a bytestring" %
509
raise errors.InvalidURLJoin("= exists in parameter key", url,
511
new_parameters[key] = value
512
return join_segment_parameters_raw(base,
513
*["%s=%s" % item for item in sorted(new_parameters.items())])
516
def _win32_strip_local_trailing_slash(url):
517
"""Strip slashes after the drive letter"""
518
if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
524
def strip_trailing_slash(url):
525
"""Strip trailing slash, except for root paths.
527
The definition of 'root path' is platform-dependent.
528
This assumes that all URLs are valid netloc urls, such that they
531
It searches for ://, and then refuses to remove the next '/'.
532
It can also handle relative paths
534
path/to/foo => path/to/foo
535
path/to/foo/ => path/to/foo
536
http://host/path/ => http://host/path
537
http://host/path => http://host/path
538
http://host/ => http://host/
540
file:///foo/ => file:///foo
541
# This is unique on win32 platforms, and is the only URL
542
# format which does it differently.
543
file:///c|/ => file:///c:/
545
if not url.endswith('/'):
548
if sys.platform == 'win32' and url.startswith('file://'):
549
return _win32_strip_local_trailing_slash(url)
551
scheme_loc, first_path_slash = _find_scheme_and_separator(url)
552
if scheme_loc is None:
553
# This is a relative path, as it has no scheme
554
# so just chop off the last character
557
if first_path_slash is None or first_path_slash == len(url)-1:
558
# Don't chop off anything if the only slash is the path
566
"""Unescape relpath from url format.
568
This returns a Unicode path from a URL
570
# jam 20060427 URLs are supposed to be ASCII only strings
571
# If they are passed in as unicode, urllib.unquote
572
# will return a UNICODE string, which actually contains
573
# utf-8 bytes. So we have to ensure that they are
574
# plain ASCII strings, or the final .decode will
575
# try to encode the UNICODE => ASCII, and then decode
579
except UnicodeError, e:
580
raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
582
unquoted = urllib.unquote(url)
584
unicode_path = unquoted.decode('utf-8')
585
except UnicodeError, e:
586
raise errors.InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
590
# These are characters that if escaped, should stay that way
591
_no_decode_chars = ';/?:@&=+$,#'
592
_no_decode_ords = [ord(c) for c in _no_decode_chars]
593
_no_decode_hex = (['%02x' % o for o in _no_decode_ords]
594
+ ['%02X' % o for o in _no_decode_ords])
595
_hex_display_map = dict(([('%02x' % o, chr(o)) for o in range(256)]
596
+ [('%02X' % o, chr(o)) for o in range(256)]))
597
#These entries get mapped to themselves
598
_hex_display_map.update((hex,'%'+hex) for hex in _no_decode_hex)
600
# These characters shouldn't be percent-encoded, and it's always safe to
601
# unencode them if they are.
602
_url_dont_escape_characters = set(
603
"abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
604
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
605
"0123456789" # Numbers
606
"-._~" # Unreserved characters
609
# These characters should not be escaped
610
_url_safe_characters = set(
611
"abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
612
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
613
"0123456789" # Numbers
614
"_.-!~*'()" # Unreserved characters
615
"/;?:@&=+$," # Reserved characters
616
"%#" # Extra reserved characters
619
def unescape_for_display(url, encoding):
620
"""Decode what you can for a URL, so that we get a nice looking path.
622
This will turn file:// urls into local paths, and try to decode
623
any portions of a http:// style url that it can.
625
Any sections of the URL which can't be represented in the encoding or
626
need to stay as escapes are left alone.
628
:param url: A 7-bit ASCII URL
629
:param encoding: The final output encoding
631
:return: A unicode string which can be safely encoded into the
635
raise ValueError('you cannot specify None for the display encoding')
636
if url.startswith('file://'):
638
path = local_path_from_url(url)
639
path.encode(encoding)
644
# Split into sections to try to decode utf-8
646
for i in xrange(1, len(res)):
647
escaped_chunks = res[i].split('%')
648
for j in xrange(1, len(escaped_chunks)):
649
item = escaped_chunks[j]
651
escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
653
# Put back the percent symbol
654
escaped_chunks[j] = '%' + item
655
except UnicodeDecodeError:
656
escaped_chunks[j] = unichr(int(item[:2], 16)) + item[2:]
657
unescaped = ''.join(escaped_chunks)
659
decoded = unescaped.decode('utf-8')
660
except UnicodeDecodeError:
661
# If this path segment cannot be properly utf-8 decoded
662
# after doing unescaping we will just leave it alone
666
decoded.encode(encoding)
667
except UnicodeEncodeError:
668
# If this chunk cannot be encoded in the local
669
# encoding, then we should leave it alone
672
# Otherwise take the url decoded one
674
return u'/'.join(res)
677
def derive_to_location(from_location):
678
"""Derive a TO_LOCATION given a FROM_LOCATION.
680
The normal case is a FROM_LOCATION of http://foo/bar => bar.
681
The Right Thing for some logical destinations may differ though
682
because no / may be present at all. In that case, the result is
683
the full name without the scheme indicator, e.g. lp:foo-bar => foo-bar.
684
This latter case also applies when a Windows drive
685
is used without a path, e.g. c:foo-bar => foo-bar.
686
If no /, path separator or : is found, the from_location is returned.
688
if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
689
return os.path.basename(from_location.rstrip("/\\"))
691
sep = from_location.find(":")
693
return from_location[sep+1:]
698
def _is_absolute(url):
699
return (osutils.pathjoin('/foo', url) == url)
702
def rebase_url(url, old_base, new_base):
703
"""Convert a relative path from an old base URL to a new base URL.
705
The result will be a relative path.
706
Absolute paths and full URLs are returned unaltered.
708
scheme, separator = _find_scheme_and_separator(url)
709
if scheme is not None:
711
if _is_absolute(url):
713
old_parsed = urlparse.urlparse(old_base)
714
new_parsed = urlparse.urlparse(new_base)
715
if (old_parsed[:2]) != (new_parsed[:2]):
716
raise errors.InvalidRebaseURLs(old_base, new_base)
717
return determine_relative_path(new_parsed[2],
718
join(old_parsed[2], url))
721
def determine_relative_path(from_path, to_path):
722
"""Determine a relative path from from_path to to_path."""
723
from_segments = osutils.splitpath(from_path)
724
to_segments = osutils.splitpath(to_path)
726
for count, (from_element, to_element) in enumerate(zip(from_segments,
728
if from_element != to_element:
732
unique_from = from_segments[count:]
733
unique_to = to_segments[count:]
734
segments = (['..'] * len(unique_from) + unique_to)
735
if len(segments) == 0:
737
return osutils.pathjoin(*segments)
743
def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
746
self.quoted_host = quoted_host
747
self.host = urllib.unquote(self.quoted_host)
748
self.quoted_user = quoted_user
749
if self.quoted_user is not None:
750
self.user = urllib.unquote(self.quoted_user)
753
self.quoted_password = quoted_password
754
if self.quoted_password is not None:
755
self.password = urllib.unquote(self.quoted_password)
759
self.quoted_path = _url_hex_escapes_re.sub(_unescape_safe_chars, quoted_path)
760
self.path = urllib.unquote(self.quoted_path)
762
def __eq__(self, other):
763
return (isinstance(other, self.__class__) and
764
self.scheme == other.scheme and
765
self.host == other.host and
766
self.user == other.user and
767
self.password == other.password and
768
self.path == other.path)
771
return "<%s(%r, %r, %r, %r, %r, %r)>" % (
772
self.__class__.__name__,
773
self.scheme, self.quoted_user, self.quoted_password,
774
self.quoted_host, self.port, self.quoted_path)
777
def from_string(cls, url):
778
"""Create a URL object from a string.
780
:param url: URL as bytestring
782
if isinstance(url, unicode):
783
raise errors.InvalidURL('should be ascii:\n%r' % url)
784
url = url.encode('utf-8')
785
(scheme, netloc, path, params,
786
query, fragment) = urlparse.urlparse(url, allow_fragments=False)
787
user = password = host = port = None
789
user, host = netloc.rsplit('@', 1)
791
user, password = user.split(':', 1)
795
if ':' in host and not (host[0] == '[' and host[-1] == ']'):
797
host, port = host.rsplit(':',1)
801
raise errors.InvalidURL('invalid port number %s in url:\n%s' %
803
if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
806
return cls(scheme, user, password, host, port, path)
809
netloc = self.quoted_host
811
netloc = "[%s]" % netloc
812
if self.quoted_user is not None:
813
# Note that we don't put the password back even if we
814
# have one so that it doesn't get accidentally
816
netloc = '%s@%s' % (self.quoted_user, netloc)
817
if self.port is not None:
818
netloc = '%s:%d' % (netloc, self.port)
819
return urlparse.urlunparse(
820
(self.scheme, netloc, self.quoted_path, None, None, None))
823
def _combine_paths(base_path, relpath):
824
"""Transform a Transport-relative path to a remote absolute path.
826
This does not handle substitution of ~ but does handle '..' and '.'
831
t._combine_paths('/home/sarah', 'project/foo')
832
=> '/home/sarah/project/foo'
833
t._combine_paths('/home/sarah', '../../etc')
835
t._combine_paths('/home/sarah', '/etc')
838
:param base_path: base path
839
:param relpath: relative url string for relative part of remote path.
840
:return: urlencoded string for final path.
842
if not isinstance(relpath, str):
843
raise errors.InvalidURL(relpath)
844
relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
845
if relpath.startswith('/'):
848
base_parts = base_path.split('/')
849
if len(base_parts) > 0 and base_parts[-1] == '':
850
base_parts = base_parts[:-1]
851
for p in relpath.split('/'):
853
if len(base_parts) == 0:
854
# In most filesystems, a request for the parent
855
# of root, just returns root.
862
path = '/'.join(base_parts)
863
if not path.startswith('/'):
867
def clone(self, offset=None):
868
"""Return a new URL for a path relative to this URL.
870
:param offset: A relative path, already urlencoded
871
:return: `URL` instance
873
if offset is not None:
874
relative = unescape(offset).encode('utf-8')
875
path = self._combine_paths(self.path, relative)
876
path = urllib.quote(path, safe="/~")
878
path = self.quoted_path
879
return self.__class__(self.scheme, self.quoted_user,
880
self.quoted_password, self.quoted_host, self.port,
885
"""Extract the server address, the credentials and the path from the url.
887
user, password, host and path should be quoted if they contain reserved
890
:param url: an quoted url
891
:return: (scheme, user, password, host, port, path) tuple, all fields
894
parsed_url = URL.from_string(url)
895
return (parsed_url.scheme, parsed_url.user, parsed_url.password,
896
parsed_url.host, parsed_url.port, parsed_url.path)