This repository was archived by the owner on Mar 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathUtils.py
93 lines (72 loc) · 2.4 KB
/
Utils.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
__version__ = "v0.2.0"
import json
import os
import re
import sys
dirpath = os.path.join(os.path.dirname(__file__), 'lib')
if dirpath not in sys.path:
sys.path.append(dirpath)
import sqlparse
# Regular expression for comments
comment_re = re.compile(
'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
re.DOTALL | re.MULTILINE
)
def parseJson(filename):
""" Parse a JSON file
First remove comments and then use the json module package
Comments look like :
// ...
or
/*
...
*/
"""
with open(filename, mode='r', encoding='utf-8') as f:
content = ''.join(f.readlines())
# Looking for comments
match = comment_re.search(content)
while match:
# single line comment
content = content[:match.start()] + content[match.end():]
match = comment_re.search(content)
# remove trailing commas
content = re.sub(r',([ \t\r\n]+)}', r'\1}', content)
content = re.sub(r',([ \t\r\n]+)\]', r'\1]', content)
# Return json file
return json.loads(content, encoding='utf-8')
def saveJson(content, filename):
with open(filename, mode='w', encoding='utf-8') as outfile:
json.dump(content, outfile,
sort_keys=True, indent=2, separators=(',', ': '))
def getResultAsList(results):
resultList = []
for result in results.splitlines():
lineResult = ''
for element in result.strip('|').split('|'):
lineResult += element.strip()
if lineResult:
resultList.append(lineResult)
return resultList
def formatSql(raw, settings):
try:
result = sqlparse.format(raw, **settings)
return result
except Exception:
return None
def merge(source, destination):
"""
run me with nosetests --with-doctest file.py
>>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
>>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
>>> merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
True
"""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
merge(value, node)
else:
destination[key] = value
return destination