/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/urlutils.py

  • Committer: Jelmer Vernooij
  • Date: 2018-05-06 11:48:54 UTC
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180506114854-h4qd9ojaqy8wxjsd
Move .mailmap to root.

Show diffs side-by-side

added added

removed removed

Lines of Context:
38
38
""")
39
39
 
40
40
from .sixish import (
41
 
    int2byte,
42
41
    PY3,
43
42
    text_type,
44
 
    unichr,
45
43
    )
46
44
 
47
45
 
68
66
    def __init__(self, from_, to):
69
67
        self.from_ = from_
70
68
        self.to = to
71
 
        errors.PathError.__init__(
72
 
            self, from_, 'URLs differ by more than path.')
 
69
        errors.PathError.__init__(self, from_, 'URLs differ by more than path.')
73
70
 
74
71
 
75
72
def basename(url, exclude_trailing_slash=True):
99
96
    return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
100
97
 
101
98
 
102
 
if PY3:
103
 
    quote_from_bytes = urlparse.quote_from_bytes
104
 
    quote = urlparse.quote
105
 
    unquote_to_bytes = urlparse.unquote_to_bytes
106
 
else:
107
 
    # Private copies of quote and unquote, copied from Python's urllib module
108
 
    # because urllib unconditionally imports socket, which imports ssl.
109
 
 
110
 
    always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
111
 
                   'abcdefghijklmnopqrstuvwxyz'
112
 
                   '0123456789' '_.-')
113
 
    _safe_map = {}
114
 
    for i, c in zip(range(256), ''.join(map(chr, range(256)))):
115
 
        _safe_map[c] = c if (
116
 
            i < 128 and c in always_safe) else '%{0:02X}'.format(i)
117
 
    _safe_quoters = {}
118
 
 
119
 
    def quote_from_bytes(s, safe='/'):
120
 
        """quote('abc def') -> 'abc%20def'
121
 
 
122
 
        Each part of a URL, e.g. the path info, the query, etc., has a
123
 
        different set of reserved characters that must be quoted.
124
 
 
125
 
        RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
126
 
        the following reserved characters.
127
 
 
128
 
        reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
129
 
                      "$" | ","
130
 
 
131
 
        Each of these characters is reserved in some component of a URL,
132
 
        but not necessarily in all of them.
133
 
 
134
 
        By default, the quote function is intended for quoting the path
135
 
        section of a URL.  Thus, it will not encode '/'.  This character
136
 
        is reserved, but in typical usage the quote function is being
137
 
        called on a path where the existing slash characters are used as
138
 
        reserved characters.
139
 
        """
140
 
        # fastpath
141
 
        if not s:
142
 
            if s is None:
143
 
                raise TypeError('None object cannot be quoted')
144
 
            return s
145
 
        cachekey = (safe, always_safe)
146
 
        try:
147
 
            (quoter, safe) = _safe_quoters[cachekey]
148
 
        except KeyError:
149
 
            safe_map = _safe_map.copy()
150
 
            safe_map.update([(c, c) for c in safe])
151
 
            quoter = safe_map.__getitem__
152
 
            safe = always_safe + safe
153
 
            _safe_quoters[cachekey] = (quoter, safe)
154
 
        if not s.rstrip(safe):
155
 
            return s
156
 
        return ''.join(map(quoter, s))
157
 
 
158
 
    quote = quote_from_bytes
159
 
    unquote_to_bytes = urlparse.unquote
 
99
# Private copies of quote and unquote, copied from Python's
 
100
# urllib module because urllib unconditionally imports socket, which imports
 
101
# ssl.
 
102
 
 
103
always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 
104
               'abcdefghijklmnopqrstuvwxyz'
 
105
               '0123456789' '_.-')
 
106
_safe_map = {}
 
107
for i, c in zip(range(256), ''.join(map(chr, range(256)))):
 
108
    _safe_map[c] = c if (i < 128 and c in always_safe) else '%{0:02X}'.format(i)
 
109
_safe_quoters = {}
 
110
 
 
111
 
 
112
def quote(s, safe='/'):
 
113
    """quote('abc def') -> 'abc%20def'
 
114
 
 
115
    Each part of a URL, e.g. the path info, the query, etc., has a
 
116
    different set of reserved characters that must be quoted.
 
117
 
 
118
    RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
 
119
    the following reserved characters.
 
120
 
 
121
    reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
 
122
                  "$" | ","
 
123
 
 
124
    Each of these characters is reserved in some component of a URL,
 
125
    but not necessarily in all of them.
 
126
 
 
127
    By default, the quote function is intended for quoting the path
 
128
    section of a URL.  Thus, it will not encode '/'.  This character
 
129
    is reserved, but in typical usage the quote function is being
 
130
    called on a path where the existing slash characters are used as
 
131
    reserved characters.
 
132
    """
 
133
    # fastpath
 
134
    if not s:
 
135
        if s is None:
 
136
            raise TypeError('None object cannot be quoted')
 
137
        return s
 
138
    cachekey = (safe, always_safe)
 
139
    try:
 
140
        (quoter, safe) = _safe_quoters[cachekey]
 
141
    except KeyError:
 
142
        safe_map = _safe_map.copy()
 
143
        safe_map.update([(c, c) for c in safe])
 
144
        quoter = safe_map.__getitem__
 
145
        safe = always_safe + safe
 
146
        _safe_quoters[cachekey] = (quoter, safe)
 
147
    if not s.rstrip(safe):
 
148
        return s
 
149
    return ''.join(map(quoter, s))
160
150
 
161
151
 
162
152
unquote = urlparse.unquote
163
153
 
164
154
 
165
 
def escape(relpath, safe='/~'):
 
155
def escape(relpath):
166
156
    """Escape relpath to be a valid url."""
167
 
    if not isinstance(relpath, str) and sys.version_info[0] == 2:
168
 
        # GZ 2019-06-16: Should use _fs_enc instead here really?
 
157
    if not isinstance(relpath, str):
169
158
        relpath = relpath.encode('utf-8')
170
 
    return quote(relpath, safe=safe)
 
159
    return quote(relpath, safe='/~')
171
160
 
172
161
 
173
162
def file_relpath(base, path):
177
166
    """
178
167
    if len(base) < MIN_ABS_FILEURL_LENGTH:
179
168
        raise ValueError('Length of base (%r) must equal or'
180
 
                         ' exceed the platform minimum url length (which is %d)' %
181
 
                         (base, MIN_ABS_FILEURL_LENGTH))
 
169
            ' exceed the platform minimum url length (which is %d)' %
 
170
            (base, MIN_ABS_FILEURL_LENGTH))
182
171
    base = osutils.normpath(local_path_from_url(base))
183
172
    path = osutils.normpath(local_path_from_url(path))
184
173
    return escape(osutils.relpath(base, path))
202
191
    first_path_slash = path.find('/')
203
192
    if first_path_slash == -1:
204
193
        return len(scheme), None
205
 
    return len(scheme), first_path_slash + m.start('path')
 
194
    return len(scheme), first_path_slash+m.start('path')
206
195
 
207
196
 
208
197
def is_url(url):
258
247
    """
259
248
    path = base.split('/')
260
249
    if len(path) > 1 and path[-1] == '':
261
 
        # If the path ends in a trailing /, remove it.
 
250
        #If the path ends in a trailing /, remove it.
262
251
        path.pop()
263
252
    for arg in args:
264
253
        if arg.startswith('/'):
269
258
            elif chunk == '..':
270
259
                if path == ['']:
271
260
                    raise InvalidURLJoin('Cannot go above root',
272
 
                                         base, args)
 
261
                            base, args)
273
262
                path.pop()
274
263
            else:
275
264
                path.append(chunk)
282
271
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
283
272
def _posix_local_path_from_url(url):
284
273
    """Convert a url like file:///path/to/foo into /path/to/foo"""
285
 
    url = strip_segment_parameters(url)
 
274
    url = split_segment_parameters_raw(url)[0]
286
275
    file_localhost_prefix = 'file://localhost/'
287
276
    if url.startswith(file_localhost_prefix):
288
277
        path = url[len(file_localhost_prefix) - 1:]
309
298
    """Convert a url like file:///C:/path/to/foo into C:/path/to/foo"""
310
299
    if not url.startswith('file://'):
311
300
        raise InvalidURL(url, 'local urls must start with file:///, '
312
 
                         'UNC path urls must start with file://')
313
 
    url = strip_segment_parameters(url)
 
301
                                     'UNC path urls must start with file://')
 
302
    url = split_segment_parameters_raw(url)[0]
314
303
    # We strip off all 3 slashes
315
304
    win32_url = url[len('file:'):]
316
305
    # check for UNC path: //HOST/path
317
306
    if not win32_url.startswith('///'):
318
307
        if (win32_url[2] == '/'
319
 
                or win32_url[3] in '|:'):
 
308
            or win32_url[3] in '|:'):
320
309
            raise InvalidURL(url, 'Win32 UNC path urls'
321
 
                             ' have form file://HOST/path')
 
310
                ' have form file://HOST/path')
322
311
        return unescape(win32_url)
323
312
 
324
313
    # allow empty paths so we can serve all roots
328
317
    # usual local path with drive letter
329
318
    if (len(win32_url) < 6
330
319
        or win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
331
 
                                'ABCDEFGHIJKLMNOPQRSTUVWXYZ') or
332
 
        win32_url[4] not in '|:'
333
 
            or win32_url[5] != '/'):
 
320
                                'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
 
321
        or win32_url[4] not in  '|:'
 
322
        or win32_url[5] != '/'):
334
323
        raise InvalidURL(url, 'Win32 file urls start with'
335
 
                         ' file:///x:/, where x is a valid drive letter')
 
324
                ' file:///x:/, where x is a valid drive letter')
336
325
    return win32_url[3].upper() + u':' + unescape(win32_url[5:])
337
326
 
338
327
 
355
344
    if win32_path.startswith('//'):
356
345
        return 'file:' + escape(win32_path)
357
346
    return ('file:///' + str(win32_path[0].upper()) + ':' +
358
 
            escape(win32_path[2:]))
 
347
        escape(win32_path[2:]))
359
348
 
360
349
 
361
350
local_path_to_url = _posix_local_path_to_url
415
404
        for c in url:
416
405
            if c not in _url_safe_characters:
417
406
                raise InvalidURL(url, 'URLs can only contain specific'
418
 
                                 ' safe characters (not %r)' % c)
 
407
                                            ' safe characters (not %r)' % c)
419
408
        path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
420
409
        return str(prefix + ''.join(path))
421
410
 
424
413
 
425
414
    for i in range(len(path_chars)):
426
415
        if path_chars[i] not in _url_safe_characters:
 
416
            chars = path_chars[i].encode('utf-8')
427
417
            path_chars[i] = ''.join(
428
 
                ['%%%02X' % c for c in bytearray(path_chars[i].encode('utf-8'))])
 
418
                ['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
429
419
    path = ''.join(path_chars)
430
420
    path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
431
421
    return str(prefix + path)
451
441
    if base_scheme != other_scheme:
452
442
        return other
453
443
    elif sys.platform == 'win32' and base_scheme == 'file://':
454
 
        base_drive = base[base_first_slash + 1:base_first_slash + 3]
455
 
        other_drive = other[other_first_slash + 1:other_first_slash + 3]
 
444
        base_drive = base[base_first_slash+1:base_first_slash+3]
 
445
        other_drive = other[other_first_slash+1:other_first_slash+3]
456
446
        if base_drive != other_drive:
457
447
            return other
458
448
 
459
 
    base_path = base[base_first_slash + 1:]
460
 
    other_path = other[other_first_slash + 1:]
 
449
    base_path = base[base_first_slash+1:]
 
450
    other_path = other[other_first_slash+1:]
461
451
 
462
452
    if base_path.endswith('/'):
463
453
        base_path = base_path[:-1]
489
479
    # path is currently /C:/foo
490
480
    if len(path) < 4 or path[2] not in ':|' or path[3] != '/':
491
481
        raise InvalidURL(url_base + path,
492
 
                         'win32 file:/// paths need a drive letter')
493
 
    url_base += path[0:3]  # file:// + /C:
494
 
    path = path[3:]  # /foo
 
482
            'win32 file:/// paths need a drive letter')
 
483
    url_base += path[0:3] # file:// + /C:
 
484
    path = path[3:] # /foo
495
485
    return url_base, path
496
486
 
497
487
 
502
492
    :param exclude_trailing_slash: Strip off a final '/' if it is part
503
493
        of the path (but not if it is part of the protocol specification)
504
494
 
505
 
    :return: (parent_url, child_dir).  child_dir may be the empty string if
506
 
        we're at the root.
 
495
    :return: (parent_url, child_dir).  child_dir may be the empty string if we're at
 
496
        the root.
507
497
    """
508
498
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
509
499
 
519
509
            return url, ''
520
510
 
521
511
    # We have a fully defined path
522
 
    url_base = url[:first_path_slash]  # http://host, file://
523
 
    path = url[first_path_slash:]  # /file/foo
 
512
    url_base = url[:first_path_slash] # http://host, file://
 
513
    path = url[first_path_slash:] # /file/foo
524
514
 
525
515
    if sys.platform == 'win32' and url.startswith('file:///'):
526
516
        # Strip off the drive letter
543
533
    """
544
534
    # GZ 2011-11-18: Dodgy removing the terminal slash like this, function
545
535
    #                operates on urls not url+segments, and Transport classes
546
 
    #                should not be blindly adding slashes in the first place.
 
536
    #                should not be blindly adding slashes in the first place. 
547
537
    lurl = strip_trailing_slash(url)
548
538
    # Segments begin at first comma after last forward slash, if one exists
549
 
    segment_start = lurl.find(",", lurl.rfind("/") + 1)
 
539
    segment_start = lurl.find(",", lurl.rfind("/")+1)
550
540
    if segment_start == -1:
551
541
        return (url, [])
552
 
    return (lurl[:segment_start],
553
 
            [str(s) for s in lurl[segment_start + 1:].split(",")])
 
542
    return (lurl[:segment_start], lurl[segment_start+1:].split(","))
554
543
 
555
544
 
556
545
def split_segment_parameters(url):
562
551
    (base_url, subsegments) = split_segment_parameters_raw(url)
563
552
    parameters = {}
564
553
    for subsegment in subsegments:
565
 
        try:
566
 
            (key, value) = subsegment.split("=", 1)
567
 
        except ValueError:
568
 
            raise InvalidURL(url, "missing = in subsegment")
569
 
        if not isinstance(key, str):
570
 
            raise TypeError(key)
571
 
        if not isinstance(value, str):
572
 
            raise TypeError(value)
 
554
        (key, value) = subsegment.split("=", 1)
573
555
        parameters[key] = value
574
556
    return (base_url, parameters)
575
557
 
576
558
 
577
 
def strip_segment_parameters(url):
578
 
    """Strip the segment parameters from a URL.
579
 
 
580
 
    :param url: A relative or absolute URL
581
 
    :return: url
582
 
    """
583
 
    base_url, subsegments = split_segment_parameters_raw(url)
584
 
    return base_url
585
 
 
586
 
 
587
559
def join_segment_parameters_raw(base, *subsegments):
588
 
    """Create a new URL by adding subsegments to an existing one.
 
560
    """Create a new URL by adding subsegments to an existing one. 
589
561
 
590
562
    This adds the specified subsegments to the last path in the specified
591
563
    base URL. The subsegments should be bytestrings.
599
571
            raise TypeError("Subsegment %r is not a bytestring" % subsegment)
600
572
        if "," in subsegment:
601
573
            raise InvalidURLJoin(", exists in subsegments",
602
 
                                 base, subsegments)
 
574
                                        base, subsegments)
603
575
    return ",".join((base,) + subsegments)
604
576
 
605
577
 
617
589
    new_parameters.update(existing_parameters)
618
590
    for key, value in parameters.items():
619
591
        if not isinstance(key, str):
620
 
            raise TypeError("parameter key %r is not a str" % key)
 
592
            raise TypeError("parameter key %r is not a bytestring" % key)
621
593
        if not isinstance(value, str):
622
 
            raise TypeError("parameter value %r for %r is not a str" %
623
 
                            (value, key))
 
594
            raise TypeError("parameter value %r for %s is not a bytestring" %
 
595
                (key, value))
624
596
        if "=" in key:
625
597
            raise InvalidURLJoin("= exists in parameter key", url,
626
 
                                 parameters)
 
598
                parameters)
627
599
        new_parameters[key] = value
628
 
    return join_segment_parameters_raw(
629
 
        base, *["%s=%s" % item for item in sorted(new_parameters.items())])
 
600
    return join_segment_parameters_raw(base, 
 
601
        *["%s=%s" % item for item in sorted(new_parameters.items())])
630
602
 
631
603
 
632
604
def _win32_strip_local_trailing_slash(url):
670
642
        # so just chop off the last character
671
643
        return url[:-1]
672
644
 
673
 
    if first_path_slash is None or first_path_slash == len(url) - 1:
 
645
    if first_path_slash is None or first_path_slash == len(url)-1:
674
646
        # Don't chop off anything if the only slash is the path
675
647
        # separating slash
676
648
        return url
690
662
    #       plain ASCII strings, or the final .decode will
691
663
    #       try to encode the UNICODE => ASCII, and then decode
692
664
    #       it into utf-8.
693
 
 
 
665
    if isinstance(url, text_type):
 
666
        try:
 
667
            url = url.encode("ascii")
 
668
        except UnicodeError as e:
 
669
            raise InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
694
670
    if PY3:
695
 
        if isinstance(url, text_type):
696
 
            try:
697
 
                url.encode("ascii")
698
 
            except UnicodeError as e:
699
 
                raise InvalidURL(
700
 
                    url, 'URL was not a plain ASCII url: %s' % (e,))
701
 
        return urlparse.unquote(url)
 
671
        unquoted = urlparse.unquote_to_bytes(url)
702
672
    else:
703
 
        if isinstance(url, text_type):
704
 
            try:
705
 
                url = url.encode("ascii")
706
 
            except UnicodeError as e:
707
 
                raise InvalidURL(
708
 
                    url, 'URL was not a plain ASCII url: %s' % (e,))
709
673
        unquoted = unquote(url)
710
 
        try:
711
 
            unicode_path = unquoted.decode('utf-8')
712
 
        except UnicodeError as e:
713
 
            raise InvalidURL(
714
 
                url, 'Unable to encode the URL as utf-8: %s' % (e,))
715
 
        return unicode_path
 
674
    try:
 
675
        unicode_path = unquoted.decode('utf-8')
 
676
    except UnicodeError as e:
 
677
        raise InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
 
678
    return unicode_path
716
679
 
717
680
 
718
681
# These are characters that if escaped, should stay that way
719
682
_no_decode_chars = ';/?:@&=+$,#'
720
683
_no_decode_ords = [ord(c) for c in _no_decode_chars]
721
684
_no_decode_hex = (['%02x' % o for o in _no_decode_ords]
722
 
                  + ['%02X' % o for o in _no_decode_ords])
723
 
_hex_display_map = dict(([('%02x' % o, int2byte(o)) for o in range(256)]
724
 
                         + [('%02X' % o, int2byte(o)) for o in range(256)]))
725
 
# These entries get mapped to themselves
726
 
_hex_display_map.update((hex, b'%' + hex.encode('ascii'))
727
 
                        for hex in _no_decode_hex)
 
685
                + ['%02X' % o for o in _no_decode_ords])
 
686
_hex_display_map = dict(([('%02x' % o, chr(o)) for o in range(256)]
 
687
                    + [('%02X' % o, chr(o)) for o in range(256)]))
 
688
#These entries get mapped to themselves
 
689
_hex_display_map.update((hex, '%'+hex) for hex in _no_decode_hex)
728
690
 
729
691
# These characters shouldn't be percent-encoded, and it's always safe to
730
692
# unencode them if they are.
731
693
_url_dont_escape_characters = set(
732
 
    "abcdefghijklmnopqrstuvwxyz"  # Lowercase alpha
733
 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  # Uppercase alpha
734
 
    "0123456789"  # Numbers
735
 
    "-._~"  # Unreserved characters
 
694
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
 
695
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
 
696
   "0123456789" # Numbers
 
697
   "-._~"  # Unreserved characters
736
698
)
737
699
 
738
700
# These characters should not be escaped
739
701
_url_safe_characters = set(
740
 
    "abcdefghijklmnopqrstuvwxyz"  # Lowercase alpha
741
 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  # Uppercase alpha
742
 
    "0123456789"  # Numbers
743
 
    "_.-!~*'()"  # Unreserved characters
744
 
    "/;?:@&=+$,"  # Reserved characters
745
 
    "%#"         # Extra reserved characters
 
702
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
 
703
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
 
704
   "0123456789" # Numbers
 
705
   "_.-!~*'()"  # Unreserved characters
 
706
   "/;?:@&=+$," # Reserved characters
 
707
   "%#"         # Extra reserved characters
746
708
)
747
709
 
748
 
 
749
 
def _unescape_segment_for_display(segment, encoding):
750
 
    """Unescape a segment for display.
751
 
 
752
 
    Helper for unescape_for_display
753
 
 
754
 
    :param url: A 7-bit ASCII URL
755
 
    :param encoding: The final output encoding
756
 
 
757
 
    :return: A unicode string which can be safely encoded into the
758
 
         specified encoding.
759
 
    """
760
 
    escaped_chunks = segment.split('%')
761
 
    escaped_chunks[0] = escaped_chunks[0].encode('utf-8')
762
 
    for j in range(1, len(escaped_chunks)):
763
 
        item = escaped_chunks[j]
764
 
        try:
765
 
            escaped_chunks[j] = _hex_display_map[item[:2]]
766
 
        except KeyError:
767
 
            # Put back the percent symbol
768
 
            escaped_chunks[j] = b'%' + \
769
 
                (item[:2].encode('utf-8') if PY3 else item[:2])
770
 
        except UnicodeDecodeError:
771
 
            escaped_chunks[j] = unichr(int(item[:2], 16)).encode('utf-8')
772
 
        escaped_chunks[j] += (item[2:].encode('utf-8') if PY3 else item[2:])
773
 
    unescaped = b''.join(escaped_chunks)
774
 
    try:
775
 
        decoded = unescaped.decode('utf-8')
776
 
    except UnicodeDecodeError:
777
 
        # If this path segment cannot be properly utf-8 decoded
778
 
        # after doing unescaping we will just leave it alone
779
 
        return segment
780
 
    else:
781
 
        try:
782
 
            decoded.encode(encoding)
783
 
        except UnicodeEncodeError:
784
 
            # If this chunk cannot be encoded in the local
785
 
            # encoding, then we should leave it alone
786
 
            return segment
787
 
        else:
788
 
            # Otherwise take the url decoded one
789
 
            return decoded
790
 
 
791
 
 
792
710
def unescape_for_display(url, encoding):
793
711
    """Decode what you can for a URL, so that we get a nice looking path.
794
712
 
817
735
    # Split into sections to try to decode utf-8
818
736
    res = url.split('/')
819
737
    for i in range(1, len(res)):
820
 
        res[i] = _unescape_segment_for_display(res[i], encoding)
 
738
        escaped_chunks = res[i].split('%')
 
739
        for j in range(1, len(escaped_chunks)):
 
740
            item = escaped_chunks[j]
 
741
            try:
 
742
                escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
 
743
            except KeyError:
 
744
                # Put back the percent symbol
 
745
                escaped_chunks[j] = '%' + item
 
746
            except UnicodeDecodeError:
 
747
                escaped_chunks[j] = unichr(int(item[:2], 16)) + item[2:]
 
748
        unescaped = ''.join(escaped_chunks)
 
749
        try:
 
750
            decoded = unescaped.decode('utf-8')
 
751
        except UnicodeDecodeError:
 
752
            # If this path segment cannot be properly utf-8 decoded
 
753
            # after doing unescaping we will just leave it alone
 
754
            pass
 
755
        else:
 
756
            try:
 
757
                decoded.encode(encoding)
 
758
            except UnicodeEncodeError:
 
759
                # If this chunk cannot be encoded in the local
 
760
                # encoding, then we should leave it alone
 
761
                pass
 
762
            else:
 
763
                # Otherwise take the url decoded one
 
764
                res[i] = decoded
821
765
    return u'/'.join(res)
822
766
 
823
767
 
832
776
    is used without a path, e.g. c:foo-bar => foo-bar.
833
777
    If no /, path separator or : is found, the from_location is returned.
834
778
    """
835
 
    from_location = strip_segment_parameters(from_location)
836
779
    if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
837
780
        return os.path.basename(from_location.rstrip("/\\"))
838
781
    else:
839
782
        sep = from_location.find(":")
840
783
        if sep > 0:
841
 
            return from_location[sep + 1:]
 
784
            return from_location[sep+1:]
842
785
        else:
843
786
            return from_location
844
787
 
872
815
    to_segments = osutils.splitpath(to_path)
873
816
    count = -1
874
817
    for count, (from_element, to_element) in enumerate(zip(from_segments,
875
 
                                                           to_segments)):
 
818
                                                       to_segments)):
876
819
        if from_element != to_element:
877
820
            break
878
821
    else:
889
832
    """Parsed URL."""
890
833
 
891
834
    def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
892
 
                 port, quoted_path):
 
835
            port, quoted_path):
893
836
        self.scheme = scheme
894
837
        self.quoted_host = quoted_host
895
838
        self.host = unquote(self.quoted_host)
904
847
        else:
905
848
            self.password = None
906
849
        self.port = port
907
 
        self.quoted_path = _url_hex_escapes_re.sub(
908
 
            _unescape_safe_chars, quoted_path)
 
850
        self.quoted_path = _url_hex_escapes_re.sub(_unescape_safe_chars, quoted_path)
909
851
        self.path = unquote(self.quoted_path)
910
852
 
911
853
    def __eq__(self, other):
929
871
        :param url: URL as bytestring
930
872
        """
931
873
        # GZ 2017-06-09: Actually validate ascii-ness
932
 
        # pad.lv/1696545: For the moment, accept both native strings and
933
 
        # unicode.
934
 
        if isinstance(url, str):
935
 
            pass
936
 
        elif isinstance(url, text_type):
937
 
            try:
938
 
                url = url.encode()
939
 
            except UnicodeEncodeError:
940
 
                raise InvalidURL(url)
941
 
        else:
942
 
            raise InvalidURL(url)
 
874
        if not isinstance(url, str):
 
875
            raise InvalidURL('should be ascii:\n%r' % url)
943
876
        (scheme, netloc, path, params,
944
877
         query, fragment) = urlparse.urlparse(url, allow_fragments=False)
945
878
        user = password = host = port = None
953
886
        if ':' in host and not (host[0] == '[' and host[-1] == ']'):
954
887
            # there *is* port
955
888
            host, port = host.rsplit(':', 1)
956
 
            if port:
957
 
                try:
958
 
                    port = int(port)
959
 
                except ValueError:
960
 
                    raise InvalidURL('invalid port number %s in url:\n%s' %
961
 
                                     (port, url))
962
 
            else:
963
 
                port = None
964
 
        if host != "" and host[0] == '[' and host[-1] == ']':  # IPv6
 
889
            try:
 
890
                port = int(port)
 
891
            except ValueError:
 
892
                raise InvalidURL('invalid port number %s in url:\n%s' %
 
893
                                 (port, url))
 
894
        if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
965
895
            host = host[1:-1]
966
896
 
967
897
        return cls(scheme, user, password, host, port, path)
1000
930
        :param relpath: relative url string for relative part of remote path.
1001
931
        :return: urlencoded string for final path.
1002
932
        """
1003
 
        # pad.lv/1696545: For the moment, accept both native strings and
1004
 
        # unicode.
1005
 
        if isinstance(relpath, str):
1006
 
            pass
1007
 
        elif isinstance(relpath, text_type):
1008
 
            try:
1009
 
                relpath = relpath.encode()
1010
 
            except UnicodeEncodeError:
1011
 
                raise InvalidURL(relpath)
1012
 
        else:
 
933
        if not isinstance(relpath, str):
1013
934
            raise InvalidURL(relpath)
1014
935
        relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
1015
936
        if relpath.startswith('/'):
1026
947
                    continue
1027
948
                base_parts.pop()
1028
949
            elif p == '.':
1029
 
                continue  # No-op
 
950
                continue # No-op
1030
951
            elif p != '':
1031
952
                base_parts.append(p)
1032
953
        path = '/'.join(base_parts)
1041
962
        :return: `URL` instance
1042
963
        """
1043
964
        if offset is not None:
1044
 
            relative = unescape(offset)
1045
 
            if sys.version_info[0] == 2:
1046
 
                relative = relative.encode('utf-8')
 
965
            relative = unescape(offset).encode('utf-8')
1047
966
            path = self._combine_paths(self.path, relative)
1048
967
            path = quote(path, safe="/~")
1049
968
        else:
1050
969
            path = self.quoted_path
1051
970
        return self.__class__(self.scheme, self.quoted_user,
1052
 
                              self.quoted_password, self.quoted_host, self.port,
1053
 
                              path)
 
971
                self.quoted_password, self.quoted_host, self.port,
 
972
                path)
1054
973
 
1055
974
 
1056
975
def parse_url(url):
1065
984
    """
1066
985
    parsed_url = URL.from_string(url)
1067
986
    return (parsed_url.scheme, parsed_url.user, parsed_url.password,
1068
 
            parsed_url.host, parsed_url.port, parsed_url.path)
 
987
        parsed_url.host, parsed_url.port, parsed_url.path)