xref: /openbmc/u-boot/tools/buildman/builder.py (revision 48ae412424ddfda64f45a9d679a960357e57433e)
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
130*48ae4124SAlex Kiernanclass Environment:
131*48ae4124SAlex Kiernan    """Holds information about environment variables for a board."""
132*48ae4124SAlex Kiernan    def __init__(self, target):
133*48ae4124SAlex Kiernan        self.target = target
134*48ae4124SAlex Kiernan        self.environment = {}
135*48ae4124SAlex Kiernan
136*48ae4124SAlex Kiernan    def Add(self, key, value):
137*48ae4124SAlex Kiernan        self.environment[key] = value
138*48ae4124SAlex 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
211*48ae4124SAlex Kiernan            environment: Dictionary keyed by environment variable, Each
212*48ae4124SAlex Kiernan                     value is the value of environment variable.
213fc3fe1c2SSimon Glass        """
214*48ae4124SAlex Kiernan        def __init__(self, rc, err_lines, sizes, func_sizes, config,
215*48ae4124SAlex 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
221*48ae4124SAlex 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: .*')
293e30965dbSSimon Glass        self._re_note = re.compile('(.*):(\d*):(\d*): note: this is the location of the previous.*')
294e30965dbSSimon Glass
295fc3fe1c2SSimon Glass        self.queue = Queue.Queue()
296fc3fe1c2SSimon Glass        self.out_queue = Queue.Queue()
297fc3fe1c2SSimon Glass        for i in range(self.num_threads):
298f79f1e0cSStephen Warren            t = builderthread.BuilderThread(self, i, incremental,
299f79f1e0cSStephen Warren                    per_board_out_dir)
300fc3fe1c2SSimon Glass            t.setDaemon(True)
301fc3fe1c2SSimon Glass            t.start()
302fc3fe1c2SSimon Glass            self.threads.append(t)
303fc3fe1c2SSimon Glass
304fc3fe1c2SSimon Glass        self.last_line_len = 0
305190064b4SSimon Glass        t = builderthread.ResultThread(self)
306fc3fe1c2SSimon Glass        t.setDaemon(True)
307fc3fe1c2SSimon Glass        t.start()
308fc3fe1c2SSimon Glass        self.threads.append(t)
309fc3fe1c2SSimon Glass
310fc3fe1c2SSimon Glass        ignore_lines = ['(make.*Waiting for unfinished)', '(Segmentation fault)']
311fc3fe1c2SSimon Glass        self.re_make_err = re.compile('|'.join(ignore_lines))
312fc3fe1c2SSimon Glass
3132f256648SSimon Glass        # Handle existing graceful with SIGINT / Ctrl-C
3142f256648SSimon Glass        signal.signal(signal.SIGINT, self.signal_handler)
3152f256648SSimon Glass
316fc3fe1c2SSimon Glass    def __del__(self):
317fc3fe1c2SSimon Glass        """Get rid of all threads created by the builder"""
318fc3fe1c2SSimon Glass        for t in self.threads:
319fc3fe1c2SSimon Glass            del t
320fc3fe1c2SSimon Glass
3212f256648SSimon Glass    def signal_handler(self, signal, frame):
3222f256648SSimon Glass        sys.exit(1)
3232f256648SSimon Glass
324b2ea7ab2SSimon Glass    def SetDisplayOptions(self, show_errors=False, show_sizes=False,
325ed966657SSimon Glass                          show_detail=False, show_bloat=False,
326*48ae4124SAlex Kiernan                          list_error_boards=False, show_config=False,
327*48ae4124SAlex Kiernan                          show_environment=False):
328b2ea7ab2SSimon Glass        """Setup display options for the builder.
329b2ea7ab2SSimon Glass
330b2ea7ab2SSimon Glass        show_errors: True to show summarised error/warning info
331b2ea7ab2SSimon Glass        show_sizes: Show size deltas
332b2ea7ab2SSimon Glass        show_detail: Show detail for each board
333b2ea7ab2SSimon Glass        show_bloat: Show detail for each function
334ed966657SSimon Glass        list_error_boards: Show the boards which caused each error/warning
335843312dcSSimon Glass        show_config: Show config deltas
336*48ae4124SAlex Kiernan        show_environment: Show environment deltas
337b2ea7ab2SSimon Glass        """
338b2ea7ab2SSimon Glass        self._show_errors = show_errors
339b2ea7ab2SSimon Glass        self._show_sizes = show_sizes
340b2ea7ab2SSimon Glass        self._show_detail = show_detail
341b2ea7ab2SSimon Glass        self._show_bloat = show_bloat
342ed966657SSimon Glass        self._list_error_boards = list_error_boards
343843312dcSSimon Glass        self._show_config = show_config
344*48ae4124SAlex Kiernan        self._show_environment = show_environment
345b2ea7ab2SSimon Glass
346fc3fe1c2SSimon Glass    def _AddTimestamp(self):
347fc3fe1c2SSimon Glass        """Add a new timestamp to the list and record the build period.
348fc3fe1c2SSimon Glass
349fc3fe1c2SSimon Glass        The build period is the length of time taken to perform a single
350fc3fe1c2SSimon Glass        build (one board, one commit).
351fc3fe1c2SSimon Glass        """
352fc3fe1c2SSimon Glass        now = datetime.now()
353fc3fe1c2SSimon Glass        self._timestamps.append(now)
354fc3fe1c2SSimon Glass        count = len(self._timestamps)
355fc3fe1c2SSimon Glass        delta = self._timestamps[-1] - self._timestamps[0]
356fc3fe1c2SSimon Glass        seconds = delta.total_seconds()
357fc3fe1c2SSimon Glass
358fc3fe1c2SSimon Glass        # If we have enough data, estimate build period (time taken for a
359fc3fe1c2SSimon Glass        # single build) and therefore completion time.
360fc3fe1c2SSimon Glass        if count > 1 and self._next_delay_update < now:
361fc3fe1c2SSimon Glass            self._next_delay_update = now + timedelta(seconds=2)
362fc3fe1c2SSimon Glass            if seconds > 0:
363fc3fe1c2SSimon Glass                self._build_period = float(seconds) / count
364fc3fe1c2SSimon Glass                todo = self.count - self.upto
365fc3fe1c2SSimon Glass                self._complete_delay = timedelta(microseconds=
366fc3fe1c2SSimon Glass                        self._build_period * todo * 1000000)
367fc3fe1c2SSimon Glass                # Round it
368fc3fe1c2SSimon Glass                self._complete_delay -= timedelta(
369fc3fe1c2SSimon Glass                        microseconds=self._complete_delay.microseconds)
370fc3fe1c2SSimon Glass
371fc3fe1c2SSimon Glass        if seconds > 60:
372fc3fe1c2SSimon Glass            self._timestamps.popleft()
373fc3fe1c2SSimon Glass            count -= 1
374fc3fe1c2SSimon Glass
375fc3fe1c2SSimon Glass    def ClearLine(self, length):
376fc3fe1c2SSimon Glass        """Clear any characters on the current line
377fc3fe1c2SSimon Glass
378fc3fe1c2SSimon Glass        Make way for a new line of length 'length', by outputting enough
379fc3fe1c2SSimon Glass        spaces to clear out the old line. Then remember the new length for
380fc3fe1c2SSimon Glass        next time.
381fc3fe1c2SSimon Glass
382fc3fe1c2SSimon Glass        Args:
383fc3fe1c2SSimon Glass            length: Length of new line, in characters
384fc3fe1c2SSimon Glass        """
385fc3fe1c2SSimon Glass        if length < self.last_line_len:
3864653a882SSimon Glass            Print(' ' * (self.last_line_len - length), newline=False)
3874653a882SSimon Glass            Print('\r', newline=False)
388fc3fe1c2SSimon Glass        self.last_line_len = length
389fc3fe1c2SSimon Glass        sys.stdout.flush()
390fc3fe1c2SSimon Glass
391fc3fe1c2SSimon Glass    def SelectCommit(self, commit, checkout=True):
392fc3fe1c2SSimon Glass        """Checkout the selected commit for this build
393fc3fe1c2SSimon Glass        """
394fc3fe1c2SSimon Glass        self.commit = commit
395fc3fe1c2SSimon Glass        if checkout and self.checkout:
396fc3fe1c2SSimon Glass            gitutil.Checkout(commit.hash)
397fc3fe1c2SSimon Glass
398fc3fe1c2SSimon Glass    def Make(self, commit, brd, stage, cwd, *args, **kwargs):
399fc3fe1c2SSimon Glass        """Run make
400fc3fe1c2SSimon Glass
401fc3fe1c2SSimon Glass        Args:
402fc3fe1c2SSimon Glass            commit: Commit object that is being built
403fc3fe1c2SSimon Glass            brd: Board object that is being built
404fd18a89eSRoger Meier            stage: Stage that we are at (mrproper, config, build)
405fc3fe1c2SSimon Glass            cwd: Directory where make should be run
406fc3fe1c2SSimon Glass            args: Arguments to pass to make
407fc3fe1c2SSimon Glass            kwargs: Arguments to pass to command.RunPipe()
408fc3fe1c2SSimon Glass        """
40999796923SMasahiro Yamada        cmd = [self.gnu_make] + list(args)
410fc3fe1c2SSimon Glass        result = command.RunPipe([cmd], capture=True, capture_stderr=True,
411fc3fe1c2SSimon Glass                cwd=cwd, raise_on_error=False, **kwargs)
41240f11fceSSimon Glass        if self.verbose_build:
41340f11fceSSimon Glass            result.stdout = '%s\n' % (' '.join(cmd)) + result.stdout
41440f11fceSSimon Glass            result.combined = '%s\n' % (' '.join(cmd)) + result.combined
415fc3fe1c2SSimon Glass        return result
416fc3fe1c2SSimon Glass
417fc3fe1c2SSimon Glass    def ProcessResult(self, result):
418fc3fe1c2SSimon Glass        """Process the result of a build, showing progress information
419fc3fe1c2SSimon Glass
420fc3fe1c2SSimon Glass        Args:
421e5a0e5d8SSimon Glass            result: A CommandResult object, which indicates the result for
422e5a0e5d8SSimon Glass                    a single build
423fc3fe1c2SSimon Glass        """
424fc3fe1c2SSimon Glass        col = terminal.Color()
425fc3fe1c2SSimon Glass        if result:
426fc3fe1c2SSimon Glass            target = result.brd.target
427fc3fe1c2SSimon Glass
428fc3fe1c2SSimon Glass            self.upto += 1
429fc3fe1c2SSimon Glass            if result.return_code != 0:
430fc3fe1c2SSimon Glass                self.fail += 1
431fc3fe1c2SSimon Glass            elif result.stderr:
432fc3fe1c2SSimon Glass                self.warned += 1
433fc3fe1c2SSimon Glass            if result.already_done:
434fc3fe1c2SSimon Glass                self.already_done += 1
435e5a0e5d8SSimon Glass            if self._verbose:
4364653a882SSimon Glass                Print('\r', newline=False)
437e5a0e5d8SSimon Glass                self.ClearLine(0)
438e5a0e5d8SSimon Glass                boards_selected = {target : result.brd}
439e5a0e5d8SSimon Glass                self.ResetResultSummary(boards_selected)
440e5a0e5d8SSimon Glass                self.ProduceResultSummary(result.commit_upto, self.commits,
441e5a0e5d8SSimon Glass                                          boards_selected)
442fc3fe1c2SSimon Glass        else:
443fc3fe1c2SSimon Glass            target = '(starting)'
444fc3fe1c2SSimon Glass
445fc3fe1c2SSimon Glass        # Display separate counts for ok, warned and fail
446fc3fe1c2SSimon Glass        ok = self.upto - self.warned - self.fail
447fc3fe1c2SSimon Glass        line = '\r' + self.col.Color(self.col.GREEN, '%5d' % ok)
448fc3fe1c2SSimon Glass        line += self.col.Color(self.col.YELLOW, '%5d' % self.warned)
449fc3fe1c2SSimon Glass        line += self.col.Color(self.col.RED, '%5d' % self.fail)
450fc3fe1c2SSimon Glass
451fc3fe1c2SSimon Glass        name = ' /%-5d  ' % self.count
452fc3fe1c2SSimon Glass
453fc3fe1c2SSimon Glass        # Add our current completion time estimate
454fc3fe1c2SSimon Glass        self._AddTimestamp()
455fc3fe1c2SSimon Glass        if self._complete_delay:
456fc3fe1c2SSimon Glass            name += '%s  : ' % self._complete_delay
457fc3fe1c2SSimon Glass        # When building all boards for a commit, we can print a commit
458fc3fe1c2SSimon Glass        # progress message.
459fc3fe1c2SSimon Glass        if result and result.commit_upto is None:
460fc3fe1c2SSimon Glass            name += 'commit %2d/%-3d' % (self.commit_upto + 1,
461fc3fe1c2SSimon Glass                    self.commit_count)
462fc3fe1c2SSimon Glass
463fc3fe1c2SSimon Glass        name += target
4644653a882SSimon Glass        Print(line + name, newline=False)
465960421ecSSimon Glass        length = 16 + len(name)
466fc3fe1c2SSimon Glass        self.ClearLine(length)
467fc3fe1c2SSimon Glass
468fc3fe1c2SSimon Glass    def _GetOutputDir(self, commit_upto):
469fc3fe1c2SSimon Glass        """Get the name of the output directory for a commit number
470fc3fe1c2SSimon Glass
471fc3fe1c2SSimon Glass        The output directory is typically .../<branch>/<commit>.
472fc3fe1c2SSimon Glass
473fc3fe1c2SSimon Glass        Args:
474fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
475fc3fe1c2SSimon Glass        """
4765971ab5cSSimon Glass        commit_dir = None
477fea5858eSSimon Glass        if self.commits:
478fc3fe1c2SSimon Glass            commit = self.commits[commit_upto]
479fc3fe1c2SSimon Glass            subject = commit.subject.translate(trans_valid_chars)
480fc3fe1c2SSimon Glass            commit_dir = ('%02d_of_%02d_g%s_%s' % (commit_upto + 1,
481fc3fe1c2SSimon Glass                    self.commit_count, commit.hash, subject[:20]))
4825971ab5cSSimon Glass        elif not self.no_subdirs:
483fea5858eSSimon Glass            commit_dir = 'current'
4845971ab5cSSimon Glass        if not commit_dir:
4855971ab5cSSimon Glass            return self.base_dir
4865971ab5cSSimon Glass        return os.path.join(self.base_dir, commit_dir)
487fc3fe1c2SSimon Glass
488fc3fe1c2SSimon Glass    def GetBuildDir(self, commit_upto, target):
489fc3fe1c2SSimon Glass        """Get the name of the build directory for a commit number
490fc3fe1c2SSimon Glass
491fc3fe1c2SSimon Glass        The build directory is typically .../<branch>/<commit>/<target>.
492fc3fe1c2SSimon Glass
493fc3fe1c2SSimon Glass        Args:
494fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
495fc3fe1c2SSimon Glass            target: Target name
496fc3fe1c2SSimon Glass        """
497fc3fe1c2SSimon Glass        output_dir = self._GetOutputDir(commit_upto)
498fc3fe1c2SSimon Glass        return os.path.join(output_dir, target)
499fc3fe1c2SSimon Glass
500fc3fe1c2SSimon Glass    def GetDoneFile(self, commit_upto, target):
501fc3fe1c2SSimon Glass        """Get the name of the done file for a commit number
502fc3fe1c2SSimon Glass
503fc3fe1c2SSimon Glass        Args:
504fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
505fc3fe1c2SSimon Glass            target: Target name
506fc3fe1c2SSimon Glass        """
507fc3fe1c2SSimon Glass        return os.path.join(self.GetBuildDir(commit_upto, target), 'done')
508fc3fe1c2SSimon Glass
509fc3fe1c2SSimon Glass    def GetSizesFile(self, commit_upto, target):
510fc3fe1c2SSimon Glass        """Get the name of the sizes file for a commit number
511fc3fe1c2SSimon Glass
512fc3fe1c2SSimon Glass        Args:
513fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
514fc3fe1c2SSimon Glass            target: Target name
515fc3fe1c2SSimon Glass        """
516fc3fe1c2SSimon Glass        return os.path.join(self.GetBuildDir(commit_upto, target), 'sizes')
517fc3fe1c2SSimon Glass
518fc3fe1c2SSimon Glass    def GetFuncSizesFile(self, commit_upto, target, elf_fname):
519fc3fe1c2SSimon Glass        """Get the name of the funcsizes file for a commit number and ELF file
520fc3fe1c2SSimon Glass
521fc3fe1c2SSimon Glass        Args:
522fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
523fc3fe1c2SSimon Glass            target: Target name
524fc3fe1c2SSimon Glass            elf_fname: Filename of elf image
525fc3fe1c2SSimon Glass        """
526fc3fe1c2SSimon Glass        return os.path.join(self.GetBuildDir(commit_upto, target),
527fc3fe1c2SSimon Glass                            '%s.sizes' % elf_fname.replace('/', '-'))
528fc3fe1c2SSimon Glass
529fc3fe1c2SSimon Glass    def GetObjdumpFile(self, commit_upto, target, elf_fname):
530fc3fe1c2SSimon Glass        """Get the name of the objdump file for a commit number and ELF file
531fc3fe1c2SSimon Glass
532fc3fe1c2SSimon Glass        Args:
533fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
534fc3fe1c2SSimon Glass            target: Target name
535fc3fe1c2SSimon Glass            elf_fname: Filename of elf image
536fc3fe1c2SSimon Glass        """
537fc3fe1c2SSimon Glass        return os.path.join(self.GetBuildDir(commit_upto, target),
538fc3fe1c2SSimon Glass                            '%s.objdump' % elf_fname.replace('/', '-'))
539fc3fe1c2SSimon Glass
540fc3fe1c2SSimon Glass    def GetErrFile(self, commit_upto, target):
541fc3fe1c2SSimon Glass        """Get the name of the err file for a commit number
542fc3fe1c2SSimon Glass
543fc3fe1c2SSimon Glass        Args:
544fc3fe1c2SSimon Glass            commit_upto: Commit number to use (0..self.count-1)
545fc3fe1c2SSimon Glass            target: Target name
546fc3fe1c2SSimon Glass        """
547fc3fe1c2SSimon Glass        output_dir = self.GetBuildDir(commit_upto, target)
548fc3fe1c2SSimon Glass        return os.path.join(output_dir, 'err')
549fc3fe1c2SSimon Glass
550fc3fe1c2SSimon Glass    def FilterErrors(self, lines):
551fc3fe1c2SSimon Glass        """Filter out errors in which we have no interest
552fc3fe1c2SSimon Glass
553fc3fe1c2SSimon Glass        We should probably use map().
554fc3fe1c2SSimon Glass
555fc3fe1c2SSimon Glass        Args:
556fc3fe1c2SSimon Glass            lines: List of error lines, each a string
557fc3fe1c2SSimon Glass        Returns:
558fc3fe1c2SSimon Glass            New list with only interesting lines included
559fc3fe1c2SSimon Glass        """
560fc3fe1c2SSimon Glass        out_lines = []
561fc3fe1c2SSimon Glass        for line in lines:
562fc3fe1c2SSimon Glass            if not self.re_make_err.search(line):
563fc3fe1c2SSimon Glass                out_lines.append(line)
564fc3fe1c2SSimon Glass        return out_lines
565fc3fe1c2SSimon Glass
566fc3fe1c2SSimon Glass    def ReadFuncSizes(self, fname, fd):
567fc3fe1c2SSimon Glass        """Read function sizes from the output of 'nm'
568fc3fe1c2SSimon Glass
569fc3fe1c2SSimon Glass        Args:
570fc3fe1c2SSimon Glass            fd: File containing data to read
571fc3fe1c2SSimon Glass            fname: Filename we are reading from (just for errors)
572fc3fe1c2SSimon Glass
573fc3fe1c2SSimon Glass        Returns:
574fc3fe1c2SSimon Glass            Dictionary containing size of each function in bytes, indexed by
575fc3fe1c2SSimon Glass            function name.
576fc3fe1c2SSimon Glass        """
577fc3fe1c2SSimon Glass        sym = {}
578fc3fe1c2SSimon Glass        for line in fd.readlines():
579fc3fe1c2SSimon Glass            try:
580fc3fe1c2SSimon Glass                size, type, name = line[:-1].split()
581fc3fe1c2SSimon Glass            except:
5824653a882SSimon Glass                Print("Invalid line in file '%s': '%s'" % (fname, line[:-1]))
583fc3fe1c2SSimon Glass                continue
584fc3fe1c2SSimon Glass            if type in 'tTdDbB':
585fc3fe1c2SSimon Glass                # function names begin with '.' on 64-bit powerpc
586fc3fe1c2SSimon Glass                if '.' in name[1:]:
587fc3fe1c2SSimon Glass                    name = 'static.' + name.split('.')[0]
588fc3fe1c2SSimon Glass                sym[name] = sym.get(name, 0) + int(size, 16)
589fc3fe1c2SSimon Glass        return sym
590fc3fe1c2SSimon Glass
591843312dcSSimon Glass    def _ProcessConfig(self, fname):
592843312dcSSimon Glass        """Read in a .config, autoconf.mk or autoconf.h file
593843312dcSSimon Glass
594843312dcSSimon Glass        This function handles all config file types. It ignores comments and
595843312dcSSimon Glass        any #defines which don't start with CONFIG_.
596843312dcSSimon Glass
597843312dcSSimon Glass        Args:
598843312dcSSimon Glass            fname: Filename to read
599843312dcSSimon Glass
600843312dcSSimon Glass        Returns:
601843312dcSSimon Glass            Dictionary:
602843312dcSSimon Glass                key: Config name (e.g. CONFIG_DM)
603843312dcSSimon Glass                value: Config value (e.g. 1)
604843312dcSSimon Glass        """
605843312dcSSimon Glass        config = {}
606843312dcSSimon Glass        if os.path.exists(fname):
607843312dcSSimon Glass            with open(fname) as fd:
608843312dcSSimon Glass                for line in fd:
609843312dcSSimon Glass                    line = line.strip()
610843312dcSSimon Glass                    if line.startswith('#define'):
611843312dcSSimon Glass                        values = line[8:].split(' ', 1)
612843312dcSSimon Glass                        if len(values) > 1:
613843312dcSSimon Glass                            key, value = values
614843312dcSSimon Glass                        else:
615843312dcSSimon Glass                            key = values[0]
616b464f8e7SSimon Glass                            value = '1' if self.squash_config_y else ''
617843312dcSSimon Glass                        if not key.startswith('CONFIG_'):
618843312dcSSimon Glass                            continue
619843312dcSSimon Glass                    elif not line or line[0] in ['#', '*', '/']:
620843312dcSSimon Glass                        continue
621843312dcSSimon Glass                    else:
622843312dcSSimon Glass                        key, value = line.split('=', 1)
623b464f8e7SSimon Glass                    if self.squash_config_y and value == 'y':
624b464f8e7SSimon Glass                        value = '1'
625843312dcSSimon Glass                    config[key] = value
626843312dcSSimon Glass        return config
627843312dcSSimon Glass
628*48ae4124SAlex Kiernan    def _ProcessEnvironment(self, fname):
629*48ae4124SAlex Kiernan        """Read in a uboot.env file
630*48ae4124SAlex Kiernan
631*48ae4124SAlex Kiernan        This function reads in environment variables from a file.
632*48ae4124SAlex Kiernan
633*48ae4124SAlex Kiernan        Args:
634*48ae4124SAlex Kiernan            fname: Filename to read
635*48ae4124SAlex Kiernan
636*48ae4124SAlex Kiernan        Returns:
637*48ae4124SAlex Kiernan            Dictionary:
638*48ae4124SAlex Kiernan                key: environment variable (e.g. bootlimit)
639*48ae4124SAlex Kiernan                value: value of environment variable (e.g. 1)
640*48ae4124SAlex Kiernan        """
641*48ae4124SAlex Kiernan        environment = {}
642*48ae4124SAlex Kiernan        if os.path.exists(fname):
643*48ae4124SAlex Kiernan            with open(fname) as fd:
644*48ae4124SAlex Kiernan                for line in fd.read().split('\0'):
645*48ae4124SAlex Kiernan                    try:
646*48ae4124SAlex Kiernan                        key, value = line.split('=', 1)
647*48ae4124SAlex Kiernan                        environment[key] = value
648*48ae4124SAlex Kiernan                    except ValueError:
649*48ae4124SAlex Kiernan                        # ignore lines we can't parse
650*48ae4124SAlex Kiernan                        pass
651*48ae4124SAlex Kiernan        return environment
652*48ae4124SAlex Kiernan
653843312dcSSimon Glass    def GetBuildOutcome(self, commit_upto, target, read_func_sizes,
654*48ae4124SAlex Kiernan                        read_config, read_environment):
655fc3fe1c2SSimon Glass        """Work out the outcome of a build.
656fc3fe1c2SSimon Glass
657fc3fe1c2SSimon Glass        Args:
658fc3fe1c2SSimon Glass            commit_upto: Commit number to check (0..n-1)
659fc3fe1c2SSimon Glass            target: Target board to check
660fc3fe1c2SSimon Glass            read_func_sizes: True to read function size information
661843312dcSSimon Glass            read_config: True to read .config and autoconf.h files
662*48ae4124SAlex Kiernan            read_environment: True to read uboot.env files
663fc3fe1c2SSimon Glass
664fc3fe1c2SSimon Glass        Returns:
665fc3fe1c2SSimon Glass            Outcome object
666fc3fe1c2SSimon Glass        """
667fc3fe1c2SSimon Glass        done_file = self.GetDoneFile(commit_upto, target)
668fc3fe1c2SSimon Glass        sizes_file = self.GetSizesFile(commit_upto, target)
669fc3fe1c2SSimon Glass        sizes = {}
670fc3fe1c2SSimon Glass        func_sizes = {}
671843312dcSSimon Glass        config = {}
672*48ae4124SAlex Kiernan        environment = {}
673fc3fe1c2SSimon Glass        if os.path.exists(done_file):
674fc3fe1c2SSimon Glass            with open(done_file, 'r') as fd:
675fc3fe1c2SSimon Glass                return_code = int(fd.readline())
676fc3fe1c2SSimon Glass                err_lines = []
677fc3fe1c2SSimon Glass                err_file = self.GetErrFile(commit_upto, target)
678fc3fe1c2SSimon Glass                if os.path.exists(err_file):
679fc3fe1c2SSimon Glass                    with open(err_file, 'r') as fd:
680fc3fe1c2SSimon Glass                        err_lines = self.FilterErrors(fd.readlines())
681fc3fe1c2SSimon Glass
682fc3fe1c2SSimon Glass                # Decide whether the build was ok, failed or created warnings
683fc3fe1c2SSimon Glass                if return_code:
684fc3fe1c2SSimon Glass                    rc = OUTCOME_ERROR
685fc3fe1c2SSimon Glass                elif len(err_lines):
686fc3fe1c2SSimon Glass                    rc = OUTCOME_WARNING
687fc3fe1c2SSimon Glass                else:
688fc3fe1c2SSimon Glass                    rc = OUTCOME_OK
689fc3fe1c2SSimon Glass
690fc3fe1c2SSimon Glass                # Convert size information to our simple format
691fc3fe1c2SSimon Glass                if os.path.exists(sizes_file):
692fc3fe1c2SSimon Glass                    with open(sizes_file, 'r') as fd:
693fc3fe1c2SSimon Glass                        for line in fd.readlines():
694fc3fe1c2SSimon Glass                            values = line.split()
695fc3fe1c2SSimon Glass                            rodata = 0
696fc3fe1c2SSimon Glass                            if len(values) > 6:
697fc3fe1c2SSimon Glass                                rodata = int(values[6], 16)
698fc3fe1c2SSimon Glass                            size_dict = {
699fc3fe1c2SSimon Glass                                'all' : int(values[0]) + int(values[1]) +
700fc3fe1c2SSimon Glass                                        int(values[2]),
701fc3fe1c2SSimon Glass                                'text' : int(values[0]) - rodata,
702fc3fe1c2SSimon Glass                                'data' : int(values[1]),
703fc3fe1c2SSimon Glass                                'bss' : int(values[2]),
704fc3fe1c2SSimon Glass                                'rodata' : rodata,
705fc3fe1c2SSimon Glass                            }
706fc3fe1c2SSimon Glass                            sizes[values[5]] = size_dict
707fc3fe1c2SSimon Glass
708fc3fe1c2SSimon Glass            if read_func_sizes:
709fc3fe1c2SSimon Glass                pattern = self.GetFuncSizesFile(commit_upto, target, '*')
710fc3fe1c2SSimon Glass                for fname in glob.glob(pattern):
711fc3fe1c2SSimon Glass                    with open(fname, 'r') as fd:
712fc3fe1c2SSimon Glass                        dict_name = os.path.basename(fname).replace('.sizes',
713fc3fe1c2SSimon Glass                                                                    '')
714fc3fe1c2SSimon Glass                        func_sizes[dict_name] = self.ReadFuncSizes(fname, fd)
715fc3fe1c2SSimon Glass
716843312dcSSimon Glass            if read_config:
717843312dcSSimon Glass                output_dir = self.GetBuildDir(commit_upto, target)
718b464f8e7SSimon Glass                for name in self.config_filenames:
719843312dcSSimon Glass                    fname = os.path.join(output_dir, name)
720843312dcSSimon Glass                    config[name] = self._ProcessConfig(fname)
721fc3fe1c2SSimon Glass
722*48ae4124SAlex Kiernan            if read_environment:
723*48ae4124SAlex Kiernan                output_dir = self.GetBuildDir(commit_upto, target)
724*48ae4124SAlex Kiernan                fname = os.path.join(output_dir, 'uboot.env')
725*48ae4124SAlex Kiernan                environment = self._ProcessEnvironment(fname)
726fc3fe1c2SSimon Glass
727*48ae4124SAlex Kiernan            return Builder.Outcome(rc, err_lines, sizes, func_sizes, config,
728*48ae4124SAlex Kiernan                                   environment)
729*48ae4124SAlex Kiernan
730*48ae4124SAlex Kiernan        return Builder.Outcome(OUTCOME_UNKNOWN, [], {}, {}, {}, {})
731843312dcSSimon Glass
732843312dcSSimon Glass    def GetResultSummary(self, boards_selected, commit_upto, read_func_sizes,
733*48ae4124SAlex Kiernan                         read_config, read_environment):
734fc3fe1c2SSimon Glass        """Calculate a summary of the results of building a commit.
735fc3fe1c2SSimon Glass
736fc3fe1c2SSimon Glass        Args:
737fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise
738fc3fe1c2SSimon Glass            commit_upto: Commit number to summarize (0..self.count-1)
739fc3fe1c2SSimon Glass            read_func_sizes: True to read function size information
740843312dcSSimon Glass            read_config: True to read .config and autoconf.h files
741*48ae4124SAlex Kiernan            read_environment: True to read uboot.env files
742fc3fe1c2SSimon Glass
743fc3fe1c2SSimon Glass        Returns:
744fc3fe1c2SSimon Glass            Tuple:
745fc3fe1c2SSimon Glass                Dict containing boards which passed building this commit.
746fc3fe1c2SSimon Glass                    keyed by board.target
747e30965dbSSimon Glass                List containing a summary of error lines
748ed966657SSimon Glass                Dict keyed by error line, containing a list of the Board
749ed966657SSimon Glass                    objects with that error
750e30965dbSSimon Glass                List containing a summary of warning lines
751e30965dbSSimon Glass                Dict keyed by error line, containing a list of the Board
752e30965dbSSimon Glass                    objects with that warning
7538270e3c1SSimon Glass                Dictionary keyed by board.target. Each value is a dictionary:
7548270e3c1SSimon Glass                    key: filename - e.g. '.config'
755843312dcSSimon Glass                    value is itself a dictionary:
756843312dcSSimon Glass                        key: config name
757843312dcSSimon Glass                        value: config value
758*48ae4124SAlex Kiernan                Dictionary keyed by board.target. Each value is a dictionary:
759*48ae4124SAlex Kiernan                    key: environment variable
760*48ae4124SAlex Kiernan                    value: value of environment variable
761fc3fe1c2SSimon Glass        """
762e30965dbSSimon Glass        def AddLine(lines_summary, lines_boards, line, board):
763e30965dbSSimon Glass            line = line.rstrip()
764e30965dbSSimon Glass            if line in lines_boards:
765e30965dbSSimon Glass                lines_boards[line].append(board)
766e30965dbSSimon Glass            else:
767e30965dbSSimon Glass                lines_boards[line] = [board]
768e30965dbSSimon Glass                lines_summary.append(line)
769e30965dbSSimon Glass
770fc3fe1c2SSimon Glass        board_dict = {}
771fc3fe1c2SSimon Glass        err_lines_summary = []
772ed966657SSimon Glass        err_lines_boards = {}
773e30965dbSSimon Glass        warn_lines_summary = []
774e30965dbSSimon Glass        warn_lines_boards = {}
775843312dcSSimon Glass        config = {}
776*48ae4124SAlex Kiernan        environment = {}
777fc3fe1c2SSimon Glass
778fc3fe1c2SSimon Glass        for board in boards_selected.itervalues():
779fc3fe1c2SSimon Glass            outcome = self.GetBuildOutcome(commit_upto, board.target,
780*48ae4124SAlex Kiernan                                           read_func_sizes, read_config,
781*48ae4124SAlex Kiernan                                           read_environment)
782fc3fe1c2SSimon Glass            board_dict[board.target] = outcome
783e30965dbSSimon Glass            last_func = None
784e30965dbSSimon Glass            last_was_warning = False
785e30965dbSSimon Glass            for line in outcome.err_lines:
786e30965dbSSimon Glass                if line:
787e30965dbSSimon Glass                    if (self._re_function.match(line) or
788e30965dbSSimon Glass                            self._re_files.match(line)):
789e30965dbSSimon Glass                        last_func = line
790ed966657SSimon Glass                    else:
791e30965dbSSimon Glass                        is_warning = self._re_warning.match(line)
792e30965dbSSimon Glass                        is_note = self._re_note.match(line)
793e30965dbSSimon Glass                        if is_warning or (last_was_warning and is_note):
794e30965dbSSimon Glass                            if last_func:
795e30965dbSSimon Glass                                AddLine(warn_lines_summary, warn_lines_boards,
796e30965dbSSimon Glass                                        last_func, board)
797e30965dbSSimon Glass                            AddLine(warn_lines_summary, warn_lines_boards,
798e30965dbSSimon Glass                                    line, board)
799e30965dbSSimon Glass                        else:
800e30965dbSSimon Glass                            if last_func:
801e30965dbSSimon Glass                                AddLine(err_lines_summary, err_lines_boards,
802e30965dbSSimon Glass                                        last_func, board)
803e30965dbSSimon Glass                            AddLine(err_lines_summary, err_lines_boards,
804e30965dbSSimon Glass                                    line, board)
805e30965dbSSimon Glass                        last_was_warning = is_warning
806e30965dbSSimon Glass                        last_func = None
807b464f8e7SSimon Glass            tconfig = Config(self.config_filenames, board.target)
808b464f8e7SSimon Glass            for fname in self.config_filenames:
809843312dcSSimon Glass                if outcome.config:
810843312dcSSimon Glass                    for key, value in outcome.config[fname].iteritems():
8118270e3c1SSimon Glass                        tconfig.Add(fname, key, value)
8128270e3c1SSimon Glass            config[board.target] = tconfig
813843312dcSSimon Glass
814*48ae4124SAlex Kiernan            tenvironment = Environment(board.target)
815*48ae4124SAlex Kiernan            if outcome.environment:
816*48ae4124SAlex Kiernan                for key, value in outcome.environment.iteritems():
817*48ae4124SAlex Kiernan                    tenvironment.Add(key, value)
818*48ae4124SAlex Kiernan            environment[board.target] = tenvironment
819*48ae4124SAlex Kiernan
820e30965dbSSimon Glass        return (board_dict, err_lines_summary, err_lines_boards,
821*48ae4124SAlex Kiernan                warn_lines_summary, warn_lines_boards, config, environment)
822fc3fe1c2SSimon Glass
823fc3fe1c2SSimon Glass    def AddOutcome(self, board_dict, arch_list, changes, char, color):
824fc3fe1c2SSimon Glass        """Add an output to our list of outcomes for each architecture
825fc3fe1c2SSimon Glass
826fc3fe1c2SSimon Glass        This simple function adds failing boards (changes) to the
827fc3fe1c2SSimon Glass        relevant architecture string, so we can print the results out
828fc3fe1c2SSimon Glass        sorted by architecture.
829fc3fe1c2SSimon Glass
830fc3fe1c2SSimon Glass        Args:
831fc3fe1c2SSimon Glass             board_dict: Dict containing all boards
832fc3fe1c2SSimon Glass             arch_list: Dict keyed by arch name. Value is a string containing
833fc3fe1c2SSimon Glass                    a list of board names which failed for that arch.
834fc3fe1c2SSimon Glass             changes: List of boards to add to arch_list
835fc3fe1c2SSimon Glass             color: terminal.Colour object
836fc3fe1c2SSimon Glass        """
837fc3fe1c2SSimon Glass        done_arch = {}
838fc3fe1c2SSimon Glass        for target in changes:
839fc3fe1c2SSimon Glass            if target in board_dict:
840fc3fe1c2SSimon Glass                arch = board_dict[target].arch
841fc3fe1c2SSimon Glass            else:
842fc3fe1c2SSimon Glass                arch = 'unknown'
843fc3fe1c2SSimon Glass            str = self.col.Color(color, ' ' + target)
844fc3fe1c2SSimon Glass            if not arch in done_arch:
84563c619eeSSimon Glass                str = ' %s  %s' % (self.col.Color(color, char), str)
846fc3fe1c2SSimon Glass                done_arch[arch] = True
847fc3fe1c2SSimon Glass            if not arch in arch_list:
848fc3fe1c2SSimon Glass                arch_list[arch] = str
849fc3fe1c2SSimon Glass            else:
850fc3fe1c2SSimon Glass                arch_list[arch] += str
851fc3fe1c2SSimon Glass
852fc3fe1c2SSimon Glass
853fc3fe1c2SSimon Glass    def ColourNum(self, num):
854fc3fe1c2SSimon Glass        color = self.col.RED if num > 0 else self.col.GREEN
855fc3fe1c2SSimon Glass        if num == 0:
856fc3fe1c2SSimon Glass            return '0'
857fc3fe1c2SSimon Glass        return self.col.Color(color, str(num))
858fc3fe1c2SSimon Glass
859fc3fe1c2SSimon Glass    def ResetResultSummary(self, board_selected):
860fc3fe1c2SSimon Glass        """Reset the results summary ready for use.
861fc3fe1c2SSimon Glass
862fc3fe1c2SSimon Glass        Set up the base board list to be all those selected, and set the
863fc3fe1c2SSimon Glass        error lines to empty.
864fc3fe1c2SSimon Glass
865fc3fe1c2SSimon Glass        Following this, calls to PrintResultSummary() will use this
866fc3fe1c2SSimon Glass        information to work out what has changed.
867fc3fe1c2SSimon Glass
868fc3fe1c2SSimon Glass        Args:
869fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise, keyed by
870fc3fe1c2SSimon Glass                board.target
871fc3fe1c2SSimon Glass        """
872fc3fe1c2SSimon Glass        self._base_board_dict = {}
873fc3fe1c2SSimon Glass        for board in board_selected:
874*48ae4124SAlex Kiernan            self._base_board_dict[board] = Builder.Outcome(0, [], [], {}, {},
875*48ae4124SAlex Kiernan                                                           {})
876fc3fe1c2SSimon Glass        self._base_err_lines = []
877e30965dbSSimon Glass        self._base_warn_lines = []
878e30965dbSSimon Glass        self._base_err_line_boards = {}
879e30965dbSSimon Glass        self._base_warn_line_boards = {}
8808270e3c1SSimon Glass        self._base_config = None
881*48ae4124SAlex Kiernan        self._base_environment = None
882fc3fe1c2SSimon Glass
883fc3fe1c2SSimon Glass    def PrintFuncSizeDetail(self, fname, old, new):
884fc3fe1c2SSimon Glass        grow, shrink, add, remove, up, down = 0, 0, 0, 0, 0, 0
885fc3fe1c2SSimon Glass        delta, common = [], {}
886fc3fe1c2SSimon Glass
887fc3fe1c2SSimon Glass        for a in old:
888fc3fe1c2SSimon Glass            if a in new:
889fc3fe1c2SSimon Glass                common[a] = 1
890fc3fe1c2SSimon Glass
891fc3fe1c2SSimon Glass        for name in old:
892fc3fe1c2SSimon Glass            if name not in common:
893fc3fe1c2SSimon Glass                remove += 1
894fc3fe1c2SSimon Glass                down += old[name]
895fc3fe1c2SSimon Glass                delta.append([-old[name], name])
896fc3fe1c2SSimon Glass
897fc3fe1c2SSimon Glass        for name in new:
898fc3fe1c2SSimon Glass            if name not in common:
899fc3fe1c2SSimon Glass                add += 1
900fc3fe1c2SSimon Glass                up += new[name]
901fc3fe1c2SSimon Glass                delta.append([new[name], name])
902fc3fe1c2SSimon Glass
903fc3fe1c2SSimon Glass        for name in common:
904fc3fe1c2SSimon Glass                diff = new.get(name, 0) - old.get(name, 0)
905fc3fe1c2SSimon Glass                if diff > 0:
906fc3fe1c2SSimon Glass                    grow, up = grow + 1, up + diff
907fc3fe1c2SSimon Glass                elif diff < 0:
908fc3fe1c2SSimon Glass                    shrink, down = shrink + 1, down - diff
909fc3fe1c2SSimon Glass                delta.append([diff, name])
910fc3fe1c2SSimon Glass
911fc3fe1c2SSimon Glass        delta.sort()
912fc3fe1c2SSimon Glass        delta.reverse()
913fc3fe1c2SSimon Glass
914fc3fe1c2SSimon Glass        args = [add, -remove, grow, -shrink, up, -down, up - down]
915d5686a61STom Rini        if max(args) == 0 and min(args) == 0:
916fc3fe1c2SSimon Glass            return
917fc3fe1c2SSimon Glass        args = [self.ColourNum(x) for x in args]
918fc3fe1c2SSimon Glass        indent = ' ' * 15
9194653a882SSimon Glass        Print('%s%s: add: %s/%s, grow: %s/%s bytes: %s/%s (%s)' %
920fc3fe1c2SSimon Glass              tuple([indent, self.col.Color(self.col.YELLOW, fname)] + args))
9214653a882SSimon Glass        Print('%s  %-38s %7s %7s %+7s' % (indent, 'function', 'old', 'new',
9224653a882SSimon Glass                                         'delta'))
923fc3fe1c2SSimon Glass        for diff, name in delta:
924fc3fe1c2SSimon Glass            if diff:
925fc3fe1c2SSimon Glass                color = self.col.RED if diff > 0 else self.col.GREEN
926fc3fe1c2SSimon Glass                msg = '%s  %-38s %7s %7s %+7d' % (indent, name,
927fc3fe1c2SSimon Glass                        old.get(name, '-'), new.get(name,'-'), diff)
9284653a882SSimon Glass                Print(msg, colour=color)
929fc3fe1c2SSimon Glass
930fc3fe1c2SSimon Glass
931fc3fe1c2SSimon Glass    def PrintSizeDetail(self, target_list, show_bloat):
932fc3fe1c2SSimon Glass        """Show details size information for each board
933fc3fe1c2SSimon Glass
934fc3fe1c2SSimon Glass        Args:
935fc3fe1c2SSimon Glass            target_list: List of targets, each a dict containing:
936fc3fe1c2SSimon Glass                    'target': Target name
937fc3fe1c2SSimon Glass                    'total_diff': Total difference in bytes across all areas
938fc3fe1c2SSimon Glass                    <part_name>: Difference for that part
939fc3fe1c2SSimon Glass            show_bloat: Show detail for each function
940fc3fe1c2SSimon Glass        """
941fc3fe1c2SSimon Glass        targets_by_diff = sorted(target_list, reverse=True,
942fc3fe1c2SSimon Glass        key=lambda x: x['_total_diff'])
943fc3fe1c2SSimon Glass        for result in targets_by_diff:
944fc3fe1c2SSimon Glass            printed_target = False
945fc3fe1c2SSimon Glass            for name in sorted(result):
946fc3fe1c2SSimon Glass                diff = result[name]
947fc3fe1c2SSimon Glass                if name.startswith('_'):
948fc3fe1c2SSimon Glass                    continue
949fc3fe1c2SSimon Glass                if diff != 0:
950fc3fe1c2SSimon Glass                    color = self.col.RED if diff > 0 else self.col.GREEN
951fc3fe1c2SSimon Glass                msg = ' %s %+d' % (name, diff)
952fc3fe1c2SSimon Glass                if not printed_target:
9534653a882SSimon Glass                    Print('%10s  %-15s:' % ('', result['_target']),
9544653a882SSimon Glass                          newline=False)
955fc3fe1c2SSimon Glass                    printed_target = True
9564653a882SSimon Glass                Print(msg, colour=color, newline=False)
957fc3fe1c2SSimon Glass            if printed_target:
9584653a882SSimon Glass                Print()
959fc3fe1c2SSimon Glass                if show_bloat:
960fc3fe1c2SSimon Glass                    target = result['_target']
961fc3fe1c2SSimon Glass                    outcome = result['_outcome']
962fc3fe1c2SSimon Glass                    base_outcome = self._base_board_dict[target]
963fc3fe1c2SSimon Glass                    for fname in outcome.func_sizes:
964fc3fe1c2SSimon Glass                        self.PrintFuncSizeDetail(fname,
965fc3fe1c2SSimon Glass                                                 base_outcome.func_sizes[fname],
966fc3fe1c2SSimon Glass                                                 outcome.func_sizes[fname])
967fc3fe1c2SSimon Glass
968fc3fe1c2SSimon Glass
969fc3fe1c2SSimon Glass    def PrintSizeSummary(self, board_selected, board_dict, show_detail,
970fc3fe1c2SSimon Glass                         show_bloat):
971fc3fe1c2SSimon Glass        """Print a summary of image sizes broken down by section.
972fc3fe1c2SSimon Glass
973fc3fe1c2SSimon Glass        The summary takes the form of one line per architecture. The
974fc3fe1c2SSimon Glass        line contains deltas for each of the sections (+ means the section
975fc3fe1c2SSimon Glass        got bigger, - means smaller). The nunmbers are the average number
976fc3fe1c2SSimon Glass        of bytes that a board in this section increased by.
977fc3fe1c2SSimon Glass
978fc3fe1c2SSimon Glass        For example:
979fc3fe1c2SSimon Glass           powerpc: (622 boards)   text -0.0
980fc3fe1c2SSimon Glass          arm: (285 boards)   text -0.0
981fc3fe1c2SSimon Glass          nds32: (3 boards)   text -8.0
982fc3fe1c2SSimon Glass
983fc3fe1c2SSimon Glass        Args:
984fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise, keyed by
985fc3fe1c2SSimon Glass                board.target
986fc3fe1c2SSimon Glass            board_dict: Dict containing boards for which we built this
987fc3fe1c2SSimon Glass                commit, keyed by board.target. The value is an Outcome object.
988fc3fe1c2SSimon Glass            show_detail: Show detail for each board
989fc3fe1c2SSimon Glass            show_bloat: Show detail for each function
990fc3fe1c2SSimon Glass        """
991fc3fe1c2SSimon Glass        arch_list = {}
992fc3fe1c2SSimon Glass        arch_count = {}
993fc3fe1c2SSimon Glass
994fc3fe1c2SSimon Glass        # Calculate changes in size for different image parts
995fc3fe1c2SSimon Glass        # The previous sizes are in Board.sizes, for each board
996fc3fe1c2SSimon Glass        for target in board_dict:
997fc3fe1c2SSimon Glass            if target not in board_selected:
998fc3fe1c2SSimon Glass                continue
999fc3fe1c2SSimon Glass            base_sizes = self._base_board_dict[target].sizes
1000fc3fe1c2SSimon Glass            outcome = board_dict[target]
1001fc3fe1c2SSimon Glass            sizes = outcome.sizes
1002fc3fe1c2SSimon Glass
1003fc3fe1c2SSimon Glass            # Loop through the list of images, creating a dict of size
1004fc3fe1c2SSimon Glass            # changes for each image/part. We end up with something like
1005fc3fe1c2SSimon Glass            # {'target' : 'snapper9g45, 'data' : 5, 'u-boot-spl:text' : -4}
1006fc3fe1c2SSimon Glass            # which means that U-Boot data increased by 5 bytes and SPL
1007fc3fe1c2SSimon Glass            # text decreased by 4.
1008fc3fe1c2SSimon Glass            err = {'_target' : target}
1009fc3fe1c2SSimon Glass            for image in sizes:
1010fc3fe1c2SSimon Glass                if image in base_sizes:
1011fc3fe1c2SSimon Glass                    base_image = base_sizes[image]
1012fc3fe1c2SSimon Glass                    # Loop through the text, data, bss parts
1013fc3fe1c2SSimon Glass                    for part in sorted(sizes[image]):
1014fc3fe1c2SSimon Glass                        diff = sizes[image][part] - base_image[part]
1015fc3fe1c2SSimon Glass                        col = None
1016fc3fe1c2SSimon Glass                        if diff:
1017fc3fe1c2SSimon Glass                            if image == 'u-boot':
1018fc3fe1c2SSimon Glass                                name = part
1019fc3fe1c2SSimon Glass                            else:
1020fc3fe1c2SSimon Glass                                name = image + ':' + part
1021fc3fe1c2SSimon Glass                            err[name] = diff
1022fc3fe1c2SSimon Glass            arch = board_selected[target].arch
1023fc3fe1c2SSimon Glass            if not arch in arch_count:
1024fc3fe1c2SSimon Glass                arch_count[arch] = 1
1025fc3fe1c2SSimon Glass            else:
1026fc3fe1c2SSimon Glass                arch_count[arch] += 1
1027fc3fe1c2SSimon Glass            if not sizes:
1028fc3fe1c2SSimon Glass                pass    # Only add to our list when we have some stats
1029fc3fe1c2SSimon Glass            elif not arch in arch_list:
1030fc3fe1c2SSimon Glass                arch_list[arch] = [err]
1031fc3fe1c2SSimon Glass            else:
1032fc3fe1c2SSimon Glass                arch_list[arch].append(err)
1033fc3fe1c2SSimon Glass
1034fc3fe1c2SSimon Glass        # We now have a list of image size changes sorted by arch
1035fc3fe1c2SSimon Glass        # Print out a summary of these
1036fc3fe1c2SSimon Glass        for arch, target_list in arch_list.iteritems():
1037fc3fe1c2SSimon Glass            # Get total difference for each type
1038fc3fe1c2SSimon Glass            totals = {}
1039fc3fe1c2SSimon Glass            for result in target_list:
1040fc3fe1c2SSimon Glass                total = 0
1041fc3fe1c2SSimon Glass                for name, diff in result.iteritems():
1042fc3fe1c2SSimon Glass                    if name.startswith('_'):
1043fc3fe1c2SSimon Glass                        continue
1044fc3fe1c2SSimon Glass                    total += diff
1045fc3fe1c2SSimon Glass                    if name in totals:
1046fc3fe1c2SSimon Glass                        totals[name] += diff
1047fc3fe1c2SSimon Glass                    else:
1048fc3fe1c2SSimon Glass                        totals[name] = diff
1049fc3fe1c2SSimon Glass                result['_total_diff'] = total
1050fc3fe1c2SSimon Glass                result['_outcome'] = board_dict[result['_target']]
1051fc3fe1c2SSimon Glass
1052fc3fe1c2SSimon Glass            count = len(target_list)
1053fc3fe1c2SSimon Glass            printed_arch = False
1054fc3fe1c2SSimon Glass            for name in sorted(totals):
1055fc3fe1c2SSimon Glass                diff = totals[name]
1056fc3fe1c2SSimon Glass                if diff:
1057fc3fe1c2SSimon Glass                    # Display the average difference in this name for this
1058fc3fe1c2SSimon Glass                    # architecture
1059fc3fe1c2SSimon Glass                    avg_diff = float(diff) / count
1060fc3fe1c2SSimon Glass                    color = self.col.RED if avg_diff > 0 else self.col.GREEN
1061fc3fe1c2SSimon Glass                    msg = ' %s %+1.1f' % (name, avg_diff)
1062fc3fe1c2SSimon Glass                    if not printed_arch:
10634653a882SSimon Glass                        Print('%10s: (for %d/%d boards)' % (arch, count,
10644653a882SSimon Glass                              arch_count[arch]), newline=False)
1065fc3fe1c2SSimon Glass                        printed_arch = True
10664653a882SSimon Glass                    Print(msg, colour=color, newline=False)
1067fc3fe1c2SSimon Glass
1068fc3fe1c2SSimon Glass            if printed_arch:
10694653a882SSimon Glass                Print()
1070fc3fe1c2SSimon Glass                if show_detail:
1071fc3fe1c2SSimon Glass                    self.PrintSizeDetail(target_list, show_bloat)
1072fc3fe1c2SSimon Glass
1073fc3fe1c2SSimon Glass
1074fc3fe1c2SSimon Glass    def PrintResultSummary(self, board_selected, board_dict, err_lines,
1075e30965dbSSimon Glass                           err_line_boards, warn_lines, warn_line_boards,
1076*48ae4124SAlex Kiernan                           config, environment, show_sizes, show_detail,
1077*48ae4124SAlex Kiernan                           show_bloat, show_config, show_environment):
1078fc3fe1c2SSimon Glass        """Compare results with the base results and display delta.
1079fc3fe1c2SSimon Glass
1080fc3fe1c2SSimon Glass        Only boards mentioned in board_selected will be considered. This
1081fc3fe1c2SSimon Glass        function is intended to be called repeatedly with the results of
1082fc3fe1c2SSimon Glass        each commit. It therefore shows a 'diff' between what it saw in
1083fc3fe1c2SSimon Glass        the last call and what it sees now.
1084fc3fe1c2SSimon Glass
1085fc3fe1c2SSimon Glass        Args:
1086fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise, keyed by
1087fc3fe1c2SSimon Glass                board.target
1088fc3fe1c2SSimon Glass            board_dict: Dict containing boards for which we built this
1089fc3fe1c2SSimon Glass                commit, keyed by board.target. The value is an Outcome object.
1090fc3fe1c2SSimon Glass            err_lines: A list of errors for this commit, or [] if there is
1091fc3fe1c2SSimon Glass                none, or we don't want to print errors
1092ed966657SSimon Glass            err_line_boards: Dict keyed by error line, containing a list of
1093ed966657SSimon Glass                the Board objects with that error
1094e30965dbSSimon Glass            warn_lines: A list of warnings for this commit, or [] if there is
1095e30965dbSSimon Glass                none, or we don't want to print errors
1096e30965dbSSimon Glass            warn_line_boards: Dict keyed by warning line, containing a list of
1097e30965dbSSimon Glass                the Board objects with that warning
1098843312dcSSimon Glass            config: Dictionary keyed by filename - e.g. '.config'. Each
1099843312dcSSimon Glass                    value is itself a dictionary:
1100843312dcSSimon Glass                        key: config name
1101843312dcSSimon Glass                        value: config value
1102*48ae4124SAlex Kiernan            environment: Dictionary keyed by environment variable, Each
1103*48ae4124SAlex Kiernan                     value is the value of environment variable.
1104fc3fe1c2SSimon Glass            show_sizes: Show image size deltas
1105fc3fe1c2SSimon Glass            show_detail: Show detail for each board
1106fc3fe1c2SSimon Glass            show_bloat: Show detail for each function
1107843312dcSSimon Glass            show_config: Show config changes
1108*48ae4124SAlex Kiernan            show_environment: Show environment changes
1109fc3fe1c2SSimon Glass        """
1110e30965dbSSimon Glass        def _BoardList(line, line_boards):
1111ed966657SSimon Glass            """Helper function to get a line of boards containing a line
1112ed966657SSimon Glass
1113ed966657SSimon Glass            Args:
1114ed966657SSimon Glass                line: Error line to search for
1115ed966657SSimon Glass            Return:
1116ed966657SSimon Glass                String containing a list of boards with that error line, or
1117ed966657SSimon Glass                '' if the user has not requested such a list
1118ed966657SSimon Glass            """
1119ed966657SSimon Glass            if self._list_error_boards:
1120ed966657SSimon Glass                names = []
1121e30965dbSSimon Glass                for board in line_boards[line]:
1122f66153beSSimon Glass                    if not board.target in names:
1123ed966657SSimon Glass                        names.append(board.target)
1124ed966657SSimon Glass                names_str = '(%s) ' % ','.join(names)
1125ed966657SSimon Glass            else:
1126ed966657SSimon Glass                names_str = ''
1127ed966657SSimon Glass            return names_str
1128ed966657SSimon Glass
1129e30965dbSSimon Glass        def _CalcErrorDelta(base_lines, base_line_boards, lines, line_boards,
1130e30965dbSSimon Glass                            char):
1131e30965dbSSimon Glass            better_lines = []
1132e30965dbSSimon Glass            worse_lines = []
1133e30965dbSSimon Glass            for line in lines:
1134e30965dbSSimon Glass                if line not in base_lines:
1135e30965dbSSimon Glass                    worse_lines.append(char + '+' +
1136e30965dbSSimon Glass                            _BoardList(line, line_boards) + line)
1137e30965dbSSimon Glass            for line in base_lines:
1138e30965dbSSimon Glass                if line not in lines:
1139e30965dbSSimon Glass                    better_lines.append(char + '-' +
1140e30965dbSSimon Glass                            _BoardList(line, base_line_boards) + line)
1141e30965dbSSimon Glass            return better_lines, worse_lines
1142e30965dbSSimon Glass
1143843312dcSSimon Glass        def _CalcConfig(delta, name, config):
1144843312dcSSimon Glass            """Calculate configuration changes
1145843312dcSSimon Glass
1146843312dcSSimon Glass            Args:
1147843312dcSSimon Glass                delta: Type of the delta, e.g. '+'
1148843312dcSSimon Glass                name: name of the file which changed (e.g. .config)
1149843312dcSSimon Glass                config: configuration change dictionary
1150843312dcSSimon Glass                    key: config name
1151843312dcSSimon Glass                    value: config value
1152843312dcSSimon Glass            Returns:
1153843312dcSSimon Glass                String containing the configuration changes which can be
1154843312dcSSimon Glass                    printed
1155843312dcSSimon Glass            """
1156843312dcSSimon Glass            out = ''
1157843312dcSSimon Glass            for key in sorted(config.keys()):
1158843312dcSSimon Glass                out += '%s=%s ' % (key, config[key])
11598270e3c1SSimon Glass            return '%s %s: %s' % (delta, name, out)
1160843312dcSSimon Glass
11618270e3c1SSimon Glass        def _AddConfig(lines, name, config_plus, config_minus, config_change):
11628270e3c1SSimon Glass            """Add changes in configuration to a list
1163843312dcSSimon Glass
1164843312dcSSimon Glass            Args:
11658270e3c1SSimon Glass                lines: list to add to
11668270e3c1SSimon Glass                name: config file name
1167843312dcSSimon Glass                config_plus: configurations added, dictionary
1168843312dcSSimon Glass                    key: config name
1169843312dcSSimon Glass                    value: config value
1170843312dcSSimon Glass                config_minus: configurations removed, dictionary
1171843312dcSSimon Glass                    key: config name
1172843312dcSSimon Glass                    value: config value
1173843312dcSSimon Glass                config_change: configurations changed, dictionary
1174843312dcSSimon Glass                    key: config name
1175843312dcSSimon Glass                    value: config value
1176843312dcSSimon Glass            """
1177843312dcSSimon Glass            if config_plus:
11788270e3c1SSimon Glass                lines.append(_CalcConfig('+', name, config_plus))
1179843312dcSSimon Glass            if config_minus:
11808270e3c1SSimon Glass                lines.append(_CalcConfig('-', name, config_minus))
1181843312dcSSimon Glass            if config_change:
11828270e3c1SSimon Glass                lines.append(_CalcConfig('c', name, config_change))
11838270e3c1SSimon Glass
11848270e3c1SSimon Glass        def _OutputConfigInfo(lines):
11858270e3c1SSimon Glass            for line in lines:
11868270e3c1SSimon Glass                if not line:
11878270e3c1SSimon Glass                    continue
11888270e3c1SSimon Glass                if line[0] == '+':
11898270e3c1SSimon Glass                    col = self.col.GREEN
11908270e3c1SSimon Glass                elif line[0] == '-':
11918270e3c1SSimon Glass                    col = self.col.RED
11928270e3c1SSimon Glass                elif line[0] == 'c':
11938270e3c1SSimon Glass                    col = self.col.YELLOW
11948270e3c1SSimon Glass                Print('   ' + line, newline=True, colour=col)
11958270e3c1SSimon Glass
1196843312dcSSimon Glass
1197fc3fe1c2SSimon Glass        better = []     # List of boards fixed since last commit
1198fc3fe1c2SSimon Glass        worse = []      # List of new broken boards since last commit
1199fc3fe1c2SSimon Glass        new = []        # List of boards that didn't exist last time
1200fc3fe1c2SSimon Glass        unknown = []    # List of boards that were not built
1201fc3fe1c2SSimon Glass
1202fc3fe1c2SSimon Glass        for target in board_dict:
1203fc3fe1c2SSimon Glass            if target not in board_selected:
1204fc3fe1c2SSimon Glass                continue
1205fc3fe1c2SSimon Glass
1206fc3fe1c2SSimon Glass            # If the board was built last time, add its outcome to a list
1207fc3fe1c2SSimon Glass            if target in self._base_board_dict:
1208fc3fe1c2SSimon Glass                base_outcome = self._base_board_dict[target].rc
1209fc3fe1c2SSimon Glass                outcome = board_dict[target]
1210fc3fe1c2SSimon Glass                if outcome.rc == OUTCOME_UNKNOWN:
1211fc3fe1c2SSimon Glass                    unknown.append(target)
1212fc3fe1c2SSimon Glass                elif outcome.rc < base_outcome:
1213fc3fe1c2SSimon Glass                    better.append(target)
1214fc3fe1c2SSimon Glass                elif outcome.rc > base_outcome:
1215fc3fe1c2SSimon Glass                    worse.append(target)
1216fc3fe1c2SSimon Glass            else:
1217fc3fe1c2SSimon Glass                new.append(target)
1218fc3fe1c2SSimon Glass
1219fc3fe1c2SSimon Glass        # Get a list of errors that have appeared, and disappeared
1220e30965dbSSimon Glass        better_err, worse_err = _CalcErrorDelta(self._base_err_lines,
1221e30965dbSSimon Glass                self._base_err_line_boards, err_lines, err_line_boards, '')
1222e30965dbSSimon Glass        better_warn, worse_warn = _CalcErrorDelta(self._base_warn_lines,
1223e30965dbSSimon Glass                self._base_warn_line_boards, warn_lines, warn_line_boards, 'w')
1224fc3fe1c2SSimon Glass
1225fc3fe1c2SSimon Glass        # Display results by arch
1226e30965dbSSimon Glass        if (better or worse or unknown or new or worse_err or better_err
1227e30965dbSSimon Glass                or worse_warn or better_warn):
1228fc3fe1c2SSimon Glass            arch_list = {}
1229fc3fe1c2SSimon Glass            self.AddOutcome(board_selected, arch_list, better, '',
1230fc3fe1c2SSimon Glass                    self.col.GREEN)
1231fc3fe1c2SSimon Glass            self.AddOutcome(board_selected, arch_list, worse, '+',
1232fc3fe1c2SSimon Glass                    self.col.RED)
1233fc3fe1c2SSimon Glass            self.AddOutcome(board_selected, arch_list, new, '*', self.col.BLUE)
1234fc3fe1c2SSimon Glass            if self._show_unknown:
1235fc3fe1c2SSimon Glass                self.AddOutcome(board_selected, arch_list, unknown, '?',
1236fc3fe1c2SSimon Glass                        self.col.MAGENTA)
1237fc3fe1c2SSimon Glass            for arch, target_list in arch_list.iteritems():
12384653a882SSimon Glass                Print('%10s: %s' % (arch, target_list))
123928370c1bSSimon Glass                self._error_lines += 1
1240fc3fe1c2SSimon Glass            if better_err:
12414653a882SSimon Glass                Print('\n'.join(better_err), colour=self.col.GREEN)
124228370c1bSSimon Glass                self._error_lines += 1
1243fc3fe1c2SSimon Glass            if worse_err:
12444653a882SSimon Glass                Print('\n'.join(worse_err), colour=self.col.RED)
124528370c1bSSimon Glass                self._error_lines += 1
1246e30965dbSSimon Glass            if better_warn:
12474653a882SSimon Glass                Print('\n'.join(better_warn), colour=self.col.CYAN)
1248e30965dbSSimon Glass                self._error_lines += 1
1249e30965dbSSimon Glass            if worse_warn:
12504653a882SSimon Glass                Print('\n'.join(worse_warn), colour=self.col.MAGENTA)
1251e30965dbSSimon Glass                self._error_lines += 1
1252fc3fe1c2SSimon Glass
1253fc3fe1c2SSimon Glass        if show_sizes:
1254fc3fe1c2SSimon Glass            self.PrintSizeSummary(board_selected, board_dict, show_detail,
1255fc3fe1c2SSimon Glass                                  show_bloat)
1256fc3fe1c2SSimon Glass
1257*48ae4124SAlex Kiernan        if show_environment and self._base_environment:
1258*48ae4124SAlex Kiernan            lines = []
1259*48ae4124SAlex Kiernan
1260*48ae4124SAlex Kiernan            for target in board_dict:
1261*48ae4124SAlex Kiernan                if target not in board_selected:
1262*48ae4124SAlex Kiernan                    continue
1263*48ae4124SAlex Kiernan
1264*48ae4124SAlex Kiernan                tbase = self._base_environment[target]
1265*48ae4124SAlex Kiernan                tenvironment = environment[target]
1266*48ae4124SAlex Kiernan                environment_plus = {}
1267*48ae4124SAlex Kiernan                environment_minus = {}
1268*48ae4124SAlex Kiernan                environment_change = {}
1269*48ae4124SAlex Kiernan                base = tbase.environment
1270*48ae4124SAlex Kiernan                for key, value in tenvironment.environment.iteritems():
1271*48ae4124SAlex Kiernan                    if key not in base:
1272*48ae4124SAlex Kiernan                        environment_plus[key] = value
1273*48ae4124SAlex Kiernan                for key, value in base.iteritems():
1274*48ae4124SAlex Kiernan                    if key not in tenvironment.environment:
1275*48ae4124SAlex Kiernan                        environment_minus[key] = value
1276*48ae4124SAlex Kiernan                for key, value in base.iteritems():
1277*48ae4124SAlex Kiernan                    new_value = tenvironment.environment.get(key)
1278*48ae4124SAlex Kiernan                    if new_value and value != new_value:
1279*48ae4124SAlex Kiernan                        desc = '%s -> %s' % (value, new_value)
1280*48ae4124SAlex Kiernan                        environment_change[key] = desc
1281*48ae4124SAlex Kiernan
1282*48ae4124SAlex Kiernan                _AddConfig(lines, target, environment_plus, environment_minus,
1283*48ae4124SAlex Kiernan                           environment_change)
1284*48ae4124SAlex Kiernan
1285*48ae4124SAlex Kiernan            _OutputConfigInfo(lines)
1286*48ae4124SAlex Kiernan
12878270e3c1SSimon Glass        if show_config and self._base_config:
12888270e3c1SSimon Glass            summary = {}
12898270e3c1SSimon Glass            arch_config_plus = {}
12908270e3c1SSimon Glass            arch_config_minus = {}
12918270e3c1SSimon Glass            arch_config_change = {}
12928270e3c1SSimon Glass            arch_list = []
12938270e3c1SSimon Glass
12948270e3c1SSimon Glass            for target in board_dict:
12958270e3c1SSimon Glass                if target not in board_selected:
12968270e3c1SSimon Glass                    continue
12978270e3c1SSimon Glass                arch = board_selected[target].arch
12988270e3c1SSimon Glass                if arch not in arch_list:
12998270e3c1SSimon Glass                    arch_list.append(arch)
13008270e3c1SSimon Glass
13018270e3c1SSimon Glass            for arch in arch_list:
13028270e3c1SSimon Glass                arch_config_plus[arch] = {}
13038270e3c1SSimon Glass                arch_config_minus[arch] = {}
13048270e3c1SSimon Glass                arch_config_change[arch] = {}
1305b464f8e7SSimon Glass                for name in self.config_filenames:
13068270e3c1SSimon Glass                    arch_config_plus[arch][name] = {}
13078270e3c1SSimon Glass                    arch_config_minus[arch][name] = {}
13088270e3c1SSimon Glass                    arch_config_change[arch][name] = {}
13098270e3c1SSimon Glass
13108270e3c1SSimon Glass            for target in board_dict:
13118270e3c1SSimon Glass                if target not in board_selected:
13128270e3c1SSimon Glass                    continue
13138270e3c1SSimon Glass
13148270e3c1SSimon Glass                arch = board_selected[target].arch
13158270e3c1SSimon Glass
1316843312dcSSimon Glass                all_config_plus = {}
1317843312dcSSimon Glass                all_config_minus = {}
1318843312dcSSimon Glass                all_config_change = {}
13198270e3c1SSimon Glass                tbase = self._base_config[target]
13208270e3c1SSimon Glass                tconfig = config[target]
13218270e3c1SSimon Glass                lines = []
1322b464f8e7SSimon Glass                for name in self.config_filenames:
13238270e3c1SSimon Glass                    if not tconfig.config[name]:
1324843312dcSSimon Glass                        continue
1325843312dcSSimon Glass                    config_plus = {}
1326843312dcSSimon Glass                    config_minus = {}
1327843312dcSSimon Glass                    config_change = {}
13288270e3c1SSimon Glass                    base = tbase.config[name]
13298270e3c1SSimon Glass                    for key, value in tconfig.config[name].iteritems():
1330843312dcSSimon Glass                        if key not in base:
1331843312dcSSimon Glass                            config_plus[key] = value
1332843312dcSSimon Glass                            all_config_plus[key] = value
1333843312dcSSimon Glass                    for key, value in base.iteritems():
13348270e3c1SSimon Glass                        if key not in tconfig.config[name]:
1335843312dcSSimon Glass                            config_minus[key] = value
1336843312dcSSimon Glass                            all_config_minus[key] = value
1337843312dcSSimon Glass                    for key, value in base.iteritems():
13388270e3c1SSimon Glass                        new_value = tconfig.config.get(key)
13398270e3c1SSimon Glass                        if new_value and value != new_value:
1340843312dcSSimon Glass                            desc = '%s -> %s' % (value, new_value)
1341843312dcSSimon Glass                            config_change[key] = desc
1342843312dcSSimon Glass                            all_config_change[key] = desc
13438270e3c1SSimon Glass
13448270e3c1SSimon Glass                    arch_config_plus[arch][name].update(config_plus)
13458270e3c1SSimon Glass                    arch_config_minus[arch][name].update(config_minus)
13468270e3c1SSimon Glass                    arch_config_change[arch][name].update(config_change)
13478270e3c1SSimon Glass
13488270e3c1SSimon Glass                    _AddConfig(lines, name, config_plus, config_minus,
13498270e3c1SSimon Glass                               config_change)
13508270e3c1SSimon Glass                _AddConfig(lines, 'all', all_config_plus, all_config_minus,
1351843312dcSSimon Glass                           all_config_change)
13528270e3c1SSimon Glass                summary[target] = '\n'.join(lines)
13538270e3c1SSimon Glass
13548270e3c1SSimon Glass            lines_by_target = {}
13558270e3c1SSimon Glass            for target, lines in summary.iteritems():
13568270e3c1SSimon Glass                if lines in lines_by_target:
13578270e3c1SSimon Glass                    lines_by_target[lines].append(target)
13588270e3c1SSimon Glass                else:
13598270e3c1SSimon Glass                    lines_by_target[lines] = [target]
13608270e3c1SSimon Glass
13618270e3c1SSimon Glass            for arch in arch_list:
13628270e3c1SSimon Glass                lines = []
13638270e3c1SSimon Glass                all_plus = {}
13648270e3c1SSimon Glass                all_minus = {}
13658270e3c1SSimon Glass                all_change = {}
1366b464f8e7SSimon Glass                for name in self.config_filenames:
13678270e3c1SSimon Glass                    all_plus.update(arch_config_plus[arch][name])
13688270e3c1SSimon Glass                    all_minus.update(arch_config_minus[arch][name])
13698270e3c1SSimon Glass                    all_change.update(arch_config_change[arch][name])
13708270e3c1SSimon Glass                    _AddConfig(lines, name, arch_config_plus[arch][name],
13718270e3c1SSimon Glass                               arch_config_minus[arch][name],
13728270e3c1SSimon Glass                               arch_config_change[arch][name])
13738270e3c1SSimon Glass                _AddConfig(lines, 'all', all_plus, all_minus, all_change)
13748270e3c1SSimon Glass                #arch_summary[target] = '\n'.join(lines)
13758270e3c1SSimon Glass                if lines:
13768270e3c1SSimon Glass                    Print('%s:' % arch)
13778270e3c1SSimon Glass                    _OutputConfigInfo(lines)
13788270e3c1SSimon Glass
13798270e3c1SSimon Glass            for lines, targets in lines_by_target.iteritems():
13808270e3c1SSimon Glass                if not lines:
13818270e3c1SSimon Glass                    continue
13828270e3c1SSimon Glass                Print('%s :' % ' '.join(sorted(targets)))
13838270e3c1SSimon Glass                _OutputConfigInfo(lines.split('\n'))
13848270e3c1SSimon Glass
1385843312dcSSimon Glass
1386fc3fe1c2SSimon Glass        # Save our updated information for the next call to this function
1387fc3fe1c2SSimon Glass        self._base_board_dict = board_dict
1388fc3fe1c2SSimon Glass        self._base_err_lines = err_lines
1389e30965dbSSimon Glass        self._base_warn_lines = warn_lines
1390e30965dbSSimon Glass        self._base_err_line_boards = err_line_boards
1391e30965dbSSimon Glass        self._base_warn_line_boards = warn_line_boards
1392843312dcSSimon Glass        self._base_config = config
1393*48ae4124SAlex Kiernan        self._base_environment = environment
1394fc3fe1c2SSimon Glass
1395fc3fe1c2SSimon Glass        # Get a list of boards that did not get built, if needed
1396fc3fe1c2SSimon Glass        not_built = []
1397fc3fe1c2SSimon Glass        for board in board_selected:
1398fc3fe1c2SSimon Glass            if not board in board_dict:
1399fc3fe1c2SSimon Glass                not_built.append(board)
1400fc3fe1c2SSimon Glass        if not_built:
14014653a882SSimon Glass            Print("Boards not built (%d): %s" % (len(not_built),
14024653a882SSimon Glass                  ', '.join(not_built)))
1403fc3fe1c2SSimon Glass
1404b2ea7ab2SSimon Glass    def ProduceResultSummary(self, commit_upto, commits, board_selected):
1405e30965dbSSimon Glass            (board_dict, err_lines, err_line_boards, warn_lines,
1406*48ae4124SAlex Kiernan             warn_line_boards, config, environment) = self.GetResultSummary(
1407ed966657SSimon Glass                    board_selected, commit_upto,
1408843312dcSSimon Glass                    read_func_sizes=self._show_bloat,
1409*48ae4124SAlex Kiernan                    read_config=self._show_config,
1410*48ae4124SAlex Kiernan                    read_environment=self._show_environment)
1411b2ea7ab2SSimon Glass            if commits:
1412b2ea7ab2SSimon Glass                msg = '%02d: %s' % (commit_upto + 1,
1413b2ea7ab2SSimon Glass                        commits[commit_upto].subject)
14144653a882SSimon Glass                Print(msg, colour=self.col.BLUE)
1415b2ea7ab2SSimon Glass            self.PrintResultSummary(board_selected, board_dict,
1416ed966657SSimon Glass                    err_lines if self._show_errors else [], err_line_boards,
1417e30965dbSSimon Glass                    warn_lines if self._show_errors else [], warn_line_boards,
1418*48ae4124SAlex Kiernan                    config, environment, self._show_sizes, self._show_detail,
1419*48ae4124SAlex Kiernan                    self._show_bloat, self._show_config, self._show_environment)
1420fc3fe1c2SSimon Glass
1421b2ea7ab2SSimon Glass    def ShowSummary(self, commits, board_selected):
1422fc3fe1c2SSimon Glass        """Show a build summary for U-Boot for a given board list.
1423fc3fe1c2SSimon Glass
1424fc3fe1c2SSimon Glass        Reset the result summary, then repeatedly call GetResultSummary on
1425fc3fe1c2SSimon Glass        each commit's results, then display the differences we see.
1426fc3fe1c2SSimon Glass
1427fc3fe1c2SSimon Glass        Args:
1428fc3fe1c2SSimon Glass            commit: Commit objects to summarise
1429fc3fe1c2SSimon Glass            board_selected: Dict containing boards to summarise
1430fc3fe1c2SSimon Glass        """
1431fea5858eSSimon Glass        self.commit_count = len(commits) if commits else 1
1432fc3fe1c2SSimon Glass        self.commits = commits
1433fc3fe1c2SSimon Glass        self.ResetResultSummary(board_selected)
143428370c1bSSimon Glass        self._error_lines = 0
1435fc3fe1c2SSimon Glass
1436fc3fe1c2SSimon Glass        for commit_upto in range(0, self.commit_count, self._step):
1437b2ea7ab2SSimon Glass            self.ProduceResultSummary(commit_upto, commits, board_selected)
143828370c1bSSimon Glass        if not self._error_lines:
14394653a882SSimon Glass            Print('(no errors to report)', colour=self.col.GREEN)
1440fc3fe1c2SSimon Glass
1441fc3fe1c2SSimon Glass
1442fc3fe1c2SSimon Glass    def SetupBuild(self, board_selected, commits):
1443fc3fe1c2SSimon Glass        """Set up ready to start a build.
1444fc3fe1c2SSimon Glass
1445fc3fe1c2SSimon Glass        Args:
1446fc3fe1c2SSimon Glass            board_selected: Selected boards to build
1447fc3fe1c2SSimon Glass            commits: Selected commits to build
1448fc3fe1c2SSimon Glass        """
1449fc3fe1c2SSimon Glass        # First work out how many commits we will build
1450fea5858eSSimon Glass        count = (self.commit_count + self._step - 1) / self._step
1451fc3fe1c2SSimon Glass        self.count = len(board_selected) * count
1452fc3fe1c2SSimon Glass        self.upto = self.warned = self.fail = 0
1453fc3fe1c2SSimon Glass        self._timestamps = collections.deque()
1454fc3fe1c2SSimon Glass
1455fc3fe1c2SSimon Glass    def GetThreadDir(self, thread_num):
1456fc3fe1c2SSimon Glass        """Get the directory path to the working dir for a thread.
1457fc3fe1c2SSimon Glass
1458fc3fe1c2SSimon Glass        Args:
1459fc3fe1c2SSimon Glass            thread_num: Number of thread to check.
1460fc3fe1c2SSimon Glass        """
1461fc3fe1c2SSimon Glass        return os.path.join(self._working_dir, '%02d' % thread_num)
1462fc3fe1c2SSimon Glass
1463fea5858eSSimon Glass    def _PrepareThread(self, thread_num, setup_git):
1464fc3fe1c2SSimon Glass        """Prepare the working directory for a thread.
1465fc3fe1c2SSimon Glass
1466fc3fe1c2SSimon Glass        This clones or fetches the repo into the thread's work directory.
1467fc3fe1c2SSimon Glass
1468fc3fe1c2SSimon Glass        Args:
1469fc3fe1c2SSimon Glass            thread_num: Thread number (0, 1, ...)
1470fea5858eSSimon Glass            setup_git: True to set up a git repo clone
1471fc3fe1c2SSimon Glass        """
1472fc3fe1c2SSimon Glass        thread_dir = self.GetThreadDir(thread_num)
1473190064b4SSimon Glass        builderthread.Mkdir(thread_dir)
1474fc3fe1c2SSimon Glass        git_dir = os.path.join(thread_dir, '.git')
1475fc3fe1c2SSimon Glass
1476fc3fe1c2SSimon Glass        # Clone the repo if it doesn't already exist
1477fc3fe1c2SSimon Glass        # TODO(sjg@chromium): Perhaps some git hackery to symlink instead, so
1478fc3fe1c2SSimon Glass        # we have a private index but uses the origin repo's contents?
1479fea5858eSSimon Glass        if setup_git and self.git_dir:
1480fc3fe1c2SSimon Glass            src_dir = os.path.abspath(self.git_dir)
1481fc3fe1c2SSimon Glass            if os.path.exists(git_dir):
1482fc3fe1c2SSimon Glass                gitutil.Fetch(git_dir, thread_dir)
1483fc3fe1c2SSimon Glass            else:
148421f0eb33SSimon Glass                Print('\rCloning repo for thread %d' % thread_num,
148521f0eb33SSimon Glass                      newline=False)
1486fc3fe1c2SSimon Glass                gitutil.Clone(src_dir, thread_dir)
148721f0eb33SSimon Glass                Print('\r%s\r' % (' ' * 30), newline=False)
1488fc3fe1c2SSimon Glass
1489fea5858eSSimon Glass    def _PrepareWorkingSpace(self, max_threads, setup_git):
1490fc3fe1c2SSimon Glass        """Prepare the working directory for use.
1491fc3fe1c2SSimon Glass
1492fc3fe1c2SSimon Glass        Set up the git repo for each thread.
1493fc3fe1c2SSimon Glass
1494fc3fe1c2SSimon Glass        Args:
1495fc3fe1c2SSimon Glass            max_threads: Maximum number of threads we expect to need.
1496fea5858eSSimon Glass            setup_git: True to set up a git repo clone
1497fc3fe1c2SSimon Glass        """
1498190064b4SSimon Glass        builderthread.Mkdir(self._working_dir)
1499fc3fe1c2SSimon Glass        for thread in range(max_threads):
1500fea5858eSSimon Glass            self._PrepareThread(thread, setup_git)
1501fc3fe1c2SSimon Glass
1502fc3fe1c2SSimon Glass    def _PrepareOutputSpace(self):
1503fc3fe1c2SSimon Glass        """Get the output directories ready to receive files.
1504fc3fe1c2SSimon Glass
1505fc3fe1c2SSimon Glass        We delete any output directories which look like ones we need to
1506fc3fe1c2SSimon Glass        create. Having left over directories is confusing when the user wants
1507fc3fe1c2SSimon Glass        to check the output manually.
1508fc3fe1c2SSimon Glass        """
15091a915675SSimon Glass        if not self.commits:
15101a915675SSimon Glass            return
1511fc3fe1c2SSimon Glass        dir_list = []
1512fc3fe1c2SSimon Glass        for commit_upto in range(self.commit_count):
1513fc3fe1c2SSimon Glass            dir_list.append(self._GetOutputDir(commit_upto))
1514fc3fe1c2SSimon Glass
1515b222abe7SSimon Glass        to_remove = []
1516fc3fe1c2SSimon Glass        for dirname in glob.glob(os.path.join(self.base_dir, '*')):
1517fc3fe1c2SSimon Glass            if dirname not in dir_list:
1518b222abe7SSimon Glass                to_remove.append(dirname)
1519b222abe7SSimon Glass        if to_remove:
1520b222abe7SSimon Glass            Print('Removing %d old build directories' % len(to_remove),
1521b222abe7SSimon Glass                  newline=False)
1522b222abe7SSimon Glass            for dirname in to_remove:
1523fc3fe1c2SSimon Glass                shutil.rmtree(dirname)
1524fc3fe1c2SSimon Glass
1525e5a0e5d8SSimon Glass    def BuildBoards(self, commits, board_selected, keep_outputs, verbose):
1526fc3fe1c2SSimon Glass        """Build all commits for a list of boards
1527fc3fe1c2SSimon Glass
1528fc3fe1c2SSimon Glass        Args:
1529fc3fe1c2SSimon Glass            commits: List of commits to be build, each a Commit object
1530fc3fe1c2SSimon Glass            boards_selected: Dict of selected boards, key is target name,
1531fc3fe1c2SSimon Glass                    value is Board object
1532fc3fe1c2SSimon Glass            keep_outputs: True to save build output files
1533e5a0e5d8SSimon Glass            verbose: Display build results as they are completed
15342c3deb97SSimon Glass        Returns:
15352c3deb97SSimon Glass            Tuple containing:
15362c3deb97SSimon Glass                - number of boards that failed to build
15372c3deb97SSimon Glass                - number of boards that issued warnings
1538fc3fe1c2SSimon Glass        """
1539fea5858eSSimon Glass        self.commit_count = len(commits) if commits else 1
1540fc3fe1c2SSimon Glass        self.commits = commits
1541e5a0e5d8SSimon Glass        self._verbose = verbose
1542fc3fe1c2SSimon Glass
1543fc3fe1c2SSimon Glass        self.ResetResultSummary(board_selected)
1544f3d015cbSThierry Reding        builderthread.Mkdir(self.base_dir, parents = True)
1545fea5858eSSimon Glass        self._PrepareWorkingSpace(min(self.num_threads, len(board_selected)),
1546fea5858eSSimon Glass                commits is not None)
1547fc3fe1c2SSimon Glass        self._PrepareOutputSpace()
1548745b395aSSimon Glass        Print('\rStarting build...', newline=False)
1549fc3fe1c2SSimon Glass        self.SetupBuild(board_selected, commits)
1550fc3fe1c2SSimon Glass        self.ProcessResult(None)
1551fc3fe1c2SSimon Glass
1552fc3fe1c2SSimon Glass        # Create jobs to build all commits for each board
1553fc3fe1c2SSimon Glass        for brd in board_selected.itervalues():
1554190064b4SSimon Glass            job = builderthread.BuilderJob()
1555fc3fe1c2SSimon Glass            job.board = brd
1556fc3fe1c2SSimon Glass            job.commits = commits
1557fc3fe1c2SSimon Glass            job.keep_outputs = keep_outputs
1558fc3fe1c2SSimon Glass            job.step = self._step
1559fc3fe1c2SSimon Glass            self.queue.put(job)
1560fc3fe1c2SSimon Glass
1561d436e381SSimon Glass        term = threading.Thread(target=self.queue.join)
1562d436e381SSimon Glass        term.setDaemon(True)
1563d436e381SSimon Glass        term.start()
1564d436e381SSimon Glass        while term.isAlive():
1565d436e381SSimon Glass            term.join(100)
1566fc3fe1c2SSimon Glass
1567fc3fe1c2SSimon Glass        # Wait until we have processed all output
1568fc3fe1c2SSimon Glass        self.out_queue.join()
15694653a882SSimon Glass        Print()
1570fc3fe1c2SSimon Glass        self.ClearLine(0)
15712c3deb97SSimon Glass        return (self.fail, self.warned)
1572