xref: /qemu/roms/edk2-build.py (revision c28a2891)
122e11539SGerd Hoffmann#!/usr/bin/python3
222e11539SGerd Hoffmann"""
322e11539SGerd Hoffmannbuild helper script for edk2, see
422e11539SGerd Hoffmannhttps://gitlab.com/kraxel/edk2-build-config
522e11539SGerd Hoffmann
622e11539SGerd Hoffmann"""
722e11539SGerd Hoffmannimport os
822e11539SGerd Hoffmannimport sys
9c28a2891SGerd Hoffmannimport time
1022e11539SGerd Hoffmannimport shutil
1122e11539SGerd Hoffmannimport argparse
1222e11539SGerd Hoffmannimport subprocess
1322e11539SGerd Hoffmannimport configparser
1422e11539SGerd Hoffmann
1522e11539SGerd Hoffmannrebase_prefix    = ""
1622e11539SGerd Hoffmannversion_override = None
1722e11539SGerd Hoffmannrelease_date     = None
1822e11539SGerd Hoffmann
1922e11539SGerd Hoffmann# pylint: disable=unused-variable
2022e11539SGerd Hoffmanndef check_rebase():
2122e11539SGerd Hoffmann    """ detect 'git rebase -x edk2-build.py master' testbuilds """
2222e11539SGerd Hoffmann    global rebase_prefix
2322e11539SGerd Hoffmann    global version_override
2422e11539SGerd Hoffmann    gitdir = '.git'
2522e11539SGerd Hoffmann
2622e11539SGerd Hoffmann    if os.path.isfile(gitdir):
2722e11539SGerd Hoffmann        with open(gitdir, 'r', encoding = 'utf-8') as f:
2822e11539SGerd Hoffmann            (unused, gitdir) = f.read().split()
2922e11539SGerd Hoffmann
3022e11539SGerd Hoffmann    if not os.path.exists(f'{gitdir}/rebase-merge/msgnum'):
3122e11539SGerd Hoffmann        return
3222e11539SGerd Hoffmann    with open(f'{gitdir}/rebase-merge/msgnum', 'r', encoding = 'utf-8') as f:
3322e11539SGerd Hoffmann        msgnum = int(f.read())
3422e11539SGerd Hoffmann    with open(f'{gitdir}/rebase-merge/end', 'r', encoding = 'utf-8') as f:
3522e11539SGerd Hoffmann        end = int(f.read())
3622e11539SGerd Hoffmann    with open(f'{gitdir}/rebase-merge/head-name', 'r', encoding = 'utf-8') as f:
3722e11539SGerd Hoffmann        head = f.read().strip().split('/')
3822e11539SGerd Hoffmann
3922e11539SGerd Hoffmann    rebase_prefix = f'[ {int(msgnum/2)} / {int(end/2)} - {head[-1]} ] '
4022e11539SGerd Hoffmann    if msgnum != end and not version_override:
4122e11539SGerd Hoffmann        # fixed version speeds up builds
4222e11539SGerd Hoffmann        version_override = "test-build-patch-series"
4322e11539SGerd Hoffmann
4422e11539SGerd Hoffmanndef get_coredir(cfg):
4522e11539SGerd Hoffmann    if cfg.has_option('global', 'core'):
4622e11539SGerd Hoffmann        return os.path.abspath(cfg['global']['core'])
4722e11539SGerd Hoffmann    return os.getcwd()
4822e11539SGerd Hoffmann
49c28a2891SGerd Hoffmanndef get_toolchain(cfg, build):
50c28a2891SGerd Hoffmann    if cfg.has_option(build, 'tool'):
51c28a2891SGerd Hoffmann        return cfg[build]['tool']
52c28a2891SGerd Hoffmann    if cfg.has_option('global', 'tool'):
53c28a2891SGerd Hoffmann        return cfg['global']['tool']
54c28a2891SGerd Hoffmann    return 'GCC5'
55c28a2891SGerd Hoffmann
56c28a2891SGerd Hoffmanndef get_version(cfg, silent = False):
5722e11539SGerd Hoffmann    coredir = get_coredir(cfg)
5822e11539SGerd Hoffmann    if version_override:
5922e11539SGerd Hoffmann        version = version_override
60c28a2891SGerd Hoffmann        if not silent:
6122e11539SGerd Hoffmann            print('')
6222e11539SGerd Hoffmann            print(f'### version [override]: {version}')
6322e11539SGerd Hoffmann        return version
6422e11539SGerd Hoffmann    if os.environ.get('RPM_PACKAGE_NAME'):
6522e11539SGerd Hoffmann        version = os.environ.get('RPM_PACKAGE_NAME')
6622e11539SGerd Hoffmann        version += '-' + os.environ.get('RPM_PACKAGE_VERSION')
6722e11539SGerd Hoffmann        version += '-' + os.environ.get('RPM_PACKAGE_RELEASE')
68c28a2891SGerd Hoffmann        if not silent:
6922e11539SGerd Hoffmann            print('')
7022e11539SGerd Hoffmann            print(f'### version [rpmbuild]: {version}')
7122e11539SGerd Hoffmann        return version
7222e11539SGerd Hoffmann    if os.path.exists(coredir + '/.git'):
7322e11539SGerd Hoffmann        cmdline = [ 'git', 'describe', '--tags', '--abbrev=8',
7422e11539SGerd Hoffmann                    '--match=edk2-stable*' ]
7522e11539SGerd Hoffmann        result = subprocess.run(cmdline, cwd = coredir,
7622e11539SGerd Hoffmann                                stdout = subprocess.PIPE,
7722e11539SGerd Hoffmann                                check = True)
7822e11539SGerd Hoffmann        version = result.stdout.decode().strip()
79c28a2891SGerd Hoffmann        if not silent:
8022e11539SGerd Hoffmann            print('')
8122e11539SGerd Hoffmann            print(f'### version [git]: {version}')
8222e11539SGerd Hoffmann        return version
8322e11539SGerd Hoffmann    return None
8422e11539SGerd Hoffmann
8522e11539SGerd Hoffmanndef pcd_string(name, value):
8622e11539SGerd Hoffmann    return f'{name}=L{value}\\0'
8722e11539SGerd Hoffmann
88c28a2891SGerd Hoffmanndef pcd_version(cfg, silent = False):
89c28a2891SGerd Hoffmann    version = get_version(cfg, silent)
9022e11539SGerd Hoffmann    if version is None:
9122e11539SGerd Hoffmann        return []
9222e11539SGerd Hoffmann    return [ '--pcd', pcd_string('PcdFirmwareVersionString', version) ]
9322e11539SGerd Hoffmann
9422e11539SGerd Hoffmanndef pcd_release_date():
9522e11539SGerd Hoffmann    if release_date is None:
9622e11539SGerd Hoffmann        return []
9722e11539SGerd Hoffmann    return [ '--pcd', pcd_string('PcdFirmwareReleaseDateString', release_date) ]
9822e11539SGerd Hoffmann
99c28a2891SGerd Hoffmanndef build_message(line, line2 = None, silent = False):
10022e11539SGerd Hoffmann    if os.environ.get('TERM') in [ 'xterm', 'xterm-256color' ]:
10122e11539SGerd Hoffmann        # setxterm  title
10222e11539SGerd Hoffmann        start  = '\x1b]2;'
10322e11539SGerd Hoffmann        end    = '\x07'
10422e11539SGerd Hoffmann        print(f'{start}{rebase_prefix}{line}{end}', end = '')
10522e11539SGerd Hoffmann
106c28a2891SGerd Hoffmann    if silent:
107c28a2891SGerd Hoffmann        print(f'### {rebase_prefix}{line}', flush = True)
108c28a2891SGerd Hoffmann    else:
10922e11539SGerd Hoffmann        print('')
11022e11539SGerd Hoffmann        print('###')
11122e11539SGerd Hoffmann        print(f'### {rebase_prefix}{line}')
11222e11539SGerd Hoffmann        if line2:
11322e11539SGerd Hoffmann            print(f'### {line2}')
11422e11539SGerd Hoffmann        print('###', flush = True)
11522e11539SGerd Hoffmann
116c28a2891SGerd Hoffmanndef build_run(cmdline, name, section, silent = False, nologs = False):
11722e11539SGerd Hoffmann    if silent:
118c28a2891SGerd Hoffmann        logfile = f'{section}.log'
119c28a2891SGerd Hoffmann        if nologs:
120c28a2891SGerd Hoffmann            print(f'### building in silent mode [no log] ...', flush = True)
121c28a2891SGerd Hoffmann        else:
122c28a2891SGerd Hoffmann            print(f'### building in silent mode [{logfile}] ...', flush = True)
123c28a2891SGerd Hoffmann        start = time.time()
12422e11539SGerd Hoffmann        result = subprocess.run(cmdline, check = False,
12522e11539SGerd Hoffmann                                stdout = subprocess.PIPE,
12622e11539SGerd Hoffmann                                stderr = subprocess.STDOUT)
127c28a2891SGerd Hoffmann        if not nologs:
12822e11539SGerd Hoffmann            with open(logfile, 'wb') as f:
12922e11539SGerd Hoffmann                f.write(result.stdout)
13022e11539SGerd Hoffmann
13122e11539SGerd Hoffmann        if result.returncode:
13222e11539SGerd Hoffmann            print('### BUILD FAILURE')
133c28a2891SGerd Hoffmann            print('### cmdline')
134c28a2891SGerd Hoffmann            print(cmdline)
13522e11539SGerd Hoffmann            print('### output')
13622e11539SGerd Hoffmann            print(result.stdout.decode())
13722e11539SGerd Hoffmann            print(f'### exit code: {result.returncode}')
13822e11539SGerd Hoffmann        else:
139c28a2891SGerd Hoffmann            secs = int(time.time() - start)
140c28a2891SGerd Hoffmann            print(f'### OK ({int(secs/60)}:{secs%60:02d})')
14122e11539SGerd Hoffmann    else:
142c28a2891SGerd Hoffmann        print(cmdline, flush = True)
14322e11539SGerd Hoffmann        result = subprocess.run(cmdline, check = False)
14422e11539SGerd Hoffmann    if result.returncode:
14522e11539SGerd Hoffmann        print(f'ERROR: {cmdline[0]} exited with {result.returncode}'
14622e11539SGerd Hoffmann              f' while building {name}')
14722e11539SGerd Hoffmann        sys.exit(result.returncode)
14822e11539SGerd Hoffmann
149c28a2891SGerd Hoffmanndef build_copy(plat, tgt, toolchain, dstdir, copy):
150c28a2891SGerd Hoffmann    srcdir = f'Build/{plat}/{tgt}_{toolchain}'
15122e11539SGerd Hoffmann    names = copy.split()
15222e11539SGerd Hoffmann    srcfile = names[0]
15322e11539SGerd Hoffmann    if len(names) > 1:
15422e11539SGerd Hoffmann        dstfile = names[1]
15522e11539SGerd Hoffmann    else:
15622e11539SGerd Hoffmann        dstfile = os.path.basename(srcfile)
15722e11539SGerd Hoffmann    print(f'# copy: {srcdir} / {srcfile}  =>  {dstdir} / {dstfile}')
15822e11539SGerd Hoffmann
15922e11539SGerd Hoffmann    src = srcdir + '/' + srcfile
16022e11539SGerd Hoffmann    dst = dstdir + '/' + dstfile
16122e11539SGerd Hoffmann    os.makedirs(os.path.dirname(dst), exist_ok = True)
16222e11539SGerd Hoffmann    shutil.copy(src, dst)
16322e11539SGerd Hoffmann
16422e11539SGerd Hoffmanndef pad_file(dstdir, pad):
16522e11539SGerd Hoffmann    args = pad.split()
16622e11539SGerd Hoffmann    if len(args) < 2:
16722e11539SGerd Hoffmann        raise RuntimeError(f'missing arg for pad ({args})')
16822e11539SGerd Hoffmann    name = args[0]
16922e11539SGerd Hoffmann    size = args[1]
17022e11539SGerd Hoffmann    cmdline = [
17122e11539SGerd Hoffmann        'truncate',
17222e11539SGerd Hoffmann        '--size', size,
17322e11539SGerd Hoffmann        dstdir + '/' + name,
17422e11539SGerd Hoffmann    ]
17522e11539SGerd Hoffmann    print(f'# padding: {dstdir} / {name}  =>  {size}')
17622e11539SGerd Hoffmann    subprocess.run(cmdline, check = True)
17722e11539SGerd Hoffmann
17822e11539SGerd Hoffmann# pylint: disable=too-many-branches
179c28a2891SGerd Hoffmanndef build_one(cfg, build, jobs = None, silent = False, nologs = False):
180c28a2891SGerd Hoffmann    b = cfg[build]
18122e11539SGerd Hoffmann
182c28a2891SGerd Hoffmann    cmdline  = [ 'build' ]
183c28a2891SGerd Hoffmann    cmdline += [ '-t', get_toolchain(cfg, build) ]
184c28a2891SGerd Hoffmann    cmdline += [ '-p', b['conf'] ]
185c28a2891SGerd Hoffmann
186c28a2891SGerd Hoffmann    if (b['conf'].startswith('OvmfPkg/') or
187c28a2891SGerd Hoffmann        b['conf'].startswith('ArmVirtPkg/')):
188c28a2891SGerd Hoffmann        cmdline += pcd_version(cfg, silent)
18922e11539SGerd Hoffmann        cmdline += pcd_release_date()
19022e11539SGerd Hoffmann
19122e11539SGerd Hoffmann    if jobs:
19222e11539SGerd Hoffmann        cmdline += [ '-n', jobs ]
193c28a2891SGerd Hoffmann    for arch in b['arch'].split():
19422e11539SGerd Hoffmann        cmdline += [ '-a', arch ]
195c28a2891SGerd Hoffmann    if 'opts' in b:
196c28a2891SGerd Hoffmann        for name in b['opts'].split():
19722e11539SGerd Hoffmann            section = 'opts.' + name
19822e11539SGerd Hoffmann            for opt in cfg[section]:
19922e11539SGerd Hoffmann                cmdline += [ '-D', opt + '=' + cfg[section][opt] ]
200c28a2891SGerd Hoffmann    if 'pcds' in b:
201c28a2891SGerd Hoffmann        for name in b['pcds'].split():
20222e11539SGerd Hoffmann            section = 'pcds.' + name
20322e11539SGerd Hoffmann            for pcd in cfg[section]:
20422e11539SGerd Hoffmann                cmdline += [ '--pcd', pcd + '=' + cfg[section][pcd] ]
205c28a2891SGerd Hoffmann    if 'tgts' in b:
206c28a2891SGerd Hoffmann        tgts = b['tgts'].split()
20722e11539SGerd Hoffmann    else:
20822e11539SGerd Hoffmann        tgts = [ 'DEBUG' ]
20922e11539SGerd Hoffmann    for tgt in tgts:
21022e11539SGerd Hoffmann        desc = None
211c28a2891SGerd Hoffmann        if 'desc' in b:
212c28a2891SGerd Hoffmann            desc = b['desc']
213c28a2891SGerd Hoffmann        build_message(f'building: {b["conf"]} ({b["arch"]}, {tgt})',
214c28a2891SGerd Hoffmann                      f'description: {desc}',
215c28a2891SGerd Hoffmann                      silent = silent)
21622e11539SGerd Hoffmann        build_run(cmdline + [ '-b', tgt ],
217c28a2891SGerd Hoffmann                  b['conf'],
21822e11539SGerd Hoffmann                  build + '.' + tgt,
219c28a2891SGerd Hoffmann                  silent,
220c28a2891SGerd Hoffmann                  nologs)
22122e11539SGerd Hoffmann
222c28a2891SGerd Hoffmann        if 'plat' in b:
22322e11539SGerd Hoffmann            # copy files
224c28a2891SGerd Hoffmann            for cpy in b:
22522e11539SGerd Hoffmann                if not cpy.startswith('cpy'):
22622e11539SGerd Hoffmann                    continue
227c28a2891SGerd Hoffmann                build_copy(b['plat'], tgt,
228c28a2891SGerd Hoffmann                           get_toolchain(cfg, build),
229c28a2891SGerd Hoffmann                           b['dest'], b[cpy])
23022e11539SGerd Hoffmann            # pad builds
231c28a2891SGerd Hoffmann            for pad in b:
23222e11539SGerd Hoffmann                if not pad.startswith('pad'):
23322e11539SGerd Hoffmann                    continue
234c28a2891SGerd Hoffmann                pad_file(b['dest'], b[pad])
23522e11539SGerd Hoffmann
236c28a2891SGerd Hoffmanndef build_basetools(silent = False, nologs = False):
237c28a2891SGerd Hoffmann    build_message('building: BaseTools', silent = silent)
23822e11539SGerd Hoffmann    basedir = os.environ['EDK_TOOLS_PATH']
23922e11539SGerd Hoffmann    cmdline = [ 'make', '-C', basedir ]
240c28a2891SGerd Hoffmann    build_run(cmdline, 'BaseTools', 'build.basetools', silent, nologs)
24122e11539SGerd Hoffmann
24222e11539SGerd Hoffmanndef binary_exists(name):
24322e11539SGerd Hoffmann    for pdir in os.environ['PATH'].split(':'):
24422e11539SGerd Hoffmann        if os.path.exists(pdir + '/' + name):
24522e11539SGerd Hoffmann            return True
24622e11539SGerd Hoffmann    return False
24722e11539SGerd Hoffmann
248c28a2891SGerd Hoffmanndef prepare_env(cfg, silent = False):
24922e11539SGerd Hoffmann    """ mimic Conf/BuildEnv.sh """
25022e11539SGerd Hoffmann    workspace = os.getcwd()
25122e11539SGerd Hoffmann    packages = [ workspace, ]
25222e11539SGerd Hoffmann    path = os.environ['PATH'].split(':')
25322e11539SGerd Hoffmann    dirs = [
25422e11539SGerd Hoffmann        'BaseTools/Bin/Linux-x86_64',
25522e11539SGerd Hoffmann        'BaseTools/BinWrappers/PosixLike'
25622e11539SGerd Hoffmann    ]
25722e11539SGerd Hoffmann
25822e11539SGerd Hoffmann    if cfg.has_option('global', 'pkgs'):
25922e11539SGerd Hoffmann        for pkgdir in cfg['global']['pkgs'].split():
26022e11539SGerd Hoffmann            packages.append(os.path.abspath(pkgdir))
26122e11539SGerd Hoffmann    coredir = get_coredir(cfg)
26222e11539SGerd Hoffmann    if coredir != workspace:
26322e11539SGerd Hoffmann        packages.append(coredir)
26422e11539SGerd Hoffmann
26522e11539SGerd Hoffmann    # add basetools to path
26622e11539SGerd Hoffmann    for pdir in dirs:
26722e11539SGerd Hoffmann        p = coredir + '/' + pdir
26822e11539SGerd Hoffmann        if not os.path.exists(p):
26922e11539SGerd Hoffmann            continue
27022e11539SGerd Hoffmann        if p in path:
27122e11539SGerd Hoffmann            continue
27222e11539SGerd Hoffmann        path.insert(0, p)
27322e11539SGerd Hoffmann
27422e11539SGerd Hoffmann    # run edksetup if needed
27522e11539SGerd Hoffmann    toolsdef = coredir + '/Conf/tools_def.txt'
27622e11539SGerd Hoffmann    if not os.path.exists(toolsdef):
27722e11539SGerd Hoffmann        os.makedirs(os.path.dirname(toolsdef), exist_ok = True)
278c28a2891SGerd Hoffmann        build_message('running BaseTools/BuildEnv', silent = silent)
27922e11539SGerd Hoffmann        cmdline = [ 'bash', 'BaseTools/BuildEnv' ]
28022e11539SGerd Hoffmann        subprocess.run(cmdline, cwd = coredir, check = True)
28122e11539SGerd Hoffmann
28222e11539SGerd Hoffmann    # set variables
28322e11539SGerd Hoffmann    os.environ['PATH'] = ':'.join(path)
28422e11539SGerd Hoffmann    os.environ['PACKAGES_PATH'] = ':'.join(packages)
28522e11539SGerd Hoffmann    os.environ['WORKSPACE'] = workspace
28622e11539SGerd Hoffmann    os.environ['EDK_TOOLS_PATH'] = coredir + '/BaseTools'
28722e11539SGerd Hoffmann    os.environ['CONF_PATH'] = coredir + '/Conf'
28822e11539SGerd Hoffmann    os.environ['PYTHON_COMMAND'] = '/usr/bin/python3'
28922e11539SGerd Hoffmann    os.environ['PYTHONHASHSEED'] = '1'
29022e11539SGerd Hoffmann
29122e11539SGerd Hoffmann    # for cross builds
292c28a2891SGerd Hoffmann    if binary_exists('arm-linux-gnueabi-gcc'):
293c28a2891SGerd Hoffmann        # ubuntu
294c28a2891SGerd Hoffmann        os.environ['GCC5_ARM_PREFIX'] = 'arm-linux-gnueabi-'
295c28a2891SGerd Hoffmann        os.environ['GCC_ARM_PREFIX'] = 'arm-linux-gnueabi-'
296c28a2891SGerd Hoffmann    elif binary_exists('arm-linux-gnu-gcc'):
297c28a2891SGerd Hoffmann        # fedora
29822e11539SGerd Hoffmann        os.environ['GCC5_ARM_PREFIX'] = 'arm-linux-gnu-'
299c28a2891SGerd Hoffmann        os.environ['GCC_ARM_PREFIX'] = 'arm-linux-gnu-'
30022e11539SGerd Hoffmann    if binary_exists('loongarch64-linux-gnu-gcc'):
30122e11539SGerd Hoffmann        os.environ['GCC5_LOONGARCH64_PREFIX'] = 'loongarch64-linux-gnu-'
302c28a2891SGerd Hoffmann        os.environ['GCC_LOONGARCH64_PREFIX'] = 'loongarch64-linux-gnu-'
30322e11539SGerd Hoffmann
30422e11539SGerd Hoffmann    hostarch = os.uname().machine
30522e11539SGerd Hoffmann    if binary_exists('aarch64-linux-gnu-gcc') and hostarch != 'aarch64':
30622e11539SGerd Hoffmann        os.environ['GCC5_AARCH64_PREFIX'] = 'aarch64-linux-gnu-'
307c28a2891SGerd Hoffmann        os.environ['GCC_AARCH64_PREFIX'] = 'aarch64-linux-gnu-'
30822e11539SGerd Hoffmann    if binary_exists('riscv64-linux-gnu-gcc') and hostarch != 'riscv64':
30922e11539SGerd Hoffmann        os.environ['GCC5_RISCV64_PREFIX'] = 'riscv64-linux-gnu-'
310c28a2891SGerd Hoffmann        os.environ['GCC_RISCV64_PREFIX'] = 'riscv64-linux-gnu-'
31122e11539SGerd Hoffmann    if binary_exists('x86_64-linux-gnu-gcc') and hostarch != 'x86_64':
31222e11539SGerd Hoffmann        os.environ['GCC5_IA32_PREFIX'] = 'x86_64-linux-gnu-'
31322e11539SGerd Hoffmann        os.environ['GCC5_X64_PREFIX'] = 'x86_64-linux-gnu-'
31422e11539SGerd Hoffmann        os.environ['GCC5_BIN'] = 'x86_64-linux-gnu-'
315c28a2891SGerd Hoffmann        os.environ['GCC_IA32_PREFIX'] = 'x86_64-linux-gnu-'
316c28a2891SGerd Hoffmann        os.environ['GCC_X64_PREFIX'] = 'x86_64-linux-gnu-'
317c28a2891SGerd Hoffmann        os.environ['GCC_BIN'] = 'x86_64-linux-gnu-'
31822e11539SGerd Hoffmann
31922e11539SGerd Hoffmanndef build_list(cfg):
32022e11539SGerd Hoffmann    for build in cfg.sections():
32122e11539SGerd Hoffmann        if not build.startswith('build.'):
32222e11539SGerd Hoffmann            continue
32322e11539SGerd Hoffmann        name = build.lstrip('build.')
32422e11539SGerd Hoffmann        desc = 'no description'
32522e11539SGerd Hoffmann        if 'desc' in cfg[build]:
32622e11539SGerd Hoffmann            desc = cfg[build]['desc']
32722e11539SGerd Hoffmann        print(f'# {name:20s} - {desc}')
32822e11539SGerd Hoffmann
32922e11539SGerd Hoffmanndef main():
33022e11539SGerd Hoffmann    parser = argparse.ArgumentParser(prog = 'edk2-build',
33122e11539SGerd Hoffmann                                     description = 'edk2 build helper script')
33222e11539SGerd Hoffmann    parser.add_argument('-c', '--config', dest = 'configfile',
33322e11539SGerd Hoffmann                        type = str, default = '.edk2.builds', metavar = 'FILE',
33422e11539SGerd Hoffmann                        help = 'read configuration from FILE (default: .edk2.builds)')
33522e11539SGerd Hoffmann    parser.add_argument('-C', '--directory', dest = 'directory', type = str,
33622e11539SGerd Hoffmann                        help = 'change to DIR before building', metavar = 'DIR')
33722e11539SGerd Hoffmann    parser.add_argument('-j', '--jobs', dest = 'jobs', type = str,
33822e11539SGerd Hoffmann                        help = 'allow up to JOBS parallel build jobs',
33922e11539SGerd Hoffmann                        metavar = 'JOBS')
340c28a2891SGerd Hoffmann    parser.add_argument('-m', '--match', dest = 'match',
341c28a2891SGerd Hoffmann                        type = str, action = 'append',
34222e11539SGerd Hoffmann                        help = 'only run builds matching INCLUDE (substring)',
34322e11539SGerd Hoffmann                        metavar = 'INCLUDE')
344c28a2891SGerd Hoffmann    parser.add_argument('-x', '--exclude', dest = 'exclude',
345c28a2891SGerd Hoffmann                        type = str, action = 'append',
34622e11539SGerd Hoffmann                        help = 'skip builds matching EXCLUDE (substring)',
34722e11539SGerd Hoffmann                        metavar = 'EXCLUDE')
34822e11539SGerd Hoffmann    parser.add_argument('-l', '--list', dest = 'list',
34922e11539SGerd Hoffmann                        action = 'store_true', default = False,
35022e11539SGerd Hoffmann                        help = 'list build configs available')
35122e11539SGerd Hoffmann    parser.add_argument('--silent', dest = 'silent',
35222e11539SGerd Hoffmann                        action = 'store_true', default = False,
35322e11539SGerd Hoffmann                        help = 'write build output to logfiles, '
35422e11539SGerd Hoffmann                        'write to console only on errors')
355c28a2891SGerd Hoffmann    parser.add_argument('--no-logs', dest = 'nologs',
356c28a2891SGerd Hoffmann                        action = 'store_true', default = False,
357c28a2891SGerd Hoffmann                        help = 'do not write build log files (with --silent)')
35822e11539SGerd Hoffmann    parser.add_argument('--core', dest = 'core', type = str, metavar = 'DIR',
35922e11539SGerd Hoffmann                        help = 'location of the core edk2 repository '
36022e11539SGerd Hoffmann                        '(i.e. where BuildTools are located)')
36122e11539SGerd Hoffmann    parser.add_argument('--pkg', '--package', dest = 'pkgs',
36222e11539SGerd Hoffmann                        type = str, action = 'append', metavar = 'DIR',
36322e11539SGerd Hoffmann                        help = 'location(s) of additional packages '
36422e11539SGerd Hoffmann                        '(can be specified multiple times)')
365c28a2891SGerd Hoffmann    parser.add_argument('-t', '--toolchain', dest = 'toolchain',
366c28a2891SGerd Hoffmann                        type = str, metavar = 'NAME',
367c28a2891SGerd Hoffmann                        help = 'tool chain to be used to build edk2')
36822e11539SGerd Hoffmann    parser.add_argument('--version-override', dest = 'version_override',
36922e11539SGerd Hoffmann                        type = str, metavar = 'VERSION',
37022e11539SGerd Hoffmann                        help = 'set firmware build version')
37122e11539SGerd Hoffmann    parser.add_argument('--release-date', dest = 'release_date',
37222e11539SGerd Hoffmann                        type = str, metavar = 'DATE',
37322e11539SGerd Hoffmann                        help = 'set firmware build release date (in MM/DD/YYYY format)')
37422e11539SGerd Hoffmann    options = parser.parse_args()
37522e11539SGerd Hoffmann
37622e11539SGerd Hoffmann    if options.directory:
37722e11539SGerd Hoffmann        os.chdir(options.directory)
37822e11539SGerd Hoffmann
37922e11539SGerd Hoffmann    if not os.path.exists(options.configfile):
380c28a2891SGerd Hoffmann        print(f'config file "{options.configfile}" not found')
38122e11539SGerd Hoffmann        return 1
38222e11539SGerd Hoffmann
38322e11539SGerd Hoffmann    cfg = configparser.ConfigParser()
38422e11539SGerd Hoffmann    cfg.optionxform = str
38522e11539SGerd Hoffmann    cfg.read(options.configfile)
38622e11539SGerd Hoffmann
38722e11539SGerd Hoffmann    if options.list:
38822e11539SGerd Hoffmann        build_list(cfg)
389c28a2891SGerd Hoffmann        return 0
39022e11539SGerd Hoffmann
39122e11539SGerd Hoffmann    if not cfg.has_section('global'):
39222e11539SGerd Hoffmann        cfg.add_section('global')
39322e11539SGerd Hoffmann    if options.core:
39422e11539SGerd Hoffmann        cfg.set('global', 'core', options.core)
39522e11539SGerd Hoffmann    if options.pkgs:
39622e11539SGerd Hoffmann        cfg.set('global', 'pkgs', ' '.join(options.pkgs))
397c28a2891SGerd Hoffmann    if options.toolchain:
398c28a2891SGerd Hoffmann        cfg.set('global', 'tool', options.toolchain)
39922e11539SGerd Hoffmann
40022e11539SGerd Hoffmann    global version_override
40122e11539SGerd Hoffmann    global release_date
40222e11539SGerd Hoffmann    check_rebase()
40322e11539SGerd Hoffmann    if options.version_override:
40422e11539SGerd Hoffmann        version_override = options.version_override
40522e11539SGerd Hoffmann    if options.release_date:
40622e11539SGerd Hoffmann        release_date = options.release_date
40722e11539SGerd Hoffmann
408c28a2891SGerd Hoffmann    prepare_env(cfg, options.silent)
409c28a2891SGerd Hoffmann    build_basetools(options.silent, options.nologs)
41022e11539SGerd Hoffmann    for build in cfg.sections():
41122e11539SGerd Hoffmann        if not build.startswith('build.'):
41222e11539SGerd Hoffmann            continue
413c28a2891SGerd Hoffmann        if options.match:
414c28a2891SGerd Hoffmann            matching = False
415c28a2891SGerd Hoffmann            for item in options.match:
416c28a2891SGerd Hoffmann                if item in build:
417c28a2891SGerd Hoffmann                    matching = True
418c28a2891SGerd Hoffmann            if not matching:
419c28a2891SGerd Hoffmann                print(f'# skipping "{build}" (not matching "{"|".join(options.match)}")')
42022e11539SGerd Hoffmann                continue
421c28a2891SGerd Hoffmann        if options.exclude:
422c28a2891SGerd Hoffmann            exclude = False
423c28a2891SGerd Hoffmann            for item in options.exclude:
424c28a2891SGerd Hoffmann                if item in build:
425c28a2891SGerd Hoffmann                    print(f'# skipping "{build}" (matching "{item}")')
426c28a2891SGerd Hoffmann                    exclude = True
427c28a2891SGerd Hoffmann            if exclude:
42822e11539SGerd Hoffmann                continue
429c28a2891SGerd Hoffmann        build_one(cfg, build, options.jobs, options.silent, options.nologs)
43022e11539SGerd Hoffmann
43122e11539SGerd Hoffmann    return 0
43222e11539SGerd Hoffmann
43322e11539SGerd Hoffmannif __name__ == '__main__':
43422e11539SGerd Hoffmann    sys.exit(main())
435