xref: /openbmc/u-boot/tools/buildman/builder.py (revision 5830791d91d1200854ef78fcb32f808c8080f0f0)
183d290c5STom Rini# SPDX-License-Identifier: GPL-2.0+
2fc3fe1c2SSimon Glass# Copyright (c) 2013 The Chromium OS Authors.
3fc3fe1c2SSimon Glass#
4fc3fe1c2SSimon Glass# Bloat-o-meter code used here Copyright 2004 Matt Mackall <mpm@selenic.com>
5fc3fe1c2SSimon Glass#
6fc3fe1c2SSimon Glass
7fc3fe1c2SSimon Glassimport collections
8fc3fe1c2SSimon Glassfrom datetime import datetime, timedelta
9fc3fe1c2SSimon Glassimport glob
10fc3fe1c2SSimon Glassimport os
11fc3fe1c2SSimon Glassimport re
12fc3fe1c2SSimon Glassimport Queue
13fc3fe1c2SSimon Glassimport shutil
142f256648SSimon Glassimport signal
15fc3fe1c2SSimon Glassimport string
16fc3fe1c2SSimon Glassimport sys
17d436e381SSimon Glassimport threading
18fc3fe1c2SSimon Glassimport time
19fc3fe1c2SSimon Glass
20190064b4SSimon Glassimport builderthread
21fc3fe1c2SSimon Glassimport command
22fc3fe1c2SSimon Glassimport gitutil
23fc3fe1c2SSimon Glassimport terminal
244653a882SSimon Glassfrom terminal import Print
25fc3fe1c2SSimon Glassimport toolchain
26fc3fe1c2SSimon Glass
27fc3fe1c2SSimon Glass
28fc3fe1c2SSimon Glass"""
29fc3fe1c2SSimon GlassTheory of Operation
30fc3fe1c2SSimon Glass
31fc3fe1c2SSimon GlassPlease see README for user documentation, and you should be familiar with
32fc3fe1c2SSimon Glassthat before trying to make sense of this.
33fc3fe1c2SSimon Glass
34fc3fe1c2SSimon GlassBuildman works by keeping the machine as busy as possible, building different
35fc3fe1c2SSimon Glasscommits for different boards on multiple CPUs at once.
36fc3fe1c2SSimon Glass
37fc3fe1c2SSimon GlassThe source repo (self.git_dir) contains all the commits to be built. Each
38fc3fe1c2SSimon Glassthread works on a single board at a time. It checks out the first commit,
39fc3fe1c2SSimon Glassconfigures it for that board, then builds it. Then it checks out the next
40fc3fe1c2SSimon Glasscommit and builds it (typically without re-configuring). When it runs out
41fc3fe1c2SSimon Glassof commits, it gets another job from the builder and starts again with that
42fc3fe1c2SSimon Glassboard.
43fc3fe1c2SSimon Glass
44fc3fe1c2SSimon GlassClearly the builder threads could work either way - they could check out a
45fc3fe1c2SSimon Glasscommit and then built it for all boards. Using separate directories for each
46fc3fe1c2SSimon Glasscommit/board pair they could leave their build product around afterwards
47fc3fe1c2SSimon Glassalso.
48fc3fe1c2SSimon Glass
49fc3fe1c2SSimon GlassThe intent behind building a single board for multiple commits, is to make
50fc3fe1c2SSimon Glassuse of incremental builds. Since each commit is built incrementally from
51fc3fe1c2SSimon Glassthe previous one, builds are faster. Reconfiguring for a different board
52fc3fe1c2SSimon Glassremoves all intermediate object files.
53fc3fe1c2SSimon Glass
54fc3fe1c2SSimon GlassMany threads can be working at once, but each has its own working directory.
55fc3fe1c2SSimon GlassWhen a thread finishes a build, it puts the output files into a result
56fc3fe1c2SSimon Glassdirectory.
57fc3fe1c2SSimon Glass
58fc3fe1c2SSimon GlassThe base directory used by buildman is normally '../<branch>', i.e.
59fc3fe1c2SSimon Glassa directory higher than the source repository and named after the branch
60fc3fe1c2SSimon Glassbeing built.
61fc3fe1c2SSimon Glass
62fc3fe1c2SSimon GlassWithin the base directory, we have one subdirectory for each commit. Within
63fc3fe1c2SSimon Glassthat is one subdirectory for each board. Within that is the build output for
64fc3fe1c2SSimon Glassthat commit/board combination.
65fc3fe1c2SSimon Glass
66fc3fe1c2SSimon GlassBuildman also create working directories for each thread, in a .bm-work/
67fc3fe1c2SSimon Glasssubdirectory in the base dir.
68fc3fe1c2SSimon Glass
69fc3fe1c2SSimon GlassAs an example, say we are building branch 'us-net' for boards 'sandbox' and
70fc3fe1c2SSimon Glass'seaboard', and say that us-net has two commits. We will have directories
71fc3fe1c2SSimon Glasslike this:
72fc3fe1c2SSimon Glass
73fc3fe1c2SSimon Glassus-net/             base directory
74fc3fe1c2SSimon Glass    01_of_02_g4ed4ebc_net--Add-tftp-speed-/
75fc3fe1c2SSimon Glass        sandbox/
76fc3fe1c2SSimon Glass            u-boot.bin
77fc3fe1c2SSimon Glass        seaboard/
78fc3fe1c2SSimon Glass            u-boot.bin
79fc3fe1c2SSimon Glass    02_of_02_g4ed4ebc_net--Check-tftp-comp/
80fc3fe1c2SSimon Glass        sandbox/
81fc3fe1c2SSimon Glass            u-boot.bin
82fc3fe1c2SSimon Glass        seaboard/
83fc3fe1c2SSimon Glass            u-boot.bin
84fc3fe1c2SSimon Glass    .bm-work/
85fc3fe1c2SSimon Glass        00/         working directory for thread 0 (contains source checkout)
86fc3fe1c2SSimon Glass            build/  build output
87fc3fe1c2SSimon Glass        01/         working directory for thread 1
88fc3fe1c2SSimon Glass            build/  build output
89fc3fe1c2SSimon Glass        ...
90fc3fe1c2SSimon Glassu-boot/             source directory
91fc3fe1c2SSimon Glass    .git/           repository
92fc3fe1c2SSimon Glass"""
93fc3fe1c2SSimon Glass
94fc3fe1c2SSimon Glass# Possible build outcomes
95fc3fe1c2SSimon GlassOUTCOME_OK, OUTCOME_WARNING, OUTCOME_ERROR, OUTCOME_UNKNOWN = range(4)
96fc3fe1c2SSimon Glass
979a6d2e2aSSimon Glass# Translate a commit subject into a valid filename (and handle unicode)
989a6d2e2aSSimon Glasstrans_valid_chars = string.maketrans('/: ', '---')
999a6d2e2aSSimon Glasstrans_valid_chars = trans_valid_chars.decode('latin-1')
100fc3fe1c2SSimon Glass
101b464f8e7SSimon GlassBASE_CONFIG_FILENAMES = [
102b464f8e7SSimon Glass    'u-boot.cfg', 'u-boot-spl.cfg', 'u-boot-tpl.cfg'
103b464f8e7SSimon Glass]
104b464f8e7SSimon Glass
105b464f8e7SSimon GlassEXTRA_CONFIG_FILENAMES = [
106843312dcSSimon Glass    '.config', '.config-spl', '.config-tpl',
107843312dcSSimon Glass    'autoconf.mk', 'autoconf-spl.mk', 'autoconf-tpl.mk',
108843312dcSSimon Glass    'autoconf.h', 'autoconf-spl.h','autoconf-tpl.h',
109843312dcSSimon Glass]
110843312dcSSimon Glass
1118270e3c1SSimon Glassclass Config:
1128270e3c1SSimon Glass    """Holds information about configuration settings for a board."""
113b464f8e7SSimon Glass    def __init__(self, config_filename, target):
1148270e3c1SSimon Glass        self.target = target
1158270e3c1SSimon Glass        self.config = {}
116b464f8e7SSimon Glass        for fname in config_filename:
1178270e3c1SSimon Glass            self.config[fname] = {}
1188270e3c1SSimon Glass
1198270e3c1SSimon Glass    def Add(self, fname, key, value):
1208270e3c1SSimon Glass        self.config[fname][key] = value
1218270e3c1SSimon Glass
1228270e3c1SSimon Glass    def __hash__(self):
1238270e3c1SSimon Glass        val = 0
1248270e3c1SSimon Glass        for fname in self.config:
1258270e3c1SSimon Glass            for key, value in self.config[fname].iteritems():
1268270e3c1SSimon Glass                print key, value
1278270e3c1SSimon Glass                val = val ^ hash(key) & hash(value)
1288270e3c1SSimon Glass        return val
129fc3fe1c2SSimon Glass
13048ae4124SAlex Kiernanclass Environment:
13148ae4124SAlex Kiernan    """Holds information about environment variables for a board."""
13248ae4124SAlex Kiernan    def __init__(self, target):
13348ae4124SAlex Kiernan        self.target = target
13448ae4124SAlex Kiernan        self.environment = {}
13548ae4124SAlex Kiernan
13648ae4124SAlex Kiernan    def Add(self, key, value):
13748ae4124SAlex Kiernan        self.environment[key] = value
13848ae4124SAlex Kiernan
139fc3fe1c2SSimon Glassclass Builder:
140fc3fe1c2SSimon Glass    """Class for building U-Boot for a particular commit.
141fc3fe1c2SSimon Glass
142fc3fe1c2SSimon Glass    Public members: (many should ->private)
143fc3fe1c2SSimon Glass        already_done: Number of builds already completed
144fc3fe1c2SSimon Glass        base_dir: Base directory to use for builder
145fc3fe1c2SSimon Glass        checkout: True to check out source, False to skip that step.
146fc3fe1c2SSimon Glass            This is used for testing.
147fc3fe1c2SSimon Glass        col: terminal.Color() object
148fc3fe1c2SSimon Glass        count: Number of commits to build
149fc3fe1c2SSimon Glass        do_make: Method to call to invoke Make
150fc3fe1c2SSimon Glass        fail: Number of builds that failed due to error
151fc3fe1c2SSimon Glass        force_build: Force building even if a build already exists
152fc3fe1c2SSimon Glass        force_config_on_failure: If a commit fails for a board, disable
153fc3fe1c2SSimon Glass            incremental building for the next commit we build for that
154fc3fe1c2SSimon Glass            board, so that we will see all warnings/errors again.
1554266dc28SSimon Glass        force_build_failures: If a previously-built build (i.e. built on
1564266dc28SSimon Glass            a previous run of buildman) is marked as failed, rebuild it.
157fc3fe1c2SSimon Glass        git_dir: Git directory containing source repository
158fc3fe1c2SSimon Glass        last_line_len: Length of the last line we printed (used for erasing
159fc3fe1c2SSimon Glass            it with new progress information)
160fc3fe1c2SSimon Glass        num_jobs: Number of jobs to run at once (passed to make as -j)
161fc3fe1c2SSimon Glass        num_threads: Number of builder threads to run
162fc3fe1c2SSimon Glass        out_queue: Queue of results to process
163fc3fe1c2SSimon Glass        re_make_err: Compiled regular expression for ignore_lines
164fc3fe1c2SSimon Glass        queue: Queue of jobs to run
165fc3fe1c2SSimon Glass        threads: List of active threads
166fc3fe1c2SSimon Glass        toolchains: Toolchains object to use for building
167fc3fe1c2SSimon Glass        upto: Current commit number we are building (0.count-1)
168fc3fe1c2SSimon Glass        warned: Number of builds that produced at least one warning
16997e91526SSimon Glass        force_reconfig: Reconfigure U-Boot on each comiit. This disables
17097e91526SSimon Glass            incremental building, where buildman reconfigures on the first
17197e91526SSimon Glass            commit for a baord, and then just does an incremental build for
17297e91526SSimon Glass            the following commits. In fact buildman will reconfigure and
17397e91526SSimon Glass            retry for any failing commits, so generally the only effect of
17497e91526SSimon Glass            this option is to slow things down.
175189a4968SSimon Glass        in_tree: Build U-Boot in-tree instead of specifying an output
176189a4968SSimon Glass            directory separate from the source code. This option is really
177189a4968SSimon Glass            only useful for testing in-tree builds.
178fc3fe1c2SSimon Glass
179fc3fe1c2SSimon Glass    Private members:
180fc3fe1c2SSimon Glass        _base_board_dict: Last-summarised Dict of boards
181fc3fe1c2SSimon Glass        _base_err_lines: Last-summarised list of errors
182e30965dbSSimon Glass        _base_warn_lines: Last-summarised list of warnings
183fc3fe1c2SSimon Glass        _build_period_us: Time taken for a single build (float object).
184fc3fe1c2SSimon Glass        _complete_delay: Expected delay until completion (timedelta)
185fc3fe1c2SSimon Glass        _next_delay_update: Next time we plan to display a progress update
186fc3fe1c2SSimon Glass                (datatime)
187fc3fe1c2SSimon Glass        _show_unknown: Show unknown boards (those not built) in summary
188fc3fe1c2SSimon Glass        _timestamps: List of timestamps for the completion of the last
189fc3fe1c2SSimon Glass            last _timestamp_count builds. Each is a datetime object.
190fc3fe1c2SSimon Glass        _timestamp_count: Number of timestamps to keep in our list.
191fc3fe1c2SSimon Glass        _working_dir: Base working directory containing all threads
192fc3fe1c2SSimon Glass    """
193fc3fe1c2SSimon Glass    class Outcome:
194fc3fe1c2SSimon Glass        """Records a build outcome for a single make invocation
195fc3fe1c2SSimon Glass
196fc3fe1c2SSimon Glass        Public Members:
197fc3fe1c2SSimon Glass            rc: Outcome value (OUTCOME_...)
198fc3fe1c2SSimon Glass            err_lines: List of error lines or [] if none
199fc3fe1c2SSimon Glass            sizes: Dictionary of image size information, keyed by filename
200fc3fe1c2SSimon Glass                - Each value is itself a dictionary containing
201fc3fe1c2SSimon Glass                    values for 'text', 'data' and 'bss', being the integer
202fc3fe1c2SSimon Glass                    size in bytes of each section.
203fc3fe1c2SSimon Glass            func_sizes: Dictionary keyed by filename - e.g. 'u-boot'. Each
204fc3fe1c2SSimon Glass                    value is itself a dictionary:
205fc3fe1c2SSimon Glass                        key: function name
206fc3fe1c2SSimon Glass                        value: Size of function in bytes
207843312dcSSimon Glass            config: Dictionary keyed by filename - e.g. '.config'. Each
208843312dcSSimon Glass                    value is itself a dictionary:
209843312dcSSimon Glass                        key: config name
210843312dcSSimon Glass                        value: config value
21148ae4124SAlex Kiernan            environment: Dictionary keyed by environment variable, Each
21248ae4124SAlex Kiernan                     value is the value of environment variable.
213fc3fe1c2SSimon Glass        """
21448ae4124SAlex Kiernan        def __init__(self, rc, err_lines, sizes, func_sizes, config,
21548ae4124SAlex Kiernan                     environment):
216fc3fe1c2SSimon Glass            self.rc = rc
217fc3fe1c2SSimon Glass            self.err_lines = err_lines
218fc3fe1c2SSimon Glass            self.sizes = sizes
219fc3fe1c2SSimon Glass            self.func_sizes = func_sizes
220843312dcSSimon Glass            self.config = config
22148ae4124SAlex Kiernan            self.environment = environment
222fc3fe1c2SSimon Glass
223fc3fe1c2SSimon Glass    def __init__(self, toolchains, base_dir, git_dir, num_threads, num_jobs,
2245971ab5cSSimon Glass                 gnu_make='make', checkout=True, show_unknown=True, step=1,
225f79f1e0cSStephen Warren                 no_subdirs=False, full_path=False, verbose_build=False,
226b50113f3SSimon Glass                 incremental=False, per_board_out_dir=False,
2272371d1bcSDaniel Schwierzeck                 config_only=False, squash_config_y=False,
2282371d1bcSDaniel Schwierzeck                 warnings_as_errors=False):
229fc3fe1c2SSimon Glass        """Create a new Builder object
230fc3fe1c2SSimon Glass
231fc3fe1c2SSimon Glass        Args:
232fc3fe1c2SSimon Glass            toolchains: Toolchains object to use for building
233fc3fe1c2SSimon Glass            base_dir: Base directory to use for builder
234fc3fe1c2SSimon Glass            git_dir: Git directory containing source repository
235fc3fe1c2SSimon Glass            num_threads: Number of builder threads to run
236fc3fe1c2SSimon Glass            num_jobs: Number of jobs to run at once (passed to make as -j)
23799796923SMasahiro Yamada            gnu_make: the command name of GNU Make.
238fc3fe1c2SSimon Glass            checkout: True to check out source, False to skip that step.
239fc3fe1c2SSimon Glass                This is used for testing.
240fc3fe1c2SSimon Glass            show_unknown: Show unknown boards (those not built) in summary
241fc3fe1c2SSimon Glass            step: 1 to process every commit, n to process every nth commit
242bb1501f2SSimon Glass            no_subdirs: Don't create subdirectories when building current
243bb1501f2SSimon Glass                source for a single board
244bb1501f2SSimon Glass            full_path: Return the full path in CROSS_COMPILE and don't set
245bb1501f2SSimon Glass                PATH
246d2ce658dSSimon Glass            verbose_build: Run build with V=1 and don't use 'make -s'
247f79f1e0cSStephen Warren            incremental: Always perform incremental builds; don't run make
248f79f1e0cSStephen Warren                mrproper when configuring
249f79f1e0cSStephen Warren            per_board_out_dir: Build in a separate persistent directory per
250f79f1e0cSStephen Warren                board rather than a thread-specific directory
251b50113f3SSimon Glass            config_only: Only configure each build, don't build it
252b464f8e7SSimon Glass            squash_config_y: Convert CONFIG options with the value 'y' to '1'
2532371d1bcSDaniel Schwierzeck            warnings_as_errors: Treat all compiler warnings as errors
254fc3fe1c2SSimon Glass        """
255fc3fe1c2SSimon Glass        self.toolchains = toolchains
256fc3fe1c2SSimon Glass        self.base_dir = base_dir
257fc3fe1c2SSimon Glass        self._working_dir = os.path.join(base_dir, '.bm-work')
258fc3fe1c2SSimon Glass        self.threads = []
259fc3fe1c2SSimon Glass        self.do_make = self.Make
26099796923SMasahiro Yamada        self.gnu_make = gnu_make
261fc3fe1c2SSimon Glass        self.checkout = checkout
262fc3fe1c2SSimon Glass        self.num_threads = num_threads
263fc3fe1c2SSimon Glass        self.num_jobs = num_jobs
264fc3fe1c2SSimon Glass        self.already_done = 0
265fc3fe1c2SSimon Glass        self.force_build = False
266fc3fe1c2SSimon Glass        self.git_dir = git_dir
267fc3fe1c2SSimon Glass        self._show_unknown = show_unknown
268fc3fe1c2SSimon Glass        self._timestamp_count = 10
269fc3fe1c2SSimon Glass        self._build_period_us = None
270fc3fe1c2SSimon Glass        self._complete_delay = None
271fc3fe1c2SSimon Glass        self._next_delay_update = datetime.now()
272fc3fe1c2SSimon Glass        self.force_config_on_failure = True
2734266dc28SSimon Glass        self.force_build_failures = False
27497e91526SSimon Glass        self.force_reconfig = False
275fc3fe1c2SSimon Glass        self._step = step
276189a4968SSimon Glass        self.in_tree = False
27728370c1bSSimon Glass        self._error_lines = 0
2785971ab5cSSimon Glass        self.no_subdirs = no_subdirs
279bb1501f2SSimon Glass        self.full_path = full_path
280d2ce658dSSimon Glass        self.verbose_build = verbose_build
281b50113f3SSimon Glass        self.config_only = config_only
282b464f8e7SSimon Glass        self.squash_config_y = squash_config_y
283b464f8e7SSimon Glass        self.config_filenames = BASE_CONFIG_FILENAMES
284b464f8e7SSimon Glass        if not self.squash_config_y:
285b464f8e7SSimon Glass            self.config_filenames += EXTRA_CONFIG_FILENAMES
286fc3fe1c2SSimon Glass
2872371d1bcSDaniel Schwierzeck        self.warnings_as_errors = warnings_as_errors
288fc3fe1c2SSimon Glass        self.col = terminal.Color()
289fc3fe1c2SSimon Glass
290e30965dbSSimon Glass        self._re_function = re.compile('(.*): In function.*')
291e30965dbSSimon Glass        self._re_files = re.compile('In file included from.*')
292e30965dbSSimon Glass        self._re_warning = re.compile('(.*):(\d*):(\d*): warning: .*')
2932d48333eSSimon Glass        self._re_dtb_warning = re.compile('(.*): Warning .*')
294e30965dbSSimon Glass        self._re_note = re.compile('(.*):(\d*):(\d*): note: this is the location of the previous.*')
295e30965dbSSimon Glass
296fc3fe1c2SSimon Glass        self.queue = Queue.Queue()
297fc3fe1c2SSimon Glass        self.out_queue = Queue.Queue()
298fc3fe1c2SSimon Glass        for i in range(self.num_threads):
299f79f1e0cSStephen Warren            t = builderthread.BuilderThread(self, i, incremental,
300f79f1e0cSStephen Warren                    per_board_out_dir)
301fc3fe1c2SSimon Glass            t.setDaemon(True)
302fc3fe1c2SSimon Glass            t.start()
303fc3fe1c2SSimon Glass            self.threads.append(t)
304fc3fe1c2SSimon Glass
305fc3fe1c2SSimon Glass        self.last_line_len = 0
306190064b4SSimon Glass        t = builderthread.ResultThread(self)
307fc3fe1c2SSimon Glass        t.setDaemon(True)
308fc3fe1c2SSimon Glass        t.start()
309fc3fe1c2SSimon Glass        self.threads.append(t)
310fc3fe1c2SSimon Glass
311fc3fe1c2SSimon Glass        ignore_lines = ['(make.*Waiting for unfinished)', '(Segmentation fault)']
312fc3fe1c2SSimon Glass        self.re_make_err = re.compile('|'.join(ignore_lines))
313fc3fe1c2SSimon Glass
3142f256648SSimon Glass        # Handle existing graceful with SIGINT / Ctrl-C
3152f256648SSimon Glass        signal.signal(signal.SIGINT, self.signal_handler)
3162f256648SSimon Glass
317fc3fe1c2SSimon Glass    def __del__(self):
318fc3fe1c2SSimon Glass        """Get rid of all threads created by the builder"""
319fc3fe1c2SSimon Glass        for t in self.threads:
320fc3fe1c2SSimon Glass            del t
321fc3fe1c2SSimon Glass
3222f256648SSimon Glass    def signal_handler(self, signal, frame):
3232f256648SSimon Glass        sys.exit(1)
3242f256648SSimon Glass
325b2ea7ab2SSimon Glass    def SetDisplayOptions(self, show_errors=False, show_sizes=False,
326ed966657SSimon Glass                          show_detail=False, show_bloat=False,
32748ae4124SAlex Kiernan                          list_error_boards=False, show_config=False,
32848ae4124SAlex Kiernan                          show_environment=False):
329b2ea7ab2SSimon Glass        """Setup display options for the builder.
330b2ea7ab2SSimon Glass
331b2ea7ab2SSimon Glass        show_errors: True to show summarised error/warning info
332b2ea7ab2SSimon Glass        show_sizes: Show size deltas
333b2ea7ab2SSimon Glass        show_detail: Show detail for each board
334b2ea7ab2SSimon Glass        show_bloat: Show detail for each function
335ed966657SSimon Glass        list_error_boards: Show the boards which caused each error/warning
336843312dcSSimon Glass        show_config: Show config deltas
33748ae4124SAlex Kiernan        show_environment: Show environment deltas
338b2ea7ab2SSimon Glass        """
339b2ea7ab2SSimon Glass        self._show_errors = show_errors
340b2ea7ab2SSimon Glass        self._show_sizes = show_sizes
341b2ea7ab2SSimon Glass        self._show_detail = show_detail
342b2ea7ab2SSimon Glass        self._show_bloat = show_bloat
343ed966657SSimon Glass        self._list_error_boards = list_error_boards
344843312dcSSimon Glass        self._show_config = show_config
34548ae4124SAlex Kiernan        self._show_environment = show_environment
346b2ea7ab2SSimon Glass
347fc3fe1c2SSimon Glass    def _AddTimestamp(self):
348fc3fe1c2SSimon Glass        """Add a new timestamp to the list and record the build period.
349fc3fe1c2SSimon Glass
350fc3fe1c2SSimon Glass        The build period is the length of time taken to perform a single
351fc3fe1c2SSimon Glass        build (one board, one commit).
352fc3fe1c2SSimon Glass        """
353fc3fe1c2SSimon Glass        now = datetime.now()
354fc3fe1c2SSimon Glass        self._timestamps.append(now)
355fc3fe1c2SSimon Glass        count = len(self._timestamps)
356fc3fe1c2SSimon Glass        delta = self._timestamps[-1] - self._timestamps[0]
357fc3fe1c2SSimon Glass        seconds = delta.total_seconds()
358fc3fe1c2SSimon Glass
359fc3fe1c2SSimon Glass        # If we have enough data, estimate build period (time taken for a
360fc3fe1c2SSimon Glass        # single build) and therefore completion time.
361fc3fe1c2SSimon Glass        if count > 1 and self._next_delay_update < now:
362fc3fe1c2SSimon Glass            self._next_delay_update = now + timedelta(seconds=2)
363fc3fe1c2SSimon Glass            if seconds > 0:
364fc3fe1c2SSimon Glass                self._build_period = float(seconds) / count
365fc3fe1c2SSimon Glass                todo = self.count - self.upto
366fc3fe1c2SSimon Glass                self._complete_delay = timedelta(microseconds=
367fc3fe1c2SSimon Glass                        self._build_period * todo * 1000000)
368fc3fe1c2SSimon Glass                # Round it
369fc3fe1c2SSimon Glass                self._complete_delay -= timedelta(
370fc3fe1c2SSimon Glass                        microseconds=self._complete_delay.microseconds)
371fc3fe1c2SSimon Glass
372fc3fe1c2SSimon Glass        if seconds > 60:
373fc3fe1c2SSimon Glass            self._timestamps.popleft()
374fc3fe1c2SSimon Glass            count -= 1
375fc3fe1c2SSimon Glass
376fc3fe1c2SSimon Glass    def ClearLine(self, length):
377fc3fe1c2SSimon Glass        """Clear any characters on the current line
378fc3fe1c2SSimon Glass
379fc3fe1c2SSimon Glass        Make way for a new line of length 'length', by outputting enough
380fc3fe1c2SSimon Glass        spaces to clear out the old line. Then remember the new length for
381fc3fe1c2SSimon Glass        next time.
382fc3fe1c2SSimon Glass
383fc3fe1c2SSimon Glass        Args:
384fc3fe1c2SSimon Glass            length: Length of new line, in characters
385fc3fe1c2SSimon Glass        """
386fc3fe1c2SSimon Glass        if length < self.last_line_len:
3874653a882SSimon Glass            Print(' ' * (self.last_line_len - length), newline=False)
3884653a882SSimon Glass            Print('\r', newline=False)
389fc3fe1c2SSimon Glass        self.last_line_len = length
390fc3fe1c2SSimon Glass        sys.stdout.flush()
391fc3fe1c2SSimon Glass
392fc3fe1c2SSimon Glass    def SelectCommit(self, commit, checkout=True):
393fc3fe1c2SSimon Glass        """Checkout the selected commit for this build
394fc3fe1c2SSimon Glass        """
395fc3fe1c2SSimon Glass        self.commit = commit
396fc3fe1c2SSimon Glass        if checkout and self.checkout:
397fc3fe1c2SSimon Glass            gitutil.Checkout(commit.hash)
398fc3fe1c2SSimon Glass
399fc3fe1c2SSimon Glass    def Make(self, commit, brd, stage, cwd, *args, **kwargs):
400fc3fe1c2SSimon Glass        """Run make
401fc3fe1c2SSimon Glass
402fc3fe1c2SSimon Glass        Args:
403fc3fe1c2SSimon Glass            commit: Commit object that is being built
404fc3fe1c2SSimon Glass            brd: Board object that is being built
405fd18a89eSRoger Meier            stage: Stage that we are at (mrproper, config, build)
406fc3fe1c2SSimon Glass            cwd: Directory where make should be run
407fc3fe1c2SSimon Glass            args: Arguments to pass to make
408fc3fe1c2SSimon Glass            kwargs: Arguments to pass to command.RunPipe()
409fc3fe1c2SSimon Glass        """
41099796923SMasahiro Yamada        cmd = [self.gnu_make] + list(args)
411fc3fe1c2SSimon Glass        result = command.RunPipe([cmd], capture=True, capture_stderr=True,
412e62a24ceSSimon Glass                cwd=cwd, raise_on_error=False, infile='/dev/null', **kwargs)
41340f11fceSSimon Glass        if self.verbose_build:
41440f11fceSSimon Glass            result.stdout = '%s\n' % (' '.join(cmd)) + result.stdout
41540f11fceSSimon Glass            result.combined = '%s\n' % (' '.join(cmd)) + result.combined
416fc3fe1c2SSimon Glass        return result
417fc3fe1c2SSimon Glass
418fc3fe1c2SSimon Glass    def ProcessResult(self, result):
419fc3fe1c2SSimon Glass        """Process the result of a build, showing progress information
420fc3fe1c2SSimon Glass
421fc3fe1c2SSimon Glass        Args:
422e5a0e5d8SSimon Glass            result: A CommandResult object, which indicates the result for
423e5a0e5d8SSimon Glass                    a single build
424fc3fe1c2SSimon Glass        """
425fc3fe1c2SSimon Glass        col = terminal.Color()
426fc3fe1c2SSimon Glass        if result:
427fc3fe1c2SSimon Glass            target = result.brd.target
428fc3fe1c2SSimon Glass
429fc3fe1c2SSimon Glass            self.upto += 1
430fc3fe1c2SSimon Glass            if result.return_code != 0:
431fc3fe1c2SSimon Glass                self.fail += 1
432fc3fe1c2SSimon Glass            elif result.stderr:
433fc3fe1c2SSimon Glass                self.warned += 1
434fc3fe1c2SSimon Glass            if result.already_done:
435fc3fe1c2SSimon Glass                self.already_done += 1
436e5a0e5d8SSimon Glass            if self._verbose:
4374653a882SSimon Glass                Print('\r', newline=False)
438e5a0e5d8SSimon Glass                self.ClearLine(0)
439e5a0e5d8SSimon Glass                boards_selected = {target : result.brd}
440e5a0e5d8SSimon Glass                self.ResetResultSummary(boards_selected)
441e5a0e5d8SSimon Glass                self.ProduceResultSummary(result.commit_upto, self.commits,
442e5a0e5d8SSimon Glass                                          boards_selected)
443fc3fe1c2SSimon Glass        else:
444fc3fe1c2SSimon Glass            target = '(starting)'
445fc3fe1c2SSimon Glass
446fc3fe1c2SSimon Glass        # Display separate counts for ok, warned and fail
447fc3fe1c2SSimon Glass        ok = self.upto - self.warned - self.fail
448fc3fe1c2SSimon Glass        line = '\r' + self.col.Color(self.col.GREEN, '%5d' % ok)
449fc3fe1c2SSimon Glass        line += self.col.Color(self.col.YELLOW, '%5d' % self.warned)
450fc3fe1c2SSimon Glass        line += self.col.Color(self.col.RED, '%5d' % self.fail)
451fc3fe1c2SSimon Glass
452fc3fe1c2SSimon Glass        name = ' /%-5d  ' % self.count
453fc3fe1c2SSimon Glass
454fc3fe1c2SSimon Glass        # Add our current completion time estimate
455fc3fe1c2SSimon Glass        self._AddTimestamp()
456fc3fe1c2SSimon Glass        if self._complete_delay:
457fc3fe1c2SSimon Glass            name += '%s  : ' % self._complete_delay
458fc3fe1c2SSimon Glass        # When building all boards for a commit, we can print a commit
459fc3fe1c2SSimon Glass        # progress message.
460fc3fe1c2SSimon Glass        if result and result.commit_upto is None:
461fc3fe1c2SSimon Glass            name += 'commit %2d/%-3d' % (self.commit_upto + 1,
462fc3fe1c2SSimon Glass                    self.commit_count)
463fc3fe1c2SSimon Glass
464fc3fe1c2SSimon Glass        name += target
4654653a882SSimon Glass        Print(line + name, newline=False)
466960421ecSSimon Glass        length = 16 + len(name)
467fc3fe1c2SSimon Glass        self.ClearLine(length)
468fc3fe1c2SSimon Glass
469fc3fe1c2SSimon Glass    def _GetOutputDir(self, commit_upto):
470fc3fe1c2SSimon Glass        """Get the name of the output directory for a commit number
471fc3fe1c2SSimon Glass
472fc3fe1c2SSimon Glass        The output directory is typically .../<branch>/<commit>.
473fc3fe1c2SSimon Glass
474fc3fe1c2SSimon Glass        Args:
475fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
476fc3fe1c2SSimon Glass        """
4775971ab5cSSimon Glass        commit_dir = None
478fea5858eSSimon Glass        if self.commits:
479fc3fe1c2SSimon Glass            commit = self.commits[commit_upto]
480fc3fe1c2SSimon Glass            subject = commit.subject.translate(trans_valid_chars)
481fc3fe1c2SSimon Glass            commit_dir = ('%02d_of_%02d_g%s_%s' % (commit_upto + 1,
482fc3fe1c2SSimon Glass                    self.commit_count, commit.hash, subject[:20]))
4835971ab5cSSimon Glass        elif not self.no_subdirs:
484fea5858eSSimon Glass            commit_dir = 'current'
4855971ab5cSSimon Glass        if not commit_dir:
4865971ab5cSSimon Glass            return self.base_dir
4875971ab5cSSimon Glass        return os.path.join(self.base_dir, commit_dir)
488fc3fe1c2SSimon Glass
489fc3fe1c2SSimon Glass    def GetBuildDir(self, commit_upto, target):
490fc3fe1c2SSimon Glass        """Get the name of the build directory for a commit number
491fc3fe1c2SSimon Glass
492fc3fe1c2SSimon Glass        The build directory is typically .../<branch>/<commit>/<target>.
493fc3fe1c2SSimon Glass
494fc3fe1c2SSimon Glass        Args:
495fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
496fc3fe1c2SSimon Glass            target: Target name
497fc3fe1c2SSimon Glass        """
498fc3fe1c2SSimon Glass        output_dir = self._GetOutputDir(commit_upto)
499fc3fe1c2SSimon Glass        return os.path.join(output_dir, target)
500fc3fe1c2SSimon Glass
501fc3fe1c2SSimon Glass    def GetDoneFile(self, commit_upto, target):
502fc3fe1c2SSimon Glass        """Get the name of the done file for a commit number
503fc3fe1c2SSimon Glass
504fc3fe1c2SSimon Glass        Args:
505fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
506fc3fe1c2SSimon Glass            target: Target name
507fc3fe1c2SSimon Glass        """
508fc3fe1c2SSimon Glass        return os.path.join(self.GetBuildDir(commit_upto, target), 'done')
509fc3fe1c2SSimon Glass
510fc3fe1c2SSimon Glass    def GetSizesFile(self, commit_upto, target):
511fc3fe1c2SSimon Glass        """Get the name of the sizes file for a commit number
512fc3fe1c2SSimon Glass
513fc3fe1c2SSimon Glass        Args:
514fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
515fc3fe1c2SSimon Glass            target: Target name
516fc3fe1c2SSimon Glass        """
517fc3fe1c2SSimon Glass        return os.path.join(self.GetBuildDir(commit_upto, target), 'sizes')
518fc3fe1c2SSimon Glass
519fc3fe1c2SSimon Glass    def GetFuncSizesFile(self, commit_upto, target, elf_fname):
520fc3fe1c2SSimon Glass        """Get the name of the funcsizes file for a commit number and ELF file
521fc3fe1c2SSimon Glass
522fc3fe1c2SSimon Glass        Args:
523fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
524fc3fe1c2SSimon Glass            target: Target name
525fc3fe1c2SSimon Glass            elf_fname: Filename of elf image
526fc3fe1c2SSimon Glass        """
527fc3fe1c2SSimon Glass        return os.path.join(self.GetBuildDir(commit_upto, target),
528fc3fe1c2SSimon Glass                            '%s.sizes' % elf_fname.replace('/', '-'))
529fc3fe1c2SSimon Glass
530fc3fe1c2SSimon Glass    def GetObjdumpFile(self, commit_upto, target, elf_fname):
531fc3fe1c2SSimon Glass        """Get the name of the objdump file for a commit number and ELF file
532fc3fe1c2SSimon Glass
533fc3fe1c2SSimon Glass        Args:
534fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
535fc3fe1c2SSimon Glass            target: Target name
536fc3fe1c2SSimon Glass            elf_fname: Filename of elf image
537fc3fe1c2SSimon Glass        """
538fc3fe1c2SSimon Glass        return os.path.join(self.GetBuildDir(commit_upto, target),
539fc3fe1c2SSimon Glass                            '%s.objdump' % elf_fname.replace('/', '-'))
540fc3fe1c2SSimon Glass
541fc3fe1c2SSimon Glass    def GetErrFile(self, commit_upto, target):
542fc3fe1c2SSimon Glass        """Get the name of the err file for a commit number
543fc3fe1c2SSimon Glass
544fc3fe1c2SSimon Glass        Args:
545fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
546fc3fe1c2SSimon Glass            target: Target name
547fc3fe1c2SSimon Glass        """
548fc3fe1c2SSimon Glass        output_dir = self.GetBuildDir(commit_upto, target)
549fc3fe1c2SSimon Glass        return os.path.join(output_dir, 'err')
550fc3fe1c2SSimon Glass
551fc3fe1c2SSimon Glass    def FilterErrors(self, lines):
552fc3fe1c2SSimon Glass        """Filter out errors in which we have no interest
553fc3fe1c2SSimon Glass
554fc3fe1c2SSimon Glass        We should probably use map().
555fc3fe1c2SSimon Glass
556fc3fe1c2SSimon Glass        Args:
557fc3fe1c2SSimon Glass            lines: List of error lines, each a string
558fc3fe1c2SSimon Glass        Returns:
559fc3fe1c2SSimon Glass            New list with only interesting lines included
560fc3fe1c2SSimon Glass        """
561fc3fe1c2SSimon Glass        out_lines = []
562fc3fe1c2SSimon Glass        for line in lines:
563fc3fe1c2SSimon Glass            if not self.re_make_err.search(line):
564fc3fe1c2SSimon Glass                out_lines.append(line)
565fc3fe1c2SSimon Glass        return out_lines
566fc3fe1c2SSimon Glass
567fc3fe1c2SSimon Glass    def ReadFuncSizes(self, fname, fd):
568fc3fe1c2SSimon Glass        """Read function sizes from the output of 'nm'
569fc3fe1c2SSimon Glass
570fc3fe1c2SSimon Glass        Args:
571fc3fe1c2SSimon Glass            fd: File containing data to read
572fc3fe1c2SSimon Glass            fname: Filename we are reading from (just for errors)
573fc3fe1c2SSimon Glass
574fc3fe1c2SSimon Glass        Returns:
575fc3fe1c2SSimon Glass            Dictionary containing size of each function in bytes, indexed by
576fc3fe1c2SSimon Glass            function name.
577fc3fe1c2SSimon Glass        """
578fc3fe1c2SSimon Glass        sym = {}
579fc3fe1c2SSimon Glass        for line in fd.readlines():
580fc3fe1c2SSimon Glass            try:
581fc3fe1c2SSimon Glass                size, type, name = line[:-1].split()
582fc3fe1c2SSimon Glass            except:
5834653a882SSimon Glass                Print("Invalid line in file '%s': '%s'" % (fname, line[:-1]))
584fc3fe1c2SSimon Glass                continue
585fc3fe1c2SSimon Glass            if type in 'tTdDbB':
586fc3fe1c2SSimon Glass                # function names begin with '.' on 64-bit powerpc
587fc3fe1c2SSimon Glass                if '.' in name[1:]:
588fc3fe1c2SSimon Glass                    name = 'static.' + name.split('.')[0]
589fc3fe1c2SSimon Glass                sym[name] = sym.get(name, 0) + int(size, 16)
590fc3fe1c2SSimon Glass        return sym
591fc3fe1c2SSimon Glass
592843312dcSSimon Glass    def _ProcessConfig(self, fname):
593843312dcSSimon Glass        """Read in a .config, autoconf.mk or autoconf.h file
594843312dcSSimon Glass
595843312dcSSimon Glass        This function handles all config file types. It ignores comments and
596843312dcSSimon Glass        any #defines which don't start with CONFIG_.
597843312dcSSimon Glass
598843312dcSSimon Glass        Args:
599843312dcSSimon Glass            fname: Filename to read
600843312dcSSimon Glass
601843312dcSSimon Glass        Returns:
602843312dcSSimon Glass            Dictionary:
603843312dcSSimon Glass                key: Config name (e.g. CONFIG_DM)
604843312dcSSimon Glass                value: Config value (e.g. 1)
605843312dcSSimon Glass        """
606843312dcSSimon Glass        config = {}
607843312dcSSimon Glass        if os.path.exists(fname):
608843312dcSSimon Glass            with open(fname) as fd:
609843312dcSSimon Glass                for line in fd:
610843312dcSSimon Glass                    line = line.strip()
611843312dcSSimon Glass                    if line.startswith('#define'):
612843312dcSSimon Glass                        values = line[8:].split(' ', 1)
613843312dcSSimon Glass                        if len(values) > 1:
614843312dcSSimon Glass                            key, value = values
615843312dcSSimon Glass                        else:
616843312dcSSimon Glass                            key = values[0]
617b464f8e7SSimon Glass                            value = '1' if self.squash_config_y else ''
618843312dcSSimon Glass                        if not key.startswith('CONFIG_'):
619843312dcSSimon Glass                            continue
620843312dcSSimon Glass                    elif not line or line[0] in ['#', '*', '/']:
621843312dcSSimon Glass                        continue
622843312dcSSimon Glass                    else:
623843312dcSSimon Glass                        key, value = line.split('=', 1)
624b464f8e7SSimon Glass                    if self.squash_config_y and value == 'y':
625b464f8e7SSimon Glass                        value = '1'
626843312dcSSimon Glass                    config[key] = value
627843312dcSSimon Glass        return config
628843312dcSSimon Glass
62948ae4124SAlex Kiernan    def _ProcessEnvironment(self, fname):
63048ae4124SAlex Kiernan        """Read in a uboot.env file
63148ae4124SAlex Kiernan
63248ae4124SAlex Kiernan        This function reads in environment variables from a file.
63348ae4124SAlex Kiernan
63448ae4124SAlex Kiernan        Args:
63548ae4124SAlex Kiernan            fname: Filename to read
63648ae4124SAlex Kiernan
63748ae4124SAlex Kiernan        Returns:
63848ae4124SAlex Kiernan            Dictionary:
63948ae4124SAlex Kiernan                key: environment variable (e.g. bootlimit)
64048ae4124SAlex Kiernan                value: value of environment variable (e.g. 1)
64148ae4124SAlex Kiernan        """
64248ae4124SAlex Kiernan        environment = {}
64348ae4124SAlex Kiernan        if os.path.exists(fname):
64448ae4124SAlex Kiernan            with open(fname) as fd:
64548ae4124SAlex Kiernan                for line in fd.read().split('\0'):
64648ae4124SAlex Kiernan                    try:
64748ae4124SAlex Kiernan                        key, value = line.split('=', 1)
64848ae4124SAlex Kiernan                        environment[key] = value
64948ae4124SAlex Kiernan                    except ValueError:
65048ae4124SAlex Kiernan                        # ignore lines we can't parse
65148ae4124SAlex Kiernan                        pass
65248ae4124SAlex Kiernan        return environment
65348ae4124SAlex Kiernan
654843312dcSSimon Glass    def GetBuildOutcome(self, commit_upto, target, read_func_sizes,
65548ae4124SAlex Kiernan                        read_config, read_environment):
656fc3fe1c2SSimon Glass        """Work out the outcome of a build.
657fc3fe1c2SSimon Glass
658fc3fe1c2SSimon Glass        Args:
659fc3fe1c2SSimon Glass            commit_upto: Commit number to check (0..n-1)
660fc3fe1c2SSimon Glass            target: Target board to check
661fc3fe1c2SSimon Glass            read_func_sizes: True to read function size information
662843312dcSSimon Glass            read_config: True to read .config and autoconf.h files
66348ae4124SAlex Kiernan            read_environment: True to read uboot.env files
664fc3fe1c2SSimon Glass
665fc3fe1c2SSimon Glass        Returns:
666fc3fe1c2SSimon Glass            Outcome object
667fc3fe1c2SSimon Glass        """
668fc3fe1c2SSimon Glass        done_file = self.GetDoneFile(commit_upto, target)
669fc3fe1c2SSimon Glass        sizes_file = self.GetSizesFile(commit_upto, target)
670fc3fe1c2SSimon Glass        sizes = {}
671fc3fe1c2SSimon Glass        func_sizes = {}
672843312dcSSimon Glass        config = {}
67348ae4124SAlex Kiernan        environment = {}
674fc3fe1c2SSimon Glass        if os.path.exists(done_file):
675fc3fe1c2SSimon Glass            with open(done_file, 'r') as fd:
676fc3fe1c2SSimon Glass                return_code = int(fd.readline())
677fc3fe1c2SSimon Glass                err_lines = []
678fc3fe1c2SSimon Glass                err_file = self.GetErrFile(commit_upto, target)
679fc3fe1c2SSimon Glass                if os.path.exists(err_file):
680fc3fe1c2SSimon Glass                    with open(err_file, 'r') as fd:
681fc3fe1c2SSimon Glass                        err_lines = self.FilterErrors(fd.readlines())
682fc3fe1c2SSimon Glass
683fc3fe1c2SSimon Glass                # Decide whether the build was ok, failed or created warnings
684fc3fe1c2SSimon Glass                if return_code:
685fc3fe1c2SSimon Glass                    rc = OUTCOME_ERROR
686fc3fe1c2SSimon Glass                elif len(err_lines):
687fc3fe1c2SSimon Glass                    rc = OUTCOME_WARNING
688fc3fe1c2SSimon Glass                else:
689fc3fe1c2SSimon Glass                    rc = OUTCOME_OK
690fc3fe1c2SSimon Glass
691fc3fe1c2SSimon Glass                # Convert size information to our simple format
692fc3fe1c2SSimon Glass                if os.path.exists(sizes_file):
693fc3fe1c2SSimon Glass                    with open(sizes_file, 'r') as fd:
694fc3fe1c2SSimon Glass                        for line in fd.readlines():
695fc3fe1c2SSimon Glass                            values = line.split()
696fc3fe1c2SSimon Glass                            rodata = 0
697fc3fe1c2SSimon Glass                            if len(values) > 6:
698fc3fe1c2SSimon Glass                                rodata = int(values[6], 16)
699fc3fe1c2SSimon Glass                            size_dict = {
700fc3fe1c2SSimon Glass                                'all' : int(values[0]) + int(values[1]) +
701fc3fe1c2SSimon Glass                                        int(values[2]),
702fc3fe1c2SSimon Glass                                'text' : int(values[0]) - rodata,
703fc3fe1c2SSimon Glass                                'data' : int(values[1]),
704fc3fe1c2SSimon Glass                                'bss' : int(values[2]),
705fc3fe1c2SSimon Glass                                'rodata' : rodata,
706fc3fe1c2SSimon Glass                            }
707fc3fe1c2SSimon Glass                            sizes[values[5]] = size_dict
708fc3fe1c2SSimon Glass
709fc3fe1c2SSimon Glass            if read_func_sizes:
710fc3fe1c2SSimon Glass                pattern = self.GetFuncSizesFile(commit_upto, target, '*')
711fc3fe1c2SSimon Glass                for fname in glob.glob(pattern):
712fc3fe1c2SSimon Glass                    with open(fname, 'r') as fd:
713fc3fe1c2SSimon Glass                        dict_name = os.path.basename(fname).replace('.sizes',
714fc3fe1c2SSimon Glass                                                                    '')
715fc3fe1c2SSimon Glass                        func_sizes[dict_name] = self.ReadFuncSizes(fname, fd)
716fc3fe1c2SSimon Glass
717843312dcSSimon Glass            if read_config:
718843312dcSSimon Glass                output_dir = self.GetBuildDir(commit_upto, target)
719b464f8e7SSimon Glass                for name in self.config_filenames:
720843312dcSSimon Glass                    fname = os.path.join(output_dir, name)
721843312dcSSimon Glass                    config[name] = self._ProcessConfig(fname)
722fc3fe1c2SSimon Glass
72348ae4124SAlex Kiernan            if read_environment:
72448ae4124SAlex Kiernan                output_dir = self.GetBuildDir(commit_upto, target)
72548ae4124SAlex Kiernan                fname = os.path.join(output_dir, 'uboot.env')
72648ae4124SAlex Kiernan                environment = self._ProcessEnvironment(fname)
727fc3fe1c2SSimon Glass
72848ae4124SAlex Kiernan            return Builder.Outcome(rc, err_lines, sizes, func_sizes, config,
72948ae4124SAlex Kiernan                                   environment)
73048ae4124SAlex Kiernan
73148ae4124SAlex Kiernan        return Builder.Outcome(OUTCOME_UNKNOWN, [], {}, {}, {}, {})
732843312dcSSimon Glass
733843312dcSSimon Glass    def GetResultSummary(self, boards_selected, commit_upto, read_func_sizes,
73448ae4124SAlex Kiernan                         read_config, read_environment):
735fc3fe1c2SSimon Glass        """Calculate a summary of the results of building a commit.
736fc3fe1c2SSimon Glass
737fc3fe1c2SSimon Glass        Args:
738fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise
739fc3fe1c2SSimon Glass            commit_upto: Commit number to summarize (0..self.count-1)
740fc3fe1c2SSimon Glass            read_func_sizes: True to read function size information
741843312dcSSimon Glass            read_config: True to read .config and autoconf.h files
74248ae4124SAlex Kiernan            read_environment: True to read uboot.env files
743fc3fe1c2SSimon Glass
744fc3fe1c2SSimon Glass        Returns:
745fc3fe1c2SSimon Glass            Tuple:
746fc3fe1c2SSimon Glass                Dict containing boards which passed building this commit.
747fc3fe1c2SSimon Glass                    keyed by board.target
748e30965dbSSimon Glass                List containing a summary of error lines
749ed966657SSimon Glass                Dict keyed by error line, containing a list of the Board
750ed966657SSimon Glass                    objects with that error
751e30965dbSSimon Glass                List containing a summary of warning lines
752e30965dbSSimon Glass                Dict keyed by error line, containing a list of the Board
753e30965dbSSimon Glass                    objects with that warning
7548270e3c1SSimon Glass                Dictionary keyed by board.target. Each value is a dictionary:
7558270e3c1SSimon Glass                    key: filename - e.g. '.config'
756843312dcSSimon Glass                    value is itself a dictionary:
757843312dcSSimon Glass                        key: config name
758843312dcSSimon Glass                        value: config value
75948ae4124SAlex Kiernan                Dictionary keyed by board.target. Each value is a dictionary:
76048ae4124SAlex Kiernan                    key: environment variable
76148ae4124SAlex Kiernan                    value: value of environment variable
762fc3fe1c2SSimon Glass        """
763e30965dbSSimon Glass        def AddLine(lines_summary, lines_boards, line, board):
764e30965dbSSimon Glass            line = line.rstrip()
765e30965dbSSimon Glass            if line in lines_boards:
766e30965dbSSimon Glass                lines_boards[line].append(board)
767e30965dbSSimon Glass            else:
768e30965dbSSimon Glass                lines_boards[line] = [board]
769e30965dbSSimon Glass                lines_summary.append(line)
770e30965dbSSimon Glass
771fc3fe1c2SSimon Glass        board_dict = {}
772fc3fe1c2SSimon Glass        err_lines_summary = []
773ed966657SSimon Glass        err_lines_boards = {}
774e30965dbSSimon Glass        warn_lines_summary = []
775e30965dbSSimon Glass        warn_lines_boards = {}
776843312dcSSimon Glass        config = {}
77748ae4124SAlex Kiernan        environment = {}
778fc3fe1c2SSimon Glass
779fc3fe1c2SSimon Glass        for board in boards_selected.itervalues():
780fc3fe1c2SSimon Glass            outcome = self.GetBuildOutcome(commit_upto, board.target,
78148ae4124SAlex Kiernan                                           read_func_sizes, read_config,
78248ae4124SAlex Kiernan                                           read_environment)
783fc3fe1c2SSimon Glass            board_dict[board.target] = outcome
784e30965dbSSimon Glass            last_func = None
785e30965dbSSimon Glass            last_was_warning = False
786e30965dbSSimon Glass            for line in outcome.err_lines:
787e30965dbSSimon Glass                if line:
788e30965dbSSimon Glass                    if (self._re_function.match(line) or
789e30965dbSSimon Glass                            self._re_files.match(line)):
790e30965dbSSimon Glass                        last_func = line
791ed966657SSimon Glass                    else:
7922d48333eSSimon Glass                        is_warning = (self._re_warning.match(line) or
7932d48333eSSimon Glass                                      self._re_dtb_warning.match(line))
794e30965dbSSimon Glass                        is_note = self._re_note.match(line)
795e30965dbSSimon Glass                        if is_warning or (last_was_warning and is_note):
796e30965dbSSimon Glass                            if last_func:
797e30965dbSSimon Glass                                AddLine(warn_lines_summary, warn_lines_boards,
798e30965dbSSimon Glass                                        last_func, board)
799e30965dbSSimon Glass                            AddLine(warn_lines_summary, warn_lines_boards,
800e30965dbSSimon Glass                                    line, board)
801e30965dbSSimon Glass                        else:
802e30965dbSSimon Glass                            if last_func:
803e30965dbSSimon Glass                                AddLine(err_lines_summary, err_lines_boards,
804e30965dbSSimon Glass                                        last_func, board)
805e30965dbSSimon Glass                            AddLine(err_lines_summary, err_lines_boards,
806e30965dbSSimon Glass                                    line, board)
807e30965dbSSimon Glass                        last_was_warning = is_warning
808e30965dbSSimon Glass                        last_func = None
809b464f8e7SSimon Glass            tconfig = Config(self.config_filenames, board.target)
810b464f8e7SSimon Glass            for fname in self.config_filenames:
811843312dcSSimon Glass                if outcome.config:
812843312dcSSimon Glass                    for key, value in outcome.config[fname].iteritems():
8138270e3c1SSimon Glass                        tconfig.Add(fname, key, value)
8148270e3c1SSimon Glass            config[board.target] = tconfig
815843312dcSSimon Glass
81648ae4124SAlex Kiernan            tenvironment = Environment(board.target)
81748ae4124SAlex Kiernan            if outcome.environment:
81848ae4124SAlex Kiernan                for key, value in outcome.environment.iteritems():
81948ae4124SAlex Kiernan                    tenvironment.Add(key, value)
82048ae4124SAlex Kiernan            environment[board.target] = tenvironment
82148ae4124SAlex Kiernan
822e30965dbSSimon Glass        return (board_dict, err_lines_summary, err_lines_boards,
82348ae4124SAlex Kiernan                warn_lines_summary, warn_lines_boards, config, environment)
824fc3fe1c2SSimon Glass
825fc3fe1c2SSimon Glass    def AddOutcome(self, board_dict, arch_list, changes, char, color):
826fc3fe1c2SSimon Glass        """Add an output to our list of outcomes for each architecture
827fc3fe1c2SSimon Glass
828fc3fe1c2SSimon Glass        This simple function adds failing boards (changes) to the
829fc3fe1c2SSimon Glass        relevant architecture string, so we can print the results out
830fc3fe1c2SSimon Glass        sorted by architecture.
831fc3fe1c2SSimon Glass
832fc3fe1c2SSimon Glass        Args:
833fc3fe1c2SSimon Glass             board_dict: Dict containing all boards
834fc3fe1c2SSimon Glass             arch_list: Dict keyed by arch name. Value is a string containing
835fc3fe1c2SSimon Glass                    a list of board names which failed for that arch.
836fc3fe1c2SSimon Glass             changes: List of boards to add to arch_list
837fc3fe1c2SSimon Glass             color: terminal.Colour object
838fc3fe1c2SSimon Glass        """
839fc3fe1c2SSimon Glass        done_arch = {}
840fc3fe1c2SSimon Glass        for target in changes:
841fc3fe1c2SSimon Glass            if target in board_dict:
842fc3fe1c2SSimon Glass                arch = board_dict[target].arch
843fc3fe1c2SSimon Glass            else:
844fc3fe1c2SSimon Glass                arch = 'unknown'
845fc3fe1c2SSimon Glass            str = self.col.Color(color, ' ' + target)
846fc3fe1c2SSimon Glass            if not arch in done_arch:
84763c619eeSSimon Glass                str = ' %s  %s' % (self.col.Color(color, char), str)
848fc3fe1c2SSimon Glass                done_arch[arch] = True
849fc3fe1c2SSimon Glass            if not arch in arch_list:
850fc3fe1c2SSimon Glass                arch_list[arch] = str
851fc3fe1c2SSimon Glass            else:
852fc3fe1c2SSimon Glass                arch_list[arch] += str
853fc3fe1c2SSimon Glass
854fc3fe1c2SSimon Glass
855fc3fe1c2SSimon Glass    def ColourNum(self, num):
856fc3fe1c2SSimon Glass        color = self.col.RED if num > 0 else self.col.GREEN
857fc3fe1c2SSimon Glass        if num == 0:
858fc3fe1c2SSimon Glass            return '0'
859fc3fe1c2SSimon Glass        return self.col.Color(color, str(num))
860fc3fe1c2SSimon Glass
861fc3fe1c2SSimon Glass    def ResetResultSummary(self, board_selected):
862fc3fe1c2SSimon Glass        """Reset the results summary ready for use.
863fc3fe1c2SSimon Glass
864fc3fe1c2SSimon Glass        Set up the base board list to be all those selected, and set the
865fc3fe1c2SSimon Glass        error lines to empty.
866fc3fe1c2SSimon Glass
867fc3fe1c2SSimon Glass        Following this, calls to PrintResultSummary() will use this
868fc3fe1c2SSimon Glass        information to work out what has changed.
869fc3fe1c2SSimon Glass
870fc3fe1c2SSimon Glass        Args:
871fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise, keyed by
872fc3fe1c2SSimon Glass                board.target
873fc3fe1c2SSimon Glass        """
874fc3fe1c2SSimon Glass        self._base_board_dict = {}
875fc3fe1c2SSimon Glass        for board in board_selected:
87648ae4124SAlex Kiernan            self._base_board_dict[board] = Builder.Outcome(0, [], [], {}, {},
87748ae4124SAlex Kiernan                                                           {})
878fc3fe1c2SSimon Glass        self._base_err_lines = []
879e30965dbSSimon Glass        self._base_warn_lines = []
880e30965dbSSimon Glass        self._base_err_line_boards = {}
881e30965dbSSimon Glass        self._base_warn_line_boards = {}
8828270e3c1SSimon Glass        self._base_config = None
88348ae4124SAlex Kiernan        self._base_environment = None
884fc3fe1c2SSimon Glass
885fc3fe1c2SSimon Glass    def PrintFuncSizeDetail(self, fname, old, new):
886fc3fe1c2SSimon Glass        grow, shrink, add, remove, up, down = 0, 0, 0, 0, 0, 0
887fc3fe1c2SSimon Glass        delta, common = [], {}
888fc3fe1c2SSimon Glass
889fc3fe1c2SSimon Glass        for a in old:
890fc3fe1c2SSimon Glass            if a in new:
891fc3fe1c2SSimon Glass                common[a] = 1
892fc3fe1c2SSimon Glass
893fc3fe1c2SSimon Glass        for name in old:
894fc3fe1c2SSimon Glass            if name not in common:
895fc3fe1c2SSimon Glass                remove += 1
896fc3fe1c2SSimon Glass                down += old[name]
897fc3fe1c2SSimon Glass                delta.append([-old[name], name])
898fc3fe1c2SSimon Glass
899fc3fe1c2SSimon Glass        for name in new:
900fc3fe1c2SSimon Glass            if name not in common:
901fc3fe1c2SSimon Glass                add += 1
902fc3fe1c2SSimon Glass                up += new[name]
903fc3fe1c2SSimon Glass                delta.append([new[name], name])
904fc3fe1c2SSimon Glass
905fc3fe1c2SSimon Glass        for name in common:
906fc3fe1c2SSimon Glass                diff = new.get(name, 0) - old.get(name, 0)
907fc3fe1c2SSimon Glass                if diff > 0:
908fc3fe1c2SSimon Glass                    grow, up = grow + 1, up + diff
909fc3fe1c2SSimon Glass                elif diff < 0:
910fc3fe1c2SSimon Glass                    shrink, down = shrink + 1, down - diff
911fc3fe1c2SSimon Glass                delta.append([diff, name])
912fc3fe1c2SSimon Glass
913fc3fe1c2SSimon Glass        delta.sort()
914fc3fe1c2SSimon Glass        delta.reverse()
915fc3fe1c2SSimon Glass
916fc3fe1c2SSimon Glass        args = [add, -remove, grow, -shrink, up, -down, up - down]
917d5686a61STom Rini        if max(args) == 0 and min(args) == 0:
918fc3fe1c2SSimon Glass            return
919fc3fe1c2SSimon Glass        args = [self.ColourNum(x) for x in args]
920fc3fe1c2SSimon Glass        indent = ' ' * 15
9214653a882SSimon Glass        Print('%s%s: add: %s/%s, grow: %s/%s bytes: %s/%s (%s)' %
922fc3fe1c2SSimon Glass              tuple([indent, self.col.Color(self.col.YELLOW, fname)] + args))
9234653a882SSimon Glass        Print('%s  %-38s %7s %7s %+7s' % (indent, 'function', 'old', 'new',
9244653a882SSimon Glass                                         'delta'))
925fc3fe1c2SSimon Glass        for diff, name in delta:
926fc3fe1c2SSimon Glass            if diff:
927fc3fe1c2SSimon Glass                color = self.col.RED if diff > 0 else self.col.GREEN
928fc3fe1c2SSimon Glass                msg = '%s  %-38s %7s %7s %+7d' % (indent, name,
929fc3fe1c2SSimon Glass                        old.get(name, '-'), new.get(name,'-'), diff)
9304653a882SSimon Glass                Print(msg, colour=color)
931fc3fe1c2SSimon Glass
932fc3fe1c2SSimon Glass
933fc3fe1c2SSimon Glass    def PrintSizeDetail(self, target_list, show_bloat):
934fc3fe1c2SSimon Glass        """Show details size information for each board
935fc3fe1c2SSimon Glass
936fc3fe1c2SSimon Glass        Args:
937fc3fe1c2SSimon Glass            target_list: List of targets, each a dict containing:
938fc3fe1c2SSimon Glass                    'target': Target name
939fc3fe1c2SSimon Glass                    'total_diff': Total difference in bytes across all areas
940fc3fe1c2SSimon Glass                    <part_name>: Difference for that part
941fc3fe1c2SSimon Glass            show_bloat: Show detail for each function
942fc3fe1c2SSimon Glass        """
943fc3fe1c2SSimon Glass        targets_by_diff = sorted(target_list, reverse=True,
944fc3fe1c2SSimon Glass        key=lambda x: x['_total_diff'])
945fc3fe1c2SSimon Glass        for result in targets_by_diff:
946fc3fe1c2SSimon Glass            printed_target = False
947fc3fe1c2SSimon Glass            for name in sorted(result):
948fc3fe1c2SSimon Glass                diff = result[name]
949fc3fe1c2SSimon Glass                if name.startswith('_'):
950fc3fe1c2SSimon Glass                    continue
951fc3fe1c2SSimon Glass                if diff != 0:
952fc3fe1c2SSimon Glass                    color = self.col.RED if diff > 0 else self.col.GREEN
953fc3fe1c2SSimon Glass                msg = ' %s %+d' % (name, diff)
954fc3fe1c2SSimon Glass                if not printed_target:
9554653a882SSimon Glass                    Print('%10s  %-15s:' % ('', result['_target']),
9564653a882SSimon Glass                          newline=False)
957fc3fe1c2SSimon Glass                    printed_target = True
9584653a882SSimon Glass                Print(msg, colour=color, newline=False)
959fc3fe1c2SSimon Glass            if printed_target:
9604653a882SSimon Glass                Print()
961fc3fe1c2SSimon Glass                if show_bloat:
962fc3fe1c2SSimon Glass                    target = result['_target']
963fc3fe1c2SSimon Glass                    outcome = result['_outcome']
964fc3fe1c2SSimon Glass                    base_outcome = self._base_board_dict[target]
965fc3fe1c2SSimon Glass                    for fname in outcome.func_sizes:
966fc3fe1c2SSimon Glass                        self.PrintFuncSizeDetail(fname,
967fc3fe1c2SSimon Glass                                                 base_outcome.func_sizes[fname],
968fc3fe1c2SSimon Glass                                                 outcome.func_sizes[fname])
969fc3fe1c2SSimon Glass
970fc3fe1c2SSimon Glass
971fc3fe1c2SSimon Glass    def PrintSizeSummary(self, board_selected, board_dict, show_detail,
972fc3fe1c2SSimon Glass                         show_bloat):
973fc3fe1c2SSimon Glass        """Print a summary of image sizes broken down by section.
974fc3fe1c2SSimon Glass
975fc3fe1c2SSimon Glass        The summary takes the form of one line per architecture. The
976fc3fe1c2SSimon Glass        line contains deltas for each of the sections (+ means the section
977fc3fe1c2SSimon Glass        got bigger, - means smaller). The nunmbers are the average number
978fc3fe1c2SSimon Glass        of bytes that a board in this section increased by.
979fc3fe1c2SSimon Glass
980fc3fe1c2SSimon Glass        For example:
981fc3fe1c2SSimon Glass           powerpc: (622 boards)   text -0.0
982fc3fe1c2SSimon Glass          arm: (285 boards)   text -0.0
983fc3fe1c2SSimon Glass          nds32: (3 boards)   text -8.0
984fc3fe1c2SSimon Glass
985fc3fe1c2SSimon Glass        Args:
986fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise, keyed by
987fc3fe1c2SSimon Glass                board.target
988fc3fe1c2SSimon Glass            board_dict: Dict containing boards for which we built this
989fc3fe1c2SSimon Glass                commit, keyed by board.target. The value is an Outcome object.
990fc3fe1c2SSimon Glass            show_detail: Show detail for each board
991fc3fe1c2SSimon Glass            show_bloat: Show detail for each function
992fc3fe1c2SSimon Glass        """
993fc3fe1c2SSimon Glass        arch_list = {}
994fc3fe1c2SSimon Glass        arch_count = {}
995fc3fe1c2SSimon Glass
996fc3fe1c2SSimon Glass        # Calculate changes in size for different image parts
997fc3fe1c2SSimon Glass        # The previous sizes are in Board.sizes, for each board
998fc3fe1c2SSimon Glass        for target in board_dict:
999fc3fe1c2SSimon Glass            if target not in board_selected:
1000fc3fe1c2SSimon Glass                continue
1001fc3fe1c2SSimon Glass            base_sizes = self._base_board_dict[target].sizes
1002fc3fe1c2SSimon Glass            outcome = board_dict[target]
1003fc3fe1c2SSimon Glass            sizes = outcome.sizes
1004fc3fe1c2SSimon Glass
1005fc3fe1c2SSimon Glass            # Loop through the list of images, creating a dict of size
1006fc3fe1c2SSimon Glass            # changes for each image/part. We end up with something like
1007fc3fe1c2SSimon Glass            # {'target' : 'snapper9g45, 'data' : 5, 'u-boot-spl:text' : -4}
1008fc3fe1c2SSimon Glass            # which means that U-Boot data increased by 5 bytes and SPL
1009fc3fe1c2SSimon Glass            # text decreased by 4.
1010fc3fe1c2SSimon Glass            err = {'_target' : target}
1011fc3fe1c2SSimon Glass            for image in sizes:
1012fc3fe1c2SSimon Glass                if image in base_sizes:
1013fc3fe1c2SSimon Glass                    base_image = base_sizes[image]
1014fc3fe1c2SSimon Glass                    # Loop through the text, data, bss parts
1015fc3fe1c2SSimon Glass                    for part in sorted(sizes[image]):
1016fc3fe1c2SSimon Glass                        diff = sizes[image][part] - base_image[part]
1017fc3fe1c2SSimon Glass                        col = None
1018fc3fe1c2SSimon Glass                        if diff:
1019fc3fe1c2SSimon Glass                            if image == 'u-boot':
1020fc3fe1c2SSimon Glass                                name = part
1021fc3fe1c2SSimon Glass                            else:
1022fc3fe1c2SSimon Glass                                name = image + ':' + part
1023fc3fe1c2SSimon Glass                            err[name] = diff
1024fc3fe1c2SSimon Glass            arch = board_selected[target].arch
1025fc3fe1c2SSimon Glass            if not arch in arch_count:
1026fc3fe1c2SSimon Glass                arch_count[arch] = 1
1027fc3fe1c2SSimon Glass            else:
1028fc3fe1c2SSimon Glass                arch_count[arch] += 1
1029fc3fe1c2SSimon Glass            if not sizes:
1030fc3fe1c2SSimon Glass                pass    # Only add to our list when we have some stats
1031fc3fe1c2SSimon Glass            elif not arch in arch_list:
1032fc3fe1c2SSimon Glass                arch_list[arch] = [err]
1033fc3fe1c2SSimon Glass            else:
1034fc3fe1c2SSimon Glass                arch_list[arch].append(err)
1035fc3fe1c2SSimon Glass
1036fc3fe1c2SSimon Glass        # We now have a list of image size changes sorted by arch
1037fc3fe1c2SSimon Glass        # Print out a summary of these
1038fc3fe1c2SSimon Glass        for arch, target_list in arch_list.iteritems():
1039fc3fe1c2SSimon Glass            # Get total difference for each type
1040fc3fe1c2SSimon Glass            totals = {}
1041fc3fe1c2SSimon Glass            for result in target_list:
1042fc3fe1c2SSimon Glass                total = 0
1043fc3fe1c2SSimon Glass                for name, diff in result.iteritems():
1044fc3fe1c2SSimon Glass                    if name.startswith('_'):
1045fc3fe1c2SSimon Glass                        continue
1046fc3fe1c2SSimon Glass                    total += diff
1047fc3fe1c2SSimon Glass                    if name in totals:
1048fc3fe1c2SSimon Glass                        totals[name] += diff
1049fc3fe1c2SSimon Glass                    else:
1050fc3fe1c2SSimon Glass                        totals[name] = diff
1051fc3fe1c2SSimon Glass                result['_total_diff'] = total
1052fc3fe1c2SSimon Glass                result['_outcome'] = board_dict[result['_target']]
1053fc3fe1c2SSimon Glass
1054fc3fe1c2SSimon Glass            count = len(target_list)
1055fc3fe1c2SSimon Glass            printed_arch = False
1056fc3fe1c2SSimon Glass            for name in sorted(totals):
1057fc3fe1c2SSimon Glass                diff = totals[name]
1058fc3fe1c2SSimon Glass                if diff:
1059fc3fe1c2SSimon Glass                    # Display the average difference in this name for this
1060fc3fe1c2SSimon Glass                    # architecture
1061fc3fe1c2SSimon Glass                    avg_diff = float(diff) / count
1062fc3fe1c2SSimon Glass                    color = self.col.RED if avg_diff > 0 else self.col.GREEN
1063fc3fe1c2SSimon Glass                    msg = ' %s %+1.1f' % (name, avg_diff)
1064fc3fe1c2SSimon Glass                    if not printed_arch:
10654653a882SSimon Glass                        Print('%10s: (for %d/%d boards)' % (arch, count,
10664653a882SSimon Glass                              arch_count[arch]), newline=False)
1067fc3fe1c2SSimon Glass                        printed_arch = True
10684653a882SSimon Glass                    Print(msg, colour=color, newline=False)
1069fc3fe1c2SSimon Glass
1070fc3fe1c2SSimon Glass            if printed_arch:
10714653a882SSimon Glass                Print()
1072fc3fe1c2SSimon Glass                if show_detail:
1073fc3fe1c2SSimon Glass                    self.PrintSizeDetail(target_list, show_bloat)
1074fc3fe1c2SSimon Glass
1075fc3fe1c2SSimon Glass
1076fc3fe1c2SSimon Glass    def PrintResultSummary(self, board_selected, board_dict, err_lines,
1077e30965dbSSimon Glass                           err_line_boards, warn_lines, warn_line_boards,
107848ae4124SAlex Kiernan                           config, environment, show_sizes, show_detail,
107948ae4124SAlex Kiernan                           show_bloat, show_config, show_environment):
1080fc3fe1c2SSimon Glass        """Compare results with the base results and display delta.
1081fc3fe1c2SSimon Glass
1082fc3fe1c2SSimon Glass        Only boards mentioned in board_selected will be considered. This
1083fc3fe1c2SSimon Glass        function is intended to be called repeatedly with the results of
1084fc3fe1c2SSimon Glass        each commit. It therefore shows a 'diff' between what it saw in
1085fc3fe1c2SSimon Glass        the last call and what it sees now.
1086fc3fe1c2SSimon Glass
1087fc3fe1c2SSimon Glass        Args:
1088fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise, keyed by
1089fc3fe1c2SSimon Glass                board.target
1090fc3fe1c2SSimon Glass            board_dict: Dict containing boards for which we built this
1091fc3fe1c2SSimon Glass                commit, keyed by board.target. The value is an Outcome object.
1092fc3fe1c2SSimon Glass            err_lines: A list of errors for this commit, or [] if there is
1093fc3fe1c2SSimon Glass                none, or we don't want to print errors
1094ed966657SSimon Glass            err_line_boards: Dict keyed by error line, containing a list of
1095ed966657SSimon Glass                the Board objects with that error
1096e30965dbSSimon Glass            warn_lines: A list of warnings for this commit, or [] if there is
1097e30965dbSSimon Glass                none, or we don't want to print errors
1098e30965dbSSimon Glass            warn_line_boards: Dict keyed by warning line, containing a list of
1099e30965dbSSimon Glass                the Board objects with that warning
1100843312dcSSimon Glass            config: Dictionary keyed by filename - e.g. '.config'. Each
1101843312dcSSimon Glass                    value is itself a dictionary:
1102843312dcSSimon Glass                        key: config name
1103843312dcSSimon Glass                        value: config value
110448ae4124SAlex Kiernan            environment: Dictionary keyed by environment variable, Each
110548ae4124SAlex Kiernan                     value is the value of environment variable.
1106fc3fe1c2SSimon Glass            show_sizes: Show image size deltas
1107fc3fe1c2SSimon Glass            show_detail: Show detail for each board
1108fc3fe1c2SSimon Glass            show_bloat: Show detail for each function
1109843312dcSSimon Glass            show_config: Show config changes
111048ae4124SAlex Kiernan            show_environment: Show environment changes
1111fc3fe1c2SSimon Glass        """
1112e30965dbSSimon Glass        def _BoardList(line, line_boards):
1113ed966657SSimon Glass            """Helper function to get a line of boards containing a line
1114ed966657SSimon Glass
1115ed966657SSimon Glass            Args:
1116ed966657SSimon Glass                line: Error line to search for
1117ed966657SSimon Glass            Return:
1118ed966657SSimon Glass                String containing a list of boards with that error line, or
1119ed966657SSimon Glass                '' if the user has not requested such a list
1120ed966657SSimon Glass            """
1121ed966657SSimon Glass            if self._list_error_boards:
1122ed966657SSimon Glass                names = []
1123e30965dbSSimon Glass                for board in line_boards[line]:
1124f66153beSSimon Glass                    if not board.target in names:
1125ed966657SSimon Glass                        names.append(board.target)
1126ed966657SSimon Glass                names_str = '(%s) ' % ','.join(names)
1127ed966657SSimon Glass            else:
1128ed966657SSimon Glass                names_str = ''
1129ed966657SSimon Glass            return names_str
1130ed966657SSimon Glass
1131e30965dbSSimon Glass        def _CalcErrorDelta(base_lines, base_line_boards, lines, line_boards,
1132e30965dbSSimon Glass                            char):
1133e30965dbSSimon Glass            better_lines = []
1134e30965dbSSimon Glass            worse_lines = []
1135e30965dbSSimon Glass            for line in lines:
1136e30965dbSSimon Glass                if line not in base_lines:
1137e30965dbSSimon Glass                    worse_lines.append(char + '+' +
1138e30965dbSSimon Glass                            _BoardList(line, line_boards) + line)
1139e30965dbSSimon Glass            for line in base_lines:
1140e30965dbSSimon Glass                if line not in lines:
1141e30965dbSSimon Glass                    better_lines.append(char + '-' +
1142e30965dbSSimon Glass                            _BoardList(line, base_line_boards) + line)
1143e30965dbSSimon Glass            return better_lines, worse_lines
1144e30965dbSSimon Glass
1145843312dcSSimon Glass        def _CalcConfig(delta, name, config):
1146843312dcSSimon Glass            """Calculate configuration changes
1147843312dcSSimon Glass
1148843312dcSSimon Glass            Args:
1149843312dcSSimon Glass                delta: Type of the delta, e.g. '+'
1150843312dcSSimon Glass                name: name of the file which changed (e.g. .config)
1151843312dcSSimon Glass                config: configuration change dictionary
1152843312dcSSimon Glass                    key: config name
1153843312dcSSimon Glass                    value: config value
1154843312dcSSimon Glass            Returns:
1155843312dcSSimon Glass                String containing the configuration changes which can be
1156843312dcSSimon Glass                    printed
1157843312dcSSimon Glass            """
1158843312dcSSimon Glass            out = ''
1159843312dcSSimon Glass            for key in sorted(config.keys()):
1160843312dcSSimon Glass                out += '%s=%s ' % (key, config[key])
11618270e3c1SSimon Glass            return '%s %s: %s' % (delta, name, out)
1162843312dcSSimon Glass
11638270e3c1SSimon Glass        def _AddConfig(lines, name, config_plus, config_minus, config_change):
11648270e3c1SSimon Glass            """Add changes in configuration to a list
1165843312dcSSimon Glass
1166843312dcSSimon Glass            Args:
11678270e3c1SSimon Glass                lines: list to add to
11688270e3c1SSimon Glass                name: config file name
1169843312dcSSimon Glass                config_plus: configurations added, dictionary
1170843312dcSSimon Glass                    key: config name
1171843312dcSSimon Glass                    value: config value
1172843312dcSSimon Glass                config_minus: configurations removed, dictionary
1173843312dcSSimon Glass                    key: config name
1174843312dcSSimon Glass                    value: config value
1175843312dcSSimon Glass                config_change: configurations changed, dictionary
1176843312dcSSimon Glass                    key: config name
1177843312dcSSimon Glass                    value: config value
1178843312dcSSimon Glass            """
1179843312dcSSimon Glass            if config_plus:
11808270e3c1SSimon Glass                lines.append(_CalcConfig('+', name, config_plus))
1181843312dcSSimon Glass            if config_minus:
11828270e3c1SSimon Glass                lines.append(_CalcConfig('-', name, config_minus))
1183843312dcSSimon Glass            if config_change:
11848270e3c1SSimon Glass                lines.append(_CalcConfig('c', name, config_change))
11858270e3c1SSimon Glass
11868270e3c1SSimon Glass        def _OutputConfigInfo(lines):
11878270e3c1SSimon Glass            for line in lines:
11888270e3c1SSimon Glass                if not line:
11898270e3c1SSimon Glass                    continue
11908270e3c1SSimon Glass                if line[0] == '+':
11918270e3c1SSimon Glass                    col = self.col.GREEN
11928270e3c1SSimon Glass                elif line[0] == '-':
11938270e3c1SSimon Glass                    col = self.col.RED
11948270e3c1SSimon Glass                elif line[0] == 'c':
11958270e3c1SSimon Glass                    col = self.col.YELLOW
11968270e3c1SSimon Glass                Print('   ' + line, newline=True, colour=col)
11978270e3c1SSimon Glass
1198843312dcSSimon Glass
11994cf2b221SSimon Glass        ok_boards = []      # List of boards fixed since last commit
1200*6af7101bSSimon Glass        warn_boards = []    # List of boards with warnings since last commit
12014cf2b221SSimon Glass        err_boards = []     # List of new broken boards since last commit
12024cf2b221SSimon Glass        new_boards = []     # List of boards that didn't exist last time
12034cf2b221SSimon Glass        unknown_boards = [] # List of boards that were not built
1204fc3fe1c2SSimon Glass
1205fc3fe1c2SSimon Glass        for target in board_dict:
1206fc3fe1c2SSimon Glass            if target not in board_selected:
1207fc3fe1c2SSimon Glass                continue
1208fc3fe1c2SSimon Glass
1209fc3fe1c2SSimon Glass            # If the board was built last time, add its outcome to a list
1210fc3fe1c2SSimon Glass            if target in self._base_board_dict:
1211fc3fe1c2SSimon Glass                base_outcome = self._base_board_dict[target].rc
1212fc3fe1c2SSimon Glass                outcome = board_dict[target]
1213fc3fe1c2SSimon Glass                if outcome.rc == OUTCOME_UNKNOWN:
12144cf2b221SSimon Glass                    unknown_boards.append(target)
1215fc3fe1c2SSimon Glass                elif outcome.rc < base_outcome:
1216*6af7101bSSimon Glass                    if outcome.rc == OUTCOME_WARNING:
1217*6af7101bSSimon Glass                        warn_boards.append(target)
1218*6af7101bSSimon Glass                    else:
12194cf2b221SSimon Glass                        ok_boards.append(target)
1220fc3fe1c2SSimon Glass                elif outcome.rc > base_outcome:
1221*6af7101bSSimon Glass                    if outcome.rc == OUTCOME_WARNING:
1222*6af7101bSSimon Glass                        warn_boards.append(target)
1223*6af7101bSSimon Glass                    else:
12244cf2b221SSimon Glass                        err_boards.append(target)
1225fc3fe1c2SSimon Glass            else:
12264cf2b221SSimon Glass                new_boards.append(target)
1227fc3fe1c2SSimon Glass
1228fc3fe1c2SSimon Glass        # Get a list of errors that have appeared, and disappeared
1229e30965dbSSimon Glass        better_err, worse_err = _CalcErrorDelta(self._base_err_lines,
1230e30965dbSSimon Glass                self._base_err_line_boards, err_lines, err_line_boards, '')
1231e30965dbSSimon Glass        better_warn, worse_warn = _CalcErrorDelta(self._base_warn_lines,
1232e30965dbSSimon Glass                self._base_warn_line_boards, warn_lines, warn_line_boards, 'w')
1233fc3fe1c2SSimon Glass
1234fc3fe1c2SSimon Glass        # Display results by arch
1235*6af7101bSSimon Glass        if any((ok_boards, warn_boards, err_boards, unknown_boards, new_boards,
1236*6af7101bSSimon Glass                worse_err, better_err, worse_warn, better_warn)):
1237fc3fe1c2SSimon Glass            arch_list = {}
12384cf2b221SSimon Glass            self.AddOutcome(board_selected, arch_list, ok_boards, '',
1239fc3fe1c2SSimon Glass                    self.col.GREEN)
1240*6af7101bSSimon Glass            self.AddOutcome(board_selected, arch_list, warn_boards, 'w+',
1241*6af7101bSSimon Glass                    self.col.YELLOW)
12424cf2b221SSimon Glass            self.AddOutcome(board_selected, arch_list, err_boards, '+',
1243fc3fe1c2SSimon Glass                    self.col.RED)
12444cf2b221SSimon Glass            self.AddOutcome(board_selected, arch_list, new_boards, '*', self.col.BLUE)
1245fc3fe1c2SSimon Glass            if self._show_unknown:
12464cf2b221SSimon Glass                self.AddOutcome(board_selected, arch_list, unknown_boards, '?',
1247fc3fe1c2SSimon Glass                        self.col.MAGENTA)
1248fc3fe1c2SSimon Glass            for arch, target_list in arch_list.iteritems():
12494653a882SSimon Glass                Print('%10s: %s' % (arch, target_list))
125028370c1bSSimon Glass                self._error_lines += 1
1251fc3fe1c2SSimon Glass            if better_err:
12524653a882SSimon Glass                Print('\n'.join(better_err), colour=self.col.GREEN)
125328370c1bSSimon Glass                self._error_lines += 1
1254fc3fe1c2SSimon Glass            if worse_err:
12554653a882SSimon Glass                Print('\n'.join(worse_err), colour=self.col.RED)
125628370c1bSSimon Glass                self._error_lines += 1
1257e30965dbSSimon Glass            if better_warn:
12584653a882SSimon Glass                Print('\n'.join(better_warn), colour=self.col.CYAN)
1259e30965dbSSimon Glass                self._error_lines += 1
1260e30965dbSSimon Glass            if worse_warn:
12614653a882SSimon Glass                Print('\n'.join(worse_warn), colour=self.col.MAGENTA)
1262e30965dbSSimon Glass                self._error_lines += 1
1263fc3fe1c2SSimon Glass
1264fc3fe1c2SSimon Glass        if show_sizes:
1265fc3fe1c2SSimon Glass            self.PrintSizeSummary(board_selected, board_dict, show_detail,
1266fc3fe1c2SSimon Glass                                  show_bloat)
1267fc3fe1c2SSimon Glass
126848ae4124SAlex Kiernan        if show_environment and self._base_environment:
126948ae4124SAlex Kiernan            lines = []
127048ae4124SAlex Kiernan
127148ae4124SAlex Kiernan            for target in board_dict:
127248ae4124SAlex Kiernan                if target not in board_selected:
127348ae4124SAlex Kiernan                    continue
127448ae4124SAlex Kiernan
127548ae4124SAlex Kiernan                tbase = self._base_environment[target]
127648ae4124SAlex Kiernan                tenvironment = environment[target]
127748ae4124SAlex Kiernan                environment_plus = {}
127848ae4124SAlex Kiernan                environment_minus = {}
127948ae4124SAlex Kiernan                environment_change = {}
128048ae4124SAlex Kiernan                base = tbase.environment
128148ae4124SAlex Kiernan                for key, value in tenvironment.environment.iteritems():
128248ae4124SAlex Kiernan                    if key not in base:
128348ae4124SAlex Kiernan                        environment_plus[key] = value
128448ae4124SAlex Kiernan                for key, value in base.iteritems():
128548ae4124SAlex Kiernan                    if key not in tenvironment.environment:
128648ae4124SAlex Kiernan                        environment_minus[key] = value
128748ae4124SAlex Kiernan                for key, value in base.iteritems():
128848ae4124SAlex Kiernan                    new_value = tenvironment.environment.get(key)
128948ae4124SAlex Kiernan                    if new_value and value != new_value:
129048ae4124SAlex Kiernan                        desc = '%s -> %s' % (value, new_value)
129148ae4124SAlex Kiernan                        environment_change[key] = desc
129248ae4124SAlex Kiernan
129348ae4124SAlex Kiernan                _AddConfig(lines, target, environment_plus, environment_minus,
129448ae4124SAlex Kiernan                           environment_change)
129548ae4124SAlex Kiernan
129648ae4124SAlex Kiernan            _OutputConfigInfo(lines)
129748ae4124SAlex Kiernan
12988270e3c1SSimon Glass        if show_config and self._base_config:
12998270e3c1SSimon Glass            summary = {}
13008270e3c1SSimon Glass            arch_config_plus = {}
13018270e3c1SSimon Glass            arch_config_minus = {}
13028270e3c1SSimon Glass            arch_config_change = {}
13038270e3c1SSimon Glass            arch_list = []
13048270e3c1SSimon Glass
13058270e3c1SSimon Glass            for target in board_dict:
13068270e3c1SSimon Glass                if target not in board_selected:
13078270e3c1SSimon Glass                    continue
13088270e3c1SSimon Glass                arch = board_selected[target].arch
13098270e3c1SSimon Glass                if arch not in arch_list:
13108270e3c1SSimon Glass                    arch_list.append(arch)
13118270e3c1SSimon Glass
13128270e3c1SSimon Glass            for arch in arch_list:
13138270e3c1SSimon Glass                arch_config_plus[arch] = {}
13148270e3c1SSimon Glass                arch_config_minus[arch] = {}
13158270e3c1SSimon Glass                arch_config_change[arch] = {}
1316b464f8e7SSimon Glass                for name in self.config_filenames:
13178270e3c1SSimon Glass                    arch_config_plus[arch][name] = {}
13188270e3c1SSimon Glass                    arch_config_minus[arch][name] = {}
13198270e3c1SSimon Glass                    arch_config_change[arch][name] = {}
13208270e3c1SSimon Glass
13218270e3c1SSimon Glass            for target in board_dict:
13228270e3c1SSimon Glass                if target not in board_selected:
13238270e3c1SSimon Glass                    continue
13248270e3c1SSimon Glass
13258270e3c1SSimon Glass                arch = board_selected[target].arch
13268270e3c1SSimon Glass
1327843312dcSSimon Glass                all_config_plus = {}
1328843312dcSSimon Glass                all_config_minus = {}
1329843312dcSSimon Glass                all_config_change = {}
13308270e3c1SSimon Glass                tbase = self._base_config[target]
13318270e3c1SSimon Glass                tconfig = config[target]
13328270e3c1SSimon Glass                lines = []
1333b464f8e7SSimon Glass                for name in self.config_filenames:
13348270e3c1SSimon Glass                    if not tconfig.config[name]:
1335843312dcSSimon Glass                        continue
1336843312dcSSimon Glass                    config_plus = {}
1337843312dcSSimon Glass                    config_minus = {}
1338843312dcSSimon Glass                    config_change = {}
13398270e3c1SSimon Glass                    base = tbase.config[name]
13408270e3c1SSimon Glass                    for key, value in tconfig.config[name].iteritems():
1341843312dcSSimon Glass                        if key not in base:
1342843312dcSSimon Glass                            config_plus[key] = value
1343843312dcSSimon Glass                            all_config_plus[key] = value
1344843312dcSSimon Glass                    for key, value in base.iteritems():
13458270e3c1SSimon Glass                        if key not in tconfig.config[name]:
1346843312dcSSimon Glass                            config_minus[key] = value
1347843312dcSSimon Glass                            all_config_minus[key] = value
1348843312dcSSimon Glass                    for key, value in base.iteritems():
13498270e3c1SSimon Glass                        new_value = tconfig.config.get(key)
13508270e3c1SSimon Glass                        if new_value and value != new_value:
1351843312dcSSimon Glass                            desc = '%s -> %s' % (value, new_value)
1352843312dcSSimon Glass                            config_change[key] = desc
1353843312dcSSimon Glass                            all_config_change[key] = desc
13548270e3c1SSimon Glass
13558270e3c1SSimon Glass                    arch_config_plus[arch][name].update(config_plus)
13568270e3c1SSimon Glass                    arch_config_minus[arch][name].update(config_minus)
13578270e3c1SSimon Glass                    arch_config_change[arch][name].update(config_change)
13588270e3c1SSimon Glass
13598270e3c1SSimon Glass                    _AddConfig(lines, name, config_plus, config_minus,
13608270e3c1SSimon Glass                               config_change)
13618270e3c1SSimon Glass                _AddConfig(lines, 'all', all_config_plus, all_config_minus,
1362843312dcSSimon Glass                           all_config_change)
13638270e3c1SSimon Glass                summary[target] = '\n'.join(lines)
13648270e3c1SSimon Glass
13658270e3c1SSimon Glass            lines_by_target = {}
13668270e3c1SSimon Glass            for target, lines in summary.iteritems():
13678270e3c1SSimon Glass                if lines in lines_by_target:
13688270e3c1SSimon Glass                    lines_by_target[lines].append(target)
13698270e3c1SSimon Glass                else:
13708270e3c1SSimon Glass                    lines_by_target[lines] = [target]
13718270e3c1SSimon Glass
13728270e3c1SSimon Glass            for arch in arch_list:
13738270e3c1SSimon Glass                lines = []
13748270e3c1SSimon Glass                all_plus = {}
13758270e3c1SSimon Glass                all_minus = {}
13768270e3c1SSimon Glass                all_change = {}
1377b464f8e7SSimon Glass                for name in self.config_filenames:
13788270e3c1SSimon Glass                    all_plus.update(arch_config_plus[arch][name])
13798270e3c1SSimon Glass                    all_minus.update(arch_config_minus[arch][name])
13808270e3c1SSimon Glass                    all_change.update(arch_config_change[arch][name])
13818270e3c1SSimon Glass                    _AddConfig(lines, name, arch_config_plus[arch][name],
13828270e3c1SSimon Glass                               arch_config_minus[arch][name],
13838270e3c1SSimon Glass                               arch_config_change[arch][name])
13848270e3c1SSimon Glass                _AddConfig(lines, 'all', all_plus, all_minus, all_change)
13858270e3c1SSimon Glass                #arch_summary[target] = '\n'.join(lines)
13868270e3c1SSimon Glass                if lines:
13878270e3c1SSimon Glass                    Print('%s:' % arch)
13888270e3c1SSimon Glass                    _OutputConfigInfo(lines)
13898270e3c1SSimon Glass
13908270e3c1SSimon Glass            for lines, targets in lines_by_target.iteritems():
13918270e3c1SSimon Glass                if not lines:
13928270e3c1SSimon Glass                    continue
13938270e3c1SSimon Glass                Print('%s :' % ' '.join(sorted(targets)))
13948270e3c1SSimon Glass                _OutputConfigInfo(lines.split('\n'))
13958270e3c1SSimon Glass
1396843312dcSSimon Glass
1397fc3fe1c2SSimon Glass        # Save our updated information for the next call to this function
1398fc3fe1c2SSimon Glass        self._base_board_dict = board_dict
1399fc3fe1c2SSimon Glass        self._base_err_lines = err_lines
1400e30965dbSSimon Glass        self._base_warn_lines = warn_lines
1401e30965dbSSimon Glass        self._base_err_line_boards = err_line_boards
1402e30965dbSSimon Glass        self._base_warn_line_boards = warn_line_boards
1403843312dcSSimon Glass        self._base_config = config
140448ae4124SAlex Kiernan        self._base_environment = environment
1405fc3fe1c2SSimon Glass
1406fc3fe1c2SSimon Glass        # Get a list of boards that did not get built, if needed
1407fc3fe1c2SSimon Glass        not_built = []
1408fc3fe1c2SSimon Glass        for board in board_selected:
1409fc3fe1c2SSimon Glass            if not board in board_dict:
1410fc3fe1c2SSimon Glass                not_built.append(board)
1411fc3fe1c2SSimon Glass        if not_built:
14124653a882SSimon Glass            Print("Boards not built (%d): %s" % (len(not_built),
14134653a882SSimon Glass                  ', '.join(not_built)))
1414fc3fe1c2SSimon Glass
1415b2ea7ab2SSimon Glass    def ProduceResultSummary(self, commit_upto, commits, board_selected):
1416e30965dbSSimon Glass            (board_dict, err_lines, err_line_boards, warn_lines,
141748ae4124SAlex Kiernan             warn_line_boards, config, environment) = self.GetResultSummary(
1418ed966657SSimon Glass                    board_selected, commit_upto,
1419843312dcSSimon Glass                    read_func_sizes=self._show_bloat,
142048ae4124SAlex Kiernan                    read_config=self._show_config,
142148ae4124SAlex Kiernan                    read_environment=self._show_environment)
1422b2ea7ab2SSimon Glass            if commits:
1423b2ea7ab2SSimon Glass                msg = '%02d: %s' % (commit_upto + 1,
1424b2ea7ab2SSimon Glass                        commits[commit_upto].subject)
14254653a882SSimon Glass                Print(msg, colour=self.col.BLUE)
1426b2ea7ab2SSimon Glass            self.PrintResultSummary(board_selected, board_dict,
1427ed966657SSimon Glass                    err_lines if self._show_errors else [], err_line_boards,
1428e30965dbSSimon Glass                    warn_lines if self._show_errors else [], warn_line_boards,
142948ae4124SAlex Kiernan                    config, environment, self._show_sizes, self._show_detail,
143048ae4124SAlex Kiernan                    self._show_bloat, self._show_config, self._show_environment)
1431fc3fe1c2SSimon Glass
1432b2ea7ab2SSimon Glass    def ShowSummary(self, commits, board_selected):
1433fc3fe1c2SSimon Glass        """Show a build summary for U-Boot for a given board list.
1434fc3fe1c2SSimon Glass
1435fc3fe1c2SSimon Glass        Reset the result summary, then repeatedly call GetResultSummary on
1436fc3fe1c2SSimon Glass        each commit's results, then display the differences we see.
1437fc3fe1c2SSimon Glass
1438fc3fe1c2SSimon Glass        Args:
1439fc3fe1c2SSimon Glass            commit: Commit objects to summarise
1440fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise
1441fc3fe1c2SSimon Glass        """
1442fea5858eSSimon Glass        self.commit_count = len(commits) if commits else 1
1443fc3fe1c2SSimon Glass        self.commits = commits
1444fc3fe1c2SSimon Glass        self.ResetResultSummary(board_selected)
144528370c1bSSimon Glass        self._error_lines = 0
1446fc3fe1c2SSimon Glass
1447fc3fe1c2SSimon Glass        for commit_upto in range(0, self.commit_count, self._step):
1448b2ea7ab2SSimon Glass            self.ProduceResultSummary(commit_upto, commits, board_selected)
144928370c1bSSimon Glass        if not self._error_lines:
14504653a882SSimon Glass            Print('(no errors to report)', colour=self.col.GREEN)
1451fc3fe1c2SSimon Glass
1452fc3fe1c2SSimon Glass
1453fc3fe1c2SSimon Glass    def SetupBuild(self, board_selected, commits):
1454fc3fe1c2SSimon Glass        """Set up ready to start a build.
1455fc3fe1c2SSimon Glass
1456fc3fe1c2SSimon Glass        Args:
1457fc3fe1c2SSimon Glass            board_selected: Selected boards to build
1458fc3fe1c2SSimon Glass            commits: Selected commits to build
1459fc3fe1c2SSimon Glass        """
1460fc3fe1c2SSimon Glass        # First work out how many commits we will build
1461fea5858eSSimon Glass        count = (self.commit_count + self._step - 1) / self._step
1462fc3fe1c2SSimon Glass        self.count = len(board_selected) * count
1463fc3fe1c2SSimon Glass        self.upto = self.warned = self.fail = 0
1464fc3fe1c2SSimon Glass        self._timestamps = collections.deque()
1465fc3fe1c2SSimon Glass
1466fc3fe1c2SSimon Glass    def GetThreadDir(self, thread_num):
1467fc3fe1c2SSimon Glass        """Get the directory path to the working dir for a thread.
1468fc3fe1c2SSimon Glass
1469fc3fe1c2SSimon Glass        Args:
1470fc3fe1c2SSimon Glass            thread_num: Number of thread to check.
1471fc3fe1c2SSimon Glass        """
1472fc3fe1c2SSimon Glass        return os.path.join(self._working_dir, '%02d' % thread_num)
1473fc3fe1c2SSimon Glass
1474fea5858eSSimon Glass    def _PrepareThread(self, thread_num, setup_git):
1475fc3fe1c2SSimon Glass        """Prepare the working directory for a thread.
1476fc3fe1c2SSimon Glass
1477fc3fe1c2SSimon Glass        This clones or fetches the repo into the thread's work directory.
1478fc3fe1c2SSimon Glass
1479fc3fe1c2SSimon Glass        Args:
1480fc3fe1c2SSimon Glass            thread_num: Thread number (0, 1, ...)
1481fea5858eSSimon Glass            setup_git: True to set up a git repo clone
1482fc3fe1c2SSimon Glass        """
1483fc3fe1c2SSimon Glass        thread_dir = self.GetThreadDir(thread_num)
1484190064b4SSimon Glass        builderthread.Mkdir(thread_dir)
1485fc3fe1c2SSimon Glass        git_dir = os.path.join(thread_dir, '.git')
1486fc3fe1c2SSimon Glass
1487fc3fe1c2SSimon Glass        # Clone the repo if it doesn't already exist
1488fc3fe1c2SSimon Glass        # TODO(sjg@chromium): Perhaps some git hackery to symlink instead, so
1489fc3fe1c2SSimon Glass        # we have a private index but uses the origin repo's contents?
1490fea5858eSSimon Glass        if setup_git and self.git_dir:
1491fc3fe1c2SSimon Glass            src_dir = os.path.abspath(self.git_dir)
1492fc3fe1c2SSimon Glass            if os.path.exists(git_dir):
1493fc3fe1c2SSimon Glass                gitutil.Fetch(git_dir, thread_dir)
1494fc3fe1c2SSimon Glass            else:
149521f0eb33SSimon Glass                Print('\rCloning repo for thread %d' % thread_num,
149621f0eb33SSimon Glass                      newline=False)
1497fc3fe1c2SSimon Glass                gitutil.Clone(src_dir, thread_dir)
149821f0eb33SSimon Glass                Print('\r%s\r' % (' ' * 30), newline=False)
1499fc3fe1c2SSimon Glass
1500fea5858eSSimon Glass    def _PrepareWorkingSpace(self, max_threads, setup_git):
1501fc3fe1c2SSimon Glass        """Prepare the working directory for use.
1502fc3fe1c2SSimon Glass
1503fc3fe1c2SSimon Glass        Set up the git repo for each thread.
1504fc3fe1c2SSimon Glass
1505fc3fe1c2SSimon Glass        Args:
1506fc3fe1c2SSimon Glass            max_threads: Maximum number of threads we expect to need.
1507fea5858eSSimon Glass            setup_git: True to set up a git repo clone
1508fc3fe1c2SSimon Glass        """
1509190064b4SSimon Glass        builderthread.Mkdir(self._working_dir)
1510fc3fe1c2SSimon Glass        for thread in range(max_threads):
1511fea5858eSSimon Glass            self._PrepareThread(thread, setup_git)
1512fc3fe1c2SSimon Glass
1513fc3fe1c2SSimon Glass    def _PrepareOutputSpace(self):
1514fc3fe1c2SSimon Glass        """Get the output directories ready to receive files.
1515fc3fe1c2SSimon Glass
1516fc3fe1c2SSimon Glass        We delete any output directories which look like ones we need to
1517fc3fe1c2SSimon Glass        create. Having left over directories is confusing when the user wants
1518fc3fe1c2SSimon Glass        to check the output manually.
1519fc3fe1c2SSimon Glass        """
15201a915675SSimon Glass        if not self.commits:
15211a915675SSimon Glass            return
1522fc3fe1c2SSimon Glass        dir_list = []
1523fc3fe1c2SSimon Glass        for commit_upto in range(self.commit_count):
1524fc3fe1c2SSimon Glass            dir_list.append(self._GetOutputDir(commit_upto))
1525fc3fe1c2SSimon Glass
1526b222abe7SSimon Glass        to_remove = []
1527fc3fe1c2SSimon Glass        for dirname in glob.glob(os.path.join(self.base_dir, '*')):
1528fc3fe1c2SSimon Glass            if dirname not in dir_list:
1529b222abe7SSimon Glass                to_remove.append(dirname)
1530b222abe7SSimon Glass        if to_remove:
1531b222abe7SSimon Glass            Print('Removing %d old build directories' % len(to_remove),
1532b222abe7SSimon Glass                  newline=False)
1533b222abe7SSimon Glass            for dirname in to_remove:
1534fc3fe1c2SSimon Glass                shutil.rmtree(dirname)
1535fc3fe1c2SSimon Glass
1536e5a0e5d8SSimon Glass    def BuildBoards(self, commits, board_selected, keep_outputs, verbose):
1537fc3fe1c2SSimon Glass        """Build all commits for a list of boards
1538fc3fe1c2SSimon Glass
1539fc3fe1c2SSimon Glass        Args:
1540fc3fe1c2SSimon Glass            commits: List of commits to be build, each a Commit object
1541fc3fe1c2SSimon Glass            boards_selected: Dict of selected boards, key is target name,
1542fc3fe1c2SSimon Glass                    value is Board object
1543fc3fe1c2SSimon Glass            keep_outputs: True to save build output files
1544e5a0e5d8SSimon Glass            verbose: Display build results as they are completed
15452c3deb97SSimon Glass        Returns:
15462c3deb97SSimon Glass            Tuple containing:
15472c3deb97SSimon Glass                - number of boards that failed to build
15482c3deb97SSimon Glass                - number of boards that issued warnings
1549fc3fe1c2SSimon Glass        """
1550fea5858eSSimon Glass        self.commit_count = len(commits) if commits else 1
1551fc3fe1c2SSimon Glass        self.commits = commits
1552e5a0e5d8SSimon Glass        self._verbose = verbose
1553fc3fe1c2SSimon Glass
1554fc3fe1c2SSimon Glass        self.ResetResultSummary(board_selected)
1555f3d015cbSThierry Reding        builderthread.Mkdir(self.base_dir, parents = True)
1556fea5858eSSimon Glass        self._PrepareWorkingSpace(min(self.num_threads, len(board_selected)),
1557fea5858eSSimon Glass                commits is not None)
1558fc3fe1c2SSimon Glass        self._PrepareOutputSpace()
1559745b395aSSimon Glass        Print('\rStarting build...', newline=False)
1560fc3fe1c2SSimon Glass        self.SetupBuild(board_selected, commits)
1561fc3fe1c2SSimon Glass        self.ProcessResult(None)
1562fc3fe1c2SSimon Glass
1563fc3fe1c2SSimon Glass        # Create jobs to build all commits for each board
1564fc3fe1c2SSimon Glass        for brd in board_selected.itervalues():
1565190064b4SSimon Glass            job = builderthread.BuilderJob()
1566fc3fe1c2SSimon Glass            job.board = brd
1567fc3fe1c2SSimon Glass            job.commits = commits
1568fc3fe1c2SSimon Glass            job.keep_outputs = keep_outputs
1569fc3fe1c2SSimon Glass            job.step = self._step
1570fc3fe1c2SSimon Glass            self.queue.put(job)
1571fc3fe1c2SSimon Glass
1572d436e381SSimon Glass        term = threading.Thread(target=self.queue.join)
1573d436e381SSimon Glass        term.setDaemon(True)
1574d436e381SSimon Glass        term.start()
1575d436e381SSimon Glass        while term.isAlive():
1576d436e381SSimon Glass            term.join(100)
1577fc3fe1c2SSimon Glass
1578fc3fe1c2SSimon Glass        # Wait until we have processed all output
1579fc3fe1c2SSimon Glass        self.out_queue.join()
15804653a882SSimon Glass        Print()
1581fc3fe1c2SSimon Glass        self.ClearLine(0)
15822c3deb97SSimon Glass        return (self.fail, self.warned)
1583