/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-02-18 21:42:57 UTC
  • mto: This revision was merged to the branch mainline in revision 6859.
  • Revision ID: jelmer@jelmer.uk-20180218214257-jpevutp1wa30tz3v
Update TODO to reference Breezy, not Bazaar.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""A collection of function for handling URL operations."""
18
18
 
 
19
from __future__ import absolute_import
 
20
 
19
21
import os
20
22
import re
21
23
import sys
22
24
 
23
 
from urllib import parse as urlparse
 
25
try:
 
26
    import urlparse
 
27
except ImportError:
 
28
    from urllib import parse as urlparse
24
29
 
25
30
from . import (
26
31
    errors,
32
37
from posixpath import split as _posix_split
33
38
""")
34
39
 
 
40
from .sixish import (
 
41
    PY3,
 
42
    text_type,
 
43
    )
35
44
 
36
45
 
37
46
class InvalidURL(errors.PathError):
57
66
    def __init__(self, from_, to):
58
67
        self.from_ = from_
59
68
        self.to = to
60
 
        errors.PathError.__init__(
61
 
            self, from_, 'URLs differ by more than path.')
 
69
        errors.PathError.__init__(self, from_, 'URLs differ by more than path.')
62
70
 
63
71
 
64
72
def basename(url, exclude_trailing_slash=True):
88
96
    return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
89
97
 
90
98
 
91
 
quote_from_bytes = urlparse.quote_from_bytes
92
 
quote = urlparse.quote
93
 
unquote_to_bytes = urlparse.unquote_to_bytes
 
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))
 
150
 
 
151
 
94
152
unquote = urlparse.unquote
95
153
 
96
154
 
97
 
def escape(relpath, safe='/~'):
 
155
def escape(relpath):
98
156
    """Escape relpath to be a valid url."""
99
 
    return quote(relpath, safe=safe)
 
157
    if not isinstance(relpath, str):
 
158
        relpath = relpath.encode('utf-8')
 
159
    return quote(relpath, safe='/~')
100
160
 
101
161
 
102
162
def file_relpath(base, path):
106
166
    """
107
167
    if len(base) < MIN_ABS_FILEURL_LENGTH:
108
168
        raise ValueError('Length of base (%r) must equal or'
109
 
                         ' exceed the platform minimum url length (which is %d)' %
110
 
                         (base, MIN_ABS_FILEURL_LENGTH))
 
169
            ' exceed the platform minimum url length (which is %d)' %
 
170
            (base, MIN_ABS_FILEURL_LENGTH))
111
171
    base = osutils.normpath(local_path_from_url(base))
112
172
    path = osutils.normpath(local_path_from_url(path))
113
173
    return escape(osutils.relpath(base, path))
131
191
    first_path_slash = path.find('/')
132
192
    if first_path_slash == -1:
133
193
        return len(scheme), None
134
 
    return len(scheme), first_path_slash + m.start('path')
 
194
    return len(scheme), first_path_slash+m.start('path')
135
195
 
136
196
 
137
197
def is_url(url):
187
247
    """
188
248
    path = base.split('/')
189
249
    if len(path) > 1 and path[-1] == '':
190
 
        # If the path ends in a trailing /, remove it.
 
250
        #If the path ends in a trailing /, remove it.
191
251
        path.pop()
192
252
    for arg in args:
193
253
        if arg.startswith('/'):
198
258
            elif chunk == '..':
199
259
                if path == ['']:
200
260
                    raise InvalidURLJoin('Cannot go above root',
201
 
                                         base, args)
 
261
                            base, args)
202
262
                path.pop()
203
263
            else:
204
264
                path.append(chunk)
211
271
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
212
272
def _posix_local_path_from_url(url):
213
273
    """Convert a url like file:///path/to/foo into /path/to/foo"""
214
 
    url = strip_segment_parameters(url)
 
274
    url = split_segment_parameters_raw(url)[0]
215
275
    file_localhost_prefix = 'file://localhost/'
216
276
    if url.startswith(file_localhost_prefix):
217
277
        path = url[len(file_localhost_prefix) - 1:]
238
298
    """Convert a url like file:///C:/path/to/foo into C:/path/to/foo"""
239
299
    if not url.startswith('file://'):
240
300
        raise InvalidURL(url, 'local urls must start with file:///, '
241
 
                         'UNC path urls must start with file://')
242
 
    url = strip_segment_parameters(url)
 
301
                                     'UNC path urls must start with file://')
 
302
    url = split_segment_parameters_raw(url)[0]
243
303
    # We strip off all 3 slashes
244
304
    win32_url = url[len('file:'):]
245
305
    # check for UNC path: //HOST/path
246
306
    if not win32_url.startswith('///'):
247
307
        if (win32_url[2] == '/'
248
 
                or win32_url[3] in '|:'):
 
308
            or win32_url[3] in '|:'):
249
309
            raise InvalidURL(url, 'Win32 UNC path urls'
250
 
                             ' have form file://HOST/path')
 
310
                ' have form file://HOST/path')
251
311
        return unescape(win32_url)
252
312
 
253
313
    # allow empty paths so we can serve all roots
257
317
    # usual local path with drive letter
258
318
    if (len(win32_url) < 6
259
319
        or win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
260
 
                                'ABCDEFGHIJKLMNOPQRSTUVWXYZ') or
261
 
        win32_url[4] not in '|:'
262
 
            or win32_url[5] != '/'):
 
320
                                'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
 
321
        or win32_url[4] not in  '|:'
 
322
        or win32_url[5] != '/'):
263
323
        raise InvalidURL(url, 'Win32 file urls start with'
264
 
                         ' file:///x:/, where x is a valid drive letter')
 
324
                ' file:///x:/, where x is a valid drive letter')
265
325
    return win32_url[3].upper() + u':' + unescape(win32_url[5:])
266
326
 
267
327
 
284
344
    if win32_path.startswith('//'):
285
345
        return 'file:' + escape(win32_path)
286
346
    return ('file:///' + str(win32_path[0].upper()) + ':' +
287
 
            escape(win32_path[2:]))
 
347
        escape(win32_path[2:]))
288
348
 
289
349
 
290
350
local_path_to_url = _posix_local_path_to_url
340
400
        return local_path_to_url(url)
341
401
    prefix = url[:path_start]
342
402
    path = url[path_start:]
343
 
    if not isinstance(url, str):
 
403
    if not isinstance(url, text_type):
344
404
        for c in url:
345
405
            if c not in _url_safe_characters:
346
406
                raise InvalidURL(url, 'URLs can only contain specific'
347
 
                                 ' safe characters (not %r)' % c)
 
407
                                            ' safe characters (not %r)' % c)
348
408
        path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
349
409
        return str(prefix + ''.join(path))
350
410
 
353
413
 
354
414
    for i in range(len(path_chars)):
355
415
        if path_chars[i] not in _url_safe_characters:
 
416
            chars = path_chars[i].encode('utf-8')
356
417
            path_chars[i] = ''.join(
357
 
                ['%%%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')])
358
419
    path = ''.join(path_chars)
359
420
    path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
360
421
    return str(prefix + path)
380
441
    if base_scheme != other_scheme:
381
442
        return other
382
443
    elif sys.platform == 'win32' and base_scheme == 'file://':
383
 
        base_drive = base[base_first_slash + 1:base_first_slash + 3]
384
 
        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]
385
446
        if base_drive != other_drive:
386
447
            return other
387
448
 
388
 
    base_path = base[base_first_slash + 1:]
389
 
    other_path = other[other_first_slash + 1:]
 
449
    base_path = base[base_first_slash+1:]
 
450
    other_path = other[other_first_slash+1:]
390
451
 
391
452
    if base_path.endswith('/'):
392
453
        base_path = base_path[:-1]
418
479
    # path is currently /C:/foo
419
480
    if len(path) < 4 or path[2] not in ':|' or path[3] != '/':
420
481
        raise InvalidURL(url_base + path,
421
 
                         'win32 file:/// paths need a drive letter')
422
 
    url_base += path[0:3]  # file:// + /C:
423
 
    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
424
485
    return url_base, path
425
486
 
426
487
 
431
492
    :param exclude_trailing_slash: Strip off a final '/' if it is part
432
493
        of the path (but not if it is part of the protocol specification)
433
494
 
434
 
    :return: (parent_url, child_dir).  child_dir may be the empty string if
435
 
        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.
436
497
    """
437
498
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
438
499
 
448
509
            return url, ''
449
510
 
450
511
    # We have a fully defined path
451
 
    url_base = url[:first_path_slash]  # http://host, file://
452
 
    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
453
514
 
454
515
    if sys.platform == 'win32' and url.startswith('file:///'):
455
516
        # Strip off the drive letter
472
533
    """
473
534
    # GZ 2011-11-18: Dodgy removing the terminal slash like this, function
474
535
    #                operates on urls not url+segments, and Transport classes
475
 
    #                should not be blindly adding slashes in the first place.
 
536
    #                should not be blindly adding slashes in the first place. 
476
537
    lurl = strip_trailing_slash(url)
477
538
    # Segments begin at first comma after last forward slash, if one exists
478
 
    segment_start = lurl.find(",", lurl.rfind("/") + 1)
 
539
    segment_start = lurl.find(",", lurl.rfind("/")+1)
479
540
    if segment_start == -1:
480
541
        return (url, [])
481
 
    return (lurl[:segment_start],
482
 
            [str(s) for s in lurl[segment_start + 1:].split(",")])
 
542
    return (lurl[:segment_start], lurl[segment_start+1:].split(","))
483
543
 
484
544
 
485
545
def split_segment_parameters(url):
491
551
    (base_url, subsegments) = split_segment_parameters_raw(url)
492
552
    parameters = {}
493
553
    for subsegment in subsegments:
494
 
        try:
495
 
            (key, value) = subsegment.split("=", 1)
496
 
        except ValueError:
497
 
            raise InvalidURL(url, "missing = in subsegment")
498
 
        if not isinstance(key, str):
499
 
            raise TypeError(key)
500
 
        if not isinstance(value, str):
501
 
            raise TypeError(value)
 
554
        (key, value) = subsegment.split("=", 1)
502
555
        parameters[key] = value
503
556
    return (base_url, parameters)
504
557
 
505
558
 
506
 
def strip_segment_parameters(url):
507
 
    """Strip the segment parameters from a URL.
508
 
 
509
 
    :param url: A relative or absolute URL
510
 
    :return: url
511
 
    """
512
 
    base_url, subsegments = split_segment_parameters_raw(url)
513
 
    return base_url
514
 
 
515
 
 
516
559
def join_segment_parameters_raw(base, *subsegments):
517
 
    """Create a new URL by adding subsegments to an existing one.
 
560
    """Create a new URL by adding subsegments to an existing one. 
518
561
 
519
562
    This adds the specified subsegments to the last path in the specified
520
563
    base URL. The subsegments should be bytestrings.
528
571
            raise TypeError("Subsegment %r is not a bytestring" % subsegment)
529
572
        if "," in subsegment:
530
573
            raise InvalidURLJoin(", exists in subsegments",
531
 
                                 base, subsegments)
 
574
                                        base, subsegments)
532
575
    return ",".join((base,) + subsegments)
533
576
 
534
577
 
546
589
    new_parameters.update(existing_parameters)
547
590
    for key, value in parameters.items():
548
591
        if not isinstance(key, str):
549
 
            raise TypeError("parameter key %r is not a str" % key)
 
592
            raise TypeError("parameter key %r is not a bytestring" % key)
550
593
        if not isinstance(value, str):
551
 
            raise TypeError("parameter value %r for %r is not a str" %
552
 
                            (value, key))
 
594
            raise TypeError("parameter value %r for %s is not a bytestring" %
 
595
                (key, value))
553
596
        if "=" in key:
554
597
            raise InvalidURLJoin("= exists in parameter key", url,
555
 
                                 parameters)
 
598
                parameters)
556
599
        new_parameters[key] = value
557
 
    return join_segment_parameters_raw(
558
 
        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())])
559
602
 
560
603
 
561
604
def _win32_strip_local_trailing_slash(url):
599
642
        # so just chop off the last character
600
643
        return url[:-1]
601
644
 
602
 
    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:
603
646
        # Don't chop off anything if the only slash is the path
604
647
        # separating slash
605
648
        return url
619
662
    #       plain ASCII strings, or the final .decode will
620
663
    #       try to encode the UNICODE => ASCII, and then decode
621
664
    #       it into utf-8.
622
 
 
623
 
    if isinstance(url, str):
 
665
    if isinstance(url, text_type):
624
666
        try:
625
 
            url.encode("ascii")
 
667
            url = url.encode("ascii")
626
668
        except UnicodeError as e:
627
 
            raise InvalidURL(
628
 
                url, 'URL was not a plain ASCII url: %s' % (e,))
629
 
    return urlparse.unquote(url)
 
669
            raise InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
 
670
    if PY3:
 
671
        unquoted = urlparse.unquote_to_bytes(url)
 
672
    else:
 
673
        unquoted = unquote(url)
 
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
630
679
 
631
680
 
632
681
# These are characters that if escaped, should stay that way
633
682
_no_decode_chars = ';/?:@&=+$,#'
634
683
_no_decode_ords = [ord(c) for c in _no_decode_chars]
635
684
_no_decode_hex = (['%02x' % o for o in _no_decode_ords]
636
 
                  + ['%02X' % o for o in _no_decode_ords])
637
 
_hex_display_map = dict(([('%02x' % o, bytes([o])) for o in range(256)]
638
 
                         + [('%02X' % o, bytes([o])) for o in range(256)]))
639
 
# These entries get mapped to themselves
640
 
_hex_display_map.update((hex, b'%' + hex.encode('ascii'))
641
 
                        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)
642
690
 
643
691
# These characters shouldn't be percent-encoded, and it's always safe to
644
692
# unencode them if they are.
645
693
_url_dont_escape_characters = set(
646
 
    "abcdefghijklmnopqrstuvwxyz"  # Lowercase alpha
647
 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  # Uppercase alpha
648
 
    "0123456789"  # Numbers
649
 
    "-._~"  # Unreserved characters
 
694
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
 
695
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
 
696
   "0123456789" # Numbers
 
697
   "-._~"  # Unreserved characters
650
698
)
651
699
 
652
700
# These characters should not be escaped
653
701
_url_safe_characters = set(
654
 
    "abcdefghijklmnopqrstuvwxyz"  # Lowercase alpha
655
 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  # Uppercase alpha
656
 
    "0123456789"  # Numbers
657
 
    "_.-!~*'()"  # Unreserved characters
658
 
    "/;?:@&=+$,"  # Reserved characters
659
 
    "%#"         # Extra reserved characters
 
702
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
 
703
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
 
704
   "0123456789" # Numbers
 
705
   "_.-!~*'()"  # Unreserved characters
 
706
   "/;?:@&=+$," # Reserved characters
 
707
   "%#"         # Extra reserved characters
660
708
)
661
709
 
662
 
 
663
 
def _unescape_segment_for_display(segment, encoding):
664
 
    """Unescape a segment for display.
665
 
 
666
 
    Helper for unescape_for_display
667
 
 
668
 
    :param url: A 7-bit ASCII URL
669
 
    :param encoding: The final output encoding
670
 
 
671
 
    :return: A unicode string which can be safely encoded into the
672
 
         specified encoding.
673
 
    """
674
 
    escaped_chunks = segment.split('%')
675
 
    escaped_chunks[0] = escaped_chunks[0].encode('utf-8')
676
 
    for j in range(1, len(escaped_chunks)):
677
 
        item = escaped_chunks[j]
678
 
        try:
679
 
            escaped_chunks[j] = _hex_display_map[item[:2]]
680
 
        except KeyError:
681
 
            # Put back the percent symbol
682
 
            escaped_chunks[j] = b'%' + (item[:2].encode('utf-8'))
683
 
        except UnicodeDecodeError:
684
 
            escaped_chunks[j] = chr(int(item[:2], 16)).encode('utf-8')
685
 
        escaped_chunks[j] += (item[2:].encode('utf-8'))
686
 
    unescaped = b''.join(escaped_chunks)
687
 
    try:
688
 
        decoded = unescaped.decode('utf-8')
689
 
    except UnicodeDecodeError:
690
 
        # If this path segment cannot be properly utf-8 decoded
691
 
        # after doing unescaping we will just leave it alone
692
 
        return segment
693
 
    else:
694
 
        try:
695
 
            decoded.encode(encoding)
696
 
        except UnicodeEncodeError:
697
 
            # If this chunk cannot be encoded in the local
698
 
            # encoding, then we should leave it alone
699
 
            return segment
700
 
        else:
701
 
            # Otherwise take the url decoded one
702
 
            return decoded
703
 
 
704
 
 
705
710
def unescape_for_display(url, encoding):
706
711
    """Decode what you can for a URL, so that we get a nice looking path.
707
712
 
730
735
    # Split into sections to try to decode utf-8
731
736
    res = url.split('/')
732
737
    for i in range(1, len(res)):
733
 
        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
734
765
    return u'/'.join(res)
735
766
 
736
767
 
745
776
    is used without a path, e.g. c:foo-bar => foo-bar.
746
777
    If no /, path separator or : is found, the from_location is returned.
747
778
    """
748
 
    from_location = strip_segment_parameters(from_location)
749
779
    if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
750
780
        return os.path.basename(from_location.rstrip("/\\"))
751
781
    else:
752
782
        sep = from_location.find(":")
753
783
        if sep > 0:
754
 
            return from_location[sep + 1:]
 
784
            return from_location[sep+1:]
755
785
        else:
756
786
            return from_location
757
787
 
785
815
    to_segments = osutils.splitpath(to_path)
786
816
    count = -1
787
817
    for count, (from_element, to_element) in enumerate(zip(from_segments,
788
 
                                                           to_segments)):
 
818
                                                       to_segments)):
789
819
        if from_element != to_element:
790
820
            break
791
821
    else:
802
832
    """Parsed URL."""
803
833
 
804
834
    def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
805
 
                 port, quoted_path):
 
835
            port, quoted_path):
806
836
        self.scheme = scheme
807
837
        self.quoted_host = quoted_host
808
838
        self.host = unquote(self.quoted_host)
817
847
        else:
818
848
            self.password = None
819
849
        self.port = port
820
 
        self.quoted_path = _url_hex_escapes_re.sub(
821
 
            _unescape_safe_chars, quoted_path)
 
850
        self.quoted_path = _url_hex_escapes_re.sub(_unescape_safe_chars, quoted_path)
822
851
        self.path = unquote(self.quoted_path)
823
852
 
824
853
    def __eq__(self, other):
842
871
        :param url: URL as bytestring
843
872
        """
844
873
        # GZ 2017-06-09: Actually validate ascii-ness
845
 
        # pad.lv/1696545: For the moment, accept both native strings and
846
 
        # unicode.
847
 
        if isinstance(url, str):
848
 
            pass
849
 
        elif isinstance(url, str):
850
 
            try:
851
 
                url = url.encode()
852
 
            except UnicodeEncodeError:
853
 
                raise InvalidURL(url)
854
 
        else:
855
 
            raise InvalidURL(url)
 
874
        if not isinstance(url, str):
 
875
            raise InvalidURL('should be ascii:\n%r' % url)
856
876
        (scheme, netloc, path, params,
857
877
         query, fragment) = urlparse.urlparse(url, allow_fragments=False)
858
878
        user = password = host = port = None
866
886
        if ':' in host and not (host[0] == '[' and host[-1] == ']'):
867
887
            # there *is* port
868
888
            host, port = host.rsplit(':', 1)
869
 
            if port:
870
 
                try:
871
 
                    port = int(port)
872
 
                except ValueError:
873
 
                    raise InvalidURL('invalid port number %s in url:\n%s' %
874
 
                                     (port, url))
875
 
            else:
876
 
                port = None
877
 
        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
878
895
            host = host[1:-1]
879
896
 
880
897
        return cls(scheme, user, password, host, port, path)
913
930
        :param relpath: relative url string for relative part of remote path.
914
931
        :return: urlencoded string for final path.
915
932
        """
916
 
        # pad.lv/1696545: For the moment, accept both native strings and
917
 
        # unicode.
918
 
        if isinstance(relpath, str):
919
 
            pass
920
 
        elif isinstance(relpath, str):
921
 
            try:
922
 
                relpath = relpath.encode()
923
 
            except UnicodeEncodeError:
924
 
                raise InvalidURL(relpath)
925
 
        else:
 
933
        if not isinstance(relpath, str):
926
934
            raise InvalidURL(relpath)
927
935
        relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
928
936
        if relpath.startswith('/'):
939
947
                    continue
940
948
                base_parts.pop()
941
949
            elif p == '.':
942
 
                continue  # No-op
 
950
                continue # No-op
943
951
            elif p != '':
944
952
                base_parts.append(p)
945
953
        path = '/'.join(base_parts)
954
962
        :return: `URL` instance
955
963
        """
956
964
        if offset is not None:
957
 
            relative = unescape(offset)
 
965
            relative = unescape(offset).encode('utf-8')
958
966
            path = self._combine_paths(self.path, relative)
959
967
            path = quote(path, safe="/~")
960
968
        else:
961
969
            path = self.quoted_path
962
970
        return self.__class__(self.scheme, self.quoted_user,
963
 
                              self.quoted_password, self.quoted_host, self.port,
964
 
                              path)
 
971
                self.quoted_password, self.quoted_host, self.port,
 
972
                path)
965
973
 
966
974
 
967
975
def parse_url(url):
976
984
    """
977
985
    parsed_url = URL.from_string(url)
978
986
    return (parsed_url.scheme, parsed_url.user, parsed_url.password,
979
 
            parsed_url.host, parsed_url.port, parsed_url.path)
 
987
        parsed_url.host, parsed_url.port, parsed_url.path)