summaryrefslogtreecommitdiff
path: root/libre/mkosi/patch.py
blob: 7d1a28086fb38ebb0fc9fe8847ad134ee2834f8c (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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#!/usr/bin/env python3
# Copyright (C) 2022 Denis 'GNUtoo' Carikli <GNUtoo@cyberdimension.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
import copy
import re

class TextSection(object):
    def __init__(self, name, start=None, end=None):
        self.name = name
        self.start = start
        self.end = end
        self.distros = []
    def set_start(self, start):
        self.start = start
    def set_end(self, end):
        self.end = end
    def get_start(self):
        return self.start
    def get_end(self):
        return self.end
    def get_distros(self):
        return self.distros
    def set_distros(self, distros):
        self.distros = distros
    def __str__(self):
        return "{} section: start={} end={} distros={}".format(
            self.name,
            self.start,
            self.end,
            self.distros)
    def __repr__(self):
        return self.__str__()

class Parser(object):
    def __init__(self):
        self._file_path = 'src/mkosi-11/mkosi.md'
        self._d_arg_section = TextSection("d_arg")
        self._file_section = TextSection("file")
        self._stock_distros = []
        self._distros = []
        self.text = ""

        self._sections = []
        self._parse_d_arg_section()
        self._parse_file_section()

    def _parse_d_arg_section(self):
        r = ""
        before = ": The distribution to install in the image. Takes one of the following arguments:".split(" ")
        i = 1
        for e in before:
            r += '.*'
            r += re.escape(e)
        
            if i != len(before):
                r += '.*(\n)?'
            i += 1
        
        r += '(?P<distros>.*)'
        f = open(self._file_path, 'r')
        self.text = f.read(-1)
        results = re.search(r, self.text, re.MULTILINE)
        
        start = results.start('distros')
        
        results = re.search(re.escape('.'), self.text[start:])
        end = results.start(0)

        self._d_arg_section.set_start(start)
        self._d_arg_section.set_end(start + end)

        self._sections.append(self._d_arg_section)
        if len(self._sections) > 1:
            self._sections.sort(key=lambda item: item.start)        

        distros = self.text[start:start + end]
        distros = distros.replace('\n', '')
        distros = distros.replace('`', '')
        distros = distros.replace(' ', '')

        self._d_arg_section.set_distros(distros.split(','))
        self._distros.extend(self._d_arg_section.get_distros())
        if len(self._stock_distros) == 0:
            self._stock_distros = copy.copy(self._d_arg_section.get_distros())
        else:
            for distro in self._d_arg_section.get_distros():
                if distro not in self._stock_distros:
                    self._stock_distros.append(distro)
        self._stock_distros.sort()
        f.close()

    def _parse_file_section(self):
        r = ""
        before = "For example, it may specify the distribution to use (".split(" ")
        i = 1
        for e in before:
            r += '.*'
            r += re.escape(e)
        
            if i != len(before):
                r += '.*(\n)?'
            i += 1
        
        r += '(?P<distros>.*)'
        results = re.search(r, self.text, re.MULTILINE)
        
        start = results.start('distros')

        results = re.search(re.escape(')'), self.text[start:])
        end = results.start(0)

        self._file_section.set_start(start)
        self._file_section.set_end(start + end)

        self._sections.append(self._file_section)
        if len(self._sections) > 1:
            self._sections.sort(key=lambda item: item.start)

        distros = self.text[start:start + end]
        distros = distros.replace('\n', '')
        distros = distros.replace('`', '')
        distros = distros.replace(' ', '')
        self._file_section.set_distros(distros.split(','))

    def list_distros(self):
        return self._distros

    def remove_distros(self, distros=None):
        if distros == None:
            self._distros = []
        elif type(distros) == type([]):
            for distro in distros:
                self._distros.remove(distro)
        else:
            self._distros.remove(distros)

    def add_distros(self, new_distros):
        if type(new_distros) == type([]):
            for new_distro in new_distros:
                if new_distro not in self._distros:
                    self._distros.append(new_distro)
        else:
            if distros not in self._distros:
                self._distros.append(new_distros)

    def check(self):
        from sh import grep
        for distro in self._stock_distros:
            try:
                output = grep(distro, self._file_path)
            except:
                print("[ OK ] {}: {}".format(distro, self._file_path))
            else:
                print("[ !! ] {}: {}".format(distro, self._file_path))
                print(output)

    def __str__(self):
        debug = False
        if debug:
            for section in self._sections:
                print(section)

        i = 0
        for section in self._sections:
            if i == 0:
                new_text = self.text[:section.get_start()]
                if debug:
                    print("{} section: i == 0: self.text[:section.get_start()={}]".format(
                        section.name,
                        section.get_start()))
            j = 0
            for distro in self._distros:
                if j == 0:
                    new_text += " "
                new_text += "`{}`".format(distro)
                if j != len(self._distros) - 1:
                    new_text += ', '

                if debug:
                    print("{} section: distro={}".format(
                        section.name,
                        distro))

                j += 1

            if i == (len( self._sections) -1 ):
                new_text += self.text[section.get_end():]
                if debug:
                    print("{} section: self.text[section.get_end()={}:]".format(
                        section.name,
                        section.get_end()))
            else:
                new_text += self.text[section.get_end():self._sections[i+1].get_start()]
                if debug:
                    print("{} section: self.text[section.get_end()={}:self._sections[i+1].get_start()={}]".format(
                        section.name,
                        section.get_end(),
                        self._sections[i+1].get_start()))
            i += 1

        if new_text[-1] == '\n':
            return new_text[:-1]
        return new_text

    def __repr__(self):
        return self.__str(self)

    def replace(self):
        f = open(self._file_path, 'w')
        f.write(self.__str__())
        f.close()

parser = Parser()
parser.remove_distros()
parser.add_distros(['parabola'])
parser.replace()
parser.check()