/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1861.2.6 by Alexander Belchenko
branding: change Bazaar-NG to Bazaar
1
# Bazaar -- distributed version control
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
2
#
2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
3
# Copyright (C) 2006 Canonical Ltd
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
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
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
21
import os
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
22
import re
23
import sys
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
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
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
28
import urllib
3242.3.26 by Aaron Bentley
Implement rebase_url
29
import urlparse
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
30
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
31
from bzrlib import (
32
    errors,
33
    osutils,
34
    )
35
""")
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
36
37
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
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
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
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
1685.1.46 by John Arbash Meinel
Sorting functions by name.
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
    """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
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)
1685.1.46 by John Arbash Meinel
Sorting functions by name.
83
    base = local_path_from_url(base)
84
    path = local_path_from_url(path)
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
85
    return escape(osutils.relpath(base, path))
1685.1.46 by John Arbash Meinel
Sorting functions by name.
86
87
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
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
    """
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
94
    m = _url_scheme_re.match(url)
95
    if not m:
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
96
        return None, None
97
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
98
    scheme = m.group('scheme')
99
    path = m.group('path')
100
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
101
    # Find the path separating slash
102
    # (first slash after the ://)
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
103
    first_path_slash = path.find('/')
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
104
    if first_path_slash == -1:
1685.1.56 by John Arbash Meinel
Fixing _find_scheme_and_separator
105
        return len(scheme), None
106
    return len(scheme), first_path_slash+len(scheme)+3
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
107
108
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
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
    """
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
121
    if not args:
122
        return base
123
    match = _url_scheme_re.match(base)
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
124
    scheme = None
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
125
    if match:
126
        scheme = match.group('scheme')
127
        path = match.group('path').split('/')
1711.2.49 by John Arbash Meinel
urlutils.join should work for root paths.
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]
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
133
    else:
134
        path = base.split('/')
135
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
136
    if scheme is not None and len(path) >= 1:
2018.5.93 by Andrew Bennetts
Fix another bug in urlutils.join.
137
        host = path[:1]
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
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:]
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
142
    else:
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
143
        # create an empty host, but dont alter the path - this might be a
144
        # relative url fragment.
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
145
        host = []
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
146
        remove_root = False
147
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
148
    for arg in args:
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
149
        match = _url_scheme_re.match(arg)
150
        if match:
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
151
            # Absolute URL
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
152
            scheme = match.group('scheme')
1986.1.10 by Robert Collins
Merge from bzr.dev, fixing found bugs handling 'has('/')' in MemoryTransport and SFTP transports.
153
            # this skips .. normalisation, making http://host/../../..
154
            # be rather strange.
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
155
            path = match.group('path').split('/')
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
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:
2018.5.92 by Andrew Bennetts
Small bugfix to urlutils.join: join('anything', 'http://bar/a/') should not strip the trailing slash.
161
                host = path[:1]
162
                path = path[1:]
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
163
                # url scheme implies absolute path.
164
                path = [''] + path
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
165
            else:
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
166
                # no url scheme we take the path as is.
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
167
                host = []
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
168
        else:
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
169
            path = '/'.join(path)
170
            path = joinpath(path, arg)
171
            path = path.split('/')
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
172
    if remove_root and path[0:1] == ['']:
173
        del path[0]
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
174
    if host:
2018.5.92 by Andrew Bennetts
Small bugfix to urlutils.join: join('anything', 'http://bar/a/') should not strip the trailing slash.
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:
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
178
            del path[0]
179
        path = host + path
1685.1.80 by Wouter van Heyst
more code cleanup
180
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
181
    if scheme is None:
182
        return '/'.join(path)
183
    return scheme + '://' + '/'.join(path)
184
185
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
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
    """
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
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()
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
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
1685.1.46 by John Arbash Meinel
Sorting functions by name.
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
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
235
    return 'file://' + escape(_posix_normpath(
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
236
        osutils._posix_abspath(path)))
1685.1.46 by John Arbash Meinel
Sorting functions by name.
237
238
239
def _win32_local_path_from_url(url):
1711.4.4 by John Arbash Meinel
Fix some broken tests because of stupid ntpath.abspath behavior
240
    """Convert a url like file:///C:/path/to/foo into C:/path/to/foo"""
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
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://')
1685.1.46 by John Arbash Meinel
Sorting functions by name.
244
    # We strip off all 3 slashes
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
245
    win32_url = url[len('file:'):]
2162.2.2 by Alexander Belchenko
Support for win32 UNC path (like: \\HOST\path)
246
    # check for UNC path: //HOST/path
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
247
    if not win32_url.startswith('///'):
2162.2.2 by Alexander Belchenko
Support for win32 UNC path (like: \\HOST\path)
248
        if (win32_url[2] == '/'
249
            or win32_url[3] in '|:'):
250
            raise errors.InvalidURL(url, 'Win32 UNC path urls'
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
251
                ' have form file://HOST/path')
2162.2.2 by Alexander Belchenko
Support for win32 UNC path (like: \\HOST\path)
252
        return unescape(win32_url)
253
    # usual local path with drive letter
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
254
    if (win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
1711.4.4 by John Arbash Meinel
Fix some broken tests because of stupid ntpath.abspath behavior
255
                             'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
256
        or win32_url[4] not in  '|:'
257
        or win32_url[5] != '/'):
1711.4.4 by John Arbash Meinel
Fix some broken tests because of stupid ntpath.abspath behavior
258
        raise errors.InvalidURL(url, 'Win32 file urls start with'
1711.4.8 by John Arbash Meinel
switch to prefering lowercase drive letters, since that matches os.getcwd() drive letters
259
                ' file:///x:/, where x is a valid drive letter')
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
260
    return win32_url[3].upper() + u':' + unescape(win32_url[5:])
1685.1.46 by John Arbash Meinel
Sorting functions by name.
261
262
263
def _win32_local_path_to_url(path):
1711.4.4 by John Arbash Meinel
Fix some broken tests because of stupid ntpath.abspath behavior
264
    """Convert a local path like ./foo into a URL like file:///C:/path/to/foo
1685.1.46 by John Arbash Meinel
Sorting functions by name.
265
266
    This also handles transforming escaping unicode characters, etc.
267
    """
268
    # importing directly from ntpath allows us to test this 
1711.4.4 by John Arbash Meinel
Fix some broken tests because of stupid ntpath.abspath behavior
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.
2279.4.2 by Alexander Belchenko
Don't do normpath after abspath, because this function is called inside abspath
274
    win32_path = osutils._win32_abspath(path)
2162.2.2 by Alexander Belchenko
Support for win32 UNC path (like: \\HOST\path)
275
    # check for UNC path \\HOST\path
276
    if win32_path.startswith('//'):
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
277
        return 'file:' + escape(win32_path)
3234.3.1 by Alexander Belchenko
ensure that local_path_to_url() always returns plain string, not unicode.
278
    return ('file:///' + str(win32_path[0].upper()) + ':' +
279
        escape(win32_path[2:]))
1685.1.46 by John Arbash Meinel
Sorting functions by name.
280
281
282
local_path_to_url = _posix_local_path_to_url
283
local_path_from_url = _posix_local_path_from_url
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
284
MIN_ABS_FILEURL_LENGTH = len('file:///')
1711.4.17 by John Arbash Meinel
[merge] bzr.dev 1790
285
WIN32_MIN_ABS_FILEURL_LENGTH = len('file:///C:/')
1685.1.46 by John Arbash Meinel
Sorting functions by name.
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
1711.2.44 by John Arbash Meinel
Factor out another win32 special case and add platform independent tests for it.
291
    MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
292
293
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
294
_url_scheme_re = re.compile(r'^(?P<scheme>[^:/]{2,})://(?P<path>.*)$')
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
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()
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
309
310
311
def normalize_url(url):
312
    """Make sure that a path string is in fully normalized URL form.
313
    
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
314
    This handles URLs which have unicode characters, spaces,
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
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
    """
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
330
    m = _url_scheme_re.match(url)
331
    if not m:
332
        return local_path_to_url(url)
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
333
    scheme = m.group('scheme')
334
    path = m.group('path')
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
335
    if not isinstance(url, unicode):
336
        for c in url:
337
            if c not in _url_safe_characters:
1685.1.53 by John Arbash Meinel
Updated normalize_url
338
                raise errors.InvalidURL(url, 'URLs can only contain specific'
339
                                            ' safe characters (not %r)' % c)
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
340
        path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
341
        return str(scheme + '://' + ''.join(path))
342
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
343
    # We have a unicode (hybrid) url
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
344
    path_chars = list(path)
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
345
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
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)
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
354
355
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
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
    """
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
362
    dummy, base_first_slash = _find_scheme_and_separator(base)
363
    if base_first_slash is None:
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
364
        return other
365
    
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
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
3139.2.1 by Alexander Belchenko
bugfix #90847: fix problem with parent location on another logical drive
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
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
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]
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
386
387
    base_sections = base_path.split('/')
388
    other_sections = other_path.split('/')
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
389
390
    if base_sections == ['']:
391
        base_sections = []
392
    if other_sections == ['']:
393
        other_sections = []
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
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)
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
400
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
401
    match_len = len(output_sections)
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
402
    output_sections = ['..' for x in base_sections[match_len:]]
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
403
    output_sections.extend(other_sections[match_len:])
404
405
    return "/".join(output_sections) or "."
406
407
1711.2.43 by John Arbash Meinel
Split out win32 specific code so that it can be tested on all platforms.
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
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
420
def split(url, exclude_trailing_slash=True):
421
    """Split a URL into its parent directory and a child directory.
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
422
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
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)
1685.1.61 by Martin Pool
[broken] Change BzrDir._make_tail to use urlutils.split
426
427
    :return: (parent_url, child_dir).  child_dir may be the empty string if we're at 
428
        the root.
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
429
    """
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
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
1711.2.43 by John Arbash Meinel
Split out win32 specific code so that it can be tested on all platforms.
449
        # url_base is currently file://
1711.2.39 by John Arbash Meinel
Fix bzrlib.urlutils.split() to work properly on win32 local paths.
450
        # path is currently /C:/foo
1711.2.43 by John Arbash Meinel
Split out win32 specific code so that it can be tested on all platforms.
451
        url_base, path = _win32_extract_drive_letter(url_base, path)
452
        # now it should be file:///C: and /foo
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
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
1685.1.46 by John Arbash Meinel
Sorting functions by name.
459
1711.2.44 by John Arbash Meinel
Factor out another win32 special case and add platform independent tests for it.
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
1685.1.47 by John Arbash Meinel
s comes before u
468
def strip_trailing_slash(url):
469
    """Strip trailing slash, except for root paths.
470
471
    The definition of 'root path' is platform-dependent.
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
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.
1711.4.8 by John Arbash Meinel
switch to prefering lowercase drive letters, since that matches os.getcwd() drive letters
487
        file:///c|/       => file:///c:/
1685.1.47 by John Arbash Meinel
s comes before u
488
    """
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
489
    if not url.endswith('/'):
490
        # Nothing to do
491
        return url
2245.6.1 by Alexander Belchenko
win32 UNC path: recursive cloning UNC path to root stops on //HOST, not on //
492
    if sys.platform == 'win32' and url.startswith('file://'):
1711.2.44 by John Arbash Meinel
Factor out another win32 special case and add platform independent tests for it.
493
        return _win32_strip_local_trailing_slash(url)
1685.1.80 by Wouter van Heyst
more code cleanup
494
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
495
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
496
    if scheme_loc is None:
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
497
        # This is a relative path, as it has no scheme
498
        # so just chop off the last character
1685.1.47 by John Arbash Meinel
s comes before u
499
        return url[:-1]
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
500
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
501
    if first_path_slash is None or first_path_slash == len(url)-1:
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
502
        # Don't chop off anything if the only slash is the path
503
        # separating slash
1685.1.47 by John Arbash Meinel
s comes before u
504
        return url
505
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
506
    return url[:-1]
507
1685.1.47 by John Arbash Meinel
s comes before u
508
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
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,))
1685.1.80 by Wouter van Heyst
more code cleanup
525
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
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])
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
539
_hex_display_map = dict(([('%02x' % o, chr(o)) for o in range(256)]
540
                    + [('%02X' % o, chr(o)) for o in range(256)]))
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
541
#These entries get mapped to themselves
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
542
_hex_display_map.update((hex,'%'+hex) for hex in _no_decode_hex)
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
543
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
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
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
553
# These characters should not be escaped
2167.2.2 by Aaron Bentley
Update safe character list
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
)
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
562
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
563
def unescape_for_display(url, encoding):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
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.
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
568
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
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
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
572
    :param url: A 7-bit ASCII URL
573
    :param encoding: The final output encoding
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
574
575
    :return: A unicode string which can be safely encoded into the 
576
         specified encoding.
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
577
    """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
578
    if encoding is None:
579
        raise ValueError('you cannot specify None for the display encoding')
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
580
    if url.startswith('file://'):
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
581
        try:
582
            path = local_path_from_url(url)
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
583
            path.encode(encoding)
584
            return path
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
585
        except UnicodeError:
586
            return url
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
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:
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
603
            decoded = unescaped.decode('utf-8')
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
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
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
608
        else:
609
            try:
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
610
                decoded.encode(encoding)
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
611
            except UnicodeEncodeError:
612
                # If this chunk cannot be encoded in the local
613
                # encoding, then we should leave it alone
614
                pass
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
615
            else:
616
                # Otherwise take the url decoded one
617
                res[i] = decoded
618
    return u'/'.join(res)
2512.4.1 by Ian Clatworthy
Fixes #115491 - 'branch lp:projname' now creates ./projname as exected
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
3242.3.26 by Aaron Bentley
Implement rebase_url
640
3242.3.35 by Aaron Bentley
Cleanups and documentation
641
3242.3.26 by Aaron Bentley
Implement rebase_url
642
def _is_absolute(url):
643
    return (osutils.pathjoin('/foo', url) == url)
644
3242.3.35 by Aaron Bentley
Cleanups and documentation
645
3242.3.26 by Aaron Bentley
Implement rebase_url
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]):
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
660
        raise errors.InvalidRebaseURLs(old_base, new_base)
3242.3.36 by Aaron Bentley
Updates from review comments
661
    return determine_relative_path(new_parsed[2],
3242.3.41 by Aaron Bentley
Fix url rebasing for 2.4 API
662
                                   osutils.pathjoin(old_parsed[2], url))
3242.3.26 by Aaron Bentley
Implement rebase_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)