comparison configmix/variables.py @ 15:0b1292e920af

Variables: namespaces and filters
author Franz Glasner <f.glasner@feldmann-mg.com>
date Wed, 09 Mar 2016 15:35:46 +0100
parents
children d70b58b0dfb9
comparison
equal deleted inserted replaced
14:36fa039f7e11 15:0b1292e920af
1 # -*- coding: utf-8 -*-
2 r"""Variable expansion: namespaces and filters
3
4 """
5
6 from __future__ import division, absolute_import, print_function
7
8 import os
9 from functools import wraps
10
11 from .compat import PY2, text_to_native_os_str, native_os_str_to_text
12
13
14 __all__ = []
15
16
17 _MARKER = object()
18
19
20 def _envlookup(name, default=_MARKER):
21 """Lookup an environment variable"""
22 try:
23 return native_os_str_to_text(os.environ[name])
24 except KeyError:
25 if default is _MARKER:
26 raise
27 else:
28 return default
29
30
31 _varns_registry = {"ENV": _envlookup}
32
33
34 def lookup_varns(name):
35 return _varns_registry[_normalized(name)]
36
37
38 _filter_registry = {}
39
40
41 def add_filter(name, fn):
42 _filter_registry[_normalized(name)] = fn
43
44
45 def lookup_filter(name):
46 return _filter_registry[_normalized(name)]
47
48
49 def filter(name):
50 """Decorator for a filter function"""
51
52 def _decorator(f):
53
54 @wraps(f)
55 def _f(appconfig, v):
56 return f(appconfig, v)
57
58 add_filter(name, _f)
59 return _f
60
61 return _decorator
62
63
64 def _normalized(name):
65 return name.replace('-', '_')
66
67
68 #
69 # Some pre-defined filter functions
70 #
71 if PY2:
72
73 @filter("urlquote")
74 def urlquote(config, v):
75 """Replace all special characters in string using the ``%xx`` escape"""
76 from urllib import quote
77 return quote(v.encode("utf-8"), safe=b"").decode("utf-8")
78
79 else:
80
81 @filter("urlquote")
82 def urlquote(config, v):
83 """Replace all special characters in string using the ``%xx`` escape"""
84 from urllib.parse import quote
85 return quote(v, safe="")
86
87
88 @filter("saslprep")
89 def saslprep(config, v):
90 """Do a `SASLprep` according to RFC4013 on `v`.
91
92 This is a Stringprep Profile for usernames and passwords
93
94 """
95 import passlib.utils
96 return passlib.utils.saslprep(v)