File: merge-systemd-units.py

package info (click to toggle)
libvirt 11.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 209,020 kB
  • sloc: ansic: 535,831; xml: 321,783; python: 11,974; perl: 2,626; sh: 2,185; makefile: 448; javascript: 126; cpp: 22
file content (104 lines) | stat: -rwxr-xr-x 2,159 bytes parent folder | download | duplicates (4)
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
#!/usr/bin/env python3

# Copyright (C) 2023 Red Hat, Inc.
# SPDX-License-Identifier: LGPL-2.1-or-later

import sys

SECTIONS = [
    "[Unit]",
    "[Service]",
    "[Socket]",
    "[Install]",
]


def parse_unit(unit_path):
    unit = {}
    current_section = "[Invalid]"

    with open(unit_path) as f:
        for line in f:
            line = line.strip()

            if line == "":
                continue

            # Comments at the very top of the file, outside of any
            # section, are allowed and will not show up in the output
            if line[0] == "#" and current_section == "[Invalid]":
                continue

            if line[0] == "[" and line[-1] == "]":
                if line not in SECTIONS:
                    print("Unknown section {}".format(line))
                    sys.exit(1)

                current_section = line
                continue

            if current_section not in unit:
                unit[current_section] = []

            unit[current_section].append(line)

    if "[Invalid]" in unit:
        print("Contents found outside of any section")
        sys.exit(1)

    return unit


def format_unit(unit):
    lines = []

    for section in SECTIONS:
        if section not in unit:
            continue

        lines.append(section)

        for line in unit[section]:
            lines.append(line)

        lines.append("")

    return "\n".join(lines)


def merge_units(base, extra):
    merged = {}

    for section in SECTIONS:
        if section in extra and section not in base:
            print("Section {} in extra but not in base".format(section))
            sys.exit(1)

        if section not in base:
            continue

        merged[section] = base[section]

        if section not in extra:
            continue

        merged[section].extend(extra[section])

    return merged


prog = sys.argv[0]
args = sys.argv[1:]

if len(args) < 1:
    print("usage: {} BASE [EXTRA]...".format(prog))
    sys.exit(1)

merged = parse_unit(args[0])

for arg in args[1:]:
    extra = parse_unit(arg)

    merged = merge_units(merged, extra)

sys.stdout.write(format_unit(merged))