File: _deb822.py

package info (click to toggle)
python-apt 2.6.0
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,044 kB
  • sloc: cpp: 10,192; python: 8,547; makefile: 94; sh: 18
file content (121 lines) | stat: -rw-r--r-- 2,822 bytes parent folder | download
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (C) Canonical Ltd
#
# SPDX-License-Identifier: GPL-2.0+

"""deb822 parser with support for comment headers and footers."""

import io
import collections
import typing

import apt_pkg


T = typing.TypeVar("T")


class Section:
    """A single deb822 section, possibly with comments.

    This represents a single deb822 section.
    """

    def __init__(self, section: str):
        comments = ["", ""]
        in_section = False
        trimmed_section = ""

        for line in section.split("\n"):
            if line.startswith("#"):
                # remove the leading #
                line = line[1:]
                comments[in_section] += line + "\n"
                continue

            in_section = True
            trimmed_section += line + "\n"

        self.tags = collections.OrderedDict(apt_pkg.TagSection(trimmed_section))
        self.header, self.footer = comments

    def __getitem__(self, key: str) -> str:
        """Get the value of a field."""
        return self.tags[key]

    def __delitem__(self, key: str) -> None:
        """Delete a field"""
        del self.tags[key]

    def __setitem__(self, key: str, val: str) -> None:
        """Set the value of a field."""
        self.tags[key] = val

    def __bool__(self) -> bool:
        return bool(self.tags)

    @typing.overload
    def get(self, key: str) -> typing.Optional[str]:
        ...

    @typing.overload
    def get(self, key: str, default: T) -> typing.Union[T, str]:
        ...

    def get(
        self, key: str, default: typing.Optional[T] = None
    ) -> typing.Union[typing.Optional[T], str]:
        try:
            return self.tags[key]
        except KeyError:
            return default

    @staticmethod
    def __comment_lines(content: str) -> str:
        return (
            "\n".join("#" + line for line in content.splitlines()) + "\n"
            if content
            else ""
        )

    def __str__(self) -> str:
        """Canonical string rendering of this section."""
        return (
            self.__comment_lines(self.header)
            + "".join(f"{k}: {v}\n" for k, v in self.tags.items())
            + self.__comment_lines(self.footer)
        )


class File:
    """
    Parse a given file object into a list of Section objects.
    """

    def __init__(self, fobj: io.TextIOBase):
        sections = fobj.read().split("\n\n")
        self.sections = [Section(s) for s in sections]

    def __iter__(self) -> typing.Iterator[Section]:
        return iter(self.sections)

    def __str__(self) -> str:
        return "\n\n".join(str(s) for s in self.sections)


if __name__ == "__main__":
    st = """# Header
# More header
K1: V1
# Inline
K2: V2
 # not a comment
# Footer
# More footer
"""

    s = Section(st)

    print(s)