summaryrefslogtreecommitdiffstats
path: root/hostinfo/prefix.py
blob: 7233c48c23053e32242a2eb1fe8c72a25e44e00e (plain)
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
# -*- coding: utf-8 -*-

class Flags:
    oneline: bool = False
    nospaces: bool = False


class Printer:
    flags = Flags()

    def __init__(self, full_key='', printer=None):
        if printer is None:
            self.output = print
        else:
            self.output = printer.pprint

        self.parent = printer
        self.empty = self.__class__.flags.oneline
        self.full_key = full_key
        self.has_output = False
        self.label = ''

    def set_label(self, label='', maxlength=0):
        self.label = self._get_label(label, maxlength)

    def _get_label(self, label: str, maxlength: int):
        if label == '':
            return label

        label = "%s: " % label
        if self.parent is None or self.parent.full_key == '':
            if self.__class__.flags.nospaces:
                return label.rjust(maxlength+4)
            else:
                return (label + "  ").rjust(maxlength+6)
        else:
            return label.ljust(maxlength+2)

    def pprint(self, data: str):
        self.output("%s%s" % (self.label, data))
        self.has_output = True
        if not self.empty:
            self.label = ' ' * len(self.label)
            self.empty = True

    def space(self, force=False):
        if not self.__class__.flags.nospaces:
            if self.has_output or force:
                self.output('')