-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.py
65 lines (52 loc) · 1.71 KB
/
helpers.py
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
"""various helper for both the document and the parser"""
import os
import json
from jinja2 import environmentfilter
from xmlcommandparser.exceptions import InvalidPathException
@environmentfilter
def sanitize_filepath(env, value):
"""a jinja2 filter that converts relative to absolute path
:return: str the absolute path to the resource
"""
norm_value = os.path.normpath(value)
for loader_path in env.loader.searchpath:
abspath = os.path.abspath(loader_path)
filepath = os.path.join(abspath, norm_value)
if os.path.isfile(filepath):
return filepath
raise InvalidPathException("Path is not a valid filename: {}".format(norm_value))
def tojson(value):
"""converts a value in json format escaping the quote '"' symbol
:param mixed: value
:return: str the value in json format
"""
if hasattr(value, 'replace'):
value = value.replace('"', '"')
return json.dumps(value)
def fromjson(value):
"""decode a value from json format escaping the quote '"' symbol
:param mixed: value
:return: str the value in json format
"""
value = json.loads(value)
if hasattr(value, 'replace'):
value = value.replace('"', '"')
return value
def xmlcommand(fnc):
"""Decorator for marking functions as xml command"""
fnc.__xmlcommand__ = True
return fnc
MACRO="""
{%- macro attr_json(key, value) -%}
json:{{key}}="{{value|tojson}}"
{%- endmacro -%}
{%- macro attr_int(key, value) -%}
int:{{key}}="{{value|string}}"
{%- endmacro -%}
{%- macro attr_float(key, value) -%}
float:{{key}}="{{value|string}}"
{%- endmacro -%}
{%- macro attr_path(key, value) -%}
path:{{key}}="{{value|string}}"
{%- endmacro -%}
"""