1
# Bazaar -- distributed version control
 
 
3
# Copyright (C) 2006 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
19
"""A collection of function for handling URL operations."""
 
 
25
from bzrlib.lazy_import import lazy_import
 
 
26
lazy_import(globals(), """
 
 
27
from posixpath import split as _posix_split, normpath as _posix_normpath
 
 
38
def basename(url, exclude_trailing_slash=True):
 
 
39
    """Return the last component of a URL.
 
 
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
 
 
48
    return split(url, exclude_trailing_slash=exclude_trailing_slash)[1]
 
 
51
def dirname(url, exclude_trailing_slash=True):
 
 
52
    """Return the parent directory of the given path.
 
 
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
 
 
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]
 
 
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))
 
 
74
def file_relpath(base, path):
 
 
75
    """Compute just the relative sub-portion of a url
 
 
77
    This assumes that both paths are already fully specified file:// URLs.
 
 
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))
 
 
88
def _find_scheme_and_separator(url):
 
 
89
    """Find the scheme separator (://) and the first path separator
 
 
91
    This is just a helper functions for other path utilities.
 
 
92
    It could probably be replaced by urlparse
 
 
94
    m = _url_scheme_re.match(url)
 
 
98
    scheme = m.group('scheme')
 
 
99
    path = m.group('path')
 
 
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
 
 
109
def join(base, *args):
 
 
110
    """Create a URL by joining sections.
 
 
112
    This will normalize '..', assuming that paths are absolute
 
 
113
    (it assumes no symlinks in either path)
 
 
115
    If any of *args is an absolute URL, it will be treated correctly.
 
 
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'
 
 
123
    match = _url_scheme_re.match(base)
 
 
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
 
 
134
        path = base.split('/')
 
 
136
    if scheme is not None and len(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.
 
 
141
        path = [''] + path[1:]
 
 
143
        # create an empty host, but dont alter the path - this might be a
 
 
144
        # relative url fragment.
 
 
149
        match = _url_scheme_re.match(arg)
 
 
152
            scheme = match.group('scheme')
 
 
153
            # this skips .. normalisation, making http://host/../../..
 
 
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:
 
 
163
                # url scheme implies absolute path.
 
 
166
                # no url scheme we take the path as is.
 
 
169
            path = '/'.join(path)
 
 
170
            path = joinpath(path, arg)
 
 
171
            path = path.split('/')
 
 
172
    if remove_root and path[0:1] == ['']:
 
 
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:
 
 
182
        return '/'.join(path)
 
 
183
    return scheme + '://' + '/'.join(path)
 
 
186
def joinpath(base, *args):
 
 
187
    """Join URL path segments to a URL path segment.
 
 
189
    This is somewhat like osutils.joinpath, but intended for URLs.
 
 
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.
 
 
196
    path = base.split('/')
 
 
197
    if len(path) > 1 and path[-1] == '':
 
 
198
        #If the path ends in a trailing /, remove it.
 
 
201
        if arg.startswith('/'):
 
 
203
        for chunk in arg.split('/'):
 
 
208
                    raise errors.InvalidURLJoin('Cannot go above root',
 
 
216
        return '/'.join(path)
 
 
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://'):])
 
 
228
def _posix_local_path_to_url(path):
 
 
229
    """Convert a local path like ./foo into a URL like file:///path/to/foo
 
 
231
    This also handles transforming escaping unicode characters, etc.
 
 
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)))
 
 
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)
 
 
254
    # allow empty paths so we can serve all roots
 
 
255
    if win32_url == '///':
 
 
258
    # usual local path with drive letter
 
 
259
    if (win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
 
 
260
                             'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
 
 
261
        or win32_url[4] not in  '|:'
 
 
262
        or win32_url[5] != '/'):
 
 
263
        raise errors.InvalidURL(url, 'Win32 file urls start with'
 
 
264
                ' file:///x:/, where x is a valid drive letter')
 
 
265
    return win32_url[3].upper() + u':' + unescape(win32_url[5:])
 
 
268
def _win32_local_path_to_url(path):
 
 
269
    """Convert a local path like ./foo into a URL like file:///C:/path/to/foo
 
 
271
    This also handles transforming escaping unicode characters, etc.
 
 
273
    # importing directly from ntpath allows us to test this 
 
 
274
    # on non-win32 platform
 
 
275
    # FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
 
 
276
    #       which actually strips trailing space characters.
 
 
277
    #       The worst part is that under linux ntpath.abspath has different
 
 
278
    #       semantics, since 'nt' is not an available module.
 
 
282
    win32_path = osutils._win32_abspath(path)
 
 
283
    # check for UNC path \\HOST\path
 
 
284
    if win32_path.startswith('//'):
 
 
285
        return 'file:' + escape(win32_path)
 
 
286
    return ('file:///' + str(win32_path[0].upper()) + ':' +
 
 
287
        escape(win32_path[2:]))
 
 
290
local_path_to_url = _posix_local_path_to_url
 
 
291
local_path_from_url = _posix_local_path_from_url
 
 
292
MIN_ABS_FILEURL_LENGTH = len('file:///')
 
 
293
WIN32_MIN_ABS_FILEURL_LENGTH = len('file:///C:/')
 
 
295
if sys.platform == 'win32':
 
 
296
    local_path_to_url = _win32_local_path_to_url
 
 
297
    local_path_from_url = _win32_local_path_from_url
 
 
299
    MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
 
 
302
_url_scheme_re = re.compile(r'^(?P<scheme>[^:/]{2,})://(?P<path>.*)$')
 
 
303
_url_hex_escapes_re = re.compile(r'(%[0-9a-fA-F]{2})')
 
 
306
def _unescape_safe_chars(matchobj):
 
 
307
    """re.sub callback to convert hex-escapes to plain characters (if safe).
 
 
309
    e.g. '%7E' will be converted to '~'.
 
 
311
    hex_digits = matchobj.group(0)[1:]
 
 
312
    char = chr(int(hex_digits, 16))
 
 
313
    if char in _url_dont_escape_characters:
 
 
316
        return matchobj.group(0).upper()
 
 
319
def normalize_url(url):
 
 
320
    """Make sure that a path string is in fully normalized URL form.
 
 
322
    This handles URLs which have unicode characters, spaces,
 
 
323
    special characters, etc.
 
 
325
    It has two basic modes of operation, depending on whether the
 
 
326
    supplied string starts with a url specifier (scheme://) or not.
 
 
327
    If it does not have a specifier it is considered a local path,
 
 
328
    and will be converted into a file:/// url. Non-ascii characters
 
 
329
    will be encoded using utf-8.
 
 
330
    If it does have a url specifier, it will be treated as a "hybrid"
 
 
331
    URL. Basically, a URL that should have URL special characters already
 
 
332
    escaped (like +?&# etc), but may have unicode characters, etc
 
 
333
    which would not be valid in a real URL.
 
 
335
    :param url: Either a hybrid URL or a local path
 
 
336
    :return: A normalized URL which only includes 7-bit ASCII characters.
 
 
338
    m = _url_scheme_re.match(url)
 
 
340
        return local_path_to_url(url)
 
 
341
    scheme = m.group('scheme')
 
 
342
    path = m.group('path')
 
 
343
    if not isinstance(url, unicode):
 
 
345
            if c not in _url_safe_characters:
 
 
346
                raise errors.InvalidURL(url, 'URLs can only contain specific'
 
 
347
                                            ' safe characters (not %r)' % c)
 
 
348
        path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
 
 
349
        return str(scheme + '://' + ''.join(path))
 
 
351
    # We have a unicode (hybrid) url
 
 
352
    path_chars = list(path)
 
 
354
    for i in xrange(len(path_chars)):
 
 
355
        if path_chars[i] not in _url_safe_characters:
 
 
356
            chars = path_chars[i].encode('utf-8')
 
 
357
            path_chars[i] = ''.join(
 
 
358
                ['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
 
 
359
    path = ''.join(path_chars)
 
 
360
    path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
 
 
361
    return str(scheme + '://' + path)
 
 
364
def relative_url(base, other):
 
 
365
    """Return a path to other from base.
 
 
367
    If other is unrelated to base, return other. Else return a relative path.
 
 
368
    This assumes no symlinks as part of the url.
 
 
370
    dummy, base_first_slash = _find_scheme_and_separator(base)
 
 
371
    if base_first_slash is None:
 
 
374
    dummy, other_first_slash = _find_scheme_and_separator(other)
 
 
375
    if other_first_slash is None:
 
 
378
    # this takes care of differing schemes or hosts
 
 
379
    base_scheme = base[:base_first_slash]
 
 
380
    other_scheme = other[:other_first_slash]
 
 
381
    if base_scheme != other_scheme:
 
 
383
    elif sys.platform == 'win32' and base_scheme == 'file://':
 
 
384
        base_drive = base[base_first_slash+1:base_first_slash+3]
 
 
385
        other_drive = other[other_first_slash+1:other_first_slash+3]
 
 
386
        if base_drive != other_drive:
 
 
389
    base_path = base[base_first_slash+1:]
 
 
390
    other_path = other[other_first_slash+1:]
 
 
392
    if base_path.endswith('/'):
 
 
393
        base_path = base_path[:-1]
 
 
395
    base_sections = base_path.split('/')
 
 
396
    other_sections = other_path.split('/')
 
 
398
    if base_sections == ['']:
 
 
400
    if other_sections == ['']:
 
 
404
    for b, o in zip(base_sections, other_sections):
 
 
407
        output_sections.append(b)
 
 
409
    match_len = len(output_sections)
 
 
410
    output_sections = ['..' for x in base_sections[match_len:]]
 
 
411
    output_sections.extend(other_sections[match_len:])
 
 
413
    return "/".join(output_sections) or "."
 
 
416
def _win32_extract_drive_letter(url_base, path):
 
 
417
    """On win32 the drive letter needs to be added to the url base."""
 
 
418
    # Strip off the drive letter
 
 
419
    # path is currently /C:/foo
 
 
420
    if len(path) < 3 or path[2] not in ':|' or path[3] != '/':
 
 
421
        raise errors.InvalidURL(url_base + path, 
 
 
422
            'win32 file:/// paths need a drive letter')
 
 
423
    url_base += path[0:3] # file:// + /C:
 
 
424
    path = path[3:] # /foo
 
 
425
    return url_base, path
 
 
428
def split(url, exclude_trailing_slash=True):
 
 
429
    """Split a URL into its parent directory and a child directory.
 
 
431
    :param url: A relative or absolute URL
 
 
432
    :param exclude_trailing_slash: Strip off a final '/' if it is part
 
 
433
        of the path (but not if it is part of the protocol specification)
 
 
435
    :return: (parent_url, child_dir).  child_dir may be the empty string if we're at 
 
 
438
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
 
 
440
    if first_path_slash is None:
 
 
441
        # We have either a relative path, or no separating slash
 
 
442
        if scheme_loc is None:
 
 
444
            if exclude_trailing_slash and url.endswith('/'):
 
 
446
            return _posix_split(url)
 
 
448
            # Scheme with no path
 
 
451
    # We have a fully defined path
 
 
452
    url_base = url[:first_path_slash] # http://host, file://
 
 
453
    path = url[first_path_slash:] # /file/foo
 
 
455
    if sys.platform == 'win32' and url.startswith('file:///'):
 
 
456
        # Strip off the drive letter
 
 
457
        # url_base is currently file://
 
 
458
        # path is currently /C:/foo
 
 
459
        url_base, path = _win32_extract_drive_letter(url_base, path)
 
 
460
        # now it should be file:///C: and /foo
 
 
462
    if exclude_trailing_slash and len(path) > 1 and path.endswith('/'):
 
 
464
    head, tail = _posix_split(path)
 
 
465
    return url_base + head, tail
 
 
468
def _win32_strip_local_trailing_slash(url):
 
 
469
    """Strip slashes after the drive letter"""
 
 
470
    if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
 
 
476
def strip_trailing_slash(url):
 
 
477
    """Strip trailing slash, except for root paths.
 
 
479
    The definition of 'root path' is platform-dependent.
 
 
480
    This assumes that all URLs are valid netloc urls, such that they
 
 
483
    It searches for ://, and then refuses to remove the next '/'.
 
 
484
    It can also handle relative paths
 
 
486
        path/to/foo       => path/to/foo
 
 
487
        path/to/foo/      => path/to/foo
 
 
488
        http://host/path/ => http://host/path
 
 
489
        http://host/path  => http://host/path
 
 
490
        http://host/      => http://host/
 
 
492
        file:///foo/      => file:///foo
 
 
493
        # This is unique on win32 platforms, and is the only URL
 
 
494
        # format which does it differently.
 
 
495
        file:///c|/       => file:///c:/
 
 
497
    if not url.endswith('/'):
 
 
500
    if sys.platform == 'win32' and url.startswith('file://'):
 
 
501
        return _win32_strip_local_trailing_slash(url)
 
 
503
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
 
 
504
    if scheme_loc is None:
 
 
505
        # This is a relative path, as it has no scheme
 
 
506
        # so just chop off the last character
 
 
509
    if first_path_slash is None or first_path_slash == len(url)-1:
 
 
510
        # Don't chop off anything if the only slash is the path
 
 
518
    """Unescape relpath from url format.
 
 
520
    This returns a Unicode path from a URL
 
 
522
    # jam 20060427 URLs are supposed to be ASCII only strings
 
 
523
    #       If they are passed in as unicode, urllib.unquote
 
 
524
    #       will return a UNICODE string, which actually contains
 
 
525
    #       utf-8 bytes. So we have to ensure that they are
 
 
526
    #       plain ASCII strings, or the final .decode will
 
 
527
    #       try to encode the UNICODE => ASCII, and then decode
 
 
531
    except UnicodeError, e:
 
 
532
        raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
 
 
534
    unquoted = urllib.unquote(url)
 
 
536
        unicode_path = unquoted.decode('utf-8')
 
 
537
    except UnicodeError, e:
 
 
538
        raise errors.InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
 
 
542
# These are characters that if escaped, should stay that way
 
 
543
_no_decode_chars = ';/?:@&=+$,#'
 
 
544
_no_decode_ords = [ord(c) for c in _no_decode_chars]
 
 
545
_no_decode_hex = (['%02x' % o for o in _no_decode_ords] 
 
 
546
                + ['%02X' % o for o in _no_decode_ords])
 
 
547
_hex_display_map = dict(([('%02x' % o, chr(o)) for o in range(256)]
 
 
548
                    + [('%02X' % o, chr(o)) for o in range(256)]))
 
 
549
#These entries get mapped to themselves
 
 
550
_hex_display_map.update((hex,'%'+hex) for hex in _no_decode_hex)
 
 
552
# These characters shouldn't be percent-encoded, and it's always safe to
 
 
553
# unencode them if they are.
 
 
554
_url_dont_escape_characters = set(
 
 
555
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
 
 
556
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
 
 
557
   "0123456789" # Numbers
 
 
558
   "-._~"  # Unreserved characters
 
 
561
# These characters should not be escaped
 
 
562
_url_safe_characters = set(
 
 
563
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
 
 
564
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
 
 
565
   "0123456789" # Numbers
 
 
566
   "_.-!~*'()"  # Unreserved characters
 
 
567
   "/;?:@&=+$," # Reserved characters
 
 
568
   "%#"         # Extra reserved characters
 
 
571
def unescape_for_display(url, encoding):
 
 
572
    """Decode what you can for a URL, so that we get a nice looking path.
 
 
574
    This will turn file:// urls into local paths, and try to decode
 
 
575
    any portions of a http:// style url that it can.
 
 
577
    Any sections of the URL which can't be represented in the encoding or 
 
 
578
    need to stay as escapes are left alone.
 
 
580
    :param url: A 7-bit ASCII URL
 
 
581
    :param encoding: The final output encoding
 
 
583
    :return: A unicode string which can be safely encoded into the 
 
 
587
        raise ValueError('you cannot specify None for the display encoding')
 
 
588
    if url.startswith('file://'):
 
 
590
            path = local_path_from_url(url)
 
 
591
            path.encode(encoding)
 
 
596
    # Split into sections to try to decode utf-8
 
 
598
    for i in xrange(1, len(res)):
 
 
599
        escaped_chunks = res[i].split('%')
 
 
600
        for j in xrange(1, len(escaped_chunks)):
 
 
601
            item = escaped_chunks[j]
 
 
603
                escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
 
 
605
                # Put back the percent symbol
 
 
606
                escaped_chunks[j] = '%' + item
 
 
607
            except UnicodeDecodeError:
 
 
608
                escaped_chunks[j] = unichr(int(item[:2], 16)) + item[2:]
 
 
609
        unescaped = ''.join(escaped_chunks)
 
 
611
            decoded = unescaped.decode('utf-8')
 
 
612
        except UnicodeDecodeError:
 
 
613
            # If this path segment cannot be properly utf-8 decoded
 
 
614
            # after doing unescaping we will just leave it alone
 
 
618
                decoded.encode(encoding)
 
 
619
            except UnicodeEncodeError:
 
 
620
                # If this chunk cannot be encoded in the local
 
 
621
                # encoding, then we should leave it alone
 
 
624
                # Otherwise take the url decoded one
 
 
626
    return u'/'.join(res)
 
 
629
def derive_to_location(from_location):
 
 
630
    """Derive a TO_LOCATION given a FROM_LOCATION.
 
 
632
    The normal case is a FROM_LOCATION of http://foo/bar => bar.
 
 
633
    The Right Thing for some logical destinations may differ though
 
 
634
    because no / may be present at all. In that case, the result is
 
 
635
    the full name without the scheme indicator, e.g. lp:foo-bar => foo-bar.
 
 
636
    This latter case also applies when a Windows drive
 
 
637
    is used without a path, e.g. c:foo-bar => foo-bar.
 
 
638
    If no /, path separator or : is found, the from_location is returned.
 
 
640
    if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
 
 
641
        return os.path.basename(from_location.rstrip("/\\"))
 
 
643
        sep = from_location.find(":")
 
 
645
            return from_location[sep+1:]
 
 
650
def _is_absolute(url):
 
 
651
    return (osutils.pathjoin('/foo', url) == url)
 
 
654
def rebase_url(url, old_base, new_base):
 
 
655
    """Convert a relative path from an old base URL to a new base URL.
 
 
657
    The result will be a relative path.
 
 
658
    Absolute paths and full URLs are returned unaltered.
 
 
660
    scheme, separator = _find_scheme_and_separator(url)
 
 
661
    if scheme is not None:
 
 
663
    if _is_absolute(url):
 
 
665
    old_parsed = urlparse.urlparse(old_base)
 
 
666
    new_parsed = urlparse.urlparse(new_base)
 
 
667
    if (old_parsed[:2]) != (new_parsed[:2]):
 
 
668
        raise errors.InvalidRebaseURLs(old_base, new_base)
 
 
669
    return determine_relative_path(new_parsed[2],
 
 
670
                                   join(old_parsed[2], url))
 
 
673
def determine_relative_path(from_path, to_path):
 
 
674
    """Determine a relative path from from_path to to_path."""
 
 
675
    from_segments = osutils.splitpath(from_path)
 
 
676
    to_segments = osutils.splitpath(to_path)
 
 
678
    for count, (from_element, to_element) in enumerate(zip(from_segments,
 
 
680
        if from_element != to_element:
 
 
684
    unique_from = from_segments[count:]
 
 
685
    unique_to = to_segments[count:]
 
 
686
    segments = (['..'] * len(unique_from) + unique_to)
 
 
687
    if len(segments) == 0:
 
 
689
    return osutils.pathjoin(*segments)