summaryrefslogtreecommitdiffstats
path: root/source-builder/sb/rtemspkg.py
blob: 492eb597b5cd5e766ff3a1d9358446440d0f950b (plain) (blame)
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
280
281
282
283
284
285
286
287
#
# RTEMS Tools Project (http://www.rtems.org/)
# Copyright 2024 Chris Johns (chrisj@rtems.org)
# All rights reserved.
#
# This file is part of the RTEMS Tools package in 'rtems-tools'.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#
# This code builds a package compiler tool suite given a tool set. A tool
# set lists the various tools. These are specific tool configurations.
#

from __future__ import print_function

import argparse
import base64
import copy
import datetime
import hashlib
import os
import sys

try:
    from . import build
    from . import download
    from . import error
    from . import git
    from . import log
    from . import path
    from . import simhost
    from . import version
except KeyboardInterrupt:
    print('abort: user terminated', file=sys.stderr)
    sys.exit(1)
except:
    raise

#
# RTEMS Packages we maintian a git hash of in the RSB
#
rpc_label = 0
rpc_config = 1
rpc_version = 2
rpc_repo = 3
rpc_repo_name = 4
rpc_branch = 5
rpc_snapshot = 6
rpc_package = 7
rtems_pkg_cfgs = [
    [
        'RTEMS Tools', 'tools/rtems-tools-%{rtems_version}.cfg',
        'rtems_tools_version', 'git://git.rtems.org/rtems-tools',
        'rtems-tools.git', 'master',
        'https://git.rtems.org/rtems-tools/snapshot/rtems-tools-%{rtems_tools_version}.tar.bz2',
        'rtems-tools-%{rtems_tools_version}.tar.bz2'
    ],
    [
        'RTEMS Kernel', 'tools/rtems-kernel-%{rtems_version}.cfg',
        'rtems_kernel_version', 'git://git.rtems.org/rtems', 'rtems.git',
        'master',
        'https://git.rtems.org/rtems/snapshot/rtems-%{rtems_kernel_version}.tar.bz2',
        'rtems-kernel-%{rtems_kernel_version}.tar.bz2'
    ],
    [
        'RTEMS LibBSD', 'tools/rtems-libbsd-%{rtems_version}.cfg',
        'rtems_libbsd_version', 'git://git.rtems.org/rtems-libbsd',
        'rtems-libbsd.git', '6-freebsd-12',
        'https://git.rtems.org/rtems-libbsd/snapshot/rtems-libbsd-%{rtems_libbsd_version}.tar.%{rtems_libbsd_ext}',
        'rtems-libbsd-%{rtems_libbsd_version}.tar.%{rtems_libbsd_ext}'
    ],
    [
        'RTEMS Net Legacy', 'tools/rtems-net-legacy-%{rtems_version}.cfg',
        'rtems_net_version', 'git://git.rtems.org/rtems-net-legacy',
        'rtems-net-legacy.git', 'main',
        'https://git.rtems.org/rtems-net-legacy/snapshot/rtems-net-legacy-%{rtems_net_version}.tar.%{rtems_net_ext}',
        'rtems-net-legacy-%{rtems_net_version}.tar.%{rtems_net_ext}'
    ],
    [
        'RTEMS Net Services', 'net/net-services-1.cfg',
        'rtems_net_services_version', 'git://git.rtems.org/rtems-net-services',
        'rtems-net-services.git', 'master',
        'https://git.rtems.org/rtems-net-services/snapshot/rtems-net-services-%{rtems_net_services_version}.tar.%{rtems_net_services_ext}',
        'rtems-net-services-%{rtems_net_services_version}.tar.%{rtems_net_services_ext}'
    ],
]


def clean_line(line):
    line = line[0:-1]
    b = line.find('#')
    if b >= 0:
        line = line[1:b] + ('\\' if line[-1] == '\\' else '')
    return line.strip()


def clean_and_pack(line, last_line):
    leading_ws = ' ' if len(line) > 0 and line[0].isspace() else ''
    line = clean_line(line)
    if len(last_line) > 0:
        line = last_line + leading_ws + line
    return line


def config_patch(configdir, config, version_label, config_hash, repo_hash,
                 checksum):
    for cd in configdir.split(':'):
        cf = path.join(cd, config)
        if path.exists(cf):
            try:
                with open(cf) as f:
                    lines = f.readlines()
            except IOError as err:
                raise error.general('config: %s: read error: %s' %
                                    (config, str(err)))
            new_config = []
            new_lines = []
            last_line = ''
            for line in lines:
                new_lines += [line]
                line = clean_and_pack(line, last_line)
                if len(line) > 0:
                    if line[-1] == '\\':
                        last_line = line[:-1]
                        continue
                    last_line = ''
                    if version_label in line and not 'rsb_version' in line:
                        if line.startswith('%define ' + version_label):
                            new_lines = [
                                '%define ' + version_label + ' ' + repo_hash +
                                os.linesep
                            ]
                        elif line.startswith('%hash '):
                            ls = line.split()
                            if len(ls) != 4:
                                raise error.general('invalid %hash: ' + line)
                            new_lines = [
                                ' '.join(ls[0:3]) + ' \\' + os.linesep,
                                '              ' + checksum + os.linesep
                            ]
                new_config += new_lines
                new_lines = []
            try:
                with open(cf, 'w') as f:
                    f.writelines(new_config)
            except IOError as err:
                raise error.general('config: %s: write error: %s' %
                                    (config, str(err)))
            return
    raise error.general('could not find: ' + config)


def checksum_sha512_base64(tarball):
    hasher = hashlib.new('sha512')
    try:
        with open(path.host(tarball), 'rb') as f:
            hasher.update(f.read())
    except IOError as err:
        log.notice('hash: %s: read error: %s' % (file_, str(err)))
    except:
        raise
        raise error.general('cannot hash the tar file')
    hash_hex = hasher.hexdigest()
    hash_base64 = base64.b64encode(hasher.digest()).decode('utf-8')
    return hash_base64


def run(args=sys.argv):
    ec = 0
    output = []
    try:
        #
        # The RSB options support cannot be used because it loads the defaults
        # for the host which we cannot do here.
        #
        description = 'RTEMS Track Dependencies a build set has for all hosts.'

        argsp = argparse.ArgumentParser(prog='sb-rtems-pkg',
                                        description=description)
        argsp.add_argument('--rtems-version',
                           help='Set the RTEMS version.',
                           type=str,
                           default=version.version())
        argsp.add_argument('--log',
                           help='Log file.',
                           type=str,
                           default=simhost.log_default('rtems-pkg'))
        argsp.add_argument('--trace',
                           help='Enable trace logging for debugging.',
                           action='store_true')
        argsp.add_argument('--dry-run',
                           help='Dry run, do not update the configurations',
                           action='store_true')
        argsp.add_argument('bsets', nargs='*', help='Build sets.')

        argopts = argsp.parse_args(args[1:])

        simhost.load_log(argopts.log)
        log.notice('RTEMS Source Builder - RTEMS Package Update, %s' %
                   (version.string()))
        log.tracing = argopts.trace

        opts = simhost.load_options(args, argopts, extras=['--with-download'])
        opts.defaults['_rsb_getting_source'] = '1'
        opts.defaults[
            'rtems_waf_build_root_suffix'] = '%{waf_build_root_suffix}'
        opts.defaults['rtems_version'] = argopts.rtems_version

        for cfg in rtems_pkg_cfgs:
            b = None
            try:
                bopts = copy.copy(opts)
                bmacros = copy.copy(opts.defaults)
                b = build.build(cfg[rpc_config], False, bopts, bmacros)
                git_hash_key = b.macros.find(cfg[rpc_version])
                if len(git_hash_key) == 0:
                    raise error.general(cfg[rpc_label] +
                                        ': cannot find version macro')
                source_dir = b.macros.expand('%{_sourcedir}')
                config_hash = b.macros.expand('%{' + cfg[rpc_version] + '}')
                repo_path = path.join(source_dir, cfg[rpc_repo_name])
                download.get_file(
                    cfg[rpc_repo] + '?fetch?checkout=' + cfg[rpc_branch],
                    repo_path, bopts, b)
                repo = git.repo(repo_path)
                repo_hash = repo.head()
                if config_hash != repo_hash:
                    update = True
                    update_str = 'UPDATE'
                else:
                    update = False
                    update_str = 'matching'
                print(cfg[rpc_label] + ': ' + update_str + ' config:' +
                      config_hash + ' repo:' + repo_hash)
                b.macros[cfg[rpc_version]] = repo_hash
                tarball = b.macros.expand(cfg[rpc_package])
                b.macros.set_write_map('hashes')
                b.macros[tarball] = 'NO-HASH NO-HASH'
                b.macros.unset_write_map()
                tarball_path = path.join(source_dir,
                                         b.macros.expand(cfg[rpc_package]))
                download.get_file(b.macros.expand(cfg[rpc_snapshot]),
                                  tarball_path, bopts, b)
                tarball_hash = checksum_sha512_base64(tarball_path)
                if update and not argopts.dry_run:
                    config_patch(b.macros.expand('%{_configdir}'),
                                 b.macros.expand(cfg[rpc_config]),
                                 cfg[rpc_version], config_hash, repo_hash,
                                 tarball_hash)
                del b
            except error.general as gerr:
                log.stderr(str(gerr))
                log.stderr('Configuration load FAILED')
                b = None
    except error.general as gerr:
        log.stderr(str(gerr))
        log.stderr('Build FAILED')
        ec = 1
    except error.internal as ierr:
        log.stderr(str(ierr))
        log.stderr('Internal Build FAILED')
        ec = 1
    except error.exit as eerr:
        pass
    except KeyboardInterrupt:
        log.notice('abort: user terminated')
        ec = 1
    except:
        raise
        log.notice('abort: unknown error')
        ec = 1
    sys.exit(ec)


if __name__ == "__main__":
    run()