/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: Martin
  • Date: 2017-06-05 20:48:31 UTC
  • mto: This revision was merged to the branch mainline in revision 6658.
  • Revision ID: gzlist@googlemail.com-20170605204831-20accykspjcrx0a8
Apply 2to3 dict fixer and clean up resulting mess using view helpers

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 bzrlib.lazy_import import lazy_import
 
25
try:
 
26
    import urlparse
 
27
except ImportError:
 
28
    from urllib import parse as urlparse
 
29
 
 
30
from .lazy_import import lazy_import
24
31
lazy_import(globals(), """
25
 
from posixpath import split as _posix_split, normpath as _posix_normpath
26
 
import urllib
27
 
import urlparse
 
32
from posixpath import split as _posix_split
28
33
 
29
 
from bzrlib import (
 
34
from breezy import (
30
35
    errors,
31
36
    osutils,
32
37
    )
33
38
""")
34
39
 
 
40
from .sixish import (
 
41
    text_type,
 
42
    )
 
43
 
35
44
 
36
45
def basename(url, exclude_trailing_slash=True):
37
46
    """Return the last component of a URL.
60
69
    return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
61
70
 
62
71
 
 
72
# Private copies of quote and unquote, copied from Python's
 
73
# urllib module because urllib unconditionally imports socket, which imports
 
74
# ssl.
 
75
 
 
76
always_safe = (b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 
77
               b'abcdefghijklmnopqrstuvwxyz'
 
78
               b'0123456789' b'_.-')
 
79
_safe_map = {}
 
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')
 
82
_safe_quoters = {}
 
83
 
 
84
 
 
85
def quote(s, safe=b'/'):
 
86
    """quote('abc def') -> 'abc%20def'
 
87
 
 
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.
 
90
 
 
91
    RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
 
92
    the following reserved characters.
 
93
 
 
94
    reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
 
95
                  "$" | ","
 
96
 
 
97
    Each of these characters is reserved in some component of a URL,
 
98
    but not necessarily in all of them.
 
99
 
 
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
 
104
    reserved characters.
 
105
    """
 
106
    # fastpath
 
107
    if not s:
 
108
        if s is None:
 
109
            raise TypeError('None object cannot be quoted')
 
110
        return s
 
111
    cachekey = (safe, always_safe)
 
112
    try:
 
113
        (quoter, safe) = _safe_quoters[cachekey]
 
114
    except KeyError:
 
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):
 
121
        return s
 
122
    return b''.join(map(quoter, s))
 
123
 
 
124
 
 
125
_hexdig = '0123456789ABCDEFabcdef'
 
126
_hextochr = dict((a + b, chr(int(a + b, 16)))
 
127
                 for a in _hexdig for b in _hexdig)
 
128
 
 
129
def unquote(s):
 
130
    """unquote('abc%20def') -> 'abc def'."""
 
131
    res = s.split(b'%')
 
132
    # fastpath
 
133
    if len(res) == 1:
 
134
        return s
 
135
    s = res[0]
 
136
    for item in res[1:]:
 
137
        try:
 
138
            s += _hextochr[item[:2]] + item[2:]
 
139
        except KeyError:
 
140
            s += b'%' + item
 
141
        except UnicodeDecodeError:
 
142
            s += unichr(int(item[:2], 16)) + item[2:]
 
143
    return s
 
144
 
 
145
 
63
146
def escape(relpath):
64
147
    """Escape relpath to be a valid url."""
65
 
    if isinstance(relpath, unicode):
 
148
    if isinstance(relpath, text_type):
66
149
        relpath = relpath.encode('utf-8')
67
 
    # After quoting and encoding, the path should be perfectly
68
 
    # safe as a plain ASCII string, str() just enforces this
69
 
    return str(urllib.quote(relpath, safe='/~'))
 
150
    return quote(relpath, safe=b'/~')
70
151
 
71
152
 
72
153
def file_relpath(base, path):
78
159
        raise ValueError('Length of base (%r) must equal or'
79
160
            ' exceed the platform minimum url length (which is %d)' %
80
161
            (base, MIN_ABS_FILEURL_LENGTH))
81
 
    base = local_path_from_url(base)
82
 
    path = local_path_from_url(path)
 
162
    base = osutils.normpath(local_path_from_url(base))
 
163
    path = osutils.normpath(local_path_from_url(path))
83
164
    return escape(osutils.relpath(base, path))
84
165
 
85
166
 
98
179
 
99
180
    # Find the path separating slash
100
181
    # (first slash after the ://)
101
 
    first_path_slash = path.find('/')
 
182
    first_path_slash = path.find(b'/')
102
183
    if first_path_slash == -1:
103
184
        return len(scheme), None
104
 
    return len(scheme), first_path_slash+len(scheme)+3
 
185
    return len(scheme), first_path_slash+m.start('path')
 
186
 
 
187
 
 
188
def is_url(url):
 
189
    """Tests whether a URL is in actual fact a URL."""
 
190
    return _url_scheme_re.match(url) is not None
105
191
 
106
192
 
107
193
def join(base, *args):
118
204
    """
119
205
    if not args:
120
206
        return base
121
 
    match = _url_scheme_re.match(base)
122
 
    scheme = None
123
 
    if match:
124
 
        scheme = match.group('scheme')
125
 
        path = match.group('path').split('/')
126
 
        if path[-1:] == ['']:
127
 
            # Strip off a trailing slash
128
 
            # This helps both when we are at the root, and when
129
 
            # 'base' has an extra slash at the end
130
 
            path = path[:-1]
131
 
    else:
132
 
        path = base.split('/')
133
 
 
134
 
    if scheme is not None and len(path) >= 1:
135
 
        host = path[:1]
136
 
        # the path should be represented as an abs path.
137
 
        # we know this must be absolute because of the presence of a URL scheme.
138
 
        remove_root = True
139
 
        path = [''] + path[1:]
140
 
    else:
141
 
        # create an empty host, but dont alter the path - this might be a
142
 
        # relative url fragment.
143
 
        host = []
144
 
        remove_root = False
145
 
 
 
207
    scheme_end, path_start = _find_scheme_and_separator(base)
 
208
    if scheme_end is None and path_start is None:
 
209
        path_start = 0
 
210
    elif path_start is None:
 
211
        path_start = len(base)
 
212
    path = base[path_start:]
146
213
    for arg in args:
147
 
        match = _url_scheme_re.match(arg)
148
 
        if match:
149
 
            # Absolute URL
150
 
            scheme = match.group('scheme')
151
 
            # this skips .. normalisation, making http://host/../../..
152
 
            # be rather strange.
153
 
            path = match.group('path').split('/')
154
 
            # set the host and path according to new absolute URL, discarding
155
 
            # any previous values.
156
 
            # XXX: duplicates mess from earlier in this function.  This URL
157
 
            # manipulation code needs some cleaning up.
158
 
            if scheme is not None and len(path) >= 1:
159
 
                host = path[:1]
160
 
                path = path[1:]
161
 
                # url scheme implies absolute path.
162
 
                path = [''] + path
163
 
            else:
164
 
                # no url scheme we take the path as is.
165
 
                host = []
 
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:
 
216
            arg_path_start = 0
 
217
        elif arg_path_start is None:
 
218
            arg_path_start = len(arg)
 
219
        if arg_scheme_end is not None:
 
220
            base = arg
 
221
            path = arg[arg_path_start:]
 
222
            scheme_end = arg_scheme_end
 
223
            path_start = arg_path_start
166
224
        else:
167
 
            path = '/'.join(path)
168
225
            path = joinpath(path, arg)
169
 
            path = path.split('/')
170
 
    if remove_root and path[0:1] == ['']:
171
 
        del path[0]
172
 
    if host:
173
 
        # Remove the leading slash from the path, so long as it isn't also the
174
 
        # trailing slash, which we want to keep if present.
175
 
        if path and path[0] == '' and len(path) > 1:
176
 
            del path[0]
177
 
        path = host + path
178
 
 
179
 
    if scheme is None:
180
 
        return '/'.join(path)
181
 
    return scheme + '://' + '/'.join(path)
 
226
    return base[:path_start] + path
182
227
 
183
228
 
184
229
def joinpath(base, *args):
191
236
    We really should try to have exactly one place in the code base responsible
192
237
    for combining paths of URLs.
193
238
    """
194
 
    path = base.split('/')
195
 
    if len(path) > 1 and path[-1] == '':
 
239
    path = base.split(b'/')
 
240
    if len(path) > 1 and path[-1] == b'':
196
241
        #If the path ends in a trailing /, remove it.
197
242
        path.pop()
198
243
    for arg in args:
199
 
        if arg.startswith('/'):
 
244
        if arg.startswith(b'/'):
200
245
            path = []
201
 
        for chunk in arg.split('/'):
202
 
            if chunk == '.':
 
246
        for chunk in arg.split(b'/'):
 
247
            if chunk == b'.':
203
248
                continue
204
 
            elif chunk == '..':
205
 
                if path == ['']:
 
249
            elif chunk == b'..':
 
250
                if path == [b'']:
206
251
                    raise errors.InvalidURLJoin('Cannot go above root',
207
252
                            base, args)
208
253
                path.pop()
209
254
            else:
210
255
                path.append(chunk)
211
 
    if path == ['']:
212
 
        return '/'
 
256
    if path == [b'']:
 
257
        return b'/'
213
258
    else:
214
 
        return '/'.join(path)
 
259
        return b'/'.join(path)
215
260
 
216
261
 
217
262
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
218
263
def _posix_local_path_from_url(url):
219
264
    """Convert a url like file:///path/to/foo into /path/to/foo"""
220
 
    file_localhost_prefix = 'file://localhost/'
 
265
    url = split_segment_parameters_raw(url)[0]
 
266
    file_localhost_prefix = b'file://localhost/'
221
267
    if url.startswith(file_localhost_prefix):
222
268
        path = url[len(file_localhost_prefix) - 1:]
223
 
    elif not url.startswith('file:///'):
 
269
    elif not url.startswith(b'file:///'):
224
270
        raise errors.InvalidURL(
225
271
            url, 'local urls must start with file:/// or file://localhost/')
226
272
    else:
227
 
        path = url[len('file://'):]
 
273
        path = url[len(b'file://'):]
228
274
    # We only strip off 2 slashes
229
275
    return unescape(path)
230
276
 
236
282
    """
237
283
    # importing directly from posixpath allows us to test this
238
284
    # on non-posix platforms
239
 
    return 'file://' + escape(_posix_normpath(
240
 
        osutils._posix_abspath(path)))
 
285
    return b'file://' + escape(osutils._posix_abspath(path))
241
286
 
242
287
 
243
288
def _win32_local_path_from_url(url):
245
290
    if not url.startswith('file://'):
246
291
        raise errors.InvalidURL(url, 'local urls must start with file:///, '
247
292
                                     'UNC path urls must start with file://')
 
293
    url = split_segment_parameters_raw(url)[0]
248
294
    # We strip off all 3 slashes
249
295
    win32_url = url[len('file:'):]
250
296
    # check for UNC path: //HOST/path
260
306
        return '/'
261
307
 
262
308
    # usual local path with drive letter
263
 
    if (win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
264
 
                             'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
 
309
    if (len(win32_url) < 6
 
310
        or win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
 
311
                                'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
265
312
        or win32_url[4] not in  '|:'
266
313
        or win32_url[5] != '/'):
267
314
        raise errors.InvalidURL(url, 'Win32 file urls start with'
278
325
    # on non-win32 platform
279
326
    # FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
280
327
    #       which actually strips trailing space characters.
281
 
    #       The worst part is that under linux ntpath.abspath has different
 
328
    #       The worst part is that on linux ntpath.abspath has different
282
329
    #       semantics, since 'nt' is not an available module.
283
330
    if path == '/':
284
331
        return 'file:///'
303
350
    MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
304
351
 
305
352
 
306
 
_url_scheme_re = re.compile(r'^(?P<scheme>[^:/]{2,})://(?P<path>.*)$')
307
 
_url_hex_escapes_re = re.compile(r'(%[0-9a-fA-F]{2})')
 
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})')
308
355
 
309
356
 
310
357
def _unescape_safe_chars(matchobj):
339
386
    :param url: Either a hybrid URL or a local path
340
387
    :return: A normalized URL which only includes 7-bit ASCII characters.
341
388
    """
342
 
    m = _url_scheme_re.match(url)
343
 
    if not m:
 
389
    scheme_end, path_start = _find_scheme_and_separator(url)
 
390
    if scheme_end is None:
344
391
        return local_path_to_url(url)
345
 
    scheme = m.group('scheme')
346
 
    path = m.group('path')
 
392
    prefix = url[:path_start]
 
393
    path = url[path_start:]
347
394
    if not isinstance(url, unicode):
348
395
        for c in url:
349
396
            if c not in _url_safe_characters:
350
397
                raise errors.InvalidURL(url, 'URLs can only contain specific'
351
398
                                            ' safe characters (not %r)' % c)
352
399
        path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
353
 
        return str(scheme + '://' + ''.join(path))
 
400
        return str(prefix + ''.join(path))
354
401
 
355
402
    # We have a unicode (hybrid) url
356
403
    path_chars = list(path)
357
404
 
358
 
    for i in xrange(len(path_chars)):
 
405
    for i in range(len(path_chars)):
359
406
        if path_chars[i] not in _url_safe_characters:
360
407
            chars = path_chars[i].encode('utf-8')
361
408
            path_chars[i] = ''.join(
362
409
                ['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
363
410
    path = ''.join(path_chars)
364
411
    path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
365
 
    return str(scheme + '://' + path)
 
412
    return str(prefix + path)
366
413
 
367
414
 
368
415
def relative_url(base, other):
421
468
    """On win32 the drive letter needs to be added to the url base."""
422
469
    # Strip off the drive letter
423
470
    # path is currently /C:/foo
424
 
    if len(path) < 3 or path[2] not in ':|' or path[3] != '/':
 
471
    if len(path) < 4 or path[2] not in ':|' or path[3] != '/':
425
472
        raise errors.InvalidURL(url_base + path,
426
473
            'win32 file:/// paths need a drive letter')
427
474
    url_base += path[0:3] # file:// + /C:
469
516
    return url_base + head, tail
470
517
 
471
518
 
 
519
def split_segment_parameters_raw(url):
 
520
    """Split the subsegment of the last segment of a URL.
 
521
 
 
522
    :param url: A relative or absolute URL
 
523
    :return: (url, subsegments)
 
524
    """
 
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:
 
532
        return (url, [])
 
533
    return (lurl[:segment_start], lurl[segment_start+1:].split(b","))
 
534
 
 
535
 
 
536
def split_segment_parameters(url):
 
537
    """Split the segment parameters of the last segment of a URL.
 
538
 
 
539
    :param url: A relative or absolute URL
 
540
    :return: (url, segment_parameters)
 
541
    """
 
542
    (base_url, subsegments) = split_segment_parameters_raw(url)
 
543
    parameters = {}
 
544
    for subsegment in subsegments:
 
545
        (key, value) = subsegment.split("=", 1)
 
546
        parameters[key] = value
 
547
    return (base_url, parameters)
 
548
 
 
549
 
 
550
def join_segment_parameters_raw(base, *subsegments):
 
551
    """Create a new URL by adding subsegments to an existing one. 
 
552
 
 
553
    This adds the specified subsegments to the last path in the specified
 
554
    base URL. The subsegments should be bytestrings.
 
555
 
 
556
    :note: You probably want to use join_segment_parameters instead.
 
557
    """
 
558
    if not subsegments:
 
559
        return base
 
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",
 
565
                                        base, subsegments)
 
566
    return ",".join((base,) + subsegments)
 
567
 
 
568
 
 
569
def join_segment_parameters(url, parameters):
 
570
    """Create a new URL by adding segment parameters to an existing one.
 
571
 
 
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.
 
574
 
 
575
    :param url: A URL, as string
 
576
    :param parameters: Dictionary of parameters, keys and values as bytestrings
 
577
    """
 
578
    (base, existing_parameters) = split_segment_parameters(url)
 
579
    new_parameters = {}
 
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" %
 
586
                (key, value))
 
587
        if "=" in key:
 
588
            raise errors.InvalidURLJoin("= exists in parameter key", url,
 
589
                parameters)
 
590
        new_parameters[key] = value
 
591
    return join_segment_parameters_raw(base, 
 
592
        *["%s=%s" % item for item in sorted(new_parameters.items())])
 
593
 
 
594
 
472
595
def _win32_strip_local_trailing_slash(url):
473
596
    """Strip slashes after the drive letter"""
474
597
    if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
498
621
        # format which does it differently.
499
622
        file:///c|/       => file:///c:/
500
623
    """
501
 
    if not url.endswith('/'):
 
624
    if not url.endswith(b'/'):
502
625
        # Nothing to do
503
626
        return url
504
 
    if sys.platform == 'win32' and url.startswith('file://'):
 
627
    if sys.platform == 'win32' and url.startswith(b'file://'):
505
628
        return _win32_strip_local_trailing_slash(url)
506
629
 
507
630
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
524
647
    This returns a Unicode path from a URL
525
648
    """
526
649
    # jam 20060427 URLs are supposed to be ASCII only strings
527
 
    #       If they are passed in as unicode, urllib.unquote
 
650
    #       If they are passed in as unicode, unquote
528
651
    #       will return a UNICODE string, which actually contains
529
652
    #       utf-8 bytes. So we have to ensure that they are
530
653
    #       plain ASCII strings, or the final .decode will
531
654
    #       try to encode the UNICODE => ASCII, and then decode
532
655
    #       it into utf-8.
533
 
    try:
534
 
        url = str(url)
535
 
    except UnicodeError, e:
536
 
        raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
 
656
    if isinstance(url, text_type):
 
657
        try:
 
658
            url = url.encode("ascii")
 
659
        except UnicodeError as e:
 
660
            raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
537
661
 
538
 
    unquoted = urllib.unquote(url)
 
662
    unquoted = unquote(url)
539
663
    try:
540
664
        unicode_path = unquoted.decode('utf-8')
541
 
    except UnicodeError, e:
 
665
    except UnicodeError as e:
542
666
        raise errors.InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
543
667
    return unicode_path
544
668
 
599
723
 
600
724
    # Split into sections to try to decode utf-8
601
725
    res = url.split('/')
602
 
    for i in xrange(1, len(res)):
 
726
    for i in range(1, len(res)):
603
727
        escaped_chunks = res[i].split('%')
604
 
        for j in xrange(1, len(escaped_chunks)):
 
728
        for j in range(1, len(escaped_chunks)):
605
729
            item = escaped_chunks[j]
606
730
            try:
607
731
                escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
693
817
    return osutils.pathjoin(*segments)
694
818
 
695
819
 
 
820
class URL(object):
 
821
    """Parsed URL."""
 
822
 
 
823
    def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
 
824
            port, quoted_path):
 
825
        self.scheme = scheme
 
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)
 
831
        else:
 
832
            self.user = None
 
833
        self.quoted_password = quoted_password
 
834
        if self.quoted_password is not None:
 
835
            self.password = unquote(self.quoted_password)
 
836
        else:
 
837
            self.password = None
 
838
        self.port = port
 
839
        self.quoted_path = _url_hex_escapes_re.sub(_unescape_safe_chars, quoted_path)
 
840
        self.path = unquote(self.quoted_path)
 
841
 
 
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)
 
849
 
 
850
    def __repr__(self):
 
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)
 
855
 
 
856
    @classmethod
 
857
    def from_string(cls, url):
 
858
        """Create a URL object from a string.
 
859
 
 
860
        :param url: URL as bytestring
 
861
        """
 
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
 
868
        if '@' in netloc:
 
869
            user, host = netloc.rsplit('@', 1)
 
870
            if ':' in user:
 
871
                user, password = user.split(':', 1)
 
872
        else:
 
873
            host = netloc
 
874
 
 
875
        if ':' in host and not (host[0] == '[' and host[-1] == ']'):
 
876
            # there *is* port
 
877
            host, port = host.rsplit(':',1)
 
878
            try:
 
879
                port = int(port)
 
880
            except ValueError:
 
881
                raise errors.InvalidURL('invalid port number %s in url:\n%s' %
 
882
                                        (port, url))
 
883
        if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
 
884
            host = host[1:-1]
 
885
 
 
886
        return cls(scheme, user, password, host, port, path)
 
887
 
 
888
    def __str__(self):
 
889
        netloc = self.quoted_host
 
890
        if ":" in netloc:
 
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
 
895
            # exposed.
 
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))
 
901
 
 
902
    @staticmethod
 
903
    def _combine_paths(base_path, relpath):
 
904
        """Transform a Transport-relative path to a remote absolute path.
 
905
 
 
906
        This does not handle substitution of ~ but does handle '..' and '.'
 
907
        components.
 
908
 
 
909
        Examples::
 
910
 
 
911
            t._combine_paths('/home/sarah', 'project/foo')
 
912
                => '/home/sarah/project/foo'
 
913
            t._combine_paths('/home/sarah', '../../etc')
 
914
                => '/etc'
 
915
            t._combine_paths('/home/sarah', '/etc')
 
916
                => '/etc'
 
917
 
 
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.
 
921
        """
 
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('/'):
 
926
            base_parts = []
 
927
        else:
 
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('/'):
 
932
            if p == '..':
 
933
                if len(base_parts) == 0:
 
934
                    # In most filesystems, a request for the parent
 
935
                    # of root, just returns root.
 
936
                    continue
 
937
                base_parts.pop()
 
938
            elif p == '.':
 
939
                continue # No-op
 
940
            elif p != '':
 
941
                base_parts.append(p)
 
942
        path = '/'.join(base_parts)
 
943
        if not path.startswith('/'):
 
944
            path = '/' + path
 
945
        return path
 
946
 
 
947
    def clone(self, offset=None):
 
948
        """Return a new URL for a path relative to this URL.
 
949
 
 
950
        :param offset: A relative path, already urlencoded
 
951
        :return: `URL` instance
 
952
        """
 
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="/~")
 
957
        else:
 
958
            path = self.quoted_path
 
959
        return self.__class__(self.scheme, self.quoted_user,
 
960
                self.quoted_password, self.quoted_host, self.port,
 
961
                path)
 
962
 
696
963
 
697
964
def parse_url(url):
698
965
    """Extract the server address, the credentials and the path from the url.
701
968
    chars.
702
969
 
703
970
    :param url: an quoted url
704
 
 
705
971
    :return: (scheme, user, password, host, port, path) tuple, all fields
706
972
        are unquoted.
707
973
    """
708
 
    if isinstance(url, unicode):
709
 
        raise errors.InvalidURL('should be ascii:\n%r' % url)
710
 
    url = url.encode('utf-8')
711
 
    (scheme, netloc, path, params,
712
 
     query, fragment) = urlparse.urlparse(url, allow_fragments=False)
713
 
    user = password = host = port = None
714
 
    if '@' in netloc:
715
 
        user, host = netloc.rsplit('@', 1)
716
 
        if ':' in user:
717
 
            user, password = user.split(':', 1)
718
 
            password = urllib.unquote(password)
719
 
        user = urllib.unquote(user)
720
 
    else:
721
 
        host = netloc
722
 
 
723
 
    if ':' in host and not (host[0] == '[' and host[-1] == ']'): #there *is* port
724
 
        host, port = host.rsplit(':',1)
725
 
        try:
726
 
            port = int(port)
727
 
        except ValueError:
728
 
            raise errors.InvalidURL('invalid port number %s in url:\n%s' %
729
 
                                    (port, url))
730
 
    if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
731
 
        host = host[1:-1]
732
 
 
733
 
    host = urllib.unquote(host)
734
 
    path = urllib.unquote(path)
735
 
 
736
 
    return (scheme, user, password, host, port, path)
 
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)