1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
import urllib
def strip_trailing_slash(path):
"""If path ends with a /, strip it and return the stripped version."""
if len(path) > 0 and path[-1] == '/':
return path[:-1]
else:
return path
def add_trailing_slash(path):
"""If path does not end with /, add it and return."""
if len(path) > 0 and path[-1] == '/':
return path
else:
return path + '/'
def url_split(path):
try:
slash_pos = strip_trailing_slash(path).rindex('/')
return path[:slash_pos+1], path[slash_pos+1:]
except ValueError:
return '', path
def split_trailing_slash(p):
if p[-1] == u'/':
return p[:-1], p[-1]
else:
return p, u''
def get_relative(ref_path, abs_path):
def get_last_agreement(ref_chain, abs_chain):
max_pos = min(len(ref_chain), len(abs_chain))
for i in xrange(max_pos):
if ref_chain[i] != abs_chain[i]:
return i
return max_pos
abs_path, abs_slash = split_trailing_slash(abs_path)
ref_chain = ref_path.split('/')
ref_chain.pop()
abs_chain = abs_path.split('/')
cut_pos = get_last_agreement(ref_chain, abs_chain)
go_up = (len(ref_chain) - cut_pos) * ['..']
go_down = abs_chain[cut_pos:]
result = u'/'.join(go_up + go_down)
if result == '' and abs_slash != '':
return './'
else:
return result + abs_slash
def parent(url):
parent_part, _child_part = url_split(url)
return parent_part
def make_url(url, args={}):
if len(args) > 0:
return u'%s?%s' % (url, urllib.urlencode(sorted(args.iteritems())))
else:
return url
def basename(url):
_parent_part, child_part = url_split(url)
return child_part
|