/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: Canonical.com Patch Queue Manager
  • Date: 2008-07-16 23:23:13 UTC
  • mfrom: (1551.19.47 Aaron's mergeable stuff)
  • Revision ID: pqm@pqm.ubuntu.com-20080716232313-9pcoze89hualg5qn
Fetch copies all required data even with stacking (abentley, #248506)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Bazaar -- distributed version control
 
2
#
 
3
# Copyright (C) 2006 Canonical Ltd
 
4
#
 
5
# This program is free software; you can redistribute it and/or modify
 
6
# it under the terms of the GNU General Public License as published by
 
7
# the Free Software Foundation; either version 2 of the License, or
 
8
# (at your option) any later version.
 
9
#
 
10
# This program is distributed in the hope that it will be useful,
 
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
# GNU General Public License for more details.
 
14
#
 
15
# You should have received a copy of the GNU General Public License
 
16
# along with this program; if not, write to the Free Software
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
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, normpath as _posix_normpath
 
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))
 
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 must be equal or'
 
81
            ' exceed the platform minimum url length (which is %d)' %
 
82
            MIN_ABS_FILEURL_LENGTH)
 
83
    base = local_path_from_url(base)
 
84
    path = 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+len(scheme)+3
 
107
 
 
108
 
 
109
def join(base, *args):
 
110
    """Create a URL by joining sections.
 
111
 
 
112
    This will normalize '..', assuming that paths are absolute
 
113
    (it assumes no symlinks in either path)
 
114
 
 
115
    If any of *args is an absolute URL, it will be treated correctly.
 
116
    Example:
 
117
        join('http://foo', 'http://bar') => 'http://bar'
 
118
        join('http://foo', 'bar') => 'http://foo/bar'
 
119
        join('http://foo', 'bar', '../baz') => 'http://foo/baz'
 
120
    """
 
121
    if not args:
 
122
        return base
 
123
    match = _url_scheme_re.match(base)
 
124
    scheme = None
 
125
    if match:
 
126
        scheme = match.group('scheme')
 
127
        path = match.group('path').split('/')
 
128
        if path[-1:] == ['']:
 
129
            # Strip off a trailing slash
 
130
            # This helps both when we are at the root, and when
 
131
            # 'base' has an extra slash at the end
 
132
            path = path[:-1]
 
133
    else:
 
134
        path = base.split('/')
 
135
 
 
136
    if scheme is not None and len(path) >= 1:
 
137
        host = path[:1]
 
138
        # the path should be represented as an abs path.
 
139
        # we know this must be absolute because of the presence of a URL scheme.
 
140
        remove_root = True
 
141
        path = [''] + path[1:]
 
142
    else:
 
143
        # create an empty host, but dont alter the path - this might be a
 
144
        # relative url fragment.
 
145
        host = []
 
146
        remove_root = False
 
147
 
 
148
    for arg in args:
 
149
        match = _url_scheme_re.match(arg)
 
150
        if match:
 
151
            # Absolute URL
 
152
            scheme = match.group('scheme')
 
153
            # this skips .. normalisation, making http://host/../../..
 
154
            # be rather strange.
 
155
            path = match.group('path').split('/')
 
156
            # set the host and path according to new absolute URL, discarding
 
157
            # any previous values.
 
158
            # XXX: duplicates mess from earlier in this function.  This URL
 
159
            # manipulation code needs some cleaning up.
 
160
            if scheme is not None and len(path) >= 1:
 
161
                host = path[:1]
 
162
                path = path[1:]
 
163
                # url scheme implies absolute path.
 
164
                path = [''] + path
 
165
            else:
 
166
                # no url scheme we take the path as is.
 
167
                host = []
 
168
        else:
 
169
            path = '/'.join(path)
 
170
            path = joinpath(path, arg)
 
171
            path = path.split('/')
 
172
    if remove_root and path[0:1] == ['']:
 
173
        del path[0]
 
174
    if host:
 
175
        # Remove the leading slash from the path, so long as it isn't also the
 
176
        # trailing slash, which we want to keep if present.
 
177
        if path and path[0] == '' and len(path) > 1:
 
178
            del path[0]
 
179
        path = host + path
 
180
 
 
181
    if scheme is None:
 
182
        return '/'.join(path)
 
183
    return scheme + '://' + '/'.join(path)
 
184
 
 
185
 
 
186
def joinpath(base, *args):
 
187
    """Join URL path segments to a URL path segment.
 
188
    
 
189
    This is somewhat like osutils.joinpath, but intended for URLs.
 
190
 
 
191
    XXX: this duplicates some normalisation logic, and also duplicates a lot of
 
192
    path handling logic that already exists in some Transport implementations.
 
193
    We really should try to have exactly one place in the code base responsible
 
194
    for combining paths of URLs.
 
195
    """
 
196
    path = base.split('/')
 
197
    if len(path) > 1 and path[-1] == '':
 
198
        #If the path ends in a trailing /, remove it.
 
199
        path.pop()
 
200
    for arg in args:
 
201
        if arg.startswith('/'):
 
202
            path = []
 
203
        for chunk in arg.split('/'):
 
204
            if chunk == '.':
 
205
                continue
 
206
            elif chunk == '..':
 
207
                if path == ['']:
 
208
                    raise errors.InvalidURLJoin('Cannot go above root',
 
209
                            base, args)
 
210
                path.pop()
 
211
            else:
 
212
                path.append(chunk)
 
213
    if path == ['']:
 
214
        return '/'
 
215
    else:
 
216
        return '/'.join(path)
 
217
 
 
218
 
 
219
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
 
220
def _posix_local_path_from_url(url):
 
221
    """Convert a url like file:///path/to/foo into /path/to/foo"""
 
222
    if not url.startswith('file:///'):
 
223
        raise errors.InvalidURL(url, 'local urls must start with file:///')
 
224
    # We only strip off 2 slashes
 
225
    return unescape(url[len('file://'):])
 
226
 
 
227
 
 
228
def _posix_local_path_to_url(path):
 
229
    """Convert a local path like ./foo into a URL like file:///path/to/foo
 
230
 
 
231
    This also handles transforming escaping unicode characters, etc.
 
232
    """
 
233
    # importing directly from posixpath allows us to test this 
 
234
    # on non-posix platforms
 
235
    return 'file://' + escape(_posix_normpath(
 
236
        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 errors.InvalidURL(url, 'local urls must start with file:///, '
 
243
                                     'UNC path urls must start with file://')
 
244
    # We strip off all 3 slashes
 
245
    win32_url = url[len('file:'):]
 
246
    # check for UNC path: //HOST/path
 
247
    if not win32_url.startswith('///'):
 
248
        if (win32_url[2] == '/'
 
249
            or win32_url[3] in '|:'):
 
250
            raise errors.InvalidURL(url, 'Win32 UNC path urls'
 
251
                ' have form file://HOST/path')
 
252
        return unescape(win32_url)
 
253
    # usual local path with drive letter
 
254
    if (win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
 
255
                             'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
 
256
        or win32_url[4] not in  '|:'
 
257
        or win32_url[5] != '/'):
 
258
        raise errors.InvalidURL(url, 'Win32 file urls start with'
 
259
                ' file:///x:/, where x is a valid drive letter')
 
260
    return win32_url[3].upper() + u':' + unescape(win32_url[5:])
 
261
 
 
262
 
 
263
def _win32_local_path_to_url(path):
 
264
    """Convert a local path like ./foo into a URL like file:///C:/path/to/foo
 
265
 
 
266
    This also handles transforming escaping unicode characters, etc.
 
267
    """
 
268
    # importing directly from ntpath allows us to test this 
 
269
    # on non-win32 platform
 
270
    # FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
 
271
    #       which actually strips trailing space characters.
 
272
    #       The worst part is that under linux ntpath.abspath has different
 
273
    #       semantics, since 'nt' is not an available module.
 
274
    win32_path = osutils._win32_abspath(path)
 
275
    # check for UNC path \\HOST\path
 
276
    if win32_path.startswith('//'):
 
277
        return 'file:' + escape(win32_path)
 
278
    return ('file:///' + str(win32_path[0].upper()) + ':' +
 
279
        escape(win32_path[2:]))
 
280
 
 
281
 
 
282
local_path_to_url = _posix_local_path_to_url
 
283
local_path_from_url = _posix_local_path_from_url
 
284
MIN_ABS_FILEURL_LENGTH = len('file:///')
 
285
WIN32_MIN_ABS_FILEURL_LENGTH = len('file:///C:/')
 
286
 
 
287
if sys.platform == 'win32':
 
288
    local_path_to_url = _win32_local_path_to_url
 
289
    local_path_from_url = _win32_local_path_from_url
 
290
 
 
291
    MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
 
292
 
 
293
 
 
294
_url_scheme_re = re.compile(r'^(?P<scheme>[^:/]{2,})://(?P<path>.*)$')
 
295
_url_hex_escapes_re = re.compile(r'(%[0-9a-fA-F]{2})')
 
296
 
 
297
 
 
298
def _unescape_safe_chars(matchobj):
 
299
    """re.sub callback to convert hex-escapes to plain characters (if safe).
 
300
    
 
301
    e.g. '%7E' will be converted to '~'.
 
302
    """
 
303
    hex_digits = matchobj.group(0)[1:]
 
304
    char = chr(int(hex_digits, 16))
 
305
    if char in _url_dont_escape_characters:
 
306
        return char
 
307
    else:
 
308
        return matchobj.group(0).upper()
 
309
 
 
310
 
 
311
def normalize_url(url):
 
312
    """Make sure that a path string is in fully normalized URL form.
 
313
    
 
314
    This handles URLs which have unicode characters, spaces,
 
315
    special characters, etc.
 
316
 
 
317
    It has two basic modes of operation, depending on whether the
 
318
    supplied string starts with a url specifier (scheme://) or not.
 
319
    If it does not have a specifier it is considered a local path,
 
320
    and will be converted into a file:/// url. Non-ascii characters
 
321
    will be encoded using utf-8.
 
322
    If it does have a url specifier, it will be treated as a "hybrid"
 
323
    URL. Basically, a URL that should have URL special characters already
 
324
    escaped (like +?&# etc), but may have unicode characters, etc
 
325
    which would not be valid in a real URL.
 
326
 
 
327
    :param url: Either a hybrid URL or a local path
 
328
    :return: A normalized URL which only includes 7-bit ASCII characters.
 
329
    """
 
330
    m = _url_scheme_re.match(url)
 
331
    if not m:
 
332
        return local_path_to_url(url)
 
333
    scheme = m.group('scheme')
 
334
    path = m.group('path')
 
335
    if not isinstance(url, unicode):
 
336
        for c in url:
 
337
            if c not in _url_safe_characters:
 
338
                raise errors.InvalidURL(url, 'URLs can only contain specific'
 
339
                                            ' safe characters (not %r)' % c)
 
340
        path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
 
341
        return str(scheme + '://' + ''.join(path))
 
342
 
 
343
    # We have a unicode (hybrid) url
 
344
    path_chars = list(path)
 
345
 
 
346
    for i in xrange(len(path_chars)):
 
347
        if path_chars[i] not in _url_safe_characters:
 
348
            chars = path_chars[i].encode('utf-8')
 
349
            path_chars[i] = ''.join(
 
350
                ['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
 
351
    path = ''.join(path_chars)
 
352
    path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
 
353
    return str(scheme + '://' + path)
 
354
 
 
355
 
 
356
def relative_url(base, other):
 
357
    """Return a path to other from base.
 
358
 
 
359
    If other is unrelated to base, return other. Else return a relative path.
 
360
    This assumes no symlinks as part of the url.
 
361
    """
 
362
    dummy, base_first_slash = _find_scheme_and_separator(base)
 
363
    if base_first_slash is None:
 
364
        return other
 
365
    
 
366
    dummy, other_first_slash = _find_scheme_and_separator(other)
 
367
    if other_first_slash is None:
 
368
        return other
 
369
 
 
370
    # this takes care of differing schemes or hosts
 
371
    base_scheme = base[:base_first_slash]
 
372
    other_scheme = other[:other_first_slash]
 
373
    if base_scheme != other_scheme:
 
374
        return other
 
375
    elif sys.platform == 'win32' and base_scheme == 'file://':
 
376
        base_drive = base[base_first_slash+1:base_first_slash+3]
 
377
        other_drive = other[other_first_slash+1:other_first_slash+3]
 
378
        if base_drive != other_drive:
 
379
            return other
 
380
 
 
381
    base_path = base[base_first_slash+1:]
 
382
    other_path = other[other_first_slash+1:]
 
383
 
 
384
    if base_path.endswith('/'):
 
385
        base_path = base_path[:-1]
 
386
 
 
387
    base_sections = base_path.split('/')
 
388
    other_sections = other_path.split('/')
 
389
 
 
390
    if base_sections == ['']:
 
391
        base_sections = []
 
392
    if other_sections == ['']:
 
393
        other_sections = []
 
394
 
 
395
    output_sections = []
 
396
    for b, o in zip(base_sections, other_sections):
 
397
        if b != o:
 
398
            break
 
399
        output_sections.append(b)
 
400
 
 
401
    match_len = len(output_sections)
 
402
    output_sections = ['..' for x in base_sections[match_len:]]
 
403
    output_sections.extend(other_sections[match_len:])
 
404
 
 
405
    return "/".join(output_sections) or "."
 
406
 
 
407
 
 
408
def _win32_extract_drive_letter(url_base, path):
 
409
    """On win32 the drive letter needs to be added to the url base."""
 
410
    # Strip off the drive letter
 
411
    # path is currently /C:/foo
 
412
    if len(path) < 3 or path[2] not in ':|' or path[3] != '/':
 
413
        raise errors.InvalidURL(url_base + path, 
 
414
            'win32 file:/// paths need a drive letter')
 
415
    url_base += path[0:3] # file:// + /C:
 
416
    path = path[3:] # /foo
 
417
    return url_base, path
 
418
 
 
419
 
 
420
def split(url, exclude_trailing_slash=True):
 
421
    """Split a URL into its parent directory and a child directory.
 
422
 
 
423
    :param url: A relative or absolute URL
 
424
    :param exclude_trailing_slash: Strip off a final '/' if it is part
 
425
        of the path (but not if it is part of the protocol specification)
 
426
 
 
427
    :return: (parent_url, child_dir).  child_dir may be the empty string if we're at 
 
428
        the root.
 
429
    """
 
430
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
 
431
 
 
432
    if first_path_slash is None:
 
433
        # We have either a relative path, or no separating slash
 
434
        if scheme_loc is None:
 
435
            # Relative path
 
436
            if exclude_trailing_slash and url.endswith('/'):
 
437
                url = url[:-1]
 
438
            return _posix_split(url)
 
439
        else:
 
440
            # Scheme with no path
 
441
            return url, ''
 
442
 
 
443
    # We have a fully defined path
 
444
    url_base = url[:first_path_slash] # http://host, file://
 
445
    path = url[first_path_slash:] # /file/foo
 
446
 
 
447
    if sys.platform == 'win32' and url.startswith('file:///'):
 
448
        # Strip off the drive letter
 
449
        # url_base is currently file://
 
450
        # path is currently /C:/foo
 
451
        url_base, path = _win32_extract_drive_letter(url_base, path)
 
452
        # now it should be file:///C: and /foo
 
453
 
 
454
    if exclude_trailing_slash and len(path) > 1 and path.endswith('/'):
 
455
        path = path[:-1]
 
456
    head, tail = _posix_split(path)
 
457
    return url_base + head, tail
 
458
 
 
459
 
 
460
def _win32_strip_local_trailing_slash(url):
 
461
    """Strip slashes after the drive letter"""
 
462
    if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
 
463
        return url[:-1]
 
464
    else:
 
465
        return url
 
466
 
 
467
 
 
468
def strip_trailing_slash(url):
 
469
    """Strip trailing slash, except for root paths.
 
470
 
 
471
    The definition of 'root path' is platform-dependent.
 
472
    This assumes that all URLs are valid netloc urls, such that they
 
473
    form:
 
474
    scheme://host/path
 
475
    It searches for ://, and then refuses to remove the next '/'.
 
476
    It can also handle relative paths
 
477
    Examples:
 
478
        path/to/foo       => path/to/foo
 
479
        path/to/foo/      => path/to/foo
 
480
        http://host/path/ => http://host/path
 
481
        http://host/path  => http://host/path
 
482
        http://host/      => http://host/
 
483
        file:///          => file:///
 
484
        file:///foo/      => file:///foo
 
485
        # This is unique on win32 platforms, and is the only URL
 
486
        # format which does it differently.
 
487
        file:///c|/       => file:///c:/
 
488
    """
 
489
    if not url.endswith('/'):
 
490
        # Nothing to do
 
491
        return url
 
492
    if sys.platform == 'win32' and url.startswith('file://'):
 
493
        return _win32_strip_local_trailing_slash(url)
 
494
 
 
495
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
 
496
    if scheme_loc is None:
 
497
        # This is a relative path, as it has no scheme
 
498
        # so just chop off the last character
 
499
        return url[:-1]
 
500
 
 
501
    if first_path_slash is None or first_path_slash == len(url)-1:
 
502
        # Don't chop off anything if the only slash is the path
 
503
        # separating slash
 
504
        return url
 
505
 
 
506
    return url[:-1]
 
507
 
 
508
 
 
509
def unescape(url):
 
510
    """Unescape relpath from url format.
 
511
 
 
512
    This returns a Unicode path from a URL
 
513
    """
 
514
    # jam 20060427 URLs are supposed to be ASCII only strings
 
515
    #       If they are passed in as unicode, urllib.unquote
 
516
    #       will return a UNICODE string, which actually contains
 
517
    #       utf-8 bytes. So we have to ensure that they are
 
518
    #       plain ASCII strings, or the final .decode will
 
519
    #       try to encode the UNICODE => ASCII, and then decode
 
520
    #       it into utf-8.
 
521
    try:
 
522
        url = str(url)
 
523
    except UnicodeError, e:
 
524
        raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
 
525
 
 
526
    unquoted = urllib.unquote(url)
 
527
    try:
 
528
        unicode_path = unquoted.decode('utf-8')
 
529
    except UnicodeError, e:
 
530
        raise errors.InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
 
531
    return unicode_path
 
532
 
 
533
 
 
534
# These are characters that if escaped, should stay that way
 
535
_no_decode_chars = ';/?:@&=+$,#'
 
536
_no_decode_ords = [ord(c) for c in _no_decode_chars]
 
537
_no_decode_hex = (['%02x' % o for o in _no_decode_ords] 
 
538
                + ['%02X' % o for o in _no_decode_ords])
 
539
_hex_display_map = dict(([('%02x' % o, chr(o)) for o in range(256)]
 
540
                    + [('%02X' % o, chr(o)) for o in range(256)]))
 
541
#These entries get mapped to themselves
 
542
_hex_display_map.update((hex,'%'+hex) for hex in _no_decode_hex)
 
543
 
 
544
# These characters shouldn't be percent-encoded, and it's always safe to
 
545
# unencode them if they are.
 
546
_url_dont_escape_characters = set(
 
547
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
 
548
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
 
549
   "0123456789" # Numbers
 
550
   "-._~"  # Unreserved characters
 
551
)
 
552
 
 
553
# These characters should not be escaped
 
554
_url_safe_characters = set(
 
555
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
 
556
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
 
557
   "0123456789" # Numbers
 
558
   "_.-!~*'()"  # Unreserved characters
 
559
   "/;?:@&=+$," # Reserved characters
 
560
   "%#"         # Extra reserved characters
 
561
)
 
562
 
 
563
def unescape_for_display(url, encoding):
 
564
    """Decode what you can for a URL, so that we get a nice looking path.
 
565
 
 
566
    This will turn file:// urls into local paths, and try to decode
 
567
    any portions of a http:// style url that it can.
 
568
 
 
569
    Any sections of the URL which can't be represented in the encoding or 
 
570
    need to stay as escapes are left alone.
 
571
 
 
572
    :param url: A 7-bit ASCII URL
 
573
    :param encoding: The final output encoding
 
574
 
 
575
    :return: A unicode string which can be safely encoded into the 
 
576
         specified encoding.
 
577
    """
 
578
    if encoding is None:
 
579
        raise ValueError('you cannot specify None for the display encoding')
 
580
    if url.startswith('file://'):
 
581
        try:
 
582
            path = local_path_from_url(url)
 
583
            path.encode(encoding)
 
584
            return path
 
585
        except UnicodeError:
 
586
            return url
 
587
 
 
588
    # Split into sections to try to decode utf-8
 
589
    res = url.split('/')
 
590
    for i in xrange(1, len(res)):
 
591
        escaped_chunks = res[i].split('%')
 
592
        for j in xrange(1, len(escaped_chunks)):
 
593
            item = escaped_chunks[j]
 
594
            try:
 
595
                escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
 
596
            except KeyError:
 
597
                # Put back the percent symbol
 
598
                escaped_chunks[j] = '%' + item
 
599
            except UnicodeDecodeError:
 
600
                escaped_chunks[j] = unichr(int(item[:2], 16)) + item[2:]
 
601
        unescaped = ''.join(escaped_chunks)
 
602
        try:
 
603
            decoded = unescaped.decode('utf-8')
 
604
        except UnicodeDecodeError:
 
605
            # If this path segment cannot be properly utf-8 decoded
 
606
            # after doing unescaping we will just leave it alone
 
607
            pass
 
608
        else:
 
609
            try:
 
610
                decoded.encode(encoding)
 
611
            except UnicodeEncodeError:
 
612
                # If this chunk cannot be encoded in the local
 
613
                # encoding, then we should leave it alone
 
614
                pass
 
615
            else:
 
616
                # Otherwise take the url decoded one
 
617
                res[i] = decoded
 
618
    return u'/'.join(res)
 
619
 
 
620
 
 
621
def derive_to_location(from_location):
 
622
    """Derive a TO_LOCATION given a FROM_LOCATION.
 
623
 
 
624
    The normal case is a FROM_LOCATION of http://foo/bar => bar.
 
625
    The Right Thing for some logical destinations may differ though
 
626
    because no / may be present at all. In that case, the result is
 
627
    the full name without the scheme indicator, e.g. lp:foo-bar => foo-bar.
 
628
    This latter case also applies when a Windows drive
 
629
    is used without a path, e.g. c:foo-bar => foo-bar.
 
630
    If no /, path separator or : is found, the from_location is returned.
 
631
    """
 
632
    if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
 
633
        return os.path.basename(from_location.rstrip("/\\"))
 
634
    else:
 
635
        sep = from_location.find(":")
 
636
        if sep > 0:
 
637
            return from_location[sep+1:]
 
638
        else:
 
639
            return from_location
 
640
 
 
641
 
 
642
def _is_absolute(url):
 
643
    return (osutils.pathjoin('/foo', url) == url)
 
644
 
 
645
 
 
646
def rebase_url(url, old_base, new_base):
 
647
    """Convert a relative path from an old base URL to a new base URL.
 
648
 
 
649
    The result will be a relative path.
 
650
    Absolute paths and full URLs are returned unaltered.
 
651
    """
 
652
    scheme, separator = _find_scheme_and_separator(url)
 
653
    if scheme is not None:
 
654
        return url
 
655
    if _is_absolute(url):
 
656
        return url
 
657
    old_parsed = urlparse.urlparse(old_base)
 
658
    new_parsed = urlparse.urlparse(new_base)
 
659
    if (old_parsed[:2]) != (new_parsed[:2]):
 
660
        raise errors.InvalidRebaseURLs(old_base, new_base)
 
661
    return determine_relative_path(new_parsed[2],
 
662
                                   osutils.pathjoin(old_parsed[2], url))
 
663
 
 
664
 
 
665
def determine_relative_path(from_path, to_path):
 
666
    """Determine a relative path from from_path to to_path."""
 
667
    from_segments = osutils.splitpath(from_path)
 
668
    to_segments = osutils.splitpath(to_path)
 
669
    count = -1
 
670
    for count, (from_element, to_element) in enumerate(zip(from_segments,
 
671
                                                       to_segments)):
 
672
        if from_element != to_element:
 
673
            break
 
674
    else:
 
675
        count += 1
 
676
    unique_from = from_segments[count:]
 
677
    unique_to = to_segments[count:]
 
678
    segments = (['..'] * len(unique_from) + unique_to)
 
679
    if len(segments) == 0:
 
680
        return '.'
 
681
    return osutils.pathjoin(*segments)