/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-03-22 01:35:14 UTC
  • mfrom: (7490.7.6 work)
  • mto: This revision was merged to the branch mainline in revision 7499.
  • Revision ID: jelmer@jelmer.uk-20200322013514-7vw1ntwho04rcuj3
merge lp:brz/3.1.

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
import re
 
21
 
 
22
from . import (
 
23
    urlutils,
 
24
    )
 
25
from .hooks import Hooks
 
26
 
 
27
 
 
28
class LocationHooks(Hooks):
 
29
    """Dictionary mapping hook name to a list of callables for location hooks.
 
30
    """
 
31
 
 
32
    def __init__(self):
 
33
        Hooks.__init__(self, "breezy.location", "hooks")
 
34
        self.add_hook(
 
35
            'rewrite_url',
 
36
            "Possibly rewrite a URL. Called with a URL to rewrite and the "
 
37
            "purpose of the URL.", (3, 0))
 
38
 
 
39
 
 
40
hooks = LocationHooks()
 
41
 
 
42
 
 
43
def rcp_location_to_url(location, scheme='ssh'):
 
44
    """Convert a rcp-style location to a URL.
 
45
 
 
46
    :param location: Location to convert, e.g. "foo:bar"
 
47
    :param schenme: URL scheme to return, defaults to "ssh"
 
48
    :return: A URL, e.g. "ssh://foo/bar"
 
49
    :raises ValueError: if this is not a RCP-style URL
 
50
    """
 
51
    m = re.match('^(?P<user>[^@:/]+@)?(?P<host>[^/:]+):(?P<path>.*)$', location)
 
52
    if not m:
 
53
        raise ValueError("Not a RCP URL")
 
54
    if m.group('path').startswith('//'):
 
55
        raise ValueError("Not a RCP URL: already looks like a URL")
 
56
    quoted_user = urlutils.quote(m.group('user')[:-1]) if m.group('user') else None
 
57
    url = urlutils.URL(
 
58
        scheme=scheme, quoted_user=quoted_user,
 
59
        port=None, quoted_password=None,
 
60
        quoted_host=urlutils.quote(m.group('host')),
 
61
        quoted_path=urlutils.quote(m.group('path')))
 
62
    return str(url)
 
63
 
 
64
 
 
65
def pserver_to_url(location):
 
66
    """Convert a CVS pserver location string to a URL.
 
67
 
 
68
    :param location: pserver URL
 
69
    :return: A cvs+pserver URL
 
70
    """
 
71
    parts = location.split(':')
 
72
    if parts[0] or parts[1] != 'pserver':
 
73
        raise ValueError('not a valid pserver location string')
 
74
    try:
 
75
        (username, hostname) = parts[2].split('@', 1)
 
76
    except IndexError:
 
77
        hostname = parts[2]
 
78
        username = None
 
79
    return str(urlutils.URL(
 
80
        scheme='cvs+pserver',
 
81
        quoted_user=urlutils.quote(username) if username else None,
 
82
        quoted_host=urlutils.quote(hostname),
 
83
        quoted_password=None,
 
84
        port=None,
 
85
        quoted_path=urlutils.quote(parts[3])))
 
86
 
 
87
 
 
88
def location_to_url(location, purpose=None):
 
89
    """Determine a fully qualified URL from a location string.
 
90
 
 
91
    This will try to interpret location as both a URL and a directory path. It
 
92
    will also lookup the location in directories.
 
93
 
 
94
    :param location: Unicode or byte string object with a location
 
95
    :param purpose: Intended method of access (None, 'read' or 'write')
 
96
    :raise InvalidURL: If the location is already a URL, but not valid.
 
97
    :return: Byte string with resulting URL
 
98
    """
 
99
    if not isinstance(location, str):
 
100
        raise AssertionError("location not a byte or unicode string")
 
101
 
 
102
    if location.startswith(':pserver:'):
 
103
        return pserver_to_url(location)
 
104
 
 
105
    from .directory_service import directories
 
106
    location = directories.dereference(location, purpose)
 
107
 
 
108
    # Catch any URLs which are passing Unicode rather than ASCII
 
109
    try:
 
110
        location = location.encode('ascii')
 
111
    except UnicodeError:
 
112
        if urlutils.is_url(location):
 
113
            raise urlutils.InvalidURL(
 
114
                path=location, extra='URLs must be properly escaped')
 
115
        location = urlutils.local_path_to_url(location)
 
116
    else:
 
117
        location = location.decode('ascii')
 
118
 
 
119
    if location.startswith("file:") and not location.startswith("file://"):
 
120
        return urlutils.join(urlutils.local_path_to_url("."), location[5:])
 
121
 
 
122
    try:
 
123
        url = rcp_location_to_url(location, scheme="ssh")
 
124
    except ValueError:
 
125
        pass
 
126
    else:
 
127
        return url
 
128
 
 
129
    if not urlutils.is_url(location):
 
130
        return urlutils.local_path_to_url(location)
 
131
 
 
132
    for hook in hooks['rewrite_url']:
 
133
        location = hook(location, purpose=purpose)
 
134
 
 
135
    return location