/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 breezy/location.py

  • Committer: Jelmer Vernooij
  • Date: 2020-02-07 02:14:30 UTC
  • mto: This revision was merged to the branch mainline in revision 7492.
  • Revision ID: jelmer@jelmer.uk-20200207021430-m49iq3x4x8xlib6x
Drop python2 support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2010 Canonical Ltd
 
2
# Copyright (C) 2018 Breezy Developers
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
 
 
18
"""UI location string handling."""
 
19
 
 
20
from __future__ import absolute_import
 
21
 
 
22
import re
 
23
 
 
24
from . import (
 
25
    urlutils,
 
26
    )
 
27
from .hooks import Hooks
 
28
 
 
29
 
 
30
class LocationHooks(Hooks):
 
31
    """Dictionary mapping hook name to a list of callables for location hooks.
 
32
    """
 
33
 
 
34
    def __init__(self):
 
35
        Hooks.__init__(self, "breezy.location", "hooks")
 
36
        self.add_hook(
 
37
            'rewrite_url',
 
38
            "Possibly rewrite a URL. Called with a URL to rewrite and the "
 
39
            "purpose of the URL.", (3, 0))
 
40
 
 
41
 
 
42
hooks = LocationHooks()
 
43
 
 
44
 
 
45
def rcp_location_to_url(location, scheme='ssh'):
 
46
    """Convert a rcp-style location to a URL.
 
47
 
 
48
    :param location: Location to convert, e.g. "foo:bar"
 
49
    :param schenme: URL scheme to return, defaults to "ssh"
 
50
    :return: A URL, e.g. "ssh://foo/bar"
 
51
    :raises ValueError: if this is not a RCP-style URL
 
52
    """
 
53
    m = re.match('^(?P<user>[^@:/]+@)?(?P<host>[^/:]+):(?P<path>.*)$', location)
 
54
    if not m:
 
55
        raise ValueError("Not a RCP URL")
 
56
    if m.group('path').startswith('//'):
 
57
        raise ValueError("Not a RCP URL: already looks like a URL")
 
58
    quoted_user = urlutils.quote(m.group('user')[:-1]) if m.group('user') else None
 
59
    url = urlutils.URL(
 
60
        scheme=scheme, quoted_user=quoted_user,
 
61
        port=None, quoted_password=None,
 
62
        quoted_host=urlutils.quote(m.group('host')),
 
63
        quoted_path=urlutils.quote(m.group('path')))
 
64
    return str(url)
 
65
 
 
66
 
 
67
def pserver_to_url(location):
 
68
    """Convert a CVS pserver location string to a URL.
 
69
 
 
70
    :param location: pserver URL
 
71
    :return: A cvs+pserver URL
 
72
    """
 
73
    parts = location.split(':')
 
74
    if parts[0] or parts[1] != 'pserver':
 
75
        raise ValueError('not a valid pserver location string')
 
76
    try:
 
77
        (username, hostname) = parts[2].split('@', 1)
 
78
    except IndexError:
 
79
        hostname = parts[2]
 
80
        username = None
 
81
    return str(urlutils.URL(
 
82
        scheme='cvs+pserver',
 
83
        quoted_user=urlutils.quote(username) if username else None,
 
84
        quoted_host=urlutils.quote(hostname),
 
85
        quoted_password=None,
 
86
        port=None,
 
87
        quoted_path=urlutils.quote(parts[3])))
 
88
 
 
89
 
 
90
def location_to_url(location, purpose=None):
 
91
    """Determine a fully qualified URL from a location string.
 
92
 
 
93
    This will try to interpret location as both a URL and a directory path. It
 
94
    will also lookup the location in directories.
 
95
 
 
96
    :param location: Unicode or byte string object with a location
 
97
    :param purpose: Intended method of access (None, 'read' or 'write')
 
98
    :raise InvalidURL: If the location is already a URL, but not valid.
 
99
    :return: Byte string with resulting URL
 
100
    """
 
101
    if not isinstance(location, str):
 
102
        raise AssertionError("location not a byte or unicode string")
 
103
 
 
104
    if location.startswith(':pserver:'):
 
105
        return pserver_to_url(location)
 
106
 
 
107
    from .directory_service import directories
 
108
    location = directories.dereference(location, purpose)
 
109
 
 
110
    # Catch any URLs which are passing Unicode rather than ASCII
 
111
    try:
 
112
        location = location.encode('ascii')
 
113
    except UnicodeError:
 
114
        if urlutils.is_url(location):
 
115
            raise urlutils.InvalidURL(
 
116
                path=location, extra='URLs must be properly escaped')
 
117
        location = urlutils.local_path_to_url(location)
 
118
    else:
 
119
        location = location.decode('ascii')
 
120
 
 
121
    if location.startswith("file:") and not location.startswith("file://"):
 
122
        return urlutils.join(urlutils.local_path_to_url("."), location[5:])
 
123
 
 
124
    try:
 
125
        url = rcp_location_to_url(location, scheme="ssh")
 
126
    except ValueError:
 
127
        pass
 
128
    else:
 
129
        return url
 
130
 
 
131
    if not urlutils.is_url(location):
 
132
        return urlutils.local_path_to_url(location)
 
133
 
 
134
    for hook in hooks['rewrite_url']:
 
135
        location = hook(location, purpose=purpose)
 
136
 
 
137
    return location