aboutsummaryrefslogtreecommitdiff
path: root/tools/amalgamate.py
blob: a8076033cd2edba6da2f05d8ce30f8c18d572648 (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
import io
import os
import sys

this_dir = os.path.dirname(os.path.abspath(__file__))

src_dir = os.path.join(this_dir, '..', 'src')

sources = (
    'queue.h',
    'log.h',
    'misc.c',
    'stringbuf.c',
    'stream.c',
    'socketstream.c',
    'stringstream.c',
    'stream_mqtt.c',
    'socket.c',
    'packet.c',
    'serialize.c',
    'deserialize.c',
    'client.c'
)


def is_header(filename):
    return os.path.splitext(filename)[1] == '.h'


def get_header(src):
    root, ext = os.path.splitext(src)
    return root + '.h'


def read_file(filename):
    def tounicode(s):
        if sys.version_info[0] == 2:
            return s.decode('utf-8')
        else:
            return s
    with open(filename, 'r') as fp:
        buf = io.StringIO()
        for line in fp:
            if line.startswith('#include "'):
                if line[10:].startswith('mqtt.h'):
                    pass
                else:
                    continue
            buf.write(tounicode(line))
        return buf.getvalue()


def file_header(filename):
    filename = os.path.basename(filename)
    # how long lines we create
    linelen = 72
    # how much space left after the necessary comment markup
    chars = linelen - 4
    # how much padding in total for filename
    padding = chars - len(filename)
    padding_l = padding // 2
    padding_r = padding - padding_l
    lines = (
        '',
        '/*' + '*'*chars + '*/',
        '/*' + ' '*padding_l + filename + ' '*padding_r + '*/',
        '/*' + '*'*chars + '*/',
        '\n',
    )
    return '\n'.join(lines)


def write_file(output, srcfilename):
    output.write(file_header(srcfilename))
    output.write(read_file(srcfilename))


output_filename = sys.argv[1]

with open(output_filename, 'w') as out:
    for source in sources:
        path = os.path.join(src_dir, source)

        if is_header(path):
            write_file(out, path)
        else:
            header = get_header(path)
            if os.path.isfile(header):
                write_file(out, header)
            write_file(out, path)