File: nsd.py

package info (click to toggle)
python-reconfigure 0.1.81%2Bgit20171214.2b8729a8-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 724 kB
  • sloc: python: 4,219; makefile: 186; sh: 7
file content (50 lines) | stat: -rw-r--r-- 1,628 bytes parent folder | download | duplicates (3)
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
from reconfigure.nodes import *
from reconfigure.parsers import BaseParser


class NSDParser (BaseParser):
    """
    A parser for NSD DNS server nsd.conf file
    """

    def parse(self, content):
        lines = content.splitlines()
        root = RootNode()
        last_comment = None
        node = root
        for line in lines:
            line = line.strip()
            if line:
                if line.startswith('#'):
                    c = line.strip('#').strip()
                    if last_comment:
                        last_comment += '\n' + c
                    else:
                        last_comment = c
                    continue

                key, value = line.split(':')
                value = value.strip()
                key = key.strip()
                if key in ['server', 'zone', 'key']:
                    node = Node(key, comment=last_comment)
                    root.append(node)
                else:
                    node.append(PropertyNode(key, value, comment=last_comment))
                last_comment = None
        return root

    def stringify_comment(self, line, comment):
        if comment:
            return ''.join('# %s\n' % x for x in comment.splitlines()) + line
        return line

    def stringify(self, tree):
        r = ''
        for node in tree.children:
            r += self.stringify_comment(node.name + ':', node.comment) + '\n'
            for subnode in node.children:
                l = '%s: %s' % (subnode.name, subnode.value)
                r += self.stringify_comment(l, subnode.comment) + '\n'
            r += '\n'
        return r