1#!/usr/bin/env python3
2import argparse
3import os
4import re
5import shlex
6import subprocess
7import sys
8import textwrap
9
10def get_git_ref_or_rev(dir: str) -> str:
11    # Run 'git symbolic-ref -q --short HEAD || git rev-parse --short HEAD'
12    cmd_ref = 'git symbolic-ref -q --short HEAD'
13    ref = subprocess.run(shlex.split(cmd_ref), cwd=dir, text=True,
14                         stdout=subprocess.PIPE)
15    if not ref.returncode:
16        return ref.stdout.strip()
17    cmd_rev = 'git rev-parse --short HEAD'
18    return subprocess.check_output(shlex.split(cmd_rev), cwd=dir,
19                                   text=True).strip()
20
21
22def main():
23    parser = argparse.ArgumentParser(description=textwrap.dedent('''
24            This script builds two versions of BOLT (with the current and
25            previous revision) and sets up symlink for llvm-bolt-wrapper.
26            Passes the options through to llvm-bolt-wrapper.
27            '''))
28    parser.add_argument('build_dir', nargs='?', default=os.getcwd(),
29                        help='Path to BOLT build directory, default is current directory')
30    args, wrapper_args = parser.parse_known_args()
31    bolt_path = f'{args.build_dir}/bin/llvm-bolt'
32
33    source_dir = None
34    # find the repo directory
35    with open(f'{args.build_dir}/CMakeCache.txt') as f:
36        for line in f:
37            m = re.match(r'LLVM_SOURCE_DIR:STATIC=(.*)', line)
38            if m:
39                source_dir = m.groups()[0]
40    if not source_dir:
41        sys.exit("Source directory is not found")
42
43    script_dir = os.path.dirname(os.path.abspath(__file__))
44    wrapper_path = f'{script_dir}/llvm-bolt-wrapper.py'
45    # build the current commit
46    subprocess.run(shlex.split("cmake --build . --target llvm-bolt"),
47                   cwd=args.build_dir)
48    # rename llvm-bolt
49    os.replace(bolt_path, f'{bolt_path}.new')
50    # memorize the old hash for logging
51    old_ref = get_git_ref_or_rev(source_dir)
52
53    # save local changes before checkout
54    subprocess.run(shlex.split("git stash"), cwd=source_dir)
55    # check out the previous commit
56    subprocess.run(shlex.split("git checkout -f HEAD^"), cwd=source_dir)
57    # get the parent commit hash for logging
58    new_ref = get_git_ref_or_rev(source_dir)
59    # build the previous commit
60    subprocess.run(shlex.split("cmake --build . --target llvm-bolt"),
61                   cwd=args.build_dir)
62    # rename llvm-bolt
63    os.replace(bolt_path, f'{bolt_path}.old')
64    # set up llvm-bolt-wrapper.ini
65    ini = subprocess.check_output(
66        shlex.split(
67            f"{wrapper_path} {bolt_path}.old {bolt_path}.new") + wrapper_args,
68        text=True)
69    with open(f'{args.build_dir}/bin/llvm-bolt-wrapper.ini', 'w') as f:
70        f.write(ini)
71    # symlink llvm-bolt-wrapper
72    os.symlink(wrapper_path, bolt_path)
73    print(f"The repository {source_dir} has been switched from rev {old_ref} "
74          f"to {new_ref}. Local changes were stashed. Switch back using\n\t"
75          f"git checkout {old_ref}\n"
76          "Current build directory is ready to run BOLT tests, e.g.\n\t"
77          "bin/llvm-lit -sv tools/bolt/test\nor\n\t"
78          "bin/llvm-lit -sv tools/bolttests")
79
80
81if __name__ == "__main__":
82    main()
83