comparison src/tools/common/regex.py @ 1920:03526c8abeb0

tools (common): added regex module with path (un)escaping methods
author Goffi <goffi@goffi.org>
date Tue, 22 Mar 2016 22:46:04 +0100
parents
children 2daf7b4c6756
comparison
equal deleted inserted replaced
1919:d3354c80bd1f 1920:03526c8abeb0
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Salut à Toi: an XMPP client
5 # Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org)
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 """ regex tools common to backend and frontends """
21
22 import re
23 path_escape = {'%': '%25', '/': '%2F', '\\': '%5c'}
24 path_escape_rev = {re.escape(v):k for k, v in path_escape.iteritems()}
25 path_escape = {re.escape(k):v for k, v in path_escape.iteritems()}
26
27
28 def reJoin(exps):
29 """Join (OR) various regexes"""
30 return re.compile('|'.join(exps))
31
32
33 def reSubDict(pattern, repl_dict, string):
34 """Replace key, value found in dict according to pattern
35
36 @param pattern(basestr): pattern using keys found in repl_dict
37 @repl_dict(dict): keys found in this dict will be replaced by
38 corresponding values
39 @param string(basestr): string to use for the replacement
40 """
41 return pattern.sub(lambda m: repl_dict[re.escape(m.group(0))], string)
42
43 path_escape_re = reJoin(path_escape.keys())
44 path_escape_rev_re = reJoin(path_escape_rev.keys())
45
46
47 def pathEscape(string):
48 """Escape string so it can be use in a file path
49
50 @param string(basestr): string to escape
51 @return (str, unicode): escaped string, usable in a file path
52 """
53 return reSubDict(path_escape_re, path_escape, string)
54
55
56 def pathUnescape(string):
57 """Unescape string from value found in file path
58
59 @param string(basestr): string found in file path
60 @return (str, unicode): unescaped string
61 """
62 return reSubDict(path_escape_rev_re, path_escape_rev, string)