-
Notifications
You must be signed in to change notification settings - Fork 2
/
systemd2nix.py
executable file
·167 lines (139 loc) · 4.48 KB
/
systemd2nix.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#!/usr/bin/env python3
import json
import re
import sys
from argparse import ArgumentParser
class Keys:
# list of options that move to the top level of the nix attrset
# The 'Environment' option is not listed because it is processed by `parse_environment()`
list_of_strings = [
'after',
'before',
'bindsTo',
'conflicts',
'documentation',
'partOf',
'requiredBy',
'requires',
'requisite',
'wantedBy',
'wants',
]
rest = [
'description',
'onFailure',
'postStart',
'postStop',
'preStart',
'preStop',
'reload',
'reloadIfChanged',
'restartIfChanged',
'restartTriggers',
'startAt',
'startLimitIntervalSec',
'stopIfChanged',
]
all = list_of_strings + rest
def key2nix(key: str):
# convert to camel case
return key[0].lower() + key[1:]
def parse_environment(env: str) -> dict:
separated = env.strip().split(' ')
return dict(map(lambda s: s.split('='), separated))
def format_config(conf: dict) -> dict:
new_conf = dict(environment={})
if 'Install' in conf:
for key, val in conf["Install"].items():
key = key2nix(key)
new_conf[key] = val
if "Service" in conf:
if "Environment" in conf['Service']:
new_conf['environment'] = parse_environment(conf['Service']['Environment'])
del conf['Service']['Environment']
new_conf['serviceConfig'] = conf['Service']
if "Unit" in conf:
for key, val in conf['Unit'].items():
key = key2nix(key)
if key in Keys.all:
new_conf[key] = val
else:
if 'unitConfig' not in conf:
new_conf['unitConfig'] = {}
new_conf['unitConfig'][key] = val
# convert some values to list of strings
for key in Keys.list_of_strings:
if key not in new_conf:
continue
new_conf[key] = new_conf[key].strip().split(' ')
return new_conf
def sort_dict(nix_dict: dict) -> dict:
new_dict = {}
for key in list(sorted(Keys.all)) + ["environment", "unitConfig", "serviceConfig"]:
if key in nix_dict:
new_dict[key] = nix_dict[key]
return new_dict
def dict2nix(d: dict) -> str:
s = json.dumps(d, indent=2)
splitter = ' "environment": {'
head, rest = s.split(splitter)
rest = splitter + rest
head = head.\
replace('":', ' =').\
replace('],', '];'). \
replace('",\n ]', '"\n ]'). \
replace('",\n "', '"\n "'). \
replace('",\n', '";\n'). \
replace('\n "', '\n ')
rest = rest.\
replace(' "', ' ').\
replace('":', ' =').\
replace('",\n', '";\n').\
replace('"\n', '";\n').\
replace(' {},', ' {};').\
replace(' },', ' };').\
replace(' }\n', ' };\n')
return head + rest
def parse_unit_file(file_content: str) -> dict:
config = {}
section = None
for line in file_content.splitlines():
# match section headers like '[Unit]'
match = re.fullmatch(r"^\[(\w*)\]$", line)
if match:
section = match.groups()[0]
if section not in config:
config[section] = {}
continue
# match key-value pairs with quotes
match = re.fullmatch(r'^(\w*)="(.*)"$', line)
# match key-value pairs without quotes
if not match:
match = re.fullmatch(r"^(\w*)=(.*)$", line)
if not match:
continue
if not section:
print("ERROR: Entry without section", file=sys.stderr)
exit(1)
key, val = match.groups()
# option assignment with empty value resets option
if key not in config[section] or val == '':
config[section][key] = []
config[section][key].append(val)
for section in config.values():
for key, val in section.items():
section[key] = ' '.join(val)
return config
def parse_args():
parser = ArgumentParser(
description="Convert systemd service files to nix syntax for nixpkgs",
usage='systemd2nix < example.service')
return parser.parse_args()
def main():
parse_args() # just to display usage
_input = sys.stdin.read()
config = parse_unit_file(_input)
formatted = format_config(config)
print(dict2nix(sort_dict(formatted)))
if __name__ == '__main__':
main()