File: compile.py

package info (click to toggle)
libdrpm 0.5.2-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 892 kB
  • sloc: ansic: 8,372; python: 133; sh: 131; makefile: 8
file content (167 lines) | stat: -rwxr-xr-x 4,351 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#!/usr/bin/python3
"""Build a trivial program using the drpm library."""

from __future__ import annotations

import argparse
import dataclasses
import os
import pathlib
import shlex
import subprocess  # noqa: S404
import sys
import tempfile


EXPECTED = [
    "make standard",
    "read standard",
    "standard",
    "make options",
    "make rpm-only",
    "read rpm-only",
    "rpm-only",
    "fine",
]


@dataclasses.dataclass(frozen=True)
class Config:
    """Runtime configuration."""

    source: pathlib.Path
    testdir: pathlib.Path

    env: dict[str, str]

    tempd: pathlib.Path
    obj: pathlib.Path
    program: pathlib.Path


def do_compile(cfg: Config) -> None:
    """Compile the test program."""
    print("Fetching the C compiler flags for drpm")
    cflags = subprocess.check_output(  # noqa: S603
        ["pkg-config", "--cflags", "drpm"],  # noqa: S607
        encoding="UTF-8",
        shell=False,
        env=cfg.env,
    ).rstrip("\r\n")
    if "\r" in cflags or "\n" in cflags:
        sys.exit(f"`pkg-config --cflags drpm` returned {cflags!r}")

    if cfg.obj.exists():
        sys.exit(f"Did not expect {cfg.obj} to exist")
    cmd = [
        "cc",
        "-c",
        "-o",
        str(cfg.obj),
        "-Wall",
        "-W",
        "-Wextra",
        "-Werror",
        *shlex.split(cflags),
        str(cfg.source),
    ]
    print(f"Running {cmd!r}")
    subprocess.check_call(cmd, shell=False, env=cfg.env)  # noqa: S603
    if not cfg.obj.is_file():
        sys.exit(f"{cmd!r} did not create the {cfg.obj} file")

    print("Fetching the C linker flags and libraries for drpm")
    libs = subprocess.check_output(  # noqa: S603
        ["pkg-config", "--libs", "drpm"],  # noqa: S607
        encoding="UTF-8",
        shell=False,
        env=cfg.env,
    ).rstrip("\r\n")
    if "\r" in libs or "\n" in libs:
        sys.exit(f"`pkg-config --libs drpm` returned {libs!r}")

    if cfg.program.exists():
        sys.exit(f"Did not expect {cfg.program} to exist")
    cmd = ["cc", "-o", str(cfg.program), str(cfg.obj), *shlex.split(libs)]
    print(f"Running {cmd!r}")
    subprocess.check_call(cmd, shell=False, env=cfg.env)  # noqa: S603
    if not cfg.program.is_file():
        sys.exit(f"{cmd!r} did not create the {cfg.program} file")
    if not os.access(cfg.program, os.X_OK):
        sys.exit(f"Not an executable file: {cfg.program}")
    print(f"Looks like we got {cfg.program}")


def parse_args(dirname: str) -> Config:
    """Parse the command-line options."""
    parser = argparse.ArgumentParser(prog="compile")
    parser.add_argument(
        "-s",
        "--source",
        type=str,
        required=True,
        help="path to the source file to compile",
    )
    parser.add_argument(
        "-t",
        "--testdir",
        type=str,
        required=True,
        help="path to the directory containing the test RPM packages",
    )

    args = parser.parse_args()

    env = dict(os.environ)
    env["LC_ALL"] = "C.UTF-8"
    env["LANGUAGES"] = ""

    source = pathlib.Path(args.source).absolute()
    if source.suffixes != [".c"]:
        sys.exit("The source file should only have a *.c extension.")
    progname = source.with_suffix("").name

    tempd = pathlib.Path(dirname).absolute()
    program = tempd / progname
    return Config(
        source=pathlib.Path(args.source),
        testdir=pathlib.Path(args.testdir),
        env=env,
        tempd=tempd,
        obj=program.with_suffix(".o"),
        program=program,
    )


def do_run(cfg: Config) -> None:
    """Run the compiled program, examine the result."""
    command = [
        cfg.program,
        cfg.testdir / "cmocka-old.rpm",
        cfg.testdir / "cmocka-new.rpm",
        cfg.tempd,
    ]
    print(f"Running {command!r}")
    lines = subprocess.check_output(  # noqa: S603
        command,
        encoding="UTF-8",
        shell=False,
        env=cfg.env,
    ).splitlines()
    print(f"Got {lines!r}")

    if lines != EXPECTED:
        sys.exit(f"The test program output {lines!r} instead of {EXPECTED!r}")


def main() -> None:
    """Parse command-line options, compile a program, run it."""
    with tempfile.TemporaryDirectory() as dirname:
        cfg = parse_args(dirname)
        do_compile(cfg)
        do_run(cfg)
        print("Seems fine!")


if __name__ == "__main__":
    main()