/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2006-2010 Canonical Ltd
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
16
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
17
"""A collection of function for handling URL operations."""
18
6379.6.3 by Jelmer Vernooij
Use absolute_import.
19
from __future__ import absolute_import
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
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
25
try:
26
    import urlparse
27
except ImportError:
28
    from urllib import parse as urlparse
29
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
30
from .lazy_import import lazy_import
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
31
lazy_import(globals(), """
6015.39.2 by Florian Vichot
Fixed an infinite loop when creating a repo at the root of the filesystem,
32
from posixpath import split as _posix_split
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
33
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
34
from breezy import (
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
35
    errors,
36
    osutils,
37
    )
38
""")
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
39
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
40
from .sixish import (
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
41
    text_type,
42
    )
43
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
44
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
45
def basename(url, exclude_trailing_slash=True):
46
    """Return the last component of a URL.
47
48
    :param url: The URL in question
49
    :param exclude_trailing_slash: If the url looks like "path/to/foo/"
50
        ignore the final slash and return 'foo' rather than ''
51
    :return: Just the final component of the URL. This can return ''
52
        if you don't exclude_trailing_slash, or if you are at the
53
        root of the URL.
54
    """
55
    return split(url, exclude_trailing_slash=exclude_trailing_slash)[1]
56
57
58
def dirname(url, exclude_trailing_slash=True):
59
    """Return the parent directory of the given path.
60
61
    :param url: Relative or absolute URL
62
    :param exclude_trailing_slash: Remove a final slash
63
        (treat http://host/foo/ as http://host/foo, but
64
        http://host/ stays http://host/)
65
    :return: Everything in the URL except the last path chunk
66
    """
67
    # TODO: jam 20060502 This was named dirname to be consistent
68
    #       with the os functions, but maybe "parent" would be better
69
    return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
70
71
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
72
# Private copies of quote and unquote, copied from Python's
73
# urllib module because urllib unconditionally imports socket, which imports
74
# ssl.
75
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
76
always_safe = (b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
77
               b'abcdefghijklmnopqrstuvwxyz'
78
               b'0123456789' b'_.-')
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
79
_safe_map = {}
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
80
for i, c in zip(range(256), bytes(bytearray(range(256)))):
81
    _safe_map[c] = c if (i < 128 and c in always_safe) else '%{0:02X}'.format(i).encode('ascii')
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
82
_safe_quoters = {}
83
84
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
85
def quote(s, safe=b'/'):
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
86
    """quote('abc def') -> 'abc%20def'
87
88
    Each part of a URL, e.g. the path info, the query, etc., has a
89
    different set of reserved characters that must be quoted.
90
91
    RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
92
    the following reserved characters.
93
94
    reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
95
                  "$" | ","
96
97
    Each of these characters is reserved in some component of a URL,
98
    but not necessarily in all of them.
99
100
    By default, the quote function is intended for quoting the path
101
    section of a URL.  Thus, it will not encode '/'.  This character
102
    is reserved, but in typical usage the quote function is being
103
    called on a path where the existing slash characters are used as
104
    reserved characters.
105
    """
106
    # fastpath
107
    if not s:
108
        if s is None:
109
            raise TypeError('None object cannot be quoted')
110
        return s
111
    cachekey = (safe, always_safe)
112
    try:
113
        (quoter, safe) = _safe_quoters[cachekey]
114
    except KeyError:
115
        safe_map = _safe_map.copy()
116
        safe_map.update([(c, c) for c in safe])
117
        quoter = safe_map.__getitem__
118
        safe = always_safe + safe
119
        _safe_quoters[cachekey] = (quoter, safe)
120
    if not s.rstrip(safe):
121
        return s
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
122
    return b''.join(map(quoter, s))
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
123
124
125
_hexdig = '0123456789ABCDEFabcdef'
126
_hextochr = dict((a + b, chr(int(a + b, 16)))
127
                 for a in _hexdig for b in _hexdig)
128
129
def unquote(s):
130
    """unquote('abc%20def') -> 'abc def'."""
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
131
    res = s.split(b'%')
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
132
    # fastpath
133
    if len(res) == 1:
134
        return s
135
    s = res[0]
136
    for item in res[1:]:
137
        try:
138
            s += _hextochr[item[:2]] + item[2:]
139
        except KeyError:
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
140
            s += b'%' + item
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
141
        except UnicodeDecodeError:
142
            s += unichr(int(item[:2], 16)) + item[2:]
143
    return s
144
145
5268.7.11 by Jelmer Vernooij
revert some unnecessary changes
146
def escape(relpath):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
147
    """Escape relpath to be a valid url."""
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
148
    if isinstance(relpath, text_type):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
149
        relpath = relpath.encode('utf-8')
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
150
    return quote(relpath, safe=b'/~')
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
151
152
1685.1.46 by John Arbash Meinel
Sorting functions by name.
153
def file_relpath(base, path):
154
    """Compute just the relative sub-portion of a url
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
155
1685.1.46 by John Arbash Meinel
Sorting functions by name.
156
    This assumes that both paths are already fully specified file:// URLs.
157
    """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
158
    if len(base) < MIN_ABS_FILEURL_LENGTH:
4539.1.1 by Andrew Bennetts
Improve error message in osutils.file_relpath.
159
        raise ValueError('Length of base (%r) must equal or'
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
160
            ' exceed the platform minimum url length (which is %d)' %
4539.1.1 by Andrew Bennetts
Improve error message in osutils.file_relpath.
161
            (base, MIN_ABS_FILEURL_LENGTH))
6240.4.3 by Martin Packman
Use filesystem rather than url path function to strip terminal slash
162
    base = osutils.normpath(local_path_from_url(base))
163
    path = osutils.normpath(local_path_from_url(path))
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
164
    return escape(osutils.relpath(base, path))
1685.1.46 by John Arbash Meinel
Sorting functions by name.
165
166
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
167
def _find_scheme_and_separator(url):
168
    """Find the scheme separator (://) and the first path separator
169
170
    This is just a helper functions for other path utilities.
171
    It could probably be replaced by urlparse
172
    """
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
173
    m = _url_scheme_re.match(url)
174
    if not m:
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
175
        return None, None
176
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
177
    scheme = m.group('scheme')
178
    path = m.group('path')
179
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
180
    # Find the path separating slash
181
    # (first slash after the ://)
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
182
    first_path_slash = path.find(b'/')
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
183
    if first_path_slash == -1:
1685.1.56 by John Arbash Meinel
Fixing _find_scheme_and_separator
184
        return len(scheme), None
5254.1.1 by Gordon Tyler
Added support to urlutils for URLs such as Launchpad's lp:foobar.
185
    return len(scheme), first_path_slash+m.start('path')
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
186
187
5254.2.1 by Gordon Tyler
Fixed how get_transport's convert_path_to_url tests whether a path is actually a URL.
188
def is_url(url):
189
    """Tests whether a URL is in actual fact a URL."""
190
    return _url_scheme_re.match(url) is not None
191
192
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
193
def join(base, *args):
194
    """Create a URL by joining sections.
195
196
    This will normalize '..', assuming that paths are absolute
197
    (it assumes no symlinks in either path)
198
199
    If any of *args is an absolute URL, it will be treated correctly.
200
    Example:
201
        join('http://foo', 'http://bar') => 'http://bar'
202
        join('http://foo', 'bar') => 'http://foo/bar'
203
        join('http://foo', 'bar', '../baz') => 'http://foo/baz'
204
    """
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
205
    if not args:
206
        return base
5254.1.1 by Gordon Tyler
Added support to urlutils for URLs such as Launchpad's lp:foobar.
207
    scheme_end, path_start = _find_scheme_and_separator(base)
208
    if scheme_end is None and path_start is None:
209
        path_start = 0
210
    elif path_start is None:
211
        path_start = len(base)
212
    path = base[path_start:]
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
213
    for arg in args:
5254.1.1 by Gordon Tyler
Added support to urlutils for URLs such as Launchpad's lp:foobar.
214
        arg_scheme_end, arg_path_start = _find_scheme_and_separator(arg)
215
        if arg_scheme_end is None and arg_path_start is None:
216
            arg_path_start = 0
217
        elif arg_path_start is None:
218
            arg_path_start = len(arg)
5254.1.5 by Gordon Tyler
Fixes according to spiv's review.
219
        if arg_scheme_end is not None:
5254.1.1 by Gordon Tyler
Added support to urlutils for URLs such as Launchpad's lp:foobar.
220
            base = arg
221
            path = arg[arg_path_start:]
222
            scheme_end = arg_scheme_end
223
            path_start = arg_path_start
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
224
        else:
2018.5.54 by Andrew Bennetts
Fix ChrootTransportDecorator's abspath method to be consistent with its clone
225
            path = joinpath(path, arg)
5254.1.1 by Gordon Tyler
Added support to urlutils for URLs such as Launchpad's lp:foobar.
226
    return base[:path_start] + path
1685.1.55 by John Arbash Meinel
Adding bzrlib.urlutils.join() to handle joining URLs
227
228
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
229
def joinpath(base, *args):
230
    """Join URL path segments to a URL path segment.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
231
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
232
    This is somewhat like osutils.joinpath, but intended for URLs.
233
234
    XXX: this duplicates some normalisation logic, and also duplicates a lot of
235
    path handling logic that already exists in some Transport implementations.
236
    We really should try to have exactly one place in the code base responsible
237
    for combining paths of URLs.
238
    """
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
239
    path = base.split(b'/')
240
    if len(path) > 1 and path[-1] == b'':
2018.5.100 by Andrew Bennetts
Fix IndexError in urlutils.join with 'http://host/a' and '../../b'.
241
        #If the path ends in a trailing /, remove it.
242
        path.pop()
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
243
    for arg in args:
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
244
        if arg.startswith(b'/'):
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
245
            path = []
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
246
        for chunk in arg.split(b'/'):
247
            if chunk == b'.':
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
248
                continue
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
249
            elif chunk == b'..':
250
                if path == [b'']:
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
251
                    raise errors.InvalidURLJoin('Cannot go above root',
252
                            base, args)
253
                path.pop()
254
            else:
255
                path.append(chunk)
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
256
    if path == [b'']:
257
        return b'/'
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
258
    else:
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
259
        return b'/'.join(path)
2018.5.46 by Andrew Bennetts
Fix ChrootTransportDecorator's clone to pass less surprising offsets to the decorated transport's clone.
260
261
1685.1.46 by John Arbash Meinel
Sorting functions by name.
262
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
263
def _posix_local_path_from_url(url):
264
    """Convert a url like file:///path/to/foo into /path/to/foo"""
5268.7.21 by Jelmer Vernooij
Cope with segment parameters in urls.
265
    url = split_segment_parameters_raw(url)[0]
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
266
    file_localhost_prefix = b'file://localhost/'
4828.1.1 by Michael Hudson
test and fix
267
    if url.startswith(file_localhost_prefix):
268
        path = url[len(file_localhost_prefix) - 1:]
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
269
    elif not url.startswith(b'file:///'):
4828.1.1 by Michael Hudson
test and fix
270
        raise errors.InvalidURL(
271
            url, 'local urls must start with file:/// or file://localhost/')
272
    else:
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
273
        path = url[len(b'file://'):]
1685.1.46 by John Arbash Meinel
Sorting functions by name.
274
    # We only strip off 2 slashes
4828.1.1 by Michael Hudson
test and fix
275
    return unescape(path)
1685.1.46 by John Arbash Meinel
Sorting functions by name.
276
277
278
def _posix_local_path_to_url(path):
279
    """Convert a local path like ./foo into a URL like file:///path/to/foo
280
281
    This also handles transforming escaping unicode characters, etc.
282
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
283
    # importing directly from posixpath allows us to test this
1685.1.46 by John Arbash Meinel
Sorting functions by name.
284
    # on non-posix platforms
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
285
    return b'file://' + escape(osutils._posix_abspath(path))
1685.1.46 by John Arbash Meinel
Sorting functions by name.
286
287
288
def _win32_local_path_from_url(url):
1711.4.4 by John Arbash Meinel
Fix some broken tests because of stupid ntpath.abspath behavior
289
    """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
290
    if not url.startswith('file://'):
291
        raise errors.InvalidURL(url, 'local urls must start with file:///, '
292
                                     'UNC path urls must start with file://')
5268.7.21 by Jelmer Vernooij
Cope with segment parameters in urls.
293
    url = split_segment_parameters_raw(url)[0]
1685.1.46 by John Arbash Meinel
Sorting functions by name.
294
    # We strip off all 3 slashes
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
295
    win32_url = url[len('file:'):]
2162.2.2 by Alexander Belchenko
Support for win32 UNC path (like: \\HOST\path)
296
    # check for UNC path: //HOST/path
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
297
    if not win32_url.startswith('///'):
2162.2.2 by Alexander Belchenko
Support for win32 UNC path (like: \\HOST\path)
298
        if (win32_url[2] == '/'
299
            or win32_url[3] in '|:'):
300
            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
301
                ' have form file://HOST/path')
2162.2.2 by Alexander Belchenko
Support for win32 UNC path (like: \\HOST\path)
302
        return unescape(win32_url)
3503.1.2 by adwi2
Permits Windows to serve all paths on all drives.
303
304
    # allow empty paths so we can serve all roots
305
    if win32_url == '///':
306
        return '/'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
307
2162.2.2 by Alexander Belchenko
Support for win32 UNC path (like: \\HOST\path)
308
    # usual local path with drive letter
5510.2.3 by Jared Bunting
Changed _win32_local_path_from_url to not allow "file:///C:" form.
309
    if (len(win32_url) < 6
5510.2.1 by Jared Bunting
Modified _win32_local_path_from_url to:
310
        or win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
311
                                'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
312
        or win32_url[4] not in  '|:'
5510.2.3 by Jared Bunting
Changed _win32_local_path_from_url to not allow "file:///C:" form.
313
        or win32_url[5] != '/'):
1711.4.4 by John Arbash Meinel
Fix some broken tests because of stupid ntpath.abspath behavior
314
        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
315
                ' 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
316
    return win32_url[3].upper() + u':' + unescape(win32_url[5:])
1685.1.46 by John Arbash Meinel
Sorting functions by name.
317
318
319
def _win32_local_path_to_url(path):
1711.4.4 by John Arbash Meinel
Fix some broken tests because of stupid ntpath.abspath behavior
320
    """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.
321
322
    This also handles transforming escaping unicode characters, etc.
323
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
324
    # 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
325
    # on non-win32 platform
326
    # FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
327
    #       which actually strips trailing space characters.
5278.1.5 by Martin Pool
Correct more sloppy use of the term 'Linux'
328
    #       The worst part is that on linux ntpath.abspath has different
1711.4.4 by John Arbash Meinel
Fix some broken tests because of stupid ntpath.abspath behavior
329
    #       semantics, since 'nt' is not an available module.
3503.1.1 by Adrian Wilkins
Add a couple of special cases to urlutils._win32_path_(from|to)_url
330
    if path == '/':
3503.1.2 by adwi2
Permits Windows to serve all paths on all drives.
331
        return 'file:///'
3503.1.1 by Adrian Wilkins
Add a couple of special cases to urlutils._win32_path_(from|to)_url
332
2279.4.2 by Alexander Belchenko
Don't do normpath after abspath, because this function is called inside abspath
333
    win32_path = osutils._win32_abspath(path)
2162.2.2 by Alexander Belchenko
Support for win32 UNC path (like: \\HOST\path)
334
    # check for UNC path \\HOST\path
335
    if win32_path.startswith('//'):
2162.2.7 by Alexander Belchenko
Win32 UNC path \\HOST\path mapped to URL file://HOST/path
336
        return 'file:' + escape(win32_path)
3234.3.1 by Alexander Belchenko
ensure that local_path_to_url() always returns plain string, not unicode.
337
    return ('file:///' + str(win32_path[0].upper()) + ':' +
338
        escape(win32_path[2:]))
1685.1.46 by John Arbash Meinel
Sorting functions by name.
339
340
341
local_path_to_url = _posix_local_path_to_url
342
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
343
MIN_ABS_FILEURL_LENGTH = len('file:///')
1711.4.17 by John Arbash Meinel
[merge] bzr.dev 1790
344
WIN32_MIN_ABS_FILEURL_LENGTH = len('file:///C:/')
1685.1.46 by John Arbash Meinel
Sorting functions by name.
345
346
if sys.platform == 'win32':
347
    local_path_to_url = _win32_local_path_to_url
348
    local_path_from_url = _win32_local_path_from_url
349
1711.2.44 by John Arbash Meinel
Factor out another win32 special case and add platform independent tests for it.
350
    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
351
352
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
353
_url_scheme_re = re.compile(b'^(?P<scheme>[^:/]{2,}):(//)?(?P<path>.*)$')
354
_url_hex_escapes_re = re.compile(b'(%[0-9a-fA-F]{2})')
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
355
356
357
def _unescape_safe_chars(matchobj):
358
    """re.sub callback to convert hex-escapes to plain characters (if safe).
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
359
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
360
    e.g. '%7E' will be converted to '~'.
361
    """
362
    hex_digits = matchobj.group(0)[1:]
363
    char = chr(int(hex_digits, 16))
364
    if char in _url_dont_escape_characters:
365
        return char
366
    else:
367
        return matchobj.group(0).upper()
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
368
369
370
def normalize_url(url):
371
    """Make sure that a path string is in fully normalized URL form.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
372
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
373
    This handles URLs which have unicode characters, spaces,
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
374
    special characters, etc.
375
376
    It has two basic modes of operation, depending on whether the
377
    supplied string starts with a url specifier (scheme://) or not.
378
    If it does not have a specifier it is considered a local path,
379
    and will be converted into a file:/// url. Non-ascii characters
380
    will be encoded using utf-8.
381
    If it does have a url specifier, it will be treated as a "hybrid"
382
    URL. Basically, a URL that should have URL special characters already
383
    escaped (like +?&# etc), but may have unicode characters, etc
384
    which would not be valid in a real URL.
385
386
    :param url: Either a hybrid URL or a local path
387
    :return: A normalized URL which only includes 7-bit ASCII characters.
388
    """
5254.1.1 by Gordon Tyler
Added support to urlutils for URLs such as Launchpad's lp:foobar.
389
    scheme_end, path_start = _find_scheme_and_separator(url)
390
    if scheme_end is None:
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
391
        return local_path_to_url(url)
5254.1.1 by Gordon Tyler
Added support to urlutils for URLs such as Launchpad's lp:foobar.
392
    prefix = url[:path_start]
393
    path = url[path_start:]
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
394
    if not isinstance(url, unicode):
395
        for c in url:
396
            if c not in _url_safe_characters:
1685.1.53 by John Arbash Meinel
Updated normalize_url
397
                raise errors.InvalidURL(url, 'URLs can only contain specific'
398
                                            ' safe characters (not %r)' % c)
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
399
        path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
5254.1.1 by Gordon Tyler
Added support to urlutils for URLs such as Launchpad's lp:foobar.
400
        return str(prefix + ''.join(path))
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
401
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
402
    # We have a unicode (hybrid) url
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
403
    path_chars = list(path)
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
404
6651.2.2 by Martin
Apply 2to3 xrange fix and fix up with sixish range
405
    for i in range(len(path_chars)):
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
406
        if path_chars[i] not in _url_safe_characters:
407
            chars = path_chars[i].encode('utf-8')
408
            path_chars[i] = ''.join(
409
                ['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
410
    path = ''.join(path_chars)
411
    path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
5254.1.1 by Gordon Tyler
Added support to urlutils for URLs such as Launchpad's lp:foobar.
412
    return str(prefix + path)
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
413
414
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
415
def relative_url(base, other):
416
    """Return a path to other from base.
417
418
    If other is unrelated to base, return other. Else return a relative path.
419
    This assumes no symlinks as part of the url.
420
    """
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
421
    dummy, base_first_slash = _find_scheme_and_separator(base)
422
    if base_first_slash is None:
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
423
        return other
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
424
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
425
    dummy, other_first_slash = _find_scheme_and_separator(other)
426
    if other_first_slash is None:
427
        return other
428
429
    # this takes care of differing schemes or hosts
430
    base_scheme = base[:base_first_slash]
431
    other_scheme = other[:other_first_slash]
432
    if base_scheme != other_scheme:
433
        return other
3139.2.1 by Alexander Belchenko
bugfix #90847: fix problem with parent location on another logical drive
434
    elif sys.platform == 'win32' and base_scheme == 'file://':
435
        base_drive = base[base_first_slash+1:base_first_slash+3]
436
        other_drive = other[other_first_slash+1:other_first_slash+3]
437
        if base_drive != other_drive:
438
            return other
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
439
440
    base_path = base[base_first_slash+1:]
441
    other_path = other[other_first_slash+1:]
442
443
    if base_path.endswith('/'):
444
        base_path = base_path[:-1]
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
445
446
    base_sections = base_path.split('/')
447
    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
448
449
    if base_sections == ['']:
450
        base_sections = []
451
    if other_sections == ['']:
452
        other_sections = []
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
453
454
    output_sections = []
455
    for b, o in zip(base_sections, other_sections):
456
        if b != o:
457
            break
458
        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
459
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
460
    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
461
    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
462
    output_sections.extend(other_sections[match_len:])
463
464
    return "/".join(output_sections) or "."
465
466
1711.2.43 by John Arbash Meinel
Split out win32 specific code so that it can be tested on all platforms.
467
def _win32_extract_drive_letter(url_base, path):
468
    """On win32 the drive letter needs to be added to the url base."""
469
    # Strip off the drive letter
470
    # path is currently /C:/foo
6123.3.2 by Martin
Treat file:///C: as invalid on windows instead of throwing an IndexError
471
    if len(path) < 4 or path[2] not in ':|' or path[3] != '/':
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
472
        raise errors.InvalidURL(url_base + path,
1711.2.43 by John Arbash Meinel
Split out win32 specific code so that it can be tested on all platforms.
473
            'win32 file:/// paths need a drive letter')
474
    url_base += path[0:3] # file:// + /C:
475
    path = path[3:] # /foo
476
    return url_base, path
477
478
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
479
def split(url, exclude_trailing_slash=True):
480
    """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
481
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
482
    :param url: A relative or absolute URL
483
    :param exclude_trailing_slash: Strip off a final '/' if it is part
484
        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
485
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
486
    :return: (parent_url, child_dir).  child_dir may be the empty string if we're at
1685.1.61 by Martin Pool
[broken] Change BzrDir._make_tail to use urlutils.split
487
        the root.
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
488
    """
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
489
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
490
491
    if first_path_slash is None:
492
        # We have either a relative path, or no separating slash
493
        if scheme_loc is None:
494
            # Relative path
495
            if exclude_trailing_slash and url.endswith('/'):
496
                url = url[:-1]
497
            return _posix_split(url)
498
        else:
499
            # Scheme with no path
500
            return url, ''
501
502
    # We have a fully defined path
503
    url_base = url[:first_path_slash] # http://host, file://
504
    path = url[first_path_slash:] # /file/foo
505
506
    if sys.platform == 'win32' and url.startswith('file:///'):
507
        # 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.
508
        # url_base is currently file://
1711.2.39 by John Arbash Meinel
Fix bzrlib.urlutils.split() to work properly on win32 local paths.
509
        # 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.
510
        url_base, path = _win32_extract_drive_letter(url_base, path)
511
        # now it should be file:///C: and /foo
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
512
513
    if exclude_trailing_slash and len(path) > 1 and path.endswith('/'):
514
        path = path[:-1]
515
    head, tail = _posix_split(path)
516
    return url_base + head, tail
517
1685.1.46 by John Arbash Meinel
Sorting functions by name.
518
5163.2.5 by Jelmer Vernooij
rename {split,join}_subsegments -> {split,join}_segment_parameters_raw and add more tests.
519
def split_segment_parameters_raw(url):
5163.2.1 by Jelmer Vernooij
Add urlutils.split_subsegments.
520
    """Split the subsegment of the last segment of a URL.
521
522
    :param url: A relative or absolute URL
523
    :return: (url, subsegments)
524
    """
6278.1.4 by Martin Packman
Fix fallout on per_transport tests from suspect terminal slash handling
525
    # GZ 2011-11-18: Dodgy removing the terminal slash like this, function
526
    #                operates on urls not url+segments, and Transport classes
6278.1.5 by Martin Packman
Spelling tweaks suggested by vila in review
527
    #                should not be blindly adding slashes in the first place. 
6278.1.4 by Martin Packman
Fix fallout on per_transport tests from suspect terminal slash handling
528
    lurl = strip_trailing_slash(url)
6278.1.5 by Martin Packman
Spelling tweaks suggested by vila in review
529
    # Segments begin at first comma after last forward slash, if one exists
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
530
    segment_start = lurl.find(b",", lurl.rfind(b"/")+1)
6278.1.3 by Martin Packman
Stop using urlutils.split before segment parameters have been removed
531
    if segment_start == -1:
5163.2.1 by Jelmer Vernooij
Add urlutils.split_subsegments.
532
        return (url, [])
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
533
    return (lurl[:segment_start], lurl[segment_start+1:].split(b","))
5163.2.1 by Jelmer Vernooij
Add urlutils.split_subsegments.
534
535
5163.2.3 by Jelmer Vernooij
Add join_segment_parameters / split_segment_parameters.
536
def split_segment_parameters(url):
537
    """Split the segment parameters of the last segment of a URL.
538
539
    :param url: A relative or absolute URL
540
    :return: (url, segment_parameters)
541
    """
5163.2.5 by Jelmer Vernooij
rename {split,join}_subsegments -> {split,join}_segment_parameters_raw and add more tests.
542
    (base_url, subsegments) = split_segment_parameters_raw(url)
5163.2.3 by Jelmer Vernooij
Add join_segment_parameters / split_segment_parameters.
543
    parameters = {}
544
    for subsegment in subsegments:
545
        (key, value) = subsegment.split("=", 1)
546
        parameters[key] = value
547
    return (base_url, parameters)
548
549
5163.2.5 by Jelmer Vernooij
rename {split,join}_subsegments -> {split,join}_segment_parameters_raw and add more tests.
550
def join_segment_parameters_raw(base, *subsegments):
5163.2.7 by Jelmer Vernooij
Add type checking.
551
    """Create a new URL by adding subsegments to an existing one. 
552
553
    This adds the specified subsegments to the last path in the specified
554
    base URL. The subsegments should be bytestrings.
5163.2.2 by Jelmer Vernooij
Add bzrlib.urlutils.join_subsegments.
555
5163.2.5 by Jelmer Vernooij
rename {split,join}_subsegments -> {split,join}_segment_parameters_raw and add more tests.
556
    :note: You probably want to use join_segment_parameters instead.
5163.2.2 by Jelmer Vernooij
Add bzrlib.urlutils.join_subsegments.
557
    """
558
    if not subsegments:
559
        return base
560
    for subsegment in subsegments:
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
561
        if not isinstance(subsegment, str):
5163.2.7 by Jelmer Vernooij
Add type checking.
562
            raise TypeError("Subsegment %r is not a bytestring" % subsegment)
5163.2.2 by Jelmer Vernooij
Add bzrlib.urlutils.join_subsegments.
563
        if "," in subsegment:
564
            raise errors.InvalidURLJoin(", exists in subsegments",
565
                                        base, subsegments)
566
    return ",".join((base,) + subsegments)
567
568
5163.2.3 by Jelmer Vernooij
Add join_segment_parameters / split_segment_parameters.
569
def join_segment_parameters(url, parameters):
570
    """Create a new URL by adding segment parameters to an existing one.
571
5163.2.7 by Jelmer Vernooij
Add type checking.
572
    The parameters of the last segment in the URL will be updated; if a
573
    parameter with the same key already exists it will be overwritten.
574
5163.2.3 by Jelmer Vernooij
Add join_segment_parameters / split_segment_parameters.
575
    :param url: A URL, as string
5163.2.7 by Jelmer Vernooij
Add type checking.
576
    :param parameters: Dictionary of parameters, keys and values as bytestrings
5163.2.3 by Jelmer Vernooij
Add join_segment_parameters / split_segment_parameters.
577
    """
578
    (base, existing_parameters) = split_segment_parameters(url)
579
    new_parameters = {}
580
    new_parameters.update(existing_parameters)
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
581
    for key, value in parameters.items():
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
582
        if not isinstance(key, str):
5163.2.7 by Jelmer Vernooij
Add type checking.
583
            raise TypeError("parameter key %r is not a bytestring" % key)
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
584
        if not isinstance(value, str):
5163.2.7 by Jelmer Vernooij
Add type checking.
585
            raise TypeError("parameter value %r for %s is not a bytestring" %
586
                (key, value))
5163.2.3 by Jelmer Vernooij
Add join_segment_parameters / split_segment_parameters.
587
        if "=" in key:
588
            raise errors.InvalidURLJoin("= exists in parameter key", url,
589
                parameters)
590
        new_parameters[key] = value
5163.2.5 by Jelmer Vernooij
rename {split,join}_subsegments -> {split,join}_segment_parameters_raw and add more tests.
591
    return join_segment_parameters_raw(base, 
5163.2.6 by Jelmer Vernooij
Fix example names in tests.
592
        *["%s=%s" % item for item in sorted(new_parameters.items())])
5163.2.3 by Jelmer Vernooij
Add join_segment_parameters / split_segment_parameters.
593
594
1711.2.44 by John Arbash Meinel
Factor out another win32 special case and add platform independent tests for it.
595
def _win32_strip_local_trailing_slash(url):
596
    """Strip slashes after the drive letter"""
597
    if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
598
        return url[:-1]
599
    else:
600
        return url
601
602
1685.1.47 by John Arbash Meinel
s comes before u
603
def strip_trailing_slash(url):
604
    """Strip trailing slash, except for root paths.
605
606
    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
607
    This assumes that all URLs are valid netloc urls, such that they
608
    form:
609
    scheme://host/path
610
    It searches for ://, and then refuses to remove the next '/'.
611
    It can also handle relative paths
612
    Examples:
613
        path/to/foo       => path/to/foo
614
        path/to/foo/      => path/to/foo
615
        http://host/path/ => http://host/path
616
        http://host/path  => http://host/path
617
        http://host/      => http://host/
618
        file:///          => file:///
619
        file:///foo/      => file:///foo
620
        # This is unique on win32 platforms, and is the only URL
621
        # 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
622
        file:///c|/       => file:///c:/
1685.1.47 by John Arbash Meinel
s comes before u
623
    """
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
624
    if not url.endswith(b'/'):
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
625
        # Nothing to do
626
        return url
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
627
    if sys.platform == 'win32' and url.startswith(b'file://'):
1711.2.44 by John Arbash Meinel
Factor out another win32 special case and add platform independent tests for it.
628
        return _win32_strip_local_trailing_slash(url)
1685.1.80 by Wouter van Heyst
more code cleanup
629
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
630
    scheme_loc, first_path_slash = _find_scheme_and_separator(url)
631
    if scheme_loc is None:
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
632
        # This is a relative path, as it has no scheme
633
        # so just chop off the last character
1685.1.47 by John Arbash Meinel
s comes before u
634
        return url[:-1]
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
635
1685.1.49 by John Arbash Meinel
Added bzrlib.urlutils.split and basename + dirname
636
    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
637
        # Don't chop off anything if the only slash is the path
638
        # separating slash
1685.1.47 by John Arbash Meinel
s comes before u
639
        return url
640
1685.1.48 by John Arbash Meinel
Updated strip_trailing_slash to support lots more url stuff, added tests
641
    return url[:-1]
642
1685.1.47 by John Arbash Meinel
s comes before u
643
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
644
def unescape(url):
645
    """Unescape relpath from url format.
646
647
    This returns a Unicode path from a URL
648
    """
649
    # jam 20060427 URLs are supposed to be ASCII only strings
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
650
    #       If they are passed in as unicode, unquote
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
651
    #       will return a UNICODE string, which actually contains
652
    #       utf-8 bytes. So we have to ensure that they are
653
    #       plain ASCII strings, or the final .decode will
654
    #       try to encode the UNICODE => ASCII, and then decode
655
    #       it into utf-8.
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
656
    if isinstance(url, text_type):
657
        try:
658
            url = url.encode("ascii")
659
        except UnicodeError as e:
660
            raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
1685.1.80 by Wouter van Heyst
more code cleanup
661
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
662
    unquoted = unquote(url)
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
663
    try:
664
        unicode_path = unquoted.decode('utf-8')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
665
    except UnicodeError as e:
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
666
        raise errors.InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
667
    return unicode_path
668
669
670
# These are characters that if escaped, should stay that way
671
_no_decode_chars = ';/?:@&=+$,#'
672
_no_decode_ords = [ord(c) for c in _no_decode_chars]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
673
_no_decode_hex = (['%02x' % o for o in _no_decode_ords]
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
674
                + ['%02X' % o for o in _no_decode_ords])
1685.1.50 by John Arbash Meinel
Added an re for handling scheme paths.
675
_hex_display_map = dict(([('%02x' % o, chr(o)) for o in range(256)]
676
                    + [('%02X' % o, chr(o)) for o in range(256)]))
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
677
#These entries get mapped to themselves
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
678
_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.
679
2208.4.1 by Andrew Bennetts
normalize_url should normalise escaping of unreserved characters, like '~'.
680
# These characters shouldn't be percent-encoded, and it's always safe to
681
# unencode them if they are.
682
_url_dont_escape_characters = set(
683
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
684
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
685
   "0123456789" # Numbers
686
   "-._~"  # Unreserved characters
687
)
688
1685.1.51 by John Arbash Meinel
Working on getting normalize_url working.
689
# These characters should not be escaped
2167.2.2 by Aaron Bentley
Update safe character list
690
_url_safe_characters = set(
691
   "abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
692
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
693
   "0123456789" # Numbers
694
   "_.-!~*'()"  # Unreserved characters
695
   "/;?:@&=+$," # Reserved characters
696
   "%#"         # Extra reserved characters
697
)
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
698
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
699
def unescape_for_display(url, encoding):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
700
    """Decode what you can for a URL, so that we get a nice looking path.
701
702
    This will turn file:// urls into local paths, and try to decode
703
    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.
704
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
705
    Any sections of the URL which can't be represented in the encoding or
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
706
    need to stay as escapes are left alone.
707
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
708
    :param url: A 7-bit ASCII URL
709
    :param encoding: The final output encoding
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
710
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
711
    :return: A unicode string which can be safely encoded into the
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
712
         specified encoding.
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
713
    """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
714
    if encoding is None:
715
        raise ValueError('you cannot specify None for the display encoding')
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
716
    if url.startswith('file://'):
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
717
        try:
718
            path = local_path_from_url(url)
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
719
            path.encode(encoding)
720
            return path
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
721
        except UnicodeError:
722
            return url
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
723
724
    # Split into sections to try to decode utf-8
725
    res = url.split('/')
6651.2.2 by Martin
Apply 2to3 xrange fix and fix up with sixish range
726
    for i in range(1, len(res)):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
727
        escaped_chunks = res[i].split('%')
6651.2.2 by Martin
Apply 2to3 xrange fix and fix up with sixish range
728
        for j in range(1, len(escaped_chunks)):
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
729
            item = escaped_chunks[j]
730
            try:
731
                escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
732
            except KeyError:
733
                # Put back the percent symbol
734
                escaped_chunks[j] = '%' + item
735
            except UnicodeDecodeError:
736
                escaped_chunks[j] = unichr(int(item[:2], 16)) + item[2:]
737
        unescaped = ''.join(escaped_chunks)
738
        try:
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
739
            decoded = unescaped.decode('utf-8')
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
740
        except UnicodeDecodeError:
741
            # If this path segment cannot be properly utf-8 decoded
742
            # after doing unescaping we will just leave it alone
743
            pass
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
744
        else:
745
            try:
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
746
                decoded.encode(encoding)
1685.1.54 by John Arbash Meinel
url_for_display now makes sure output can be properly encoded.
747
            except UnicodeEncodeError:
748
                # If this chunk cannot be encoded in the local
749
                # encoding, then we should leave it alone
750
                pass
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
751
            else:
752
                # Otherwise take the url decoded one
753
                res[i] = decoded
754
    return u'/'.join(res)
2512.4.1 by Ian Clatworthy
Fixes #115491 - 'branch lp:projname' now creates ./projname as exected
755
756
757
def derive_to_location(from_location):
758
    """Derive a TO_LOCATION given a FROM_LOCATION.
759
760
    The normal case is a FROM_LOCATION of http://foo/bar => bar.
761
    The Right Thing for some logical destinations may differ though
762
    because no / may be present at all. In that case, the result is
763
    the full name without the scheme indicator, e.g. lp:foo-bar => foo-bar.
764
    This latter case also applies when a Windows drive
765
    is used without a path, e.g. c:foo-bar => foo-bar.
766
    If no /, path separator or : is found, the from_location is returned.
767
    """
768
    if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
769
        return os.path.basename(from_location.rstrip("/\\"))
770
    else:
771
        sep = from_location.find(":")
772
        if sep > 0:
773
            return from_location[sep+1:]
774
        else:
775
            return from_location
3242.3.26 by Aaron Bentley
Implement rebase_url
776
3242.3.35 by Aaron Bentley
Cleanups and documentation
777
3242.3.26 by Aaron Bentley
Implement rebase_url
778
def _is_absolute(url):
779
    return (osutils.pathjoin('/foo', url) == url)
780
3242.3.35 by Aaron Bentley
Cleanups and documentation
781
3242.3.26 by Aaron Bentley
Implement rebase_url
782
def rebase_url(url, old_base, new_base):
783
    """Convert a relative path from an old base URL to a new base URL.
784
785
    The result will be a relative path.
786
    Absolute paths and full URLs are returned unaltered.
787
    """
788
    scheme, separator = _find_scheme_and_separator(url)
789
    if scheme is not None:
790
        return url
791
    if _is_absolute(url):
792
        return url
793
    old_parsed = urlparse.urlparse(old_base)
794
    new_parsed = urlparse.urlparse(new_base)
795
    if (old_parsed[:2]) != (new_parsed[:2]):
3242.3.33 by Aaron Bentley
Handle relative URL stacking cleanly
796
        raise errors.InvalidRebaseURLs(old_base, new_base)
3242.3.36 by Aaron Bentley
Updates from review comments
797
    return determine_relative_path(new_parsed[2],
3567.2.1 by Michael Hudson
urlutils.rebase_url handles '..' path segments in 'url'
798
                                   join(old_parsed[2], url))
3242.3.26 by Aaron Bentley
Implement rebase_url
799
800
801
def determine_relative_path(from_path, to_path):
802
    """Determine a relative path from from_path to to_path."""
803
    from_segments = osutils.splitpath(from_path)
804
    to_segments = osutils.splitpath(to_path)
805
    count = -1
806
    for count, (from_element, to_element) in enumerate(zip(from_segments,
807
                                                       to_segments)):
808
        if from_element != to_element:
809
            break
810
    else:
811
        count += 1
812
    unique_from = from_segments[count:]
813
    unique_to = to_segments[count:]
814
    segments = (['..'] * len(unique_from) + unique_to)
815
    if len(segments) == 0:
816
        return '.'
817
    return osutils.pathjoin(*segments)
3873.3.1 by Martin Pool
Move Transport._split_url to urlutils, and ad a simple test
818
819
6055.2.7 by Jelmer Vernooij
Change parse_url to URL.from_string.
820
class URL(object):
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
821
    """Parsed URL."""
822
6055.2.7 by Jelmer Vernooij
Change parse_url to URL.from_string.
823
    def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
824
            port, quoted_path):
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
825
        self.scheme = scheme
826
        self.quoted_host = quoted_host
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
827
        self.host = unquote(self.quoted_host)
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
828
        self.quoted_user = quoted_user
829
        if self.quoted_user is not None:
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
830
            self.user = unquote(self.quoted_user)
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
831
        else:
832
            self.user = None
833
        self.quoted_password = quoted_password
834
        if self.quoted_password is not None:
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
835
            self.password = unquote(self.quoted_password)
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
836
        else:
837
            self.password = None
838
        self.port = port
6061.1.4 by Martin Packman
Unescape unreserved characters for quoted_path member of URL class
839
        self.quoted_path = _url_hex_escapes_re.sub(_unescape_safe_chars, quoted_path)
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
840
        self.path = unquote(self.quoted_path)
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
841
6055.2.8 by Jelmer Vernooij
Add repr()
842
    def __eq__(self, other):
843
        return (isinstance(other, self.__class__) and
844
                self.scheme == other.scheme and
845
                self.host == other.host and
846
                self.user == other.user and
847
                self.password == other.password and
848
                self.path == other.path)
849
850
    def __repr__(self):
6055.2.11 by Jelmer Vernooij
Fix tests.
851
        return "<%s(%r, %r, %r, %r, %r, %r)>" % (
6055.2.8 by Jelmer Vernooij
Add repr()
852
            self.__class__.__name__,
6055.2.11 by Jelmer Vernooij
Fix tests.
853
            self.scheme, self.quoted_user, self.quoted_password,
854
            self.quoted_host, self.port, self.quoted_path)
6055.2.8 by Jelmer Vernooij
Add repr()
855
6055.2.6 by Jelmer Vernooij
Split out parse_url.
856
    @classmethod
6055.2.7 by Jelmer Vernooij
Change parse_url to URL.from_string.
857
    def from_string(cls, url):
858
        """Create a URL object from a string.
6055.2.6 by Jelmer Vernooij
Split out parse_url.
859
860
        :param url: URL as bytestring
861
        """
862
        if isinstance(url, unicode):
863
            raise errors.InvalidURL('should be ascii:\n%r' % url)
864
        url = url.encode('utf-8')
865
        (scheme, netloc, path, params,
866
         query, fragment) = urlparse.urlparse(url, allow_fragments=False)
867
        user = password = host = port = None
868
        if '@' in netloc:
869
            user, host = netloc.rsplit('@', 1)
870
            if ':' in user:
871
                user, password = user.split(':', 1)
872
        else:
873
            host = netloc
874
6055.2.14 by Jelmer Vernooij
Fix long line.
875
        if ':' in host and not (host[0] == '[' and host[-1] == ']'):
876
            # there *is* port
6055.2.6 by Jelmer Vernooij
Split out parse_url.
877
            host, port = host.rsplit(':',1)
878
            try:
879
                port = int(port)
880
            except ValueError:
881
                raise errors.InvalidURL('invalid port number %s in url:\n%s' %
882
                                        (port, url))
883
        if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
884
            host = host[1:-1]
885
886
        return cls(scheme, user, password, host, port, path)
887
6055.2.13 by Jelmer Vernooij
Add URL.__str__.
888
    def __str__(self):
889
        netloc = self.quoted_host
890
        if ":" in netloc:
891
            netloc = "[%s]" % netloc
892
        if self.quoted_user is not None:
893
            # Note that we don't put the password back even if we
894
            # have one so that it doesn't get accidentally
895
            # exposed.
896
            netloc = '%s@%s' % (self.quoted_user, netloc)
897
        if self.port is not None:
898
            netloc = '%s:%d' % (netloc, self.port)
899
        return urlparse.urlunparse(
900
            (self.scheme, netloc, self.quoted_path, None, None, None))
901
6055.2.15 by Jelmer Vernooij
Add URL._combine_paths.
902
    @staticmethod
903
    def _combine_paths(base_path, relpath):
904
        """Transform a Transport-relative path to a remote absolute path.
905
906
        This does not handle substitution of ~ but does handle '..' and '.'
907
        components.
908
909
        Examples::
910
911
            t._combine_paths('/home/sarah', 'project/foo')
912
                => '/home/sarah/project/foo'
913
            t._combine_paths('/home/sarah', '../../etc')
914
                => '/etc'
915
            t._combine_paths('/home/sarah', '/etc')
916
                => '/etc'
917
918
        :param base_path: base path
919
        :param relpath: relative url string for relative part of remote path.
920
        :return: urlencoded string for final path.
921
        """
922
        if not isinstance(relpath, str):
923
            raise errors.InvalidURL(relpath)
6061.1.5 by Martin Packman
Unescape unreserved characters in relative portion when combining paths
924
        relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
6055.2.15 by Jelmer Vernooij
Add URL._combine_paths.
925
        if relpath.startswith('/'):
926
            base_parts = []
927
        else:
928
            base_parts = base_path.split('/')
929
        if len(base_parts) > 0 and base_parts[-1] == '':
930
            base_parts = base_parts[:-1]
931
        for p in relpath.split('/'):
932
            if p == '..':
933
                if len(base_parts) == 0:
934
                    # In most filesystems, a request for the parent
935
                    # of root, just returns root.
936
                    continue
937
                base_parts.pop()
938
            elif p == '.':
939
                continue # No-op
940
            elif p != '':
941
                base_parts.append(p)
942
        path = '/'.join(base_parts)
943
        if not path.startswith('/'):
944
            path = '/' + path
945
        return path
946
6055.2.17 by Jelmer Vernooij
Add URL.clone().
947
    def clone(self, offset=None):
948
        """Return a new URL for a path relative to this URL.
949
950
        :param offset: A relative path, already urlencoded
951
        :return: `URL` instance
952
        """
953
        if offset is not None:
954
            relative = unescape(offset).encode('utf-8')
955
            path = self._combine_paths(self.path, relative)
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
956
            path = quote(path, safe="/~")
6055.2.17 by Jelmer Vernooij
Add URL.clone().
957
        else:
958
            path = self.quoted_path
959
        return self.__class__(self.scheme, self.quoted_user,
960
                self.quoted_password, self.quoted_host, self.port,
961
                path)
962
3873.3.1 by Martin Pool
Move Transport._split_url to urlutils, and ad a simple test
963
964
def parse_url(url):
965
    """Extract the server address, the credentials and the path from the url.
966
967
    user, password, host and path should be quoted if they contain reserved
968
    chars.
969
970
    :param url: an quoted url
971
    :return: (scheme, user, password, host, port, path) tuple, all fields
972
        are unquoted.
973
    """
6055.2.7 by Jelmer Vernooij
Change parse_url to URL.from_string.
974
    parsed_url = URL.from_string(url)
6055.2.6 by Jelmer Vernooij
Split out parse_url.
975
    return (parsed_url.scheme, parsed_url.user, parsed_url.password,
976
        parsed_url.host, parsed_url.port, parsed_url.path)