source: rtems-source-builder/source-builder/sb/bootstrap.py @ 5f7c53a

5
Last change on this file since 5f7c53a was 5f7c53a, checked in by Chris Johns <chrisj@…>, on 11/17/19 at 05:39:43

sb: Align the version processing with rtems-tools.

  • Use the same VERSION file format as rtems-tools so a common release generation can be used.
  • The version.py is almost the same as rtems-tools. There are some minor differences, one is the RTEMS version is present in this file while rtems-tool uses config/rtems-release.ini.

Updates #3822

  • Property mode set to 100644
File size: 9.4 KB
Line 
1#
2# RTEMS Tools Project (http://www.rtems.org/)
3# Copyright 2013-2016 Chris Johns (chrisj@rtems.org)
4# All rights reserved.
5#
6# This file is part of the RTEMS Tools package in 'rtems-tools'.
7#
8# Permission to use, copy, modify, and/or distribute this software for any
9# purpose with or without fee is hereby granted, provided that the above
10# copyright notice and this permission notice appear in all copies.
11#
12# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19#
20
21from __future__ import print_function
22
23import datetime
24import operator
25import os
26import re
27import sys
28import threading
29import time
30
31import error
32import log
33import options
34import path
35import version
36
37def _collect(path_, file):
38    confs = []
39    for root, dirs, files in os.walk(path.host(path_), topdown = True):
40        for f in files:
41            if f == file:
42                confs += [path.shell(path.join(root, f))]
43    return confs
44
45def _grep(file, pattern):
46    rege = re.compile(pattern)
47    try:
48        f = open(path.host(file), 'r')
49        matches = [rege.match(l) != None for l in f.readlines()]
50        f.close()
51    except IOError as err:
52        raise error.general('reading: %s' % (file))
53    return True in matches
54
55class command:
56
57    def __init__(self, cmd, cwd):
58        self.exit_code = 0
59        self.thread = None
60        self.output = None
61        self.cmd = cmd
62        self.cwd = cwd
63        self.result = None
64
65    def runner(self):
66
67        import subprocess
68
69        #
70        # Support Python 2.6
71        #
72        if "check_output" not in dir(subprocess):
73            def f(*popenargs, **kwargs):
74                if 'stdout' in kwargs:
75                    raise ValueError('stdout argument not allowed, it will be overridden.')
76                process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
77                output, unused_err = process.communicate()
78                retcode = process.poll()
79                if retcode:
80                    cmd = kwargs.get("args")
81                    if cmd is None:
82                        cmd = popenargs[0]
83                    raise subprocess.CalledProcessError(retcode, cmd)
84                return output
85            subprocess.check_output = f
86
87        self.start_time = datetime.datetime.now()
88        self.exit_code = 0
89        try:
90            try:
91                if os.name == 'nt':
92                    cmd = ['sh', '-c'] + self.cmd
93                else:
94                    cmd = self.cmd
95                self.output = subprocess.check_output(cmd, cwd = path.host(self.cwd))
96            except subprocess.CalledProcessError as cpe:
97                self.exit_code = cpe.returncode
98                self.output = cpe.output
99            except OSError as ose:
100                raise error.general('bootstrap failed: %s in %s: %s' % \
101                                        (' '.join(cmd), path.host(self.cwd), (str(ose))))
102            except KeyboardInterrupt:
103                pass
104            except:
105                raise
106        except:
107            self.result = sys.exc_info()
108        self.end_time = datetime.datetime.now()
109
110    def run(self):
111        self.thread = threading.Thread(target = self.runner)
112        self.thread.start()
113
114    def is_alive(self):
115        return self.thread and self.thread.is_alive()
116
117    def reraise(self):
118        if self.result is not None:
119            raise self.result[0](self.result[1])
120
121class autoreconf:
122
123    def __init__(self, topdir, configure):
124        self.topdir = topdir
125        self.configure = configure
126        self.cwd = path.dirname(self.configure)
127        self.command = command(['autoreconf', '-i', '--no-recursive'], self.cwd)
128        self.command.run()
129
130    def is_alive(self):
131        return self.command.is_alive()
132
133    def post_process(self):
134        if self.command is not None:
135            self.command.reraise()
136            if self.command.exit_code != 0:
137                raise error.general('error: autoreconf: %s' % (' '.join(self.command.cmd)))
138            makefile = path.join(self.cwd, 'Makefile.am')
139            if path.exists(makefile):
140                if _grep(makefile, 'stamp-h\.in'):
141                    stamp_h = path.join(self.cwd, 'stamp-h.in')
142                    try:
143                        t = open(path.host(stamp_h), 'w')
144                        t.write('timestamp')
145                        t.close()
146                    except IOError as err:
147                        raise error.general('writing: %s' % (stamp_h))
148
149def generate(topdir, jobs):
150    if type(jobs) is str:
151        jobs = int(jobs)
152    start_time = datetime.datetime.now()
153    confs = _collect(topdir, 'configure.ac')
154    next = 0
155    autoreconfs = []
156    while next < len(confs) or len(autoreconfs) > 0:
157        if next < len(confs) and len(autoreconfs) < jobs:
158            log.notice('%3d/%3d: autoreconf: %s' % \
159                           (next + 1, len(confs), confs[next][len(topdir) + 1:]))
160            autoreconfs += [autoreconf(topdir, confs[next])]
161            next += 1
162        else:
163            for ac in autoreconfs:
164                if not ac.is_alive():
165                    ac.post_process()
166                    autoreconfs.remove(ac)
167                    del ac
168            if len(autoreconfs) >= jobs:
169                time.sleep(1)
170    end_time = datetime.datetime.now()
171    log.notice('Bootstrap time: %s' % (str(end_time - start_time)))
172
173class ampolish3:
174
175    def __init__(self, topdir, makefile):
176        self.topdir = topdir
177        self.makefile = makefile
178        self.preinstall = path.join(path.dirname(makefile), 'preinstall.am')
179        self.command = command([path.join(topdir, 'ampolish3'), makefile], self.topdir)
180        self.command.run()
181
182    def is_alive(self):
183        return self.command.is_alive()
184
185    def post_process(self):
186        if self.command is not None:
187            if self.command.exit_code != 0:
188                raise error.general('error: ampolish3: %s' % (' '.join(self.command.cmd)))
189            try:
190                p = open(path.host(self.preinstall), 'w')
191                for l in self.command.output:
192                    p.write(l)
193                p.close()
194            except IOError as err:
195                raise error.general('writing: %s' % (self.preinstall))
196
197def preinstall(topdir, jobs):
198    if type(jobs) is str:
199        jobs = int(jobs)
200    start_time = datetime.datetime.now()
201    makes = []
202    for am in _collect(topdir, 'Makefile.am'):
203        if _grep(am, 'include .*/preinstall\.am'):
204            makes += [am]
205    next = 0
206    ampolish3s = []
207    while next < len(makes) or len(ampolish3s) > 0:
208        if next < len(makes) and len(ampolish3s) < jobs:
209            log.notice('%3d/%3d: ampolish3: %s' % \
210                           (next + 1, len(makes), makes[next][len(topdir) + 1:]))
211            ampolish3s += [ampolish3(topdir, makes[next])]
212            next += 1
213        else:
214            for ap in ampolish3s:
215                if not ap.is_alive():
216                    ap.post_process()
217                    ampolish3s.remove(ap)
218                    del ap
219            if len(ampolish3s) >= jobs:
220                time.sleep(1)
221    end_time = datetime.datetime.now()
222    log.notice('Preinstall time: %s' % (str(end_time - start_time)))
223
224def run(args):
225    try:
226        #
227        # On Windows MSYS2 prepends a path to itself to the environment
228        # path. This means the RTEMS specific automake is not found and which
229        # breaks the bootstrap. We need to remove the prepended path. Also
230        # remove any ACLOCAL paths from the environment.
231        #
232        if os.name == 'nt':
233            cspath = os.environ['PATH'].split(os.pathsep)
234            if 'msys' in cspath[0] and cspath[0].endswith('bin'):
235                os.environ['PATH'] = os.pathsep.join(cspath[1:])
236            if 'ACLOCAL_PATH' in os.environ:
237                #
238                # The clear fails on a current MSYS2 python (Feb 2016). Delete
239                # the entry if the clear fails.
240                #
241                try:
242                    os.environ['ACLOCAL_PATH'].clear()
243                except:
244                    del os.environ['ACLOCAL_PATH']
245        optargs = { '--rtems':       'The RTEMS source directory',
246                    '--preinstall':  'Preinstall AM generation' }
247        log.notice('RTEMS Source Builder - RTEMS Bootstrap, %s' % (version.string()))
248        opts = options.load(sys.argv, optargs, logfile = False)
249        if opts.get_arg('--rtems'):
250            topdir = opts.get_arg('--rtems')
251        else:
252            topdir = os.getcwd()
253        if opts.get_arg('--preinstall'):
254            preinstall(topdir, opts.jobs(opts.defaults['_ncpus']))
255        else:
256            generate(topdir, opts.jobs(opts.defaults['_ncpus']))
257    except error.general as gerr:
258        print(gerr)
259        print('Bootstrap FAILED', file = sys.stderr)
260        sys.exit(1)
261    except error.internal as ierr:
262        print(ierr)
263        print('Bootstrap FAILED', file = sys.stderr)
264        sys.exit(1)
265    except error.exit as eerr:
266        pass
267    except KeyboardInterrupt:
268        log.notice('abort: user terminated')
269        sys.exit(1)
270    sys.exit(0)
271
272if __name__ == "__main__":
273    run(sys.argv)
Note: See TracBrowser for help on using the repository browser.