/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/urlutils.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-18 15:28:38 UTC
  • mto: This revision was merged to the branch mainline in revision 6386.
  • Revision ID: jelmer@samba.org-20111218152838-5wxpfnugk2jd625k
UseĀ absolute_import.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
from __future__ import absolute_import
 
18
 
17
19
"""A collection of function for handling URL operations."""
18
20
 
19
21
import os
22
24
 
23
25
from bzrlib.lazy_import import lazy_import
24
26
lazy_import(globals(), """
25
 
from posixpath import split as _posix_split, normpath as _posix_normpath
 
27
from posixpath import split as _posix_split
26
28
import urllib
27
29
import urlparse
28
30
 
78
80
        raise ValueError('Length of base (%r) must equal or'
79
81
            ' exceed the platform minimum url length (which is %d)' %
80
82
            (base, MIN_ABS_FILEURL_LENGTH))
81
 
    base = local_path_from_url(base)
82
 
    path = local_path_from_url(path)
 
83
    base = osutils.normpath(local_path_from_url(base))
 
84
    path = osutils.normpath(local_path_from_url(path))
83
85
    return escape(osutils.relpath(base, path))
84
86
 
85
87
 
101
103
    first_path_slash = path.find('/')
102
104
    if first_path_slash == -1:
103
105
        return len(scheme), None
104
 
    return len(scheme), first_path_slash+len(scheme)+3
 
106
    return len(scheme), first_path_slash+m.start('path')
 
107
 
 
108
 
 
109
def is_url(url):
 
110
    """Tests whether a URL is in actual fact a URL."""
 
111
    return _url_scheme_re.match(url) is not None
105
112
 
106
113
 
107
114
def join(base, *args):
118
125
    """
119
126
    if not args:
120
127
        return base
121
 
    match = _url_scheme_re.match(base)
122
 
    scheme = None
123
 
    if match:
124
 
        scheme = match.group('scheme')
125
 
        path = match.group('path').split('/')
126
 
        if path[-1:] == ['']:
127
 
            # Strip off a trailing slash
128
 
            # This helps both when we are at the root, and when
129
 
            # 'base' has an extra slash at the end
130
 
            path = path[:-1]
131
 
    else:
132
 
        path = base.split('/')
133
 
 
134
 
    if scheme is not None and len(path) >= 1:
135
 
        host = path[:1]
136
 
        # the path should be represented as an abs path.
137
 
        # we know this must be absolute because of the presence of a URL scheme.
138
 
        remove_root = True
139
 
        path = [''] + path[1:]
140
 
    else:
141
 
        # create an empty host, but dont alter the path - this might be a
142
 
        # relative url fragment.
143
 
        host = []
144
 
        remove_root = False
145
 
 
 
128
    scheme_end, path_start = _find_scheme_and_separator(base)
 
129
    if scheme_end is None and path_start is None:
 
130
        path_start = 0
 
131
    elif path_start is None:
 
132
        path_start = len(base)
 
133
    path = base[path_start:]
146
134
    for arg in args:
147
 
        match = _url_scheme_re.match(arg)
148
 
        if match:
149
 
            # Absolute URL
150
 
            scheme = match.group('scheme')
151
 
            # this skips .. normalisation, making http://host/../../..
152
 
            # be rather strange.
153
 
            path = match.group('path').split('/')
154
 
            # set the host and path according to new absolute URL, discarding
155
 
            # any previous values.
156
 
            # XXX: duplicates mess from earlier in this function.  This URL
157
 
            # manipulation code needs some cleaning up.
158
 
            if scheme is not None and len(path) >= 1:
159
 
                host = path[:1]
160
 
                path = path[1:]
161
 
                # url scheme implies absolute path.
162
 
                path = [''] + path
163
 
            else:
164
 
                # no url scheme we take the path as is.
165
 
                host = []
 
135
        arg_scheme_end, arg_path_start = _find_scheme_and_separator(arg)
 
136
        if arg_scheme_end is None and arg_path_start is None:
 
137
            arg_path_start = 0
 
138
        elif arg_path_start is None:
 
139
            arg_path_start = len(arg)
 
140
        if arg_scheme_end is not None:
 
141
            base = arg
 
142
            path = arg[arg_path_start:]
 
143
            scheme_end = arg_scheme_end
 
144
            path_start = arg_path_start
166
145
        else:
167
 
            path = '/'.join(path)
168
146
            path = joinpath(path, arg)
169
 
            path = path.split('/')
170
 
    if remove_root and path[0:1] == ['']:
171
 
        del path[0]
172
 
    if host:
173
 
        # Remove the leading slash from the path, so long as it isn't also the
174
 
        # trailing slash, which we want to keep if present.
175
 
        if path and path[0] == '' and len(path) > 1:
176
 
            del path[0]
177
 
        path = host + path
178
 
 
179
 
    if scheme is None:
180
 
        return '/'.join(path)
181
 
    return scheme + '://' + '/'.join(path)
 
147
    return base[:path_start] + path
182
148
 
183
149
 
184
150
def joinpath(base, *args):
217
183
# jam 20060502 Sorted to 'l' because the final target is 'local_path_from_url'
218
184
def _posix_local_path_from_url(url):
219
185
    """Convert a url like file:///path/to/foo into /path/to/foo"""
 
186
    url = split_segment_parameters_raw(url)[0]
220
187
    file_localhost_prefix = 'file://localhost/'
221
188
    if url.startswith(file_localhost_prefix):
222
189
        path = url[len(file_localhost_prefix) - 1:]
236
203
    """
237
204
    # importing directly from posixpath allows us to test this
238
205
    # on non-posix platforms
239
 
    return 'file://' + escape(_posix_normpath(
240
 
        osutils._posix_abspath(path)))
 
206
    return 'file://' + escape(osutils._posix_abspath(path))
241
207
 
242
208
 
243
209
def _win32_local_path_from_url(url):
245
211
    if not url.startswith('file://'):
246
212
        raise errors.InvalidURL(url, 'local urls must start with file:///, '
247
213
                                     'UNC path urls must start with file://')
 
214
    url = split_segment_parameters_raw(url)[0]
248
215
    # We strip off all 3 slashes
249
216
    win32_url = url[len('file:'):]
250
217
    # check for UNC path: //HOST/path
260
227
        return '/'
261
228
 
262
229
    # usual local path with drive letter
263
 
    if (win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
264
 
                             'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
 
230
    if (len(win32_url) < 6
 
231
        or win32_url[3] not in ('abcdefghijklmnopqrstuvwxyz'
 
232
                                'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
265
233
        or win32_url[4] not in  '|:'
266
234
        or win32_url[5] != '/'):
267
235
        raise errors.InvalidURL(url, 'Win32 file urls start with'
278
246
    # on non-win32 platform
279
247
    # FIXME: It turns out that on nt, ntpath.abspath uses nt._getfullpathname
280
248
    #       which actually strips trailing space characters.
281
 
    #       The worst part is that under linux ntpath.abspath has different
 
249
    #       The worst part is that on linux ntpath.abspath has different
282
250
    #       semantics, since 'nt' is not an available module.
283
251
    if path == '/':
284
252
        return 'file:///'
303
271
    MIN_ABS_FILEURL_LENGTH = WIN32_MIN_ABS_FILEURL_LENGTH
304
272
 
305
273
 
306
 
_url_scheme_re = re.compile(r'^(?P<scheme>[^:/]{2,})://(?P<path>.*)$')
 
274
_url_scheme_re = re.compile(r'^(?P<scheme>[^:/]{2,}):(//)?(?P<path>.*)$')
307
275
_url_hex_escapes_re = re.compile(r'(%[0-9a-fA-F]{2})')
308
276
 
309
277
 
339
307
    :param url: Either a hybrid URL or a local path
340
308
    :return: A normalized URL which only includes 7-bit ASCII characters.
341
309
    """
342
 
    m = _url_scheme_re.match(url)
343
 
    if not m:
 
310
    scheme_end, path_start = _find_scheme_and_separator(url)
 
311
    if scheme_end is None:
344
312
        return local_path_to_url(url)
345
 
    scheme = m.group('scheme')
346
 
    path = m.group('path')
 
313
    prefix = url[:path_start]
 
314
    path = url[path_start:]
347
315
    if not isinstance(url, unicode):
348
316
        for c in url:
349
317
            if c not in _url_safe_characters:
350
318
                raise errors.InvalidURL(url, 'URLs can only contain specific'
351
319
                                            ' safe characters (not %r)' % c)
352
320
        path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
353
 
        return str(scheme + '://' + ''.join(path))
 
321
        return str(prefix + ''.join(path))
354
322
 
355
323
    # We have a unicode (hybrid) url
356
324
    path_chars = list(path)
362
330
                ['%%%02X' % ord(c) for c in path_chars[i].encode('utf-8')])
363
331
    path = ''.join(path_chars)
364
332
    path = _url_hex_escapes_re.sub(_unescape_safe_chars, path)
365
 
    return str(scheme + '://' + path)
 
333
    return str(prefix + path)
366
334
 
367
335
 
368
336
def relative_url(base, other):
421
389
    """On win32 the drive letter needs to be added to the url base."""
422
390
    # Strip off the drive letter
423
391
    # path is currently /C:/foo
424
 
    if len(path) < 3 or path[2] not in ':|' or path[3] != '/':
 
392
    if len(path) < 4 or path[2] not in ':|' or path[3] != '/':
425
393
        raise errors.InvalidURL(url_base + path,
426
394
            'win32 file:/// paths need a drive letter')
427
395
    url_base += path[0:3] # file:// + /C:
469
437
    return url_base + head, tail
470
438
 
471
439
 
 
440
def split_segment_parameters_raw(url):
 
441
    """Split the subsegment of the last segment of a URL.
 
442
 
 
443
    :param url: A relative or absolute URL
 
444
    :return: (url, subsegments)
 
445
    """
 
446
    # GZ 2011-11-18: Dodgy removing the terminal slash like this, function
 
447
    #                operates on urls not url+segments, and Transport classes
 
448
    #                should not be blindly adding slashes in the first place. 
 
449
    lurl = strip_trailing_slash(url)
 
450
    # Segments begin at first comma after last forward slash, if one exists
 
451
    segment_start = lurl.find(",", lurl.rfind("/")+1)
 
452
    if segment_start == -1:
 
453
        return (url, [])
 
454
    return (lurl[:segment_start], lurl[segment_start+1:].split(","))
 
455
 
 
456
 
 
457
def split_segment_parameters(url):
 
458
    """Split the segment parameters of the last segment of a URL.
 
459
 
 
460
    :param url: A relative or absolute URL
 
461
    :return: (url, segment_parameters)
 
462
    """
 
463
    (base_url, subsegments) = split_segment_parameters_raw(url)
 
464
    parameters = {}
 
465
    for subsegment in subsegments:
 
466
        (key, value) = subsegment.split("=", 1)
 
467
        parameters[key] = value
 
468
    return (base_url, parameters)
 
469
 
 
470
 
 
471
def join_segment_parameters_raw(base, *subsegments):
 
472
    """Create a new URL by adding subsegments to an existing one. 
 
473
 
 
474
    This adds the specified subsegments to the last path in the specified
 
475
    base URL. The subsegments should be bytestrings.
 
476
 
 
477
    :note: You probably want to use join_segment_parameters instead.
 
478
    """
 
479
    if not subsegments:
 
480
        return base
 
481
    for subsegment in subsegments:
 
482
        if type(subsegment) is not str:
 
483
            raise TypeError("Subsegment %r is not a bytestring" % subsegment)
 
484
        if "," in subsegment:
 
485
            raise errors.InvalidURLJoin(", exists in subsegments",
 
486
                                        base, subsegments)
 
487
    return ",".join((base,) + subsegments)
 
488
 
 
489
 
 
490
def join_segment_parameters(url, parameters):
 
491
    """Create a new URL by adding segment parameters to an existing one.
 
492
 
 
493
    The parameters of the last segment in the URL will be updated; if a
 
494
    parameter with the same key already exists it will be overwritten.
 
495
 
 
496
    :param url: A URL, as string
 
497
    :param parameters: Dictionary of parameters, keys and values as bytestrings
 
498
    """
 
499
    (base, existing_parameters) = split_segment_parameters(url)
 
500
    new_parameters = {}
 
501
    new_parameters.update(existing_parameters)
 
502
    for key, value in parameters.iteritems():
 
503
        if type(key) is not str:
 
504
            raise TypeError("parameter key %r is not a bytestring" % key)
 
505
        if type(value) is not str:
 
506
            raise TypeError("parameter value %r for %s is not a bytestring" %
 
507
                (key, value))
 
508
        if "=" in key:
 
509
            raise errors.InvalidURLJoin("= exists in parameter key", url,
 
510
                parameters)
 
511
        new_parameters[key] = value
 
512
    return join_segment_parameters_raw(base, 
 
513
        *["%s=%s" % item for item in sorted(new_parameters.items())])
 
514
 
 
515
 
472
516
def _win32_strip_local_trailing_slash(url):
473
517
    """Strip slashes after the drive letter"""
474
518
    if len(url) > WIN32_MIN_ABS_FILEURL_LENGTH:
693
737
    return osutils.pathjoin(*segments)
694
738
 
695
739
 
 
740
class URL(object):
 
741
    """Parsed URL."""
 
742
 
 
743
    def __init__(self, scheme, quoted_user, quoted_password, quoted_host,
 
744
            port, quoted_path):
 
745
        self.scheme = scheme
 
746
        self.quoted_host = quoted_host
 
747
        self.host = urllib.unquote(self.quoted_host)
 
748
        self.quoted_user = quoted_user
 
749
        if self.quoted_user is not None:
 
750
            self.user = urllib.unquote(self.quoted_user)
 
751
        else:
 
752
            self.user = None
 
753
        self.quoted_password = quoted_password
 
754
        if self.quoted_password is not None:
 
755
            self.password = urllib.unquote(self.quoted_password)
 
756
        else:
 
757
            self.password = None
 
758
        self.port = port
 
759
        self.quoted_path = _url_hex_escapes_re.sub(_unescape_safe_chars, quoted_path)
 
760
        self.path = urllib.unquote(self.quoted_path)
 
761
 
 
762
    def __eq__(self, other):
 
763
        return (isinstance(other, self.__class__) and
 
764
                self.scheme == other.scheme and
 
765
                self.host == other.host and
 
766
                self.user == other.user and
 
767
                self.password == other.password and
 
768
                self.path == other.path)
 
769
 
 
770
    def __repr__(self):
 
771
        return "<%s(%r, %r, %r, %r, %r, %r)>" % (
 
772
            self.__class__.__name__,
 
773
            self.scheme, self.quoted_user, self.quoted_password,
 
774
            self.quoted_host, self.port, self.quoted_path)
 
775
 
 
776
    @classmethod
 
777
    def from_string(cls, url):
 
778
        """Create a URL object from a string.
 
779
 
 
780
        :param url: URL as bytestring
 
781
        """
 
782
        if isinstance(url, unicode):
 
783
            raise errors.InvalidURL('should be ascii:\n%r' % url)
 
784
        url = url.encode('utf-8')
 
785
        (scheme, netloc, path, params,
 
786
         query, fragment) = urlparse.urlparse(url, allow_fragments=False)
 
787
        user = password = host = port = None
 
788
        if '@' in netloc:
 
789
            user, host = netloc.rsplit('@', 1)
 
790
            if ':' in user:
 
791
                user, password = user.split(':', 1)
 
792
        else:
 
793
            host = netloc
 
794
 
 
795
        if ':' in host and not (host[0] == '[' and host[-1] == ']'):
 
796
            # there *is* port
 
797
            host, port = host.rsplit(':',1)
 
798
            try:
 
799
                port = int(port)
 
800
            except ValueError:
 
801
                raise errors.InvalidURL('invalid port number %s in url:\n%s' %
 
802
                                        (port, url))
 
803
        if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
 
804
            host = host[1:-1]
 
805
 
 
806
        return cls(scheme, user, password, host, port, path)
 
807
 
 
808
    def __str__(self):
 
809
        netloc = self.quoted_host
 
810
        if ":" in netloc:
 
811
            netloc = "[%s]" % netloc
 
812
        if self.quoted_user is not None:
 
813
            # Note that we don't put the password back even if we
 
814
            # have one so that it doesn't get accidentally
 
815
            # exposed.
 
816
            netloc = '%s@%s' % (self.quoted_user, netloc)
 
817
        if self.port is not None:
 
818
            netloc = '%s:%d' % (netloc, self.port)
 
819
        return urlparse.urlunparse(
 
820
            (self.scheme, netloc, self.quoted_path, None, None, None))
 
821
 
 
822
    @staticmethod
 
823
    def _combine_paths(base_path, relpath):
 
824
        """Transform a Transport-relative path to a remote absolute path.
 
825
 
 
826
        This does not handle substitution of ~ but does handle '..' and '.'
 
827
        components.
 
828
 
 
829
        Examples::
 
830
 
 
831
            t._combine_paths('/home/sarah', 'project/foo')
 
832
                => '/home/sarah/project/foo'
 
833
            t._combine_paths('/home/sarah', '../../etc')
 
834
                => '/etc'
 
835
            t._combine_paths('/home/sarah', '/etc')
 
836
                => '/etc'
 
837
 
 
838
        :param base_path: base path
 
839
        :param relpath: relative url string for relative part of remote path.
 
840
        :return: urlencoded string for final path.
 
841
        """
 
842
        if not isinstance(relpath, str):
 
843
            raise errors.InvalidURL(relpath)
 
844
        relpath = _url_hex_escapes_re.sub(_unescape_safe_chars, relpath)
 
845
        if relpath.startswith('/'):
 
846
            base_parts = []
 
847
        else:
 
848
            base_parts = base_path.split('/')
 
849
        if len(base_parts) > 0 and base_parts[-1] == '':
 
850
            base_parts = base_parts[:-1]
 
851
        for p in relpath.split('/'):
 
852
            if p == '..':
 
853
                if len(base_parts) == 0:
 
854
                    # In most filesystems, a request for the parent
 
855
                    # of root, just returns root.
 
856
                    continue
 
857
                base_parts.pop()
 
858
            elif p == '.':
 
859
                continue # No-op
 
860
            elif p != '':
 
861
                base_parts.append(p)
 
862
        path = '/'.join(base_parts)
 
863
        if not path.startswith('/'):
 
864
            path = '/' + path
 
865
        return path
 
866
 
 
867
    def clone(self, offset=None):
 
868
        """Return a new URL for a path relative to this URL.
 
869
 
 
870
        :param offset: A relative path, already urlencoded
 
871
        :return: `URL` instance
 
872
        """
 
873
        if offset is not None:
 
874
            relative = unescape(offset).encode('utf-8')
 
875
            path = self._combine_paths(self.path, relative)
 
876
            path = urllib.quote(path, safe="/~")
 
877
        else:
 
878
            path = self.quoted_path
 
879
        return self.__class__(self.scheme, self.quoted_user,
 
880
                self.quoted_password, self.quoted_host, self.port,
 
881
                path)
 
882
 
696
883
 
697
884
def parse_url(url):
698
885
    """Extract the server address, the credentials and the path from the url.
701
888
    chars.
702
889
 
703
890
    :param url: an quoted url
704
 
 
705
891
    :return: (scheme, user, password, host, port, path) tuple, all fields
706
892
        are unquoted.
707
893
    """
708
 
    if isinstance(url, unicode):
709
 
        raise errors.InvalidURL('should be ascii:\n%r' % url)
710
 
    url = url.encode('utf-8')
711
 
    (scheme, netloc, path, params,
712
 
     query, fragment) = urlparse.urlparse(url, allow_fragments=False)
713
 
    user = password = host = port = None
714
 
    if '@' in netloc:
715
 
        user, host = netloc.rsplit('@', 1)
716
 
        if ':' in user:
717
 
            user, password = user.split(':', 1)
718
 
            password = urllib.unquote(password)
719
 
        user = urllib.unquote(user)
720
 
    else:
721
 
        host = netloc
722
 
 
723
 
    if ':' in host and not (host[0] == '[' and host[-1] == ']'): #there *is* port
724
 
        host, port = host.rsplit(':',1)
725
 
        try:
726
 
            port = int(port)
727
 
        except ValueError:
728
 
            raise errors.InvalidURL('invalid port number %s in url:\n%s' %
729
 
                                    (port, url))
730
 
    if host != "" and host[0] == '[' and host[-1] == ']': #IPv6
731
 
        host = host[1:-1]
732
 
 
733
 
    host = urllib.unquote(host)
734
 
    path = urllib.unquote(path)
735
 
 
736
 
    return (scheme, user, password, host, port, path)
 
894
    parsed_url = URL.from_string(url)
 
895
    return (parsed_url.scheme, parsed_url.user, parsed_url.password,
 
896
        parsed_url.host, parsed_url.port, parsed_url.path)