/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: 2017-06-08 00:00:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6672.
  • Revision ID: jelmer@jelmer.uk-20170608000028-e3ggtt4wjbcjh91j
Drop pycurl support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2010 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""A collection of function for handling URL operations."""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
import os
 
22
import re
 
23
import sys
 
24
 
 
25
try:
 
26
    import urlparse
 
27
except ImportError:
 
28
    from urllib import parse as urlparse
 
29
 
 
30
from .lazy_import import lazy_import
 
31
lazy_import(globals(), """
 
32
from posixpath import split as _posix_split
 
33
 
 
34
from breezy import (
 
35
    errors,
 
36
    osutils,
 
37
    )
 
38
""")
 
39
 
 
40
from .sixish import (
 
41
    text_type,
 
42
    )
 
43
 
 
44
 
 
45
def basename(url, exclude_trailing_slash=True):
 
46
    """Return the last component of a URL.
 
47
 
 
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
 
53
        root of the URL.
 
54
    """
 
55
    return split(url, exclude_trailing_slash=exclude_trailing_slash)[1]
 
56
 
 
57
 
 
58
def dirname(url, exclude_trailing_slash=True):
 
59
    """Return the parent directory of the given path.
 
60
 
 
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
 
66
    """
 
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]
 
70
 
 
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
 
 
146
def escape(relpath):
 
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'/~')
 
151
 
 
152
 
 
153
def file_relpath(base, path):
 
154
    """Compute just the relative sub-portion of a url
 
155
 
 
156
    This assumes that both paths are already fully specified file:// URLs.
 
157
    """
 
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))
 
165
 
 
166
 
 
167
def _find_scheme_and_separator(url):
 
168
    """Find the scheme separator (://) and the first path separator
 
169
 
 
170
    This is just a helper functions for other path utilities.
 
171
    It could probably be replaced by urlparse
 
172
    """
 
173
    m = _url_scheme_re.match(url)
 
174
    if not m:
 
175
        return None, None
 
176
 
 
177
    scheme = m.group('scheme')
 
178
    path = m.group('path')
 
179
 
 
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')
 
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
 
191
 
 
192
 
 
193
def join(base, *args):
 
194
    """Create a URL by joining sections.
 
195
 
 
196
    This will normalize '..', assuming that paths are absolute
 
197
    (it assumes no symlinks in either path)
 
198
 
 
199
    If any of *args is an absolute URL, it will be treated correctly.
 
200
    Example:
 
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'
 
204
    """
 
205
    if not args:
 
206
        return base
 
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:]
 
213
    for arg in args:
 
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
 
224
        else:
 
225
            path = joinpath(path, arg)
 
226
    return base[:path_start] + path
 
227
 
 
228
 
 
229
def joinpath(base, *args):
 
230
    """Join URL path segments to a URL path segment.
 
231
 
 
232
    This is somewhat like osutils.joinpath, but intended for URLs.
 
233
 
 
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.
 
238
    """
 
239
    path = base.split(b'/')
 
240
    if len(path) > 1 and path[-1] == b'':
 
241
        #If the path ends in a trailing /, remove it.
 
242
        path.pop()
 
243
    for arg in args:
 
244
        if arg.startswith(b'/'):
 
245
            path = []
 
246
        for chunk in arg.split(b'/'):
 
247
            if chunk == b'.':
 
248
                continue
 
249
            elif chunk == b'..':
 
250
                if path == [b'']:
 
251
                    raise errors.InvalidURLJoin('Cannot go above root',
 
252
                            base, args)
 
253
                path.pop()
 
254
            else:
 
255
                path.append(chunk)
 
256
    if path == [b'']:
 
257
        return b'/'
 
258
    else:
 
259
        return b'/'.join(path)
 
260
 
 
261
 
 
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/')
 
272
    else:
 
273
        path = url[len(b'file://'):]
 
274
    # We only strip off 2 slashes
 
275
    return unescape(path)
 
276
 
 
277
 
 
278
def _posix_local_path_to_url(path):
 
279
    """Convert a local path like ./foo into a URL like file:///path/to/foo
 
280
 
 
281
    This also handles transforming escaping unicode characters, etc.
 
282
    """
 
283
    # importing directly from posixpath allows us to test this
 
284
    # on non-posix platforms
 
285
    return b'file://' + escape(osutils._posix_abspath(path))
 
286
 
 
287
 
 
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)
 
303
 
 
304
    # allow empty paths so we can serve all roots
 
305
    if win32_url == '///':
 
306
        return '/'
 
307
 
 
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:])
 
317
 
 
318
 
 
319
def _win32_local_path_to_url(path):
 
320
    """Convert a local path like ./foo into a URL like file:///C:/path/to/foo
 
321
 
 
322
    This also handles transforming escaping unicode characters, etc.
 
323
    """
 
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.
 
330
    if path == '/':
 
331
        return 'file:///'
 
332
 
 
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:]))
 
339
 
 
340
 
 
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:/')
 
345
 
 
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
 
349
 
 
350
    MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
 
351
 
 
352
 
 
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})')
 
355
 
 
356
 
 
357
def _unescape_safe_chars(matchobj):
 
358
    """re.sub callback to convert hex-escapes to plain characters (if safe).
 
359
 
 
360
    e.g. '%7E' will be converted to '~'.
 
361
    """
 
362
    hex_digits = matchobj.group(0)[1:]
 
363
    char = chr(int(hex_digits, 16))
 
364
    if char in _url_dont_escape_characters:
 
365
        return char
 
366
    else:
 
367
        return matchobj.group(0).upper()
 
368
 
 
369
 
 
370
def normalize_url(url):
 
371
    """Make sure that a path string is in fully normalized URL form.
 
372
 
 
373
    This handles URLs which have unicode characters, spaces,
 
374
    special characters, etc.
 
375
 
 
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.
 
385
 
 
386
    :param url: Either a hybrid URL or a local path
 
387
    :return: A normalized URL which only includes 7-bit ASCII characters.
 
388
    """
 
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):
 
395
        for c in url:
 
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))
 
401
 
 
402
    # We have a unicode (hybrid) url
 
403
    path_chars = list(path)
 
404
 
 
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)
 
413
 
 
414
 
 
415
def relative_url(base, other):
 
416
    """Return a path to other from base.
 
417
 
 
418
    If other is unrelated to base, return other. Else return a relative path.
 
419
    This assumes no symlinks as part of the url.
 
420
    """
 
421
    dummy, base_first_slash = _find_scheme_and_separator(base)
 
422
    if base_first_slash is None:
 
423
        return other
 
424
 
 
425
    dummy, other_first_slash = _find_scheme_and_separator(other)
 
426
    if other_first_slash is None:
 
427
        return other
 
428
 
 
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:
 
433
        return other
 
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:
 
438
            return other
 
439
 
 
440
    base_path = base[base_first_slash+1:]
 
441
    other_path = other[other_first_slash+1:]
 
442
 
 
443
    if base_path.endswith('/'):
 
444
        base_path = base_path[:-1]
 
445
 
 
446
    base_sections = base_path.split('/')
 
447
    other_sections = other_path.split('/')
 
448
 
 
449
    if base_sections == ['']:
 
450
        base_sections = []
 
451
    if other_sections == ['']:
 
452
        other_sections = []
 
453
 
 
454
    output_sections = []
 
455
    for b, o in zip(base_sections, other_sections):
 
456
        if b != o:
 
457
            break
 
458
        output_sections.append(b)
 
459
 
 
460
    match_len = len(output_sections)
 
461
    output_sections = ['..' for x in base_sections[match_len:]]
 
462
    output_sections.extend(other_sections[match_len:])
 
463
 
 
464
    return "/".join(output_sections) or "."
 
465
 
 
466
 
 
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
 
477
 
 
478
 
 
479
def split(url, exclude_trailing_slash=True):
 
480
    """Split a URL into its parent directory and a child directory.
 
481
 
 
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)
 
485
 
 
486
    :return: (parent_url, child_dir).  child_dir may be the empty string if we're at
 
487
        the root.
 
488
    """
 
489
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
 
490
 
 
491
    if first_path_slash is None:
 
492
        # We have either a relative path, or no separating slash
 
493
        if scheme_loc is None:
 
494
            # Relative path
 
495
            if exclude_trailing_slash and url.endswith('/'):
 
496
                url = url[:-1]
 
497
            return _posix_split(url)
 
498
        else:
 
499
            # Scheme with no path
 
500
            return url, ''
 
501
 
 
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
 
505
 
 
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
 
512
 
 
513
    if exclude_trailing_slash and len(path) > 1 and path.endswith('/'):
 
514
        path = path[:-1]
 
515
    head, tail = _posix_split(path)
 
516
    return url_base + head, tail
 
517
 
 
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
 
 
595
def _win32_strip_local_trailing_slash(url):
 
596
    """Strip slashes after the drive letter"""
 
597
    if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
 
598
        return url[:-1]
 
599
    else:
 
600
        return url
 
601
 
 
602
 
 
603
def strip_trailing_slash(url):
 
604
    """Strip trailing slash, except for root paths.
 
605
 
 
606
    The definition of 'root path' is platform-dependent.
 
607
    This assumes that all URLs are valid netloc urls, such that they
 
608
    form:
 
609
    scheme://host/path
 
610
    It searches for ://, and then refuses to remove the next '/'.
 
611
    It can also handle relative paths
 
612
    Examples:
 
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/
 
618
        file:///          => file:///
 
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:/
 
623
    """
 
624
    if not url.endswith(b'/'):
 
625
        # Nothing to do
 
626
        return url
 
627
    if sys.platform == 'win32' and url.startswith(b'file://'):
 
628
        return _win32_strip_local_trailing_slash(url)
 
629
 
 
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
 
634
        return url[:-1]
 
635
 
 
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
 
638
        # separating slash
 
639
        return url
 
640
 
 
641
    return url[:-1]
 
642
 
 
643
 
 
644
def unescape(url):
 
645
    """Unescape relpath from url format.
 
646
 
 
647
    This returns a Unicode path from a URL
 
648
    """
 
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
 
655
    #       it into utf-8.
 
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,))
 
661
 
 
662
    unquoted = unquote(url)
 
663
    try:
 
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,))
 
667
    return unicode_path
 
668
 
 
669
 
 
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)
 
679
 
 
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
 
687
)
 
688
 
 
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
 
697
)
 
698
 
 
699
def unescape_for_display(url, encoding):
 
700
    """Decode what you can for a URL, so that we get a nice looking path.
 
701
 
 
702
    This will turn file:// urls into local paths, and try to decode
 
703
    any portions of a http:// style url that it can.
 
704
 
 
705
    Any sections of the URL which can't be represented in the encoding or
 
706
    need to stay as escapes are left alone.
 
707
 
 
708
    :param url: A 7-bit ASCII URL
 
709
    :param encoding: The final output encoding
 
710
 
 
711
    :return: A unicode string which can be safely encoded into the
 
712
         specified encoding.
 
713
    """
 
714
    if encoding is None:
 
715
        raise ValueError('you cannot specify None for the display encoding')
 
716
    if url.startswith('file://'):
 
717
        try:
 
718
            path = local_path_from_url(url)
 
719
            path.encode(encoding)
 
720
            return path
 
721
        except UnicodeError:
 
722
            return url
 
723
 
 
724
    # Split into sections to try to decode utf-8
 
725
    res = url.split('/')
 
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]
 
730
            try:
 
731
                escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
 
732
            except KeyError:
 
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)
 
738
        try:
 
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
 
743
            pass
 
744
        else:
 
745
            try:
 
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
 
750
                pass
 
751
            else:
 
752
                # Otherwise take the url decoded one
 
753
                res[i] = decoded
 
754
    return u'/'.join(res)
 
755
 
 
756
 
 
757
def derive_to_location(from_location):
 
758
    """Derive a TO_LOCATION given a FROM_LOCATION.
 
759
 
 
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.
 
767
    """
 
768
    if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
 
769
        return os.path.basename(from_location.rstrip("/\\"))
 
770
    else:
 
771
        sep = from_location.find(":")
 
772
        if sep > 0:
 
773
            return from_location[sep+1:]
 
774
        else:
 
775
            return from_location
 
776
 
 
777
 
 
778
def _is_absolute(url):
 
779
    return (osutils.pathjoin('/foo', url) == url)
 
780
 
 
781
 
 
782
def rebase_url(url, old_base, new_base):
 
783
    """Convert a relative path from an old base URL to a new base URL.
 
784
 
 
785
    The result will be a relative path.
 
786
    Absolute paths and full URLs are returned unaltered.
 
787
    """
 
788
    scheme, separator = _find_scheme_and_separator(url)
 
789
    if scheme is not None:
 
790
        return url
 
791
    if _is_absolute(url):
 
792
        return 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))
 
799
 
 
800
 
 
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)
 
805
    count = -1
 
806
    for count, (from_element, to_element) in enumerate(zip(from_segments,
 
807
                                                       to_segments)):
 
808
        if from_element != to_element:
 
809
            break
 
810
    else:
 
811
        count += 1
 
812
    unique_from = from_segments[count:]
 
813
    unique_to = to_segments[count:]
 
814
    segments = (['..'] * len(unique_from) + unique_to)
 
815
    if len(segments) == 0:
 
816
        return '.'
 
817
    return osutils.pathjoin(*segments)
 
818
 
 
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
 
 
963
 
 
964
def parse_url(url):
 
965
    """Extract the server address, the credentials and the path from the url.
 
966
 
 
967
    user, password, host and path should be quoted if they contain reserved
 
968
    chars.
 
969
 
 
970
    :param url: an quoted url
 
971
    :return: (scheme, user, password, host, port, path) tuple, all fields
 
972
        are unquoted.
 
973
    """
 
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)