forked from d4nj1/TLPUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.py
87 lines (65 loc) · 2.36 KB
/
file.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
import re
from io import open
from json import load
from os import remove, close, path
from shutil import move
from tempfile import mkstemp
from config import TlpConfig
def get_json_schema_object(objectname) -> dict:
tlpprovidedschema = '/usr/share/tlp-pm/configschema.json'
if path.exists(tlpprovidedschema):
return get_json_schema_object_from_file(objectname, tlpprovidedschema)
else:
return get_json_schema_object_from_file(objectname, 'configschema.json')
def get_json_schema_object_from_file(objectname, filename) -> dict:
jsonfile = open(filename)
jsonobject = load(jsonfile)
return jsonobject[objectname]
def read_tlp_file_config(filename) -> dict:
propertypattern = re.compile('^#?[A-Z_\d]+=')
fileproperties = dict()
fileopener = open(filename)
lines = fileopener.readlines()
fileopener.close()
linenumber = 0
for line in lines:
linenumber += 1
if propertypattern.match(line):
cleanline = line.lstrip().rstrip()
if (cleanline.startswith('#')):
enabled = False
cleanline = cleanline.lstrip('#')
else:
enabled = True
property = cleanline.split('=', maxsplit=1)
propertyname = property[0]
propertyvalue = property[1]
if propertyvalue.startswith('\"') and propertyvalue.endswith('\"'):
isquoted = True
propertyvalue = propertyvalue.lstrip('\"').rstrip('\"')
else:
isquoted = False
fileproperties[propertyname] = TlpConfig(line, linenumber, enabled, propertyname, propertyvalue, isquoted)
return fileproperties
def write_tlp_file_config(changedproperties, filename):
fh, tmpfilename = mkstemp()
newfile = open(tmpfilename, 'w')
oldfile = open(filename)
lines = oldfile.readlines()
oldfile.close()
linenumber = 0
for line in lines:
linenumber += 1
changedline = False
for property in changedproperties:
if line == property[0] and linenumber == property[1]:
newfile.write(property[2] + '\n')
changedline = True
break
if not changedline:
newfile.write(line)
newfile.close()
close(fh)
oldfile.close()
remove(filename)
move(tmpfilename, filename)