llvm-project
110 строк · 3.3 Кб
1#!/usr/bin/env python3
2"""Generate test body using split-file and a custom script.
3
4The script will prepare extra files with `split-file`, invoke `gen`, and then
5rewrite the part after `gen` with its stdout.
6
7https://llvm.org/docs/TestingGuide.html#elaborated-tests
8
9Example:
10PATH=/path/to/clang_build/bin:$PATH llvm/utils/update_test_body.py path/to/test.s
11"""
12import argparse13import contextlib14import os15import re16import subprocess17import sys18import tempfile19
20
21@contextlib.contextmanager22def cd(directory):23cwd = os.getcwd()24os.chdir(directory)25try:26yield27finally:28os.chdir(cwd)29
30
31def process(args, path):32prolog = []33seen_gen = False34with open(path) as f:35for line in f.readlines():36line = line.rstrip()37prolog.append(line)38if (seen_gen and re.match(r"(.|//)---", line)) or line.startswith(".endif"):39break40if re.match(r"(.|//)--- gen", line):41seen_gen = True42else:43print(44"'gen' should be followed by another part (---) or .endif",45file=sys.stderr,46)47return 148
49if not seen_gen:50print("'gen' does not exist", file=sys.stderr)51return 152with tempfile.TemporaryDirectory(prefix="update_test_body_") as dir:53try:54# If the last line starts with ".endif", remove it.55sub = subprocess.run(56["split-file", "-", dir],57input="\n".join(58prolog[:-1] if prolog[-1].startswith(".endif") else prolog59).encode(),60capture_output=True,61check=True,62)63except subprocess.CalledProcessError as ex:64sys.stderr.write(ex.stderr.decode())65return 166with cd(dir):67if args.shell:68print(f"invoke shell in the temporary directory '{dir}'")69subprocess.run([os.environ.get("SHELL", "sh")])70return 071
72sub = subprocess.run(73["sh", "-eu", "gen"],74capture_output=True,75# Don't encode the directory information to the Clang output.76# Remove unneeded details (.ident) as well.77env=dict(78os.environ,79CCC_OVERRIDE_OPTIONS="#^-fno-ident",80PWD="/proc/self/cwd",81),82)83sys.stderr.write(sub.stderr.decode())84if sub.returncode != 0:85print("'gen' failed", file=sys.stderr)86return sub.returncode87if not sub.stdout:88print("stdout is empty; forgot -o - ?", file=sys.stderr)89return 190content = sub.stdout.decode()91
92with open(path, "w") as f:93# Print lines up to '.endif'.94print("\n".join(prolog), file=f)95# Then print the stdout of 'gen'.96f.write(content)97
98
99parser = argparse.ArgumentParser(100description="Generate test body using split-file and a custom script"101)
102parser.add_argument("files", nargs="+")103parser.add_argument(104"--shell", action="store_true", help="invoke shell instead of 'gen'"105)
106args = parser.parse_args()107for path in args.files:108retcode = process(args, path)109if retcode != 0:110sys.exit(retcode)111