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