summaryrefslogtreecommitdiff
path: root/tools/notsd-fixup--includes
blob: 196fd488a340e05abfa8ae6a173188e1d0dee128 (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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/env python3

# If you are thinking "this file looks gross!", it is.  It
# started out as a set of Bash one-liners.  Which got turned
# into a script.  Which grew somewhat organically.  Not huge,
# but given that it started as some one liners, that's not a
# very pretty several hunderd lines.  Then got fairly litterally
# translated into this, for speed.  So yes, it is gross.
# Rewrites welcome; just don't introduce any behavioral changes
# (easy since `tools/notsd-move` runs it on the entire repo and
# puts the results in git history).

import json
import os
import re
import shlex
import subprocess
import sys

################################################################
# Everything else in this program is just fluff and bookkeeping
# around around calling classify().

# Return a tuple of (class/group, path); which is a class that
# the header path belongs to, and a normalized path for it.
#
# There are a fixed number of classes that it may put a header
# in; in order of most-public to most-private:
#
#  system
#  linux
#  public
#  protected
#  private
def classify(expensive, current_file, path):
    if path.startswith('linux/'):
        return 'linux', path
    elif expensive.exists(os.path.join(os.path.dirname(current_file), path)):
        return 'private', path
    elif not path.startswith('systemd/') and path != 'libudev.h' and expensive.cpp(path):
        return 'system', path
    else:
        if path.endswith('-to-name.h') or path.endswith('-from-name.h'):
            base = re.fullmatch('(.*)-(to|from)-name\.h', os.path.basename(path)).group(1)
            d={
                'dns_type'      : 'src/grp-resolve/systemd-resolved',
                'keyboard-keys' : 'src/grp-udev/libudev-core',
                'af'            : 'src/libsystemd-basic/src',
                'arphrd'        : 'src/libsystemd-basic/src',
                'cap'           : 'src/libsystemd-basic/src',
                'errno'         : 'src/libsystemd-basic/src',
                'audit_type'    : 'src/libsystemd/src/sd-journal',
            }
            file = os.path.join(d[base], os.path.basename(path))
            if current_file.startswith(d[base]):
                return 'private', os.path.basename(file)
            elif '/include/' in file:
                return 'protected', re.sub('.*/include/', '', file)
            else:
                return 'protected', os.path.basename(file)
        elif path in [ 'asm/sgidefs.h', 'dbus/dbus.h', 'efi.h', 'efilib.h', 'gio/gio.h', 'glib.h', 'libmount.h' ]:
            return 'system', path
        elif os.path.basename(path) == 'util.h':
            if '/systemd-boot/' in current_file:
                return 'private', 'util.h'
            else:
                return 'protected', 'systemd-basic/util.h'
        else:
            find = expensive.find(os.path.basename(path))
            if len(find) == 1:
                file = find[0]
                if '/src/' in file:
                    if os.path.dirname(current_file) == os.path.dirname(file):
                        return 'private', os.path.basename(file)
                    else:
                        return 'protected', re.sub('.*/src/', '', file)
                elif ('/libsystemd/include/' in file) or ('/libudev/include/' in file):
                    return 'public', re.sub('.*/include/', '', file)
                elif '/include/' in file:
                    return 'protected', re.sub('.*/include/', '', file)
                elif '/include-staging/' in file:
                    return 'protected', re.sub('.*/include-staging/', '', file)
                else:
                    if os.path.dirname(current_file) == os.path.dirname(file):
                        return 'private', os.path.basename(file)
                    else:
                        return 'protected', os.path.basename(file)
            else:
                sys.exit('Cannot figure out: {0}'.format(path))

################################################################
# Cache expensive things

class Cache:
    def __init__(self, filename):
        self.cache = {
            'find': None,
            'cpp': {}
        }
        self.dirty = True

        if os.path.isfile(filename):
            with open(filename) as file:
                self.cache = json.load(file)
                self.dirty = False

    def save(self, filename):
        if self.dirty:
            with open(filename, 'w') as file:
                json.dump(self.cache, file)

    def real_cpp(path):
        # `cpp -include "$path" <<<'' &>/dev/null`
        print('  -> cpp({0})'.format(path), file=sys.stderr)
        with subprocess.Popen(['cpp', '-include', path],
                                stdin=subprocess.PIPE,
                                stdout=subprocess.DEVNULL,
                                stderr=subprocess.DEVNULL) as proc:
            proc.stdin.close()
            return proc.wait() == 0

    def real_find():
        # This can probably be done with os.walk or something,
        # but since it is only called once, it isn't a good
        # place to start optimizing.
        #
        # `find src -name '*.h' \( -type l -printf 'l %p\n' -o -type f -printf 'f %p\n' \)`
        print('  -> find()', file=sys.stderr)
        ret = {}
        with subprocess.Popen(['find', 'src', '-name', '*.h', '(', '-type', 'l', '-printf', 'l %p\n', '-o', '-type', 'f', '-printf', 'f %p\n', ')'],
                              stdin=subprocess.DEVNULL,
                              stdout=subprocess.PIPE, universal_newlines=True,
                              stderr=subprocess.DEVNULL) as proc:
            for line in proc.stdout:
                t, p = line.rstrip('\n').split(' ', 1)
                ret[p]=t
        return ret

    def cpp(self, path):
        # `cpp -include "$path" <<<'' &>/dev/null`
        if path not in self.cache['cpp']:
            self.cache['cpp'][path] = Cache.real_cpp(path)
            self.dirty = True
        return self.cache['cpp'][path]

    def exists(self, path):
        # `test -f "$path"`
        if not self.cache['find']:
            self.cache['find'] = Cache.real_find()
            self.dirty = True
        return path in self.cache['find']

    def find(self, name):
        # `find src -type f -name "$name"`
        if not self.cache['find']:
            self.cache['find'] = Cache.real_find()
            self.dirty = True
        return [p for p in self.cache['find'].keys() if self.cache['find'][p]=='f' and os.path.basename(p) == name]

################################################################
# Data structure for storing a chunk of `#include` lines.

class IncludeSection:
    def __init__(self):
        self.trailing_nl = ''
        self.system = []
        self.linux = []
        self.public = []
        self.protected = []
        self.typedef = []
        self.typedef_last = True
        self.private = []
    def print(self, file=sys.stdout):
        b=''
        if len(self.system) > 0:
            for line in sorted(set(self.system)):
                print(line, file=file)
            b='\n'
        if len(self.linux) > 0:
            print(b, end='', file=file)
            for line in self.linux:
                print(line, file=file)
            b='\n'
        if len(self.public) > 0:
            print(b, end='', file=file)
            for line in sorted(set(self.public)):
                print(line, file=file)
            b='\n'
        if len(self.protected) > 0:
            print(b, end='', file=file)
            for line in sorted(set(self.protected)):
                print(line, file=file)
            b='\n'
        if len(self.typedef) > 0 and not self.typedef_last:
            print(b, end='', file=file)
            for line in sorted(set(self.typedef)):
                print(line, file=file)
            b='\n'
        if len(self.private) > 0:
            print(b, end='', file=file)
            for line in sorted(set(self.private)):
                print(line, file=file)
            b='\n'
        if len(self.typedef) > 0 and self.typedef_last:
            print(b, end='', file=file)
            for line in sorted(set(self.typedef)):
                print(line, file=file)
        print(self.trailing_nl, end='', file=file)
    def add(self, group, path, extra):
        if group == 'system':
            self.system.append('#include <{0}>{1}'.format(path, extra))
        elif group == 'linux':
            self.linux.append('#include <{0}>{1}'.format(path, extra))
        elif group == 'public':
            self.public.append('#include <{0}>{1}'.format(path, extra))
        elif group == 'protected':
            self.protected.append('#include "{0}"{1}'.format(path, extra))
        elif group == 'private':
            if len(self.typedef) > 0:
                self.typedef_last = False
            self.private.append('#include "{0}"{1}'.format(path, extra))
        else:
            sys.exit('panic: unrecognized line class: {0}'.format(group))

################################################################
# The main program loop

def phase0(cache, filename, line):
    global phase
    phase = phase0

    if re.fullmatch('#include.*|typedef .*;', line):
        global includes
        includes = IncludeSection()
        phase1(cache, filename, line)
    else:
        print(line)

def phase1(cache, filename, line):
    global phase, includes
    phase = phase1

    if line == '':
        includes.trailing_nl += '\n'
    elif line.startswith('#include'):
        includes.trailing_nl = ''
        match = re.fullmatch('^#include [<"]([^">]*)[">](.*)', line)
        if match:
            group, path = classify(cache, filename, match.group(1))
            includes.add(group, path, match.group(2))
        else:
            sys.exit('panic: malformed #include line')
    elif re.fullmatch('typedef .*;', line):
        includes.trailing_nl = ''
        includes.typedef.append(line)
    else:
        includes.print()
        includes = None
        phase0(cache, filename, line)

includes = None
phase = phase0

def main(argv):
    filename = argv[1]
    print(' => {0} {1}'.format(
        shlex.quote(__file__),
        shlex.quote(filename),
    ), file=sys.stderr)
    cache = Cache(__file__+'.cache')
    with open(filename) as f:
        for line in f:
            phase(cache, filename, line.rstrip('\n'))
    if includes:
        includes.print()
    cache.save(__file__+'.cache')

if __name__ == '__main__':
    main(sys.argv)