1
# Copyright (C) 2006-2010 Canonical Ltd
2
# Copyright (C) 2018 Breezy Developers
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.
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.
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
18
"""UI location string handling."""
20
from __future__ import absolute_import
25
from .hooks import Hooks
32
class LocationHooks(Hooks):
33
"""Dictionary mapping hook name to a list of callables for location hooks.
37
Hooks.__init__(self, "breezy.location", "hooks")
40
"Possibly rewrite a URL. Called with a URL to rewrite and the "
41
"purpose of the URL.", (3, 0))
44
hooks = LocationHooks()
47
def location_to_url(location, purpose=None):
48
"""Determine a fully qualified URL from a location string.
50
This will try to interpret location as both a URL and a directory path. It
51
will also lookup the location in directories.
53
:param location: Unicode or byte string object with a location
54
:param purpose: Intended method of access (None, 'read' or 'write')
55
:raise InvalidURL: If the location is already a URL, but not valid.
56
:return: Byte string with resulting URL
58
if not isinstance(location, string_types):
59
raise AssertionError("location not a byte or unicode string")
60
from .directory_service import directories
61
location = directories.dereference(location, purpose)
63
# Catch any URLs which are passing Unicode rather than ASCII
65
location = location.encode('ascii')
67
if urlutils.is_url(location):
68
raise urlutils.InvalidURL(path=location,
69
extra='URLs must be properly escaped')
70
location = urlutils.local_path_to_url(location)
73
location = location.decode('ascii')
75
if location.startswith("file:") and not location.startswith("file://"):
76
return urlutils.join(urlutils.local_path_to_url("."), location[5:])
78
if not urlutils.is_url(location):
79
return urlutils.local_path_to_url(location)
81
for hook in hooks['rewrite_url']:
82
location = hook(location, purpose=purpose)