render / rpms / edk2

Forked from rpms/edk2 3 months ago
Clone
795857
#!/usr/bin/python3
795857
import os
795857
import sys
795857
import glob
795857
import shutil
795857
import optparse
795857
import subprocess
795857
import configparser
795857
795857
rebase_prefix    = ""
795857
version_override = None
795857
release_date     = None
795857
795857
def check_rebase():
795857
    """ detect 'git rebase -x edk2-build.py master' testbuilds """
795857
    global rebase_prefix
795857
    global version_override
795857
795857
    if not os.path.exists('.git/rebase-merge/msgnum'):
795857
        return ""
795857
    with open('.git/rebase-merge/msgnum', 'r') as f:
795857
        msgnum = int(f.read())
795857
    with open('.git/rebase-merge/end', 'r') as f:
795857
        end = int(f.read())
795857
    with open('.git/rebase-merge/head-name', 'r') as f:
795857
        head = f.read().strip().split('/')
795857
795857
    rebase_prefix = f'[ {int(msgnum/2)} / {int(end/2)} - {head[-1]} ] '
795857
    if msgnum != end and not version_override:
795857
        # fixed version speeds up builds
795857
        version_override = "test-build-patch-series"
795857
795857
def get_coredir(cfg):
795857
    if cfg.has_option('global', 'core'):
795857
        return os.path.abspath(cfg['global']['core'])
795857
    else:
795857
        return os.getcwd()
795857
795857
def get_version(cfg):
795857
    coredir = get_coredir(cfg)
795857
    if version_override:
795857
        version = version_override
795857
        print('')
795857
        print(f'### version [override]: {version}')
795857
        return version
795857
    if os.environ.get('RPM_PACKAGE_NAME'):
795857
        version = os.environ.get('RPM_PACKAGE_NAME');
795857
        version += '-' + os.environ.get('RPM_PACKAGE_VERSION');
795857
        version += '-' + os.environ.get('RPM_PACKAGE_RELEASE');
795857
        print('')
795857
        print(f'### version [rpmbuild]: {version}')
795857
        return version
795857
    if os.path.exists(coredir + '/.git'):
795857
        cmdline = [ 'git', 'describe', '--tags', '--abbrev=8', '--match=edk2-stable*' ]
795857
        result = subprocess.run(cmdline, stdout = subprocess.PIPE, cwd = coredir)
795857
        version = result.stdout.decode().strip()
795857
        print('')
795857
        print(f'### version [git]: {version}')
795857
        return version
795857
    return None
795857
795857
def pcd_string(name, value):
795857
    return f'{name}=L{value}\\0'
795857
795857
def pcd_version(cfg):
795857
    version = get_version(cfg)
795857
    if version is None:
795857
        return []
795857
    return [ '--pcd', pcd_string('PcdFirmwareVersionString', version) ]
795857
795857
def pcd_release_date(cfg):
795857
    if release_date is None:
795857
        return []
795857
    return [ '--pcd', pcd_string('PcdFirmwareReleaseDateString', release_date) ]
795857
795857
def build_message(line, line2 = None):
795857
    if os.environ.get('TERM') in [ 'xterm', 'xterm-256color' ]:
795857
        # setxterm  title
795857
        start  = '\x1b]2;'
795857
        end    = '\x07'
795857
        print(f'{start}{rebase_prefix}{line}{end}', end = '')
795857
795857
    print('')
795857
    print('###')
795857
    print(f'### {rebase_prefix}{line}')
795857
    if line2:
795857
        print(f'### {line2}')
795857
    print('###')
795857
795857
def build_run(cmdline, name, section, silent = False):
795857
    print(cmdline)
795857
    if silent:
795857
        print('### building in silent mode ...', flush = True)
795857
        result = subprocess.run(cmdline,
795857
                                stdout = subprocess.PIPE,
795857
                                stderr = subprocess.STDOUT)
795857
795857
        logfile = f'{section}.log'
795857
        print(f'### writing log to {logfile} ...')
795857
        with open(logfile, 'wb') as f:
795857
            f.write(result.stdout)
795857
795857
        if result.returncode:
795857
            print('### BUILD FAILURE')
795857
            print('### output')
795857
            print(result.stdout.decode())
795857
            print(f'### exit code: {result.returncode}')
795857
        else:
795857
            print('### OK')
795857
    else:
795857
        result = subprocess.run(cmdline)
795857
    if result.returncode:
795857
        print(f'ERROR: {cmdline[0]} exited with {result.returncode} while building {name}')
795857
        sys.exit(result.returncode)
795857
795857
def build_copy(plat, tgt, dstdir, copy):
795857
    srcdir = f'Build/{plat}/{tgt}_GCC5'
795857
    names = copy.split()
795857
    srcfile = names[0]
795857
    if len(names) > 1:
795857
        dstfile = names[1]
795857
    else:
795857
        dstfile = os.path.basename(srcfile)
795857
    print(f'# copy: {srcdir} / {srcfile}  =>  {dstdir} / {dstfile}')
795857
795857
    src = srcdir + '/' + srcfile
795857
    dst = dstdir + '/' + dstfile
795857
    os.makedirs(os.path.dirname(dst), exist_ok = True)
795857
    shutil.copy(src, dst)
795857
795857
def pad_file(dstdir, pad):
795857
    args = pad.split()
795857
    if len(args) < 2:
795857
        raise RuntimeError(f'missing arg for pad ({args})')
795857
    name = args[0]
795857
    size = args[1]
795857
    cmdline = [
795857
        'truncate',
795857
        '--size', size,
795857
        dstdir + '/' + name,
795857
    ]
795857
    print(f'# padding: {dstdir} / {name}  =>  {size}')
795857
    subprocess.run(cmdline)
795857
795857
def build_one(cfg, build, jobs = None, silent = False):
795857
    cmdline  = [ 'build' ]
795857
    cmdline += [ '-t', 'GCC5' ]
795857
    cmdline += [ '-p', cfg[build]['conf'] ]
795857
795857
    if (cfg[build]['conf'].startswith('OvmfPkg/') or
795857
        cfg[build]['conf'].startswith('ArmVirtPkg/')):
795857
        cmdline += pcd_version(cfg)
795857
        cmdline += pcd_release_date(cfg)
795857
795857
    if jobs:
795857
        cmdline += [ '-n', jobs ]
795857
    for arch in cfg[build]['arch'].split():
795857
        cmdline += [ '-a', arch ]
795857
    if 'opts' in cfg[build]:
795857
        for name in cfg[build]['opts'].split():
795857
            section = 'opts.' + name
795857
            for opt in cfg[section]:
795857
                cmdline += [ '-D', opt + '=' + cfg[section][opt] ]
795857
    if 'pcds' in cfg[build]:
795857
        for name in cfg[build]['pcds'].split():
795857
            section = 'pcds.' + name
795857
            for pcd in cfg[section]:
795857
                cmdline += [ '--pcd', pcd + '=' + cfg[section][pcd] ]
795857
    if 'tgts' in cfg[build]:
795857
        tgts = cfg[build]['tgts'].split()
795857
    else:
795857
        tgts = [ 'DEBUG' ]
795857
    for tgt in tgts:
795857
        desc = None
795857
        if 'desc' in cfg[build]:
795857
            desc = cfg[build]['desc']
795857
        build_message(f'building: {cfg[build]["conf"]} ({cfg[build]["arch"]}, {tgt})',
795857
                      f'description: {desc}')
795857
        build_run(cmdline + [ '-b', tgt ],
795857
                  cfg[build]['conf'],
795857
                  build + '.' + tgt,
795857
                  silent)
795857
795857
        if 'plat' in cfg[build]:
795857
            # copy files
795857
            for cpy in cfg[build]:
795857
                if not cpy.startswith('cpy'):
795857
                    continue
795857
                build_copy(cfg[build]['plat'],
795857
                           tgt,
795857
                           cfg[build]['dest'],
795857
                           cfg[build][cpy])
795857
            # pad builds
795857
            for pad in cfg[build]:
795857
                if not pad.startswith('pad'):
795857
                    continue
795857
                pad_file(cfg[build]['dest'],
795857
                         cfg[build][pad])
795857
795857
def build_basetools(silent = False):
795857
    build_message(f'building: BaseTools')
795857
    basedir = os.environ['EDK_TOOLS_PATH']
795857
    cmdline = [ 'make', '-C', basedir ]
795857
    build_run(cmdline, 'BaseTools', 'build.basetools', silent)
795857
795857
def binary_exists(name):
795857
    for dir in os.environ['PATH'].split(':'):
795857
        if os.path.exists(dir + '/' + name):
795857
            return True
795857
    return False
795857
795857
def prepare_env(cfg):
795857
    """ mimic Conf/BuildEnv.sh """
795857
    workspace = os.getcwd()
795857
    packages = [ workspace, ]
795857
    path = os.environ['PATH'].split(':')
795857
    dirs = [
795857
        'BaseTools/Bin/Linux-x86_64',
795857
        'BaseTools/BinWrappers/PosixLike'
795857
    ]
795857
795857
    if cfg.has_option('global', 'pkgs'):
795857
        for pkgdir in cfg['global']['pkgs'].split():
795857
            packages.append(os.path.abspath(pkgdir))
795857
    coredir = get_coredir(cfg)
795857
    if coredir != workspace:
795857
        packages.append(coredir)
795857
795857
    # add basetools to path
795857
    for dir in dirs:
795857
        p = coredir + '/' + dir
795857
        if not os.path.exists(p):
795857
            continue
795857
        if p in path:
795857
            continue
795857
        path.insert(0, p)
795857
795857
    # run edksetup if needed
795857
    toolsdef = coredir + '/Conf/tools_def.txt';
795857
    if not os.path.exists(toolsdef):
795857
        os.makedirs(os.path.dirname(toolsdef), exist_ok = True)
795857
        build_message('running BaseTools/BuildEnv')
795857
        cmdline = [ 'sh', 'BaseTools/BuildEnv' ]
795857
        subprocess.run(cmdline, cwd = coredir)
795857
795857
    # set variables
795857
    os.environ['PATH'] = ':'.join(path)
795857
    os.environ['PACKAGES_PATH'] = ':'.join(packages)
795857
    os.environ['WORKSPACE'] = workspace
795857
    os.environ['EDK_TOOLS_PATH'] = coredir + '/BaseTools'
795857
    os.environ['CONF_PATH'] = coredir + '/Conf'
795857
    os.environ['PYTHON_COMMAND'] = '/usr/bin/python3'
795857
    os.environ['PYTHONHASHSEED'] = '1'
795857
795857
    # for cross builds
795857
    if binary_exists('arm-linux-gnu-gcc'):
795857
        os.environ['GCC5_ARM_PREFIX'] = 'arm-linux-gnu-'
795857
    if binary_exists('aarch64-linux-gnu-gcc'):
795857
        os.environ['GCC5_AARCH64_PREFIX'] = 'aarch64-linux-gnu-'
795857
    if binary_exists('riscv64-linux-gnu-gcc'):
795857
        os.environ['GCC5_RISCV64_PREFIX'] = 'riscv64-linux-gnu-'
795857
    if binary_exists('x86_64-linux-gnu-gcc'):
795857
        os.environ['GCC5_IA32_PREFIX'] = 'x86_64-linux-gnu-'
795857
        os.environ['GCC5_X64_PREFIX'] = 'x86_64-linux-gnu-'
795857
        os.environ['GCC5_BIN'] = 'x86_64-linux-gnu-'
795857
795857
def build_list(cfg):
795857
    for build in cfg.sections():
795857
        if not build.startswith('build.'):
795857
            continue
795857
        name = build.lstrip('build.')
795857
        desc = 'no description'
795857
        if 'desc' in cfg[build]:
795857
            desc = cfg[build]['desc']
795857
        print(f'# {name:20s} - {desc}')
795857
    
795857
def main():
795857
    parser = optparse.OptionParser()
795857
    parser.add_option('-c', '--config', dest = 'configfile',
795857
                      type = 'string', default = '.edk2.builds')
795857
    parser.add_option('-C', '--directory', dest = 'directory', type = 'string')
795857
    parser.add_option('-j', '--jobs', dest = 'jobs', type = 'string')
795857
    parser.add_option('-m', '--match', dest = 'match', type = 'string')
795857
    parser.add_option('-l', '--list', dest = 'list', action = 'store_true', default = False)
795857
    parser.add_option('--silent', dest = 'silent', action = 'store_true', default = False)
795857
    parser.add_option('--core', dest = 'core', type = 'string')
795857
    parser.add_option('--pkg', '--package', dest = 'pkgs', type = 'string', action = 'append')
795857
    parser.add_option('--version-override', dest = 'version_override', type = 'string')
795857
    parser.add_option('--release-date', dest = 'release_date', type = 'string')
795857
    (options, args) = parser.parse_args()
795857
795857
    if options.directory:
795857
        os.chdir(options.directory)
795857
795857
    cfg = configparser.ConfigParser()
795857
    cfg.optionxform = str
795857
    cfg.read(options.configfile)
795857
795857
    if options.list:
795857
        build_list(cfg)
795857
        return
795857
795857
    if not cfg.has_section('global'):
795857
        cfg.add_section('global')
795857
    if options.core:
795857
        cfg.set('global', 'core', options.core)
795857
    if options.pkgs:
795857
        cfg.set('global', 'pkgs', ' '.join(options.pkgs))
795857
795857
    global version_override
795857
    global release_date
795857
    check_rebase()
795857
    if options.version_override:
795857
        version_override = options.version_override
795857
    if options.release_date:
795857
        release_date = options.release_date
795857
795857
    prepare_env(cfg)
795857
    build_basetools(options.silent)
795857
    for build in cfg.sections():
795857
        if not build.startswith('build.'):
795857
            continue
795857
        if options.match and options.match not in build:
795857
            print(f'# skipping "{build}" (not matching "{options.match}")')
795857
            continue
795857
        build_one(cfg, build, options.jobs, options.silent)
795857
795857
if __name__ == '__main__':
795857
    sys.exit(main())