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
"""A collection of function for handling URL operations."""
19
from __future__ import absolute_import
28
from urllib import parse as urlparse
30
from .lazy_import import lazy_import
31
lazy_import(globals(), """
32
from posixpath import split as _posix_split
45
def basename(url, exclude_trailing_slash=True):
46
"""Return the last component of a URL.
48
:param url: The URL in question
49
:param exclude_trailing_slash: If the url looks like "path/to/foo/"
50
ignore the final slash and return 'foo' rather than ''
51
:return: Just the final component of the URL. This can return ''
52
if you don't exclude_trailing_slash, or if you are at the
55
return split(url, exclude_trailing_slash=exclude_trailing_slash)[1]
58
def dirname(url, exclude_trailing_slash=True):
59
"""Return the parent directory of the given path.
61
:param url: Relative or absolute URL
62
:param exclude_trailing_slash: Remove a final slash
63
(treat http://host/foo/ as http://host/foo, but
64
http://host/ stays http://host/)
65
:return: Everything in the URL except the last path chunk
67
# TODO: jam 20060502 This was named dirname to be consistent
68
# with the os functions, but maybe "parent" would be better
69
return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
72
# Private copies of quote and unquote, copied from Python's
73
# urllib module because urllib unconditionally imports socket, which imports
76
always_safe = (b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
77
b'abcdefghijklmnopqrstuvwxyz'
80
for i, c in zip(range(256), bytes(bytearray(range(256)))):
81
_safe_map[c] = c if (i < 128 and c in always_safe) else '%{0:02X}'.format(i).encode('ascii')
85
def quote(s, safe=b'/'):
86
"""quote('abc def') -> 'abc%20def'
88
Each part of a URL, e.g. the path info, the query, etc., has a
89
different set of reserved characters that must be quoted.
91
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
92
the following reserved characters.
94
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
97
Each of these characters is reserved in some component of a URL,
98
but not necessarily in all of them.
100
By default, the quote function is intended for quoting the path
101
section of a URL. Thus, it will not encode '/'. This character
102
is reserved, but in typical usage the quote function is being
103
called on a path where the existing slash characters are used as
109
raise TypeError('None object cannot be quoted')
111
cachekey = (safe, always_safe)
113
(quoter, safe) = _safe_quoters[cachekey]
115
safe_map = _safe_map.copy()
116
safe_map.update([(c, c) for c in safe])
117
quoter = safe_map.__getitem__
118
safe = always_safe + safe
119
_safe_quoters[cachekey] = (quoter, safe)
120
if not s.rstrip(safe):
122
return b''.join(map(quoter, s))
125
_hexdig = '0123456789ABCDEFabcdef'
126
_hextochr = dict((a + b, chr(int(a + b, 16)))
127
for a in _hexdig for b in _hexdig)
130
"""unquote('abc%20def') -> 'abc def'."""
138
s += _hextochr[item[:2]] + item[2:]
141
except UnicodeDecodeError:
142
s += unichr(int(item[:2], 16)) + item[2:]
147
"""Escape relpath to be a valid url."""
148
if isinstance(relpath, text_type):
149
relpath = relpath.encode('utf-8')
150
return quote(relpath, safe=b'/~')
153
def file_relpath(base, path):
154
"""Compute just the relative sub-portion of a url
156
This assumes that both paths are already fully specified file:// URLs.
158
if len(base) < MIN_ABS_FILEURL_LENGTH:
159
raise ValueError('Length of base (%r) must equal or'
160
' exceed the platform minimum url length (which is %d)' %
161
(base, MIN_ABS_FILEURL_LENGTH))
162
base = osutils.normpath(local_path_from_url(base))
163
path = osutils.normpath(local_path_from_url(path))
164
return escape(osutils.relpath(base, path))
167
def _find_scheme_and_separator(url):
168
"""Find the scheme separator (://) and the first path separator
170
This is just a helper functions for other path utilities.
171
It could probably be replaced by urlparse
173
m = _url_scheme_re.match(url)
177
scheme = m.group('scheme')
178
path = m.group('path')
180
# Find the path separating slash
181
# (first slash after the ://)
182
first_path_slash = path.find(b'/')
183
if first_path_slash == -1:
184
return len(scheme), None
185
return len(scheme), first_path_slash+m.start('path')
189
"""Tests whether a URL is in actual fact a URL."""
190
return _url_scheme_re.match(url) is not None
193
def join(base, *args):
194
"""Create a URL by joining sections.
196
This will normalize '..', assuming that paths are absolute
197
(it assumes no symlinks in either path)
199
If any of *args is an absolute URL, it will be treated correctly.
201
join('http://foo', 'http://bar') => 'http://bar'
202
join('http://foo', 'bar') => 'http://foo/bar'
203
join('http://foo', 'bar', '../baz') => 'http://foo/baz'
207
scheme_end, path_start = _find_scheme_and_separator(base)
208
if scheme_end is None and path_start is None:
210
elif path_start is None:
211
path_start = len(base)
212
path = base[path_start:]
214
arg_scheme_end, arg_path_start = _find_scheme_and_separator(arg)
215
if arg_scheme_end is None and arg_path_start is None:
217
elif arg_path_start is None:
218
arg_path_start = len(arg)
219
if arg_scheme_end is not None:
221
path = arg[arg_path_start:]
222
scheme_end = arg_scheme_end
223
path_start = arg_path_start
225
path = joinpath(path, arg)
226
return base[:path_start] + path
229
def joinpath(base, *args):
230
"""Join URL path segments to a URL path segment.
232
This is somewhat like osutils.joinpath, but intended for URLs.
234
XXX: this duplicates some normalisation logic, and also duplicates a lot of
235
path handling logic that already exists in some Transport implementations.
236
We really should try to have exactly one place in the code base responsible
237
for combining paths of URLs.
239
path = base.split(b'/')
240
if len(path) > 1 and path[-1] == b'':
241
#If the path ends in a trailing /, remove it.
244
if arg.startswith(b'/'):
246
for chunk in arg.split(b'/'):
251
raise errors.InvalidURLJoin('Cannot go above root',
259
return b'/'.join(path)
262
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
263
def _posix_local_path_from_url(url):
264
"""Convert a url like file:///path/to/foo into /path/to/foo"""
265
url = split_segment_parameters_raw(url)[0]
266
file_localhost_prefix = b'file://localhost/'
267
if url.startswith(file_localhost_prefix):
268
path = url[len(file_localhost_prefix) - 1:]
269
elif not url.startswith(b'file:///'):
270
raise errors.InvalidURL(
271
url, 'local urls must start with file:/// or file://localhost/')
273
path = url[len(b'file://'):]
274
# We only strip off 2 slashes
275
return unescape(path)
278
def _posix_local_path_to_url(path):
279
"""Convert a local path like ./foo into a URL like file:///path/to/foo
281
This also handles transforming escaping unicode characters, etc.
283
# importing directly from posixpath allows us to test this
284
# on non-posix platforms
285
return b'file://' + escape(osutils._posix_abspath(path))
288
def _win32_local_path_from_url(url):
289
"""Convert a url like file:///C:/path/to/foo into C:/path/to/foo"""
290
if not url.startswith('file://'):
291
raise errors.InvalidURL(url, 'local urls must start with file:///, '
292
'UNC path urls must start with file://')
293
url = split_segment_parameters_raw(url)[0]
294
# We strip off all 3 slashes
295
win32_url = url[len('file:'):]
296
# check for UNC path: //HOST/path
297
if not win32_url.startswith('///'):
298
if (win32_url[2] == '/'
299
or win32_url[3] in '|:'):
300
raise errors.InvalidURL(url, 'Win32 UNC path urls'
301
' have form file://HOST/path')
302
return unescape(win32_url)
304
# allow empty paths so we can serve all roots
305
if win32_url == '///':
308
# usual local path with drive letter
309
if (len(win32_url) < 6
310
or win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
311
'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
312
or win32_url[4] not in '|:'
313
or win32_url[5] != '/'):
314
raise errors.InvalidURL(url, 'Win32 file urls start with'
315
' file:///x:/, where x is a valid drive letter')
316
return win32_url[3].upper() + u':' + unescape(win32_url[5:])
319
def _win32_local_path_to_url(path):
320
"""Convert a local path like ./foo into a URL like file:///C:/path/to/foo
322
This also handles transforming escaping unicode characters, etc.
324
# importing directly from ntpath allows us to test this
325
# on non-win32 platform
326
# FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
327
# which actually strips trailing space characters.
328
# The worst part is that on linux ntpath.abspath has different
329
# semantics, since 'nt' is not an available module.
333
win32_path = osutils._win32_abspath(path)
334
# check for UNC path \\HOST\path
335
if win32_path.startswith('//'):
336
return 'file:' + escape(win32_path)
337
return ('file:///' + str(win32_path[0].upper()) + ':' +
338
escape(win32_path[2:]))
341
local_path_to_url = _posix_local_path_to_url
342
local_path_from_url = _posix_local_path_from_url
343
MIN_ABS_FILEURL_LENGTH = len('file:///')
344
WIN32_MIN_ABS_FILEURL_LENGTH = len('file:///C:/')
346
if sys.platform == 'win32':
347
local_path_to_url = _win32_local_path_to_url
348
local_path_from_url = _win32_local_path_from_url
350
MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
353
_url_scheme_re = re.compile(b'^(?P<scheme>[^:/]{2,}):(//)?(?P<path>.*)$')
354
_url_hex_escapes_re = re.compile(b'(%[0-9a-fA-F]{2})')
357
def _unescape_safe_chars(matchobj):
358
"""re.sub callback to convert hex-escapes to plain characters (if safe).
360
e.g. '%7E' will be converted to '~'.
362
hex_digits = matchobj.group(0)[1:]
363
char = chr(int(hex_digits, 16))
364
if char in _url_dont_escape_characters:
367
return matchobj.group(0).upper()
370
def normalize_url(url):
371
"""Make sure that a path string is in fully normalized URL form.
373
This handles URLs which have unicode characters, spaces,
374
special characters, etc.
376
It has two basic modes of operation, depending on whether the
377
supplied string starts with a url specifier (scheme://) or not.
378
If it does not have a specifier it is considered a local path,
379
and will be converted into a file:/// url. Non-ascii characters
380
will be encoded using utf-8.
381
If it does have a url specifier, it will be treated as a "hybrid"
382
URL. Basically, a URL that should have URL special characters already
383
escaped (like +?&# etc), but may have unicode characters, etc
384
which would not be valid in a real URL.
386
:param url: Either a hybrid URL or a local path
387
:return: A normalized URL which only includes 7-bit ASCII characters.
389
scheme_end, path_start = _find_scheme_and_separator(url)
390
if scheme_end is None:
391
return local_path_to_url(url)
392
prefix = url[:path_start]
393
path = url[path_start:]
394
if not isinstance(url, unicode):
396
if c not in _url_safe_characters:
397
raise errors.InvalidURL(url, 'URLs can only contain specific'
398
' safe characters (not %r)' % c)
399
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
400
return str(prefix + ''.join(path))
402
# We have a unicode (hybrid) url
403
path_chars = list(path)
405
for i in range(len(path_chars)):
406
if path_chars[i] not in _url_safe_characters:
407
chars = path_chars[i].encode('utf-8')
408
path_chars[i] = ''.join(
409
['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
410
path = ''.join(path_chars)
411
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
412
return str(prefix + path)
415
def relative_url(base, other):
416
"""Return a path to other from base.
418
If other is unrelated to base, return other. Else return a relative path.
419
This assumes no symlinks as part of the url.
421
dummy, base_first_slash = _find_scheme_and_separator(base)
422
if base_first_slash is None:
425
dummy, other_first_slash = _find_scheme_and_separator(other)
426
if other_first_slash is None:
429
# this takes care of differing schemes or hosts
430
base_scheme = base[:base_first_slash]
431
other_scheme = other[:other_first_slash]
432
if base_scheme != other_scheme:
434
elif sys.platform == 'win32' and base_scheme == 'file://':
435
base_drive = base[base_first_slash+1:base_first_slash+3]
436
other_drive = other[other_first_slash+1:other_first_slash+3]
437
if base_drive != other_drive:
440
base_path = base[base_first_slash+1:]
441
other_path = other[other_first_slash+1:]
443
if base_path.endswith('/'):
444
base_path = base_path[:-1]
446
base_sections = base_path.split('/')
447
other_sections = other_path.split('/')
449
if base_sections == ['']:
451
if other_sections == ['']:
455
for b, o in zip(base_sections, other_sections):
458
output_sections.append(b)
460
match_len = len(output_sections)
461
output_sections = ['..' for x in base_sections[match_len:]]
462
output_sections.extend(other_sections[match_len:])
464
return "/".join(output_sections) or "."
467
def _win32_extract_drive_letter(url_base, path):
468
"""On win32 the drive letter needs to be added to the url base."""
469
# Strip off the drive letter
470
# path is currently /C:/foo
471
if len(path) < 4 or path[2] not in ':|' or path[3] != '/':
472
raise errors.InvalidURL(url_base + path,
473
'win32 file:/// paths need a drive letter')
474
url_base += path[0:3] # file:// + /C:
475
path = path[3:] # /foo
476
return url_base, path
479
def split(url, exclude_trailing_slash=True):
480
"""Split a URL into its parent directory and a child directory.
482
:param url: A relative or absolute URL
483
:param exclude_trailing_slash: Strip off a final '/' if it is part
484
of the path (but not if it is part of the protocol specification)
486
:return: (parent_url, child_dir). child_dir may be the empty string if we're at
489
scheme_loc, first_path_slash = _find_scheme_and_separator(url)
491
if first_path_slash is None:
492
# We have either a relative path, or no separating slash
493
if scheme_loc is None:
495
if exclude_trailing_slash and url.endswith('/'):
497
return _posix_split(url)
499
# Scheme with no path
502
# We have a fully defined path
503
url_base = url[:first_path_slash] # http://host, file://
504
path = url[first_path_slash:] # /file/foo
506
if sys.platform == 'win32' and url.startswith('file:///'):
507
# Strip off the drive letter
508
# url_base is currently file://
509
# path is currently /C:/foo
510
url_base, path = _win32_extract_drive_letter(url_base, path)
511
# now it should be file:///C: and /foo
513
if exclude_trailing_slash and len(path) > 1 and path.endswith('/'):
515
head, tail = _posix_split(path)
516
return url_base + head, tail
519
def split_segment_parameters_raw(url):
520
"""Split the subsegment of the last segment of a URL.
522
:param url: A relative or absolute URL
523
:return: (url, subsegments)
525
# GZ 2011-11-18: Dodgy removing the terminal slash like this, function
526
# operates on urls not url+segments, and Transport classes
527
# should not be blindly adding slashes in the first place.
528
lurl = strip_trailing_slash(url)
529
# Segments begin at first comma after last forward slash, if one exists
530
segment_start = lurl.find(b",", lurl.rfind(b"/")+1)
531
if segment_start == -1:
533
return (lurl[:segment_start], lurl[segment_start+1:].split(b","))
536
def split_segment_parameters(url):
537
"""Split the segment parameters of the last segment of a URL.
539
:param url: A relative or absolute URL
540
:return: (url, segment_parameters)
542
(base_url, subsegments) = split_segment_parameters_raw(url)
544
for subsegment in subsegments:
545
(key, value) = subsegment.split("=", 1)
546
parameters[key] = value
547
return (base_url, parameters)
550
def join_segment_parameters_raw(base, *subsegments):
551
"""Create a new URL by adding subsegments to an existing one.
553
This adds the specified subsegments to the last path in the specified
554
base URL. The subsegments should be bytestrings.
556
:note: You probably want to use join_segment_parameters instead.
560
for subsegment in subsegments:
561
if not isinstance(subsegment, str):
562
raise TypeError("Subsegment %r is not a bytestring" % subsegment)
563
if "," in subsegment:
564
raise errors.InvalidURLJoin(", exists in subsegments",
566
return ",".join((base,) + subsegments)
569
def join_segment_parameters(url, parameters):
570
"""Create a new URL by adding segment parameters to an existing one.
572
The parameters of the last segment in the URL will be updated; if a
573
parameter with the same key already exists it will be overwritten.
575
:param url: A URL, as string
576
:param parameters: Dictionary of parameters, keys and values as bytestrings
578
(base, existing_parameters) = split_segment_parameters(url)
580
new_parameters.update(existing_parameters)
581
for key, value in parameters.items():
582
if not isinstance(key, str):
583
raise TypeError("parameter key %r is not a bytestring" % key)
584
if not isinstance(value, str):
585
raise TypeError("parameter value %r for %s is not a bytestring" %
588
raise errors.InvalidURLJoin("= exists in parameter key", url,
590
new_parameters[key] = value
591
return join_segment_parameters_raw(base,
592
*["%s=%s" % item for item in sorted(new_parameters.items())])
595
def _win32_strip_local_trailing_slash(url):
596
"""Strip slashes after the drive letter"""
597
if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
603
def strip_trailing_slash(url):
604
"""Strip trailing slash, except for root paths.
606
The definition of 'root path' is platform-dependent.
607
This assumes that all URLs are valid netloc urls, such that they
610
It searches for ://, and then refuses to remove the next '/'.
611
It can also handle relative paths
613
path/to/foo => path/to/foo
614
path/to/foo/ => path/to/foo
615
http://host/path/ => http://host/path
616
http://host/path => http://host/path
617
http://host/ => http://host/
619
file:///foo/ => file:///foo
620
# This is unique on win32 platforms, and is the only URL
621
# format which does it differently.
622
file:///c|/ => file:///c:/
624
if not url.endswith(b'/'):
627
if sys.platform == 'win32' and url.startswith(b'file://'):
628
return _win32_strip_local_trailing_slash(url)
630
scheme_loc, first_path_slash = _find_scheme_and_separator(url)
631
if scheme_loc is None:
632
# This is a relative path, as it has no scheme
633
# so just chop off the last character
636
if first_path_slash is None or first_path_slash == len(url)-1:
637
# Don't chop off anything if the only slash is the path
645
"""Unescape relpath from url format.
647
This returns a Unicode path from a URL
649
# jam 20060427 URLs are supposed to be ASCII only strings
650
# If they are passed in as unicode, unquote
651
# will return a UNICODE string, which actually contains
652
# utf-8 bytes. So we have to ensure that they are
653
# plain ASCII strings, or the final .decode will
654
# try to encode the UNICODE => ASCII, and then decode
656
if isinstance(url, text_type):
658
url = url.encode("ascii")
659
except UnicodeError as e:
660
raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
662
unquoted = unquote(url)
664
unicode_path = unquoted.decode('utf-8')
665
except UnicodeError as e:
666
raise errors.InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
670
# These are characters that if escaped, should stay that way
671
_no_decode_chars = ';/?:@&=+$,#'
672
_no_decode_ords = [ord(c) for c in _no_decode_chars]
673
_no_decode_hex = (['%02x' % o for o in _no_decode_ords]
674
+ ['%02X' % o for o in _no_decode_ords])
675
_hex_display_map = dict(([('%02x' % o, chr(o)) for o in range(256)]
676
+ [('%02X' % o, chr(o)) for o in range(256)]))
677
#These entries get mapped to themselves
678
_hex_display_map.update((hex,'%'+hex) for hex in _no_decode_hex)
680
# These characters shouldn't be percent-encoded, and it's always safe to
681
# unencode them if they are.
682
_url_dont_escape_characters = set(
683
"abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
684
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
685
"0123456789" # Numbers
686
"-._~" # Unreserved characters
689
# These characters should not be escaped
690
_url_safe_characters = set(
691
"abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
692
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
693
"0123456789" # Numbers
694
"_.-!~*'()" # Unreserved characters
695
"/;?:@&=+$," # Reserved characters
696
"%#" # Extra reserved characters
699
def unescape_for_display(url, encoding):
700
"""Decode what you can for a URL, so that we get a nice looking path.
702
This will turn file:// urls into local paths, and try to decode
703
any portions of a http:// style url that it can.
705
Any sections of the URL which can't be represented in the encoding or
706
need to stay as escapes are left alone.
708
:param url: A 7-bit ASCII URL
709
:param encoding: The final output encoding
711
:return: A unicode string which can be safely encoded into the
715
raise ValueError('you cannot specify None for the display encoding')
716
if url.startswith('file://'):
718
path = local_path_from_url(url)
719
path.encode(encoding)
724
# Split into sections to try to decode utf-8
726
for i in range(1, len(res)):
727
escaped_chunks = res[i].split('%')
728
for j in range(1, len(escaped_chunks)):
729
item = escaped_chunks[j]
731
escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
733
# Put back the percent symbol
734
escaped_chunks[j] = '%' + item
735
except UnicodeDecodeError:
736
escaped_chunks[j] = unichr(int(item[:2], 16)) + item[2:]
737
unescaped = ''.join(escaped_chunks)
739
decoded = unescaped.decode('utf-8')
740
except UnicodeDecodeError:
741
# If this path segment cannot be properly utf-8 decoded
742
# after doing unescaping we will just leave it alone
746
decoded.encode(encoding)
747
except UnicodeEncodeError:
748
# If this chunk cannot be encoded in the local
749
# encoding, then we should leave it alone
752
# Otherwise take the url decoded one
754
return u'/'.join(res)
757
def derive_to_location(from_location):
758
"""Derive a TO_LOCATION given a FROM_LOCATION.
760
The normal case is a FROM_LOCATION of http://foo/bar => bar.
761
The Right Thing for some logical destinations may differ though
762
because no / may be present at all. In that case, the result is
763
the full name without the scheme indicator, e.g. lp:foo-bar => foo-bar.
764
This latter case also applies when a Windows drive
765
is used without a path, e.g. c:foo-bar => foo-bar.
766
If no /, path separator or : is found, the from_location is returned.
768
if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
769
return os.path.basename(from_location.rstrip("/\\"))
771
sep = from_location.find(":")
773
return from_location[sep+1:]
778
def _is_absolute(url):
779
return (osutils.pathjoin('/foo', url) == url)
782
def rebase_url(url, old_base, new_base):
783
"""Convert a relative path from an old base URL to a new base URL.
785
The result will be a relative path.
786
Absolute paths and full URLs are returned unaltered.
788
scheme, separator = _find_scheme_and_separator(url)
789
if scheme is not None:
791
if _is_absolute(url):
793
old_parsed = urlparse.urlparse(old_base)
794
new_parsed = urlparse.urlparse(new_base)
795
if (old_parsed[:2]) != (new_parsed[:2]):
796
raise errors.InvalidRebaseURLs(old_base, new_base)
797
return determine_relative_path(new_parsed[2],
798
join(old_parsed[2], url))
801
def determine_relative_path(from_path, to_path):
802
"""Determine a relative path from from_path to to_path."""
803
from_segments = osutils.splitpath(from_path)
804
to_segments = osutils.splitpath(to_path)
806
for count, (from_element, to_element) in enumerate(zip(from_segments,
808
if from_element != to_element:
812
unique_from = from_segments[count:]
813
unique_to = to_segments[count:]
814
segments = (['..'] * len(unique_from) + unique_to)
815
if len(segments) == 0:
817
return osutils.pathjoin(*segments)
823
def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
826
self.quoted_host = quoted_host
827
self.host = unquote(self.quoted_host)
828
self.quoted_user = quoted_user
829
if self.quoted_user is not None:
830
self.user = unquote(self.quoted_user)
833
self.quoted_password = quoted_password
834
if self.quoted_password is not None:
835
self.password = unquote(self.quoted_password)
839
self.quoted_path = _url_hex_escapes_re.sub(_unescape_safe_chars, quoted_path)
840
self.path = unquote(self.quoted_path)
842
def __eq__(self, other):
843
return (isinstance(other, self.__class__) and
844
self.scheme == other.scheme and
845
self.host == other.host and
846
self.user == other.user and
847
self.password == other.password and
848
self.path == other.path)
851
return "<%s(%r, %r, %r, %r, %r, %r)>" % (
852
self.__class__.__name__,
853
self.scheme, self.quoted_user, self.quoted_password,
854
self.quoted_host, self.port, self.quoted_path)
857
def from_string(cls, url):
858
"""Create a URL object from a string.
860
:param url: URL as bytestring
862
if isinstance(url, unicode):
863
raise errors.InvalidURL('should be ascii:\n%r' % url)
864
url = url.encode('utf-8')
865
(scheme, netloc, path, params,
866
query, fragment) = urlparse.urlparse(url, allow_fragments=False)
867
user = password = host = port = None
869
user, host = netloc.rsplit('@', 1)
871
user, password = user.split(':', 1)
875
if ':' in host and not (host[0] == '[' and host[-1] == ']'):
877
host, port = host.rsplit(':',1)
881
raise errors.InvalidURL('invalid port number %s in url:\n%s' %
883
if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
886
return cls(scheme, user, password, host, port, path)
889
netloc = self.quoted_host
891
netloc = "[%s]" % netloc
892
if self.quoted_user is not None:
893
# Note that we don't put the password back even if we
894
# have one so that it doesn't get accidentally
896
netloc = '%s@%s' % (self.quoted_user, netloc)
897
if self.port is not None:
898
netloc = '%s:%d' % (netloc, self.port)
899
return urlparse.urlunparse(
900
(self.scheme, netloc, self.quoted_path, None, None, None))
903
def _combine_paths(base_path, relpath):
904
"""Transform a Transport-relative path to a remote absolute path.
906
This does not handle substitution of ~ but does handle '..' and '.'
911
t._combine_paths('/home/sarah', 'project/foo')
912
=> '/home/sarah/project/foo'
913
t._combine_paths('/home/sarah', '../../etc')
915
t._combine_paths('/home/sarah', '/etc')
918
:param base_path: base path
919
:param relpath: relative url string for relative part of remote path.
920
:return: urlencoded string for final path.
922
if not isinstance(relpath, str):
923
raise errors.InvalidURL(relpath)
924
relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
925
if relpath.startswith('/'):
928
base_parts = base_path.split('/')
929
if len(base_parts) > 0 and base_parts[-1] == '':
930
base_parts = base_parts[:-1]
931
for p in relpath.split('/'):
933
if len(base_parts) == 0:
934
# In most filesystems, a request for the parent
935
# of root, just returns root.
942
path = '/'.join(base_parts)
943
if not path.startswith('/'):
947
def clone(self, offset=None):
948
"""Return a new URL for a path relative to this URL.
950
:param offset: A relative path, already urlencoded
951
:return: `URL` instance
953
if offset is not None:
954
relative = unescape(offset).encode('utf-8')
955
path = self._combine_paths(self.path, relative)
956
path = quote(path, safe="/~")
958
path = self.quoted_path
959
return self.__class__(self.scheme, self.quoted_user,
960
self.quoted_password, self.quoted_host, self.port,
965
"""Extract the server address, the credentials and the path from the url.
967
user, password, host and path should be quoted if they contain reserved
970
:param url: an quoted url
971
:return: (scheme, user, password, host, port, path) tuple, all fields
974
parsed_url = URL.from_string(url)
975
return (parsed_url.scheme, parsed_url.user, parsed_url.password,
976
parsed_url.host, parsed_url.port, parsed_url.path)