/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: 2020-02-07 02:14:30 UTC
  • mto: This revision was merged to the branch mainline in revision 7492.
  • Revision ID: jelmer@jelmer.uk-20200207021430-m49iq3x4x8xlib6x
Drop python2 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
from urllib import parse as urlparse
 
26
 
 
27
from . import (
 
28
    errors,
 
29
    osutils,
 
30
    )
 
31
 
 
32
from .lazy_import import lazy_import
 
33
lazy_import(globals(), """
 
34
from posixpath import split as _posix_split
 
35
""")
 
36
 
 
37
 
 
38
 
 
39
class InvalidURL(errors.PathError):
 
40
 
 
41
    _fmt = 'Invalid url supplied to transport: "%(path)s"%(extra)s'
 
42
 
 
43
 
 
44
class InvalidURLJoin(errors.PathError):
 
45
 
 
46
    _fmt = "Invalid URL join request: %(reason)s: %(base)r + %(join_args)r"
 
47
 
 
48
    def __init__(self, reason, base, join_args):
 
49
        self.reason = reason
 
50
        self.base = base
 
51
        self.join_args = join_args
 
52
        errors.PathError.__init__(self, base, reason)
 
53
 
 
54
 
 
55
class InvalidRebaseURLs(errors.PathError):
 
56
 
 
57
    _fmt = "URLs differ by more than path: %(from_)r and %(to)r"
 
58
 
 
59
    def __init__(self, from_, to):
 
60
        self.from_ = from_
 
61
        self.to = to
 
62
        errors.PathError.__init__(
 
63
            self, from_, 'URLs differ by more than path.')
 
64
 
 
65
 
 
66
def basename(url, exclude_trailing_slash=True):
 
67
    """Return the last component of a URL.
 
68
 
 
69
    :param url: The URL in question
 
70
    :param exclude_trailing_slash: If the url looks like "path/to/foo/"
 
71
        ignore the final slash and return 'foo' rather than ''
 
72
    :return: Just the final component of the URL. This can return ''
 
73
        if you don't exclude_trailing_slash, or if you are at the
 
74
        root of the URL.
 
75
    """
 
76
    return split(url, exclude_trailing_slash=exclude_trailing_slash)[1]
 
77
 
 
78
 
 
79
def dirname(url, exclude_trailing_slash=True):
 
80
    """Return the parent directory of the given path.
 
81
 
 
82
    :param url: Relative or absolute URL
 
83
    :param exclude_trailing_slash: Remove a final slash
 
84
        (treat http://host/foo/ as http://host/foo, but
 
85
        http://host/ stays http://host/)
 
86
    :return: Everything in the URL except the last path chunk
 
87
    """
 
88
    # TODO: jam 20060502 This was named dirname to be consistent
 
89
    #       with the os functions, but maybe "parent" would be better
 
90
    return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
 
91
 
 
92
 
 
93
quote_from_bytes = urlparse.quote_from_bytes
 
94
quote = urlparse.quote
 
95
unquote_to_bytes = urlparse.unquote_to_bytes
 
96
unquote = urlparse.unquote
 
97
 
 
98
 
 
99
def escape(relpath, safe='/~'):
 
100
    """Escape relpath to be a valid url."""
 
101
    return quote(relpath, safe=safe)
 
102
 
 
103
 
 
104
def file_relpath(base, path):
 
105
    """Compute just the relative sub-portion of a url
 
106
 
 
107
    This assumes that both paths are already fully specified file:// URLs.
 
108
    """
 
109
    if len(base) < MIN_ABS_FILEURL_LENGTH:
 
110
        raise ValueError('Length of base (%r) must equal or'
 
111
                         ' exceed the platform minimum url length (which is %d)' %
 
112
                         (base, MIN_ABS_FILEURL_LENGTH))
 
113
    base = osutils.normpath(local_path_from_url(base))
 
114
    path = osutils.normpath(local_path_from_url(path))
 
115
    return escape(osutils.relpath(base, path))
 
116
 
 
117
 
 
118
def _find_scheme_and_separator(url):
 
119
    """Find the scheme separator (://) and the first path separator
 
120
 
 
121
    This is just a helper functions for other path utilities.
 
122
    It could probably be replaced by urlparse
 
123
    """
 
124
    m = _url_scheme_re.match(url)
 
125
    if not m:
 
126
        return None, None
 
127
 
 
128
    scheme = m.group('scheme')
 
129
    path = m.group('path')
 
130
 
 
131
    # Find the path separating slash
 
132
    # (first slash after the ://)
 
133
    first_path_slash = path.find('/')
 
134
    if first_path_slash == -1:
 
135
        return len(scheme), None
 
136
    return len(scheme), first_path_slash + m.start('path')
 
137
 
 
138
 
 
139
def is_url(url):
 
140
    """Tests whether a URL is in actual fact a URL."""
 
141
    return _url_scheme_re.match(url) is not None
 
142
 
 
143
 
 
144
def join(base, *args):
 
145
    """Create a URL by joining sections.
 
146
 
 
147
    This will normalize '..', assuming that paths are absolute
 
148
    (it assumes no symlinks in either path)
 
149
 
 
150
    If any of *args is an absolute URL, it will be treated correctly.
 
151
    Example:
 
152
        join('http://foo', 'http://bar') => 'http://bar'
 
153
        join('http://foo', 'bar') => 'http://foo/bar'
 
154
        join('http://foo', 'bar', '../baz') => 'http://foo/baz'
 
155
    """
 
156
    if not args:
 
157
        return base
 
158
    scheme_end, path_start = _find_scheme_and_separator(base)
 
159
    if scheme_end is None and path_start is None:
 
160
        path_start = 0
 
161
    elif path_start is None:
 
162
        path_start = len(base)
 
163
    path = base[path_start:]
 
164
    for arg in args:
 
165
        arg_scheme_end, arg_path_start = _find_scheme_and_separator(arg)
 
166
        if arg_scheme_end is None and arg_path_start is None:
 
167
            arg_path_start = 0
 
168
        elif arg_path_start is None:
 
169
            arg_path_start = len(arg)
 
170
        if arg_scheme_end is not None:
 
171
            base = arg
 
172
            path = arg[arg_path_start:]
 
173
            scheme_end = arg_scheme_end
 
174
            path_start = arg_path_start
 
175
        else:
 
176
            path = joinpath(path, arg)
 
177
    return base[:path_start] + path
 
178
 
 
179
 
 
180
def joinpath(base, *args):
 
181
    """Join URL path segments to a URL path segment.
 
182
 
 
183
    This is somewhat like osutils.joinpath, but intended for URLs.
 
184
 
 
185
    XXX: this duplicates some normalisation logic, and also duplicates a lot of
 
186
    path handling logic that already exists in some Transport implementations.
 
187
    We really should try to have exactly one place in the code base responsible
 
188
    for combining paths of URLs.
 
189
    """
 
190
    path = base.split('/')
 
191
    if len(path) > 1 and path[-1] == '':
 
192
        # If the path ends in a trailing /, remove it.
 
193
        path.pop()
 
194
    for arg in args:
 
195
        if arg.startswith('/'):
 
196
            path = []
 
197
        for chunk in arg.split('/'):
 
198
            if chunk == '.':
 
199
                continue
 
200
            elif chunk == '..':
 
201
                if path == ['']:
 
202
                    raise InvalidURLJoin('Cannot go above root',
 
203
                                         base, args)
 
204
                path.pop()
 
205
            else:
 
206
                path.append(chunk)
 
207
    if path == ['']:
 
208
        return '/'
 
209
    else:
 
210
        return '/'.join(path)
 
211
 
 
212
 
 
213
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
 
214
def _posix_local_path_from_url(url):
 
215
    """Convert a url like file:///path/to/foo into /path/to/foo"""
 
216
    url = strip_segment_parameters(url)
 
217
    file_localhost_prefix = 'file://localhost/'
 
218
    if url.startswith(file_localhost_prefix):
 
219
        path = url[len(file_localhost_prefix) - 1:]
 
220
    elif not url.startswith('file:///'):
 
221
        raise InvalidURL(
 
222
            url, 'local urls must start with file:/// or file://localhost/')
 
223
    else:
 
224
        path = url[len('file://'):]
 
225
    # We only strip off 2 slashes
 
226
    return unescape(path)
 
227
 
 
228
 
 
229
def _posix_local_path_to_url(path):
 
230
    """Convert a local path like ./foo into a URL like file:///path/to/foo
 
231
 
 
232
    This also handles transforming escaping unicode characters, etc.
 
233
    """
 
234
    # importing directly from posixpath allows us to test this
 
235
    # on non-posix platforms
 
236
    return 'file://' + escape(osutils._posix_abspath(path))
 
237
 
 
238
 
 
239
def _win32_local_path_from_url(url):
 
240
    """Convert a url like file:///C:/path/to/foo into C:/path/to/foo"""
 
241
    if not url.startswith('file://'):
 
242
        raise InvalidURL(url, 'local urls must start with file:///, '
 
243
                         'UNC path urls must start with file://')
 
244
    url = strip_segment_parameters(url)
 
245
    # We strip off all 3 slashes
 
246
    win32_url = url[len('file:'):]
 
247
    # check for UNC path: //HOST/path
 
248
    if not win32_url.startswith('///'):
 
249
        if (win32_url[2] == '/'
 
250
                or win32_url[3] in '|:'):
 
251
            raise InvalidURL(url, 'Win32 UNC path urls'
 
252
                             ' have form file://HOST/path')
 
253
        return unescape(win32_url)
 
254
 
 
255
    # allow empty paths so we can serve all roots
 
256
    if win32_url == '///':
 
257
        return '/'
 
258
 
 
259
    # usual local path with drive letter
 
260
    if (len(win32_url) < 6
 
261
        or win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
 
262
                                'ABCDEFGHIJKLMNOPQRSTUVWXYZ') or
 
263
        win32_url[4] not in '|:'
 
264
            or win32_url[5] != '/'):
 
265
        raise InvalidURL(url, 'Win32 file urls start with'
 
266
                         ' file:///x:/, where x is a valid drive letter')
 
267
    return win32_url[3].upper() + u':' + unescape(win32_url[5:])
 
268
 
 
269
 
 
270
def _win32_local_path_to_url(path):
 
271
    """Convert a local path like ./foo into a URL like file:///C:/path/to/foo
 
272
 
 
273
    This also handles transforming escaping unicode characters, etc.
 
274
    """
 
275
    # importing directly from ntpath allows us to test this
 
276
    # on non-win32 platform
 
277
    # FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
 
278
    #       which actually strips trailing space characters.
 
279
    #       The worst part is that on linux ntpath.abspath has different
 
280
    #       semantics, since 'nt' is not an available module.
 
281
    if path == '/':
 
282
        return 'file:///'
 
283
 
 
284
    win32_path = osutils._win32_abspath(path)
 
285
    # check for UNC path \\HOST\path
 
286
    if win32_path.startswith('//'):
 
287
        return 'file:' + escape(win32_path)
 
288
    return ('file:///' + str(win32_path[0].upper()) + ':' +
 
289
            escape(win32_path[2:]))
 
290
 
 
291
 
 
292
local_path_to_url = _posix_local_path_to_url
 
293
local_path_from_url = _posix_local_path_from_url
 
294
MIN_ABS_FILEURL_LENGTH = len('file:///')
 
295
WIN32_MIN_ABS_FILEURL_LENGTH = len('file:///C:/')
 
296
 
 
297
if sys.platform == 'win32':
 
298
    local_path_to_url = _win32_local_path_to_url
 
299
    local_path_from_url = _win32_local_path_from_url
 
300
 
 
301
    MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
 
302
 
 
303
 
 
304
_url_scheme_re = re.compile('^(?P<scheme>[^:/]{2,}):(//)?(?P<path>.*)$')
 
305
_url_hex_escapes_re = re.compile('(%[0-9a-fA-F]{2})')
 
306
 
 
307
 
 
308
def _unescape_safe_chars(matchobj):
 
309
    """re.sub callback to convert hex-escapes to plain characters (if safe).
 
310
 
 
311
    e.g. '%7E' will be converted to '~'.
 
312
    """
 
313
    hex_digits = matchobj.group(0)[1:]
 
314
    char = chr(int(hex_digits, 16))
 
315
    if char in _url_dont_escape_characters:
 
316
        return char
 
317
    else:
 
318
        return matchobj.group(0).upper()
 
319
 
 
320
 
 
321
def normalize_url(url):
 
322
    """Make sure that a path string is in fully normalized URL form.
 
323
 
 
324
    This handles URLs which have unicode characters, spaces,
 
325
    special characters, etc.
 
326
 
 
327
    It has two basic modes of operation, depending on whether the
 
328
    supplied string starts with a url specifier (scheme://) or not.
 
329
    If it does not have a specifier it is considered a local path,
 
330
    and will be converted into a file:/// url. Non-ascii characters
 
331
    will be encoded using utf-8.
 
332
    If it does have a url specifier, it will be treated as a "hybrid"
 
333
    URL. Basically, a URL that should have URL special characters already
 
334
    escaped (like +?&# etc), but may have unicode characters, etc
 
335
    which would not be valid in a real URL.
 
336
 
 
337
    :param url: Either a hybrid URL or a local path
 
338
    :return: A normalized URL which only includes 7-bit ASCII characters.
 
339
    """
 
340
    scheme_end, path_start = _find_scheme_and_separator(url)
 
341
    if scheme_end is None:
 
342
        return local_path_to_url(url)
 
343
    prefix = url[:path_start]
 
344
    path = url[path_start:]
 
345
    if not isinstance(url, str):
 
346
        for c in url:
 
347
            if c not in _url_safe_characters:
 
348
                raise InvalidURL(url, 'URLs can only contain specific'
 
349
                                 ' safe characters (not %r)' % c)
 
350
        path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
 
351
        return str(prefix + ''.join(path))
 
352
 
 
353
    # We have a unicode (hybrid) url
 
354
    path_chars = list(path)
 
355
 
 
356
    for i in range(len(path_chars)):
 
357
        if path_chars[i] not in _url_safe_characters:
 
358
            path_chars[i] = ''.join(
 
359
                ['%%%02X' % c for c in bytearray(path_chars[i].encode('utf-8'))])
 
360
    path = ''.join(path_chars)
 
361
    path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
 
362
    return str(prefix + path)
 
363
 
 
364
 
 
365
def relative_url(base, other):
 
366
    """Return a path to other from base.
 
367
 
 
368
    If other is unrelated to base, return other. Else return a relative path.
 
369
    This assumes no symlinks as part of the url.
 
370
    """
 
371
    dummy, base_first_slash = _find_scheme_and_separator(base)
 
372
    if base_first_slash is None:
 
373
        return other
 
374
 
 
375
    dummy, other_first_slash = _find_scheme_and_separator(other)
 
376
    if other_first_slash is None:
 
377
        return other
 
378
 
 
379
    # this takes care of differing schemes or hosts
 
380
    base_scheme = base[:base_first_slash]
 
381
    other_scheme = other[:other_first_slash]
 
382
    if base_scheme != other_scheme:
 
383
        return other
 
384
    elif sys.platform == 'win32' and base_scheme == 'file://':
 
385
        base_drive = base[base_first_slash + 1:base_first_slash + 3]
 
386
        other_drive = other[other_first_slash + 1:other_first_slash + 3]
 
387
        if base_drive != other_drive:
 
388
            return other
 
389
 
 
390
    base_path = base[base_first_slash + 1:]
 
391
    other_path = other[other_first_slash + 1:]
 
392
 
 
393
    if base_path.endswith('/'):
 
394
        base_path = base_path[:-1]
 
395
 
 
396
    base_sections = base_path.split('/')
 
397
    other_sections = other_path.split('/')
 
398
 
 
399
    if base_sections == ['']:
 
400
        base_sections = []
 
401
    if other_sections == ['']:
 
402
        other_sections = []
 
403
 
 
404
    output_sections = []
 
405
    for b, o in zip(base_sections, other_sections):
 
406
        if b != o:
 
407
            break
 
408
        output_sections.append(b)
 
409
 
 
410
    match_len = len(output_sections)
 
411
    output_sections = ['..' for x in base_sections[match_len:]]
 
412
    output_sections.extend(other_sections[match_len:])
 
413
 
 
414
    return "/".join(output_sections) or "."
 
415
 
 
416
 
 
417
def _win32_extract_drive_letter(url_base, path):
 
418
    """On win32 the drive letter needs to be added to the url base."""
 
419
    # Strip off the drive letter
 
420
    # path is currently /C:/foo
 
421
    if len(path) < 4 or path[2] not in ':|' or path[3] != '/':
 
422
        raise InvalidURL(url_base + path,
 
423
                         'win32 file:/// paths need a drive letter')
 
424
    url_base += path[0:3]  # file:// + /C:
 
425
    path = path[3:]  # /foo
 
426
    return url_base, path
 
427
 
 
428
 
 
429
def split(url, exclude_trailing_slash=True):
 
430
    """Split a URL into its parent directory and a child directory.
 
431
 
 
432
    :param url: A relative or absolute URL
 
433
    :param exclude_trailing_slash: Strip off a final '/' if it is part
 
434
        of the path (but not if it is part of the protocol specification)
 
435
 
 
436
    :return: (parent_url, child_dir).  child_dir may be the empty string if
 
437
        we're at the root.
 
438
    """
 
439
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
 
440
 
 
441
    if first_path_slash is None:
 
442
        # We have either a relative path, or no separating slash
 
443
        if scheme_loc is None:
 
444
            # Relative path
 
445
            if exclude_trailing_slash and url.endswith('/'):
 
446
                url = url[:-1]
 
447
            return _posix_split(url)
 
448
        else:
 
449
            # Scheme with no path
 
450
            return url, ''
 
451
 
 
452
    # We have a fully defined path
 
453
    url_base = url[:first_path_slash]  # http://host, file://
 
454
    path = url[first_path_slash:]  # /file/foo
 
455
 
 
456
    if sys.platform == 'win32' and url.startswith('file:///'):
 
457
        # Strip off the drive letter
 
458
        # url_base is currently file://
 
459
        # path is currently /C:/foo
 
460
        url_base, path = _win32_extract_drive_letter(url_base, path)
 
461
        # now it should be file:///C: and /foo
 
462
 
 
463
    if exclude_trailing_slash and len(path) > 1 and path.endswith('/'):
 
464
        path = path[:-1]
 
465
    head, tail = _posix_split(path)
 
466
    return url_base + head, tail
 
467
 
 
468
 
 
469
def split_segment_parameters_raw(url):
 
470
    """Split the subsegment of the last segment of a URL.
 
471
 
 
472
    :param url: A relative or absolute URL
 
473
    :return: (url, subsegments)
 
474
    """
 
475
    # GZ 2011-11-18: Dodgy removing the terminal slash like this, function
 
476
    #                operates on urls not url+segments, and Transport classes
 
477
    #                should not be blindly adding slashes in the first place.
 
478
    lurl = strip_trailing_slash(url)
 
479
    # Segments begin at first comma after last forward slash, if one exists
 
480
    segment_start = lurl.find(",", lurl.rfind("/") + 1)
 
481
    if segment_start == -1:
 
482
        return (url, [])
 
483
    return (lurl[:segment_start],
 
484
            [str(s) for s in lurl[segment_start + 1:].split(",")])
 
485
 
 
486
 
 
487
def split_segment_parameters(url):
 
488
    """Split the segment parameters of the last segment of a URL.
 
489
 
 
490
    :param url: A relative or absolute URL
 
491
    :return: (url, segment_parameters)
 
492
    """
 
493
    (base_url, subsegments) = split_segment_parameters_raw(url)
 
494
    parameters = {}
 
495
    for subsegment in subsegments:
 
496
        try:
 
497
            (key, value) = subsegment.split("=", 1)
 
498
        except ValueError:
 
499
            raise InvalidURL(url, "missing = in subsegment")
 
500
        if not isinstance(key, str):
 
501
            raise TypeError(key)
 
502
        if not isinstance(value, str):
 
503
            raise TypeError(value)
 
504
        parameters[key] = value
 
505
    return (base_url, parameters)
 
506
 
 
507
 
 
508
def strip_segment_parameters(url):
 
509
    """Strip the segment parameters from a URL.
 
510
 
 
511
    :param url: A relative or absolute URL
 
512
    :return: url
 
513
    """
 
514
    base_url, subsegments = split_segment_parameters_raw(url)
 
515
    return base_url
 
516
 
 
517
 
 
518
def join_segment_parameters_raw(base, *subsegments):
 
519
    """Create a new URL by adding subsegments to an existing one.
 
520
 
 
521
    This adds the specified subsegments to the last path in the specified
 
522
    base URL. The subsegments should be bytestrings.
 
523
 
 
524
    :note: You probably want to use join_segment_parameters instead.
 
525
    """
 
526
    if not subsegments:
 
527
        return base
 
528
    for subsegment in subsegments:
 
529
        if not isinstance(subsegment, str):
 
530
            raise TypeError("Subsegment %r is not a bytestring" % subsegment)
 
531
        if "," in subsegment:
 
532
            raise InvalidURLJoin(", exists in subsegments",
 
533
                                 base, subsegments)
 
534
    return ",".join((base,) + subsegments)
 
535
 
 
536
 
 
537
def join_segment_parameters(url, parameters):
 
538
    """Create a new URL by adding segment parameters to an existing one.
 
539
 
 
540
    The parameters of the last segment in the URL will be updated; if a
 
541
    parameter with the same key already exists it will be overwritten.
 
542
 
 
543
    :param url: A URL, as string
 
544
    :param parameters: Dictionary of parameters, keys and values as bytestrings
 
545
    """
 
546
    (base, existing_parameters) = split_segment_parameters(url)
 
547
    new_parameters = {}
 
548
    new_parameters.update(existing_parameters)
 
549
    for key, value in parameters.items():
 
550
        if not isinstance(key, str):
 
551
            raise TypeError("parameter key %r is not a str" % key)
 
552
        if not isinstance(value, str):
 
553
            raise TypeError("parameter value %r for %r is not a str" %
 
554
                            (value, key))
 
555
        if "=" in key:
 
556
            raise InvalidURLJoin("= exists in parameter key", url,
 
557
                                 parameters)
 
558
        new_parameters[key] = value
 
559
    return join_segment_parameters_raw(
 
560
        base, *["%s=%s" % item for item in sorted(new_parameters.items())])
 
561
 
 
562
 
 
563
def _win32_strip_local_trailing_slash(url):
 
564
    """Strip slashes after the drive letter"""
 
565
    if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
 
566
        return url[:-1]
 
567
    else:
 
568
        return url
 
569
 
 
570
 
 
571
def strip_trailing_slash(url):
 
572
    """Strip trailing slash, except for root paths.
 
573
 
 
574
    The definition of 'root path' is platform-dependent.
 
575
    This assumes that all URLs are valid netloc urls, such that they
 
576
    form:
 
577
    scheme://host/path
 
578
    It searches for ://, and then refuses to remove the next '/'.
 
579
    It can also handle relative paths
 
580
    Examples:
 
581
        path/to/foo       => path/to/foo
 
582
        path/to/foo/      => path/to/foo
 
583
        http://host/path/ => http://host/path
 
584
        http://host/path  => http://host/path
 
585
        http://host/      => http://host/
 
586
        file:///          => file:///
 
587
        file:///foo/      => file:///foo
 
588
        # This is unique on win32 platforms, and is the only URL
 
589
        # format which does it differently.
 
590
        file:///c|/       => file:///c:/
 
591
    """
 
592
    if not url.endswith('/'):
 
593
        # Nothing to do
 
594
        return url
 
595
    if sys.platform == 'win32' and url.startswith('file://'):
 
596
        return _win32_strip_local_trailing_slash(url)
 
597
 
 
598
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
 
599
    if scheme_loc is None:
 
600
        # This is a relative path, as it has no scheme
 
601
        # so just chop off the last character
 
602
        return url[:-1]
 
603
 
 
604
    if first_path_slash is None or first_path_slash == len(url) - 1:
 
605
        # Don't chop off anything if the only slash is the path
 
606
        # separating slash
 
607
        return url
 
608
 
 
609
    return url[:-1]
 
610
 
 
611
 
 
612
def unescape(url):
 
613
    """Unescape relpath from url format.
 
614
 
 
615
    This returns a Unicode path from a URL
 
616
    """
 
617
    # jam 20060427 URLs are supposed to be ASCII only strings
 
618
    #       If they are passed in as unicode, unquote
 
619
    #       will return a UNICODE string, which actually contains
 
620
    #       utf-8 bytes. So we have to ensure that they are
 
621
    #       plain ASCII strings, or the final .decode will
 
622
    #       try to encode the UNICODE => ASCII, and then decode
 
623
    #       it into utf-8.
 
624
 
 
625
    if isinstance(url, str):
 
626
        try:
 
627
            url.encode("ascii")
 
628
        except UnicodeError as e:
 
629
            raise InvalidURL(
 
630
                url, 'URL was not a plain ASCII url: %s' % (e,))
 
631
    return urlparse.unquote(url)
 
632
 
 
633
 
 
634
# These are characters that if escaped, should stay that way
 
635
_no_decode_chars = ';/?:@&=+$,#'
 
636
_no_decode_ords = [ord(c) for c in _no_decode_chars]
 
637
_no_decode_hex = (['%02x' % o for o in _no_decode_ords]
 
638
                  + ['%02X' % o for o in _no_decode_ords])
 
639
_hex_display_map = dict(([('%02x' % o, bytes([o])) for o in range(256)]
 
640
                         + [('%02X' % o, bytes([o])) for o in range(256)]))
 
641
# These entries get mapped to themselves
 
642
_hex_display_map.update((hex, b'%' + hex.encode('ascii'))
 
643
                        for hex in _no_decode_hex)
 
644
 
 
645
# These characters shouldn't be percent-encoded, and it's always safe to
 
646
# unencode them if they are.
 
647
_url_dont_escape_characters = set(
 
648
    "abcdefghijklmnopqrstuvwxyz"  # Lowercase alpha
 
649
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  # Uppercase alpha
 
650
    "0123456789"  # Numbers
 
651
    "-._~"  # Unreserved characters
 
652
)
 
653
 
 
654
# These characters should not be escaped
 
655
_url_safe_characters = set(
 
656
    "abcdefghijklmnopqrstuvwxyz"  # Lowercase alpha
 
657
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  # Uppercase alpha
 
658
    "0123456789"  # Numbers
 
659
    "_.-!~*'()"  # Unreserved characters
 
660
    "/;?:@&=+$,"  # Reserved characters
 
661
    "%#"         # Extra reserved characters
 
662
)
 
663
 
 
664
 
 
665
def _unescape_segment_for_display(segment, encoding):
 
666
    """Unescape a segment for display.
 
667
 
 
668
    Helper for unescape_for_display
 
669
 
 
670
    :param url: A 7-bit ASCII URL
 
671
    :param encoding: The final output encoding
 
672
 
 
673
    :return: A unicode string which can be safely encoded into the
 
674
         specified encoding.
 
675
    """
 
676
    escaped_chunks = segment.split('%')
 
677
    escaped_chunks[0] = escaped_chunks[0].encode('utf-8')
 
678
    for j in range(1, len(escaped_chunks)):
 
679
        item = escaped_chunks[j]
 
680
        try:
 
681
            escaped_chunks[j] = _hex_display_map[item[:2]]
 
682
        except KeyError:
 
683
            # Put back the percent symbol
 
684
            escaped_chunks[j] = b'%' + (item[:2].encode('utf-8'))
 
685
        except UnicodeDecodeError:
 
686
            escaped_chunks[j] = chr(int(item[:2], 16)).encode('utf-8')
 
687
        escaped_chunks[j] += (item[2:].encode('utf-8'))
 
688
    unescaped = b''.join(escaped_chunks)
 
689
    try:
 
690
        decoded = unescaped.decode('utf-8')
 
691
    except UnicodeDecodeError:
 
692
        # If this path segment cannot be properly utf-8 decoded
 
693
        # after doing unescaping we will just leave it alone
 
694
        return segment
 
695
    else:
 
696
        try:
 
697
            decoded.encode(encoding)
 
698
        except UnicodeEncodeError:
 
699
            # If this chunk cannot be encoded in the local
 
700
            # encoding, then we should leave it alone
 
701
            return segment
 
702
        else:
 
703
            # Otherwise take the url decoded one
 
704
            return decoded
 
705
 
 
706
 
 
707
def unescape_for_display(url, encoding):
 
708
    """Decode what you can for a URL, so that we get a nice looking path.
 
709
 
 
710
    This will turn file:// urls into local paths, and try to decode
 
711
    any portions of a http:// style url that it can.
 
712
 
 
713
    Any sections of the URL which can't be represented in the encoding or
 
714
    need to stay as escapes are left alone.
 
715
 
 
716
    :param url: A 7-bit ASCII URL
 
717
    :param encoding: The final output encoding
 
718
 
 
719
    :return: A unicode string which can be safely encoded into the
 
720
         specified encoding.
 
721
    """
 
722
    if encoding is None:
 
723
        raise ValueError('you cannot specify None for the display encoding')
 
724
    if url.startswith('file://'):
 
725
        try:
 
726
            path = local_path_from_url(url)
 
727
            path.encode(encoding)
 
728
            return path
 
729
        except UnicodeError:
 
730
            return url
 
731
 
 
732
    # Split into sections to try to decode utf-8
 
733
    res = url.split('/')
 
734
    for i in range(1, len(res)):
 
735
        res[i] = _unescape_segment_for_display(res[i], encoding)
 
736
    return u'/'.join(res)
 
737
 
 
738
 
 
739
def derive_to_location(from_location):
 
740
    """Derive a TO_LOCATION given a FROM_LOCATION.
 
741
 
 
742
    The normal case is a FROM_LOCATION of http://foo/bar => bar.
 
743
    The Right Thing for some logical destinations may differ though
 
744
    because no / may be present at all. In that case, the result is
 
745
    the full name without the scheme indicator, e.g. lp:foo-bar => foo-bar.
 
746
    This latter case also applies when a Windows drive
 
747
    is used without a path, e.g. c:foo-bar => foo-bar.
 
748
    If no /, path separator or : is found, the from_location is returned.
 
749
    """
 
750
    from_location = strip_segment_parameters(from_location)
 
751
    if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
 
752
        return os.path.basename(from_location.rstrip("/\\"))
 
753
    else:
 
754
        sep = from_location.find(":")
 
755
        if sep > 0:
 
756
            return from_location[sep + 1:]
 
757
        else:
 
758
            return from_location
 
759
 
 
760
 
 
761
def _is_absolute(url):
 
762
    return (osutils.pathjoin('/foo', url) == url)
 
763
 
 
764
 
 
765
def rebase_url(url, old_base, new_base):
 
766
    """Convert a relative path from an old base URL to a new base URL.
 
767
 
 
768
    The result will be a relative path.
 
769
    Absolute paths and full URLs are returned unaltered.
 
770
    """
 
771
    scheme, separator = _find_scheme_and_separator(url)
 
772
    if scheme is not None:
 
773
        return url
 
774
    if _is_absolute(url):
 
775
        return url
 
776
    old_parsed = urlparse.urlparse(old_base)
 
777
    new_parsed = urlparse.urlparse(new_base)
 
778
    if (old_parsed[:2]) != (new_parsed[:2]):
 
779
        raise InvalidRebaseURLs(old_base, new_base)
 
780
    return determine_relative_path(new_parsed[2],
 
781
                                   join(old_parsed[2], url))
 
782
 
 
783
 
 
784
def determine_relative_path(from_path, to_path):
 
785
    """Determine a relative path from from_path to to_path."""
 
786
    from_segments = osutils.splitpath(from_path)
 
787
    to_segments = osutils.splitpath(to_path)
 
788
    count = -1
 
789
    for count, (from_element, to_element) in enumerate(zip(from_segments,
 
790
                                                           to_segments)):
 
791
        if from_element != to_element:
 
792
            break
 
793
    else:
 
794
        count += 1
 
795
    unique_from = from_segments[count:]
 
796
    unique_to = to_segments[count:]
 
797
    segments = (['..'] * len(unique_from) + unique_to)
 
798
    if len(segments) == 0:
 
799
        return '.'
 
800
    return osutils.pathjoin(*segments)
 
801
 
 
802
 
 
803
class URL(object):
 
804
    """Parsed URL."""
 
805
 
 
806
    def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
 
807
                 port, quoted_path):
 
808
        self.scheme = scheme
 
809
        self.quoted_host = quoted_host
 
810
        self.host = unquote(self.quoted_host)
 
811
        self.quoted_user = quoted_user
 
812
        if self.quoted_user is not None:
 
813
            self.user = unquote(self.quoted_user)
 
814
        else:
 
815
            self.user = None
 
816
        self.quoted_password = quoted_password
 
817
        if self.quoted_password is not None:
 
818
            self.password = unquote(self.quoted_password)
 
819
        else:
 
820
            self.password = None
 
821
        self.port = port
 
822
        self.quoted_path = _url_hex_escapes_re.sub(
 
823
            _unescape_safe_chars, quoted_path)
 
824
        self.path = unquote(self.quoted_path)
 
825
 
 
826
    def __eq__(self, other):
 
827
        return (isinstance(other, self.__class__) and
 
828
                self.scheme == other.scheme and
 
829
                self.host == other.host and
 
830
                self.user == other.user and
 
831
                self.password == other.password and
 
832
                self.path == other.path)
 
833
 
 
834
    def __repr__(self):
 
835
        return "<%s(%r, %r, %r, %r, %r, %r)>" % (
 
836
            self.__class__.__name__,
 
837
            self.scheme, self.quoted_user, self.quoted_password,
 
838
            self.quoted_host, self.port, self.quoted_path)
 
839
 
 
840
    @classmethod
 
841
    def from_string(cls, url):
 
842
        """Create a URL object from a string.
 
843
 
 
844
        :param url: URL as bytestring
 
845
        """
 
846
        # GZ 2017-06-09: Actually validate ascii-ness
 
847
        # pad.lv/1696545: For the moment, accept both native strings and
 
848
        # unicode.
 
849
        if isinstance(url, str):
 
850
            pass
 
851
        elif isinstance(url, str):
 
852
            try:
 
853
                url = url.encode()
 
854
            except UnicodeEncodeError:
 
855
                raise InvalidURL(url)
 
856
        else:
 
857
            raise InvalidURL(url)
 
858
        (scheme, netloc, path, params,
 
859
         query, fragment) = urlparse.urlparse(url, allow_fragments=False)
 
860
        user = password = host = port = None
 
861
        if '@' in netloc:
 
862
            user, host = netloc.rsplit('@', 1)
 
863
            if ':' in user:
 
864
                user, password = user.split(':', 1)
 
865
        else:
 
866
            host = netloc
 
867
 
 
868
        if ':' in host and not (host[0] == '[' and host[-1] == ']'):
 
869
            # there *is* port
 
870
            host, port = host.rsplit(':', 1)
 
871
            if port:
 
872
                try:
 
873
                    port = int(port)
 
874
                except ValueError:
 
875
                    raise InvalidURL('invalid port number %s in url:\n%s' %
 
876
                                     (port, url))
 
877
            else:
 
878
                port = None
 
879
        if host != "" and host[0] == '[' and host[-1] == ']':  # IPv6
 
880
            host = host[1:-1]
 
881
 
 
882
        return cls(scheme, user, password, host, port, path)
 
883
 
 
884
    def __str__(self):
 
885
        netloc = self.quoted_host
 
886
        if ":" in netloc:
 
887
            netloc = "[%s]" % netloc
 
888
        if self.quoted_user is not None:
 
889
            # Note that we don't put the password back even if we
 
890
            # have one so that it doesn't get accidentally
 
891
            # exposed.
 
892
            netloc = '%s@%s' % (self.quoted_user, netloc)
 
893
        if self.port is not None:
 
894
            netloc = '%s:%d' % (netloc, self.port)
 
895
        return urlparse.urlunparse(
 
896
            (self.scheme, netloc, self.quoted_path, None, None, None))
 
897
 
 
898
    @staticmethod
 
899
    def _combine_paths(base_path, relpath):
 
900
        """Transform a Transport-relative path to a remote absolute path.
 
901
 
 
902
        This does not handle substitution of ~ but does handle '..' and '.'
 
903
        components.
 
904
 
 
905
        Examples::
 
906
 
 
907
            t._combine_paths('/home/sarah', 'project/foo')
 
908
                => '/home/sarah/project/foo'
 
909
            t._combine_paths('/home/sarah', '../../etc')
 
910
                => '/etc'
 
911
            t._combine_paths('/home/sarah', '/etc')
 
912
                => '/etc'
 
913
 
 
914
        :param base_path: base path
 
915
        :param relpath: relative url string for relative part of remote path.
 
916
        :return: urlencoded string for final path.
 
917
        """
 
918
        # pad.lv/1696545: For the moment, accept both native strings and
 
919
        # unicode.
 
920
        if isinstance(relpath, str):
 
921
            pass
 
922
        elif isinstance(relpath, str):
 
923
            try:
 
924
                relpath = relpath.encode()
 
925
            except UnicodeEncodeError:
 
926
                raise InvalidURL(relpath)
 
927
        else:
 
928
            raise InvalidURL(relpath)
 
929
        relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
 
930
        if relpath.startswith('/'):
 
931
            base_parts = []
 
932
        else:
 
933
            base_parts = base_path.split('/')
 
934
        if len(base_parts) > 0 and base_parts[-1] == '':
 
935
            base_parts = base_parts[:-1]
 
936
        for p in relpath.split('/'):
 
937
            if p == '..':
 
938
                if len(base_parts) == 0:
 
939
                    # In most filesystems, a request for the parent
 
940
                    # of root, just returns root.
 
941
                    continue
 
942
                base_parts.pop()
 
943
            elif p == '.':
 
944
                continue  # No-op
 
945
            elif p != '':
 
946
                base_parts.append(p)
 
947
        path = '/'.join(base_parts)
 
948
        if not path.startswith('/'):
 
949
            path = '/' + path
 
950
        return path
 
951
 
 
952
    def clone(self, offset=None):
 
953
        """Return a new URL for a path relative to this URL.
 
954
 
 
955
        :param offset: A relative path, already urlencoded
 
956
        :return: `URL` instance
 
957
        """
 
958
        if offset is not None:
 
959
            relative = unescape(offset)
 
960
            path = self._combine_paths(self.path, relative)
 
961
            path = quote(path, safe="/~")
 
962
        else:
 
963
            path = self.quoted_path
 
964
        return self.__class__(self.scheme, self.quoted_user,
 
965
                              self.quoted_password, self.quoted_host, self.port,
 
966
                              path)
 
967
 
 
968
 
 
969
def parse_url(url):
 
970
    """Extract the server address, the credentials and the path from the url.
 
971
 
 
972
    user, password, host and path should be quoted if they contain reserved
 
973
    chars.
 
974
 
 
975
    :param url: an quoted url
 
976
    :return: (scheme, user, password, host, port, path) tuple, all fields
 
977
        are unquoted.
 
978
    """
 
979
    parsed_url = URL.from_string(url)
 
980
    return (parsed_url.scheme, parsed_url.user, parsed_url.password,
 
981
            parsed_url.host, parsed_url.port, parsed_url.path)