1
# Bazaar -- distributed version control
3
# Copyright (C) 2006 Canonical Ltd
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
"""A collection of function for handling URL operations."""
25
from bzrlib.lazy_import import lazy_import
26
lazy_import(globals(), """
27
from posixpath import split as _posix_split, normpath as _posix_normpath
38
def basename(url, exclude_trailing_slash=True):
39
"""Return the last component of a URL.
41
:param url: The URL in question
42
:param exclude_trailing_slash: If the url looks like "path/to/foo/"
43
ignore the final slash and return 'foo' rather than ''
44
:return: Just the final component of the URL. This can return ''
45
if you don't exclude_trailing_slash, or if you are at the
48
return split(url, exclude_trailing_slash=exclude_trailing_slash)[1]
51
def dirname(url, exclude_trailing_slash=True):
52
"""Return the parent directory of the given path.
54
:param url: Relative or absolute URL
55
:param exclude_trailing_slash: Remove a final slash
56
(treat http://host/foo/ as http://host/foo, but
57
http://host/ stays http://host/)
58
:return: Everything in the URL except the last path chunk
60
# TODO: jam 20060502 This was named dirname to be consistent
61
# with the os functions, but maybe "parent" would be better
62
return split(url, exclude_trailing_slash=exclude_trailing_slash)[0]
66
"""Escape relpath to be a valid url."""
67
if isinstance(relpath, unicode):
68
relpath = relpath.encode('utf-8')
69
# After quoting and encoding, the path should be perfectly
70
# safe as a plain ASCII string, str() just enforces this
71
return str(urllib.quote(relpath))
74
def file_relpath(base, path):
75
"""Compute just the relative sub-portion of a url
77
This assumes that both paths are already fully specified file:// URLs.
79
if len(base) < MIN_ABS_FILEURL_LENGTH:
80
raise ValueError('Length of base must be equal or'
81
' exceed the platform minimum url length (which is %d)' %
82
MIN_ABS_FILEURL_LENGTH)
83
base = local_path_from_url(base)
84
path = local_path_from_url(path)
85
return escape(osutils.relpath(base, path))
88
def _find_scheme_and_separator(url):
89
"""Find the scheme separator (://) and the first path separator
91
This is just a helper functions for other path utilities.
92
It could probably be replaced by urlparse
94
m = _url_scheme_re.match(url)
98
scheme = m.group('scheme')
99
path = m.group('path')
101
# Find the path separating slash
102
# (first slash after the ://)
103
first_path_slash = path.find('/')
104
if first_path_slash == -1:
105
return len(scheme), None
106
return len(scheme), first_path_slash+len(scheme)+3
109
def join(base, *args):
110
"""Create a URL by joining sections.
112
This will normalize '..', assuming that paths are absolute
113
(it assumes no symlinks in either path)
115
If any of *args is an absolute URL, it will be treated correctly.
117
join('http://foo', 'http://bar') => 'http://bar'
118
join('http://foo', 'bar') => 'http://foo/bar'
119
join('http://foo', 'bar', '../baz') => 'http://foo/baz'
123
match = _url_scheme_re.match(base)
126
scheme = match.group('scheme')
127
path = match.group('path').split('/')
128
if path[-1:] == ['']:
129
# Strip off a trailing slash
130
# This helps both when we are at the root, and when
131
# 'base' has an extra slash at the end
134
path = base.split('/')
136
if scheme is not None and len(path) >= 1:
138
# the path should be represented as an abs path.
139
# we know this must be absolute because of the presence of a URL scheme.
141
path = [''] + path[1:]
143
# create an empty host, but dont alter the path - this might be a
144
# relative url fragment.
149
match = _url_scheme_re.match(arg)
152
scheme = match.group('scheme')
153
# this skips .. normalisation, making http://host/../../..
155
path = match.group('path').split('/')
156
# set the host and path according to new absolute URL, discarding
157
# any previous values.
158
# XXX: duplicates mess from earlier in this function. This URL
159
# manipulation code needs some cleaning up.
160
if scheme is not None and len(path) >= 1:
163
# url scheme implies absolute path.
166
# no url scheme we take the path as is.
169
path = '/'.join(path)
170
path = joinpath(path, arg)
171
path = path.split('/')
172
if remove_root and path[0:1] == ['']:
175
# Remove the leading slash from the path, so long as it isn't also the
176
# trailing slash, which we want to keep if present.
177
if path and path[0] == '' and len(path) > 1:
182
return '/'.join(path)
183
return scheme + '://' + '/'.join(path)
186
def joinpath(base, *args):
187
"""Join URL path segments to a URL path segment.
189
This is somewhat like osutils.joinpath, but intended for URLs.
191
XXX: this duplicates some normalisation logic, and also duplicates a lot of
192
path handling logic that already exists in some Transport implementations.
193
We really should try to have exactly one place in the code base responsible
194
for combining paths of URLs.
196
path = base.split('/')
197
if len(path) > 1 and path[-1] == '':
198
#If the path ends in a trailing /, remove it.
201
if arg.startswith('/'):
203
for chunk in arg.split('/'):
208
raise errors.InvalidURLJoin('Cannot go above root',
216
return '/'.join(path)
219
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
220
def _posix_local_path_from_url(url):
221
"""Convert a url like file:///path/to/foo into /path/to/foo"""
222
if not url.startswith('file:///'):
223
raise errors.InvalidURL(url, 'local urls must start with file:///')
224
# We only strip off 2 slashes
225
return unescape(url[len('file://'):])
228
def _posix_local_path_to_url(path):
229
"""Convert a local path like ./foo into a URL like file:///path/to/foo
231
This also handles transforming escaping unicode characters, etc.
233
# importing directly from posixpath allows us to test this
234
# on non-posix platforms
235
return 'file://' + escape(_posix_normpath(
236
osutils._posix_abspath(path)))
239
def _win32_local_path_from_url(url):
240
"""Convert a url like file:///C:/path/to/foo into C:/path/to/foo"""
241
if not url.startswith('file://'):
242
raise errors.InvalidURL(url, 'local urls must start with file:///, '
243
'UNC path urls must start with file://')
244
# We strip off all 3 slashes
245
win32_url = url[len('file:'):]
246
# check for UNC path: //HOST/path
247
if not win32_url.startswith('///'):
248
if (win32_url[2] == '/'
249
or win32_url[3] in '|:'):
250
raise errors.InvalidURL(url, 'Win32 UNC path urls'
251
' have form file://HOST/path')
252
return unescape(win32_url)
253
# usual local path with drive letter
254
if (win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
255
'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
256
or win32_url[4] not in '|:'
257
or win32_url[5] != '/'):
258
raise errors.InvalidURL(url, 'Win32 file urls start with'
259
' file:///x:/, where x is a valid drive letter')
260
return win32_url[3].upper() + u':' + unescape(win32_url[5:])
263
def _win32_local_path_to_url(path):
264
"""Convert a local path like ./foo into a URL like file:///C:/path/to/foo
266
This also handles transforming escaping unicode characters, etc.
268
# importing directly from ntpath allows us to test this
269
# on non-win32 platform
270
# FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
271
# which actually strips trailing space characters.
272
# The worst part is that under linux ntpath.abspath has different
273
# semantics, since 'nt' is not an available module.
274
win32_path = osutils._win32_abspath(path)
275
# check for UNC path \\HOST\path
276
if win32_path.startswith('//'):
277
return 'file:' + escape(win32_path)
278
return ('file:///' + str(win32_path[0].upper()) + ':' +
279
escape(win32_path[2:]))
282
local_path_to_url = _posix_local_path_to_url
283
local_path_from_url = _posix_local_path_from_url
284
MIN_ABS_FILEURL_LENGTH = len('file:///')
285
WIN32_MIN_ABS_FILEURL_LENGTH = len('file:///C:/')
287
if sys.platform == 'win32':
288
local_path_to_url = _win32_local_path_to_url
289
local_path_from_url = _win32_local_path_from_url
291
MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
294
_url_scheme_re = re.compile(r'^(?P<scheme>[^:/]{2,})://(?P<path>.*)$')
295
_url_hex_escapes_re = re.compile(r'(%[0-9a-fA-F]{2})')
298
def _unescape_safe_chars(matchobj):
299
"""re.sub callback to convert hex-escapes to plain characters (if safe).
301
e.g. '%7E' will be converted to '~'.
303
hex_digits = matchobj.group(0)[1:]
304
char = chr(int(hex_digits, 16))
305
if char in _url_dont_escape_characters:
308
return matchobj.group(0).upper()
311
def normalize_url(url):
312
"""Make sure that a path string is in fully normalized URL form.
314
This handles URLs which have unicode characters, spaces,
315
special characters, etc.
317
It has two basic modes of operation, depending on whether the
318
supplied string starts with a url specifier (scheme://) or not.
319
If it does not have a specifier it is considered a local path,
320
and will be converted into a file:/// url. Non-ascii characters
321
will be encoded using utf-8.
322
If it does have a url specifier, it will be treated as a "hybrid"
323
URL. Basically, a URL that should have URL special characters already
324
escaped (like +?&# etc), but may have unicode characters, etc
325
which would not be valid in a real URL.
327
:param url: Either a hybrid URL or a local path
328
:return: A normalized URL which only includes 7-bit ASCII characters.
330
m = _url_scheme_re.match(url)
332
return local_path_to_url(url)
333
scheme = m.group('scheme')
334
path = m.group('path')
335
if not isinstance(url, unicode):
337
if c not in _url_safe_characters:
338
raise errors.InvalidURL(url, 'URLs can only contain specific'
339
' safe characters (not %r)' % c)
340
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
341
return str(scheme + '://' + ''.join(path))
343
# We have a unicode (hybrid) url
344
path_chars = list(path)
346
for i in xrange(len(path_chars)):
347
if path_chars[i] not in _url_safe_characters:
348
chars = path_chars[i].encode('utf-8')
349
path_chars[i] = ''.join(
350
['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
351
path = ''.join(path_chars)
352
path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
353
return str(scheme + '://' + path)
356
def relative_url(base, other):
357
"""Return a path to other from base.
359
If other is unrelated to base, return other. Else return a relative path.
360
This assumes no symlinks as part of the url.
362
dummy, base_first_slash = _find_scheme_and_separator(base)
363
if base_first_slash is None:
366
dummy, other_first_slash = _find_scheme_and_separator(other)
367
if other_first_slash is None:
370
# this takes care of differing schemes or hosts
371
base_scheme = base[:base_first_slash]
372
other_scheme = other[:other_first_slash]
373
if base_scheme != other_scheme:
375
elif sys.platform == 'win32' and base_scheme == 'file://':
376
base_drive = base[base_first_slash+1:base_first_slash+3]
377
other_drive = other[other_first_slash+1:other_first_slash+3]
378
if base_drive != other_drive:
381
base_path = base[base_first_slash+1:]
382
other_path = other[other_first_slash+1:]
384
if base_path.endswith('/'):
385
base_path = base_path[:-1]
387
base_sections = base_path.split('/')
388
other_sections = other_path.split('/')
390
if base_sections == ['']:
392
if other_sections == ['']:
396
for b, o in zip(base_sections, other_sections):
399
output_sections.append(b)
401
match_len = len(output_sections)
402
output_sections = ['..' for x in base_sections[match_len:]]
403
output_sections.extend(other_sections[match_len:])
405
return "/".join(output_sections) or "."
408
def _win32_extract_drive_letter(url_base, path):
409
"""On win32 the drive letter needs to be added to the url base."""
410
# Strip off the drive letter
411
# path is currently /C:/foo
412
if len(path) < 3 or path[2] not in ':|' or path[3] != '/':
413
raise errors.InvalidURL(url_base + path,
414
'win32 file:/// paths need a drive letter')
415
url_base += path[0:3] # file:// + /C:
416
path = path[3:] # /foo
417
return url_base, path
420
def split(url, exclude_trailing_slash=True):
421
"""Split a URL into its parent directory and a child directory.
423
:param url: A relative or absolute URL
424
:param exclude_trailing_slash: Strip off a final '/' if it is part
425
of the path (but not if it is part of the protocol specification)
427
:return: (parent_url, child_dir). child_dir may be the empty string if we're at
430
scheme_loc, first_path_slash = _find_scheme_and_separator(url)
432
if first_path_slash is None:
433
# We have either a relative path, or no separating slash
434
if scheme_loc is None:
436
if exclude_trailing_slash and url.endswith('/'):
438
return _posix_split(url)
440
# Scheme with no path
443
# We have a fully defined path
444
url_base = url[:first_path_slash] # http://host, file://
445
path = url[first_path_slash:] # /file/foo
447
if sys.platform == 'win32' and url.startswith('file:///'):
448
# Strip off the drive letter
449
# url_base is currently file://
450
# path is currently /C:/foo
451
url_base, path = _win32_extract_drive_letter(url_base, path)
452
# now it should be file:///C: and /foo
454
if exclude_trailing_slash and len(path) > 1 and path.endswith('/'):
456
head, tail = _posix_split(path)
457
return url_base + head, tail
460
def _win32_strip_local_trailing_slash(url):
461
"""Strip slashes after the drive letter"""
462
if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
468
def strip_trailing_slash(url):
469
"""Strip trailing slash, except for root paths.
471
The definition of 'root path' is platform-dependent.
472
This assumes that all URLs are valid netloc urls, such that they
475
It searches for ://, and then refuses to remove the next '/'.
476
It can also handle relative paths
478
path/to/foo => path/to/foo
479
path/to/foo/ => path/to/foo
480
http://host/path/ => http://host/path
481
http://host/path => http://host/path
482
http://host/ => http://host/
484
file:///foo/ => file:///foo
485
# This is unique on win32 platforms, and is the only URL
486
# format which does it differently.
487
file:///c|/ => file:///c:/
489
if not url.endswith('/'):
492
if sys.platform == 'win32' and url.startswith('file://'):
493
return _win32_strip_local_trailing_slash(url)
495
scheme_loc, first_path_slash = _find_scheme_and_separator(url)
496
if scheme_loc is None:
497
# This is a relative path, as it has no scheme
498
# so just chop off the last character
501
if first_path_slash is None or first_path_slash == len(url)-1:
502
# Don't chop off anything if the only slash is the path
510
"""Unescape relpath from url format.
512
This returns a Unicode path from a URL
514
# jam 20060427 URLs are supposed to be ASCII only strings
515
# If they are passed in as unicode, urllib.unquote
516
# will return a UNICODE string, which actually contains
517
# utf-8 bytes. So we have to ensure that they are
518
# plain ASCII strings, or the final .decode will
519
# try to encode the UNICODE => ASCII, and then decode
523
except UnicodeError, e:
524
raise errors.InvalidURL(url, 'URL was not a plain ASCII url: %s' % (e,))
526
unquoted = urllib.unquote(url)
528
unicode_path = unquoted.decode('utf-8')
529
except UnicodeError, e:
530
raise errors.InvalidURL(url, 'Unable to encode the URL as utf-8: %s' % (e,))
534
# These are characters that if escaped, should stay that way
535
_no_decode_chars = ';/?:@&=+$,#'
536
_no_decode_ords = [ord(c) for c in _no_decode_chars]
537
_no_decode_hex = (['%02x' % o for o in _no_decode_ords]
538
+ ['%02X' % o for o in _no_decode_ords])
539
_hex_display_map = dict(([('%02x' % o, chr(o)) for o in range(256)]
540
+ [('%02X' % o, chr(o)) for o in range(256)]))
541
#These entries get mapped to themselves
542
_hex_display_map.update((hex,'%'+hex) for hex in _no_decode_hex)
544
# These characters shouldn't be percent-encoded, and it's always safe to
545
# unencode them if they are.
546
_url_dont_escape_characters = set(
547
"abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
548
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
549
"0123456789" # Numbers
550
"-._~" # Unreserved characters
553
# These characters should not be escaped
554
_url_safe_characters = set(
555
"abcdefghijklmnopqrstuvwxyz" # Lowercase alpha
556
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Uppercase alpha
557
"0123456789" # Numbers
558
"_.-!~*'()" # Unreserved characters
559
"/;?:@&=+$," # Reserved characters
560
"%#" # Extra reserved characters
563
def unescape_for_display(url, encoding):
564
"""Decode what you can for a URL, so that we get a nice looking path.
566
This will turn file:// urls into local paths, and try to decode
567
any portions of a http:// style url that it can.
569
Any sections of the URL which can't be represented in the encoding or
570
need to stay as escapes are left alone.
572
:param url: A 7-bit ASCII URL
573
:param encoding: The final output encoding
575
:return: A unicode string which can be safely encoded into the
579
raise ValueError('you cannot specify None for the display encoding')
580
if url.startswith('file://'):
582
path = local_path_from_url(url)
583
path.encode(encoding)
588
# Split into sections to try to decode utf-8
590
for i in xrange(1, len(res)):
591
escaped_chunks = res[i].split('%')
592
for j in xrange(1, len(escaped_chunks)):
593
item = escaped_chunks[j]
595
escaped_chunks[j] = _hex_display_map[item[:2]] + item[2:]
597
# Put back the percent symbol
598
escaped_chunks[j] = '%' + item
599
except UnicodeDecodeError:
600
escaped_chunks[j] = unichr(int(item[:2], 16)) + item[2:]
601
unescaped = ''.join(escaped_chunks)
603
decoded = unescaped.decode('utf-8')
604
except UnicodeDecodeError:
605
# If this path segment cannot be properly utf-8 decoded
606
# after doing unescaping we will just leave it alone
610
decoded.encode(encoding)
611
except UnicodeEncodeError:
612
# If this chunk cannot be encoded in the local
613
# encoding, then we should leave it alone
616
# Otherwise take the url decoded one
618
return u'/'.join(res)
621
def derive_to_location(from_location):
622
"""Derive a TO_LOCATION given a FROM_LOCATION.
624
The normal case is a FROM_LOCATION of http://foo/bar => bar.
625
The Right Thing for some logical destinations may differ though
626
because no / may be present at all. In that case, the result is
627
the full name without the scheme indicator, e.g. lp:foo-bar => foo-bar.
628
This latter case also applies when a Windows drive
629
is used without a path, e.g. c:foo-bar => foo-bar.
630
If no /, path separator or : is found, the from_location is returned.
632
if from_location.find("/") >= 0 or from_location.find(os.sep) >= 0:
633
return os.path.basename(from_location.rstrip("/\\"))
635
sep = from_location.find(":")
637
return from_location[sep+1:]
642
def _is_absolute(url):
643
return (osutils.pathjoin('/foo', url) == url)
646
def rebase_url(url, old_base, new_base):
647
"""Convert a relative path from an old base URL to a new base URL.
649
The result will be a relative path.
650
Absolute paths and full URLs are returned unaltered.
652
scheme, separator = _find_scheme_and_separator(url)
653
if scheme is not None:
655
if _is_absolute(url):
657
old_parsed = urlparse.urlparse(old_base)
658
new_parsed = urlparse.urlparse(new_base)
659
if (old_parsed[:2]) != (new_parsed[:2]):
660
raise errors.InvalidRebaseURLs(old_base, new_base)
661
return determine_relative_path(new_parsed[2],
662
osutils.pathjoin(old_parsed[2], url))
665
def determine_relative_path(from_path, to_path):
666
"""Determine a relative path from from_path to to_path."""
667
from_segments = osutils.splitpath(from_path)
668
to_segments = osutils.splitpath(to_path)
670
for count, (from_element, to_element) in enumerate(zip(from_segments,
672
if from_element != to_element:
676
unique_from = from_segments[count:]
677
unique_to = to_segments[count:]
678
segments = (['..'] * len(unique_from) + unique_to)
679
if len(segments) == 0:
681
return osutils.pathjoin(*segments)