/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 bzrlib/urlutils.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-18 15:28:38 UTC
  • mto: This revision was merged to the branch mainline in revision 6386.
  • Revision ID: jelmer@samba.org-20111218152838-5wxpfnugk2jd625k
UseĀ absolute_import.

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