File: windows_build.py

package info (click to toggle)
graphviz 14.1.2-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 139,476 kB
  • sloc: ansic: 142,288; cpp: 11,975; python: 7,883; makefile: 4,044; yacc: 3,030; xml: 2,972; tcl: 2,495; sh: 1,391; objc: 1,159; java: 560; lex: 423; perl: 243; awk: 156; pascal: 139; php: 58; ruby: 49; cs: 31; sed: 1
file content (229 lines) | stat: -rw-r--r-- 6,877 bytes parent folder | download
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#!/usr/bin/env python3

"""Graphviz CI script for compilation on Windows"""

import argparse
import io
import itertools
import os
import shlex
import shutil
import subprocess
import sys
import textwrap
from pathlib import Path
from typing import Optional, TextIO, Union


def run(
    args: list[Union[str, Path]],
    cwd: Path,
    env: dict[str, str],
    out: Optional[TextIO] = None,
) -> None:
    """run a command, echoing it beforehand"""

    print(f"+ {shlex.join(str(x) for x in args)}", flush=True)
    kwargs = {}
    if out is not None:
        kwargs["stdout"] = subprocess.PIPE
        kwargs["stderr"] = subprocess.STDOUT
    p = subprocess.run(args, cwd=cwd, check=False, text=True, env=env, **kwargs)
    if out is not None:
        sys.stderr.write(p.stdout)
        out.write(p.stdout)
    p.check_returncode()


def require(program: str, fallback: Path, env: dict[str, str], log: TextIO) -> None:
    """
    detect if a given program is missing from the default $Path and needs a fallback

    Args:
        program: The name of a program to look for, without its “.exe” suffix.
        fallback: A path at which to find a version of that program. This alternate
            version will be used if the sought program is not found in $Path.
        env: An environment to use when searching for the program. If the program needs
            a fallback, the $Path variable in this environment will be adjusted.
        log: Sink to write informational messages to.
    """
    assert (
        fallback / f"{program}.exe"
    ).exists(), "{fallback} is not a valid fallback path for {program}"
    which = shutil.which(f"{program}.exe", path=env["PATH"])
    if which is None:
        log.write(
            textwrap.dedent(
                f"""\
        {program} not found
        Fallback needed for: {program}
        Setting up fallback path for: {program} to {fallback}
        """
            )
        )
        env["PATH"] = f"{fallback}{os.pathsep}{env['PATH']}"
    else:
        log.write(f"Found {program} at {which}\n")


def main(args: list[str]) -> int:
    """entry point"""

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--build-shared-libs",
        choices=("ON", "OFF"),
        default="ON",
        help="control shared libraries selection",
    )
    parser.add_argument(
        "--configuration",
        choices=("Debug", "Release"),
        required=True,
        help="build configuration to select",
    )
    parser.add_argument(
        "--platform", choices=("Win32", "x64"), required=True, help="target platform"
    )
    options = parser.parse_args(args[1:])

    # find the repository root directory
    root = Path(__file__).resolve().parent.parent

    # install Python dependencies
    run([sys.executable, "-m", "pip", "install", "uv"], root, None)
    run(
        [
            sys.executable,
            "-m",
            "uv",
            "pip",
            "install",
            "--requirement",
            "requirements.txt",
        ],
        root,
        None,
    )

    # retrieve submodules, dependencies are stored there
    run(["git", "submodule", "update", "--init", "--depth=1"], root, None)

    # an environment we will use during configuration/compilation
    build_env = os.environ.copy()

    # buffer for output so we can report warning count later
    log = io.StringIO()

    # find some external build dependencies
    utilities = root / "windows/dependencies/graphviz-build-utilities"
    require("win_bison", utilities / "winflexbison", build_env, log)
    require("win_flex", utilities / "winflexbison", build_env, log)
    require("makensis", utilities / "NSIS/Bin", build_env, log)

    build = root / "build"
    if build.exists():
        shutil.rmtree(build)
    build.mkdir(parents=True)
    run(["cmake", "--version"], build, None, log)
    run(
        [
            "cmake",
            "--log-level=VERBOSE",
            "-G",
            "Visual Studio 17 2022",
            "-A",
            options.platform,
            f"-DBUILD_SHARED_LIBS={options.build_shared_libs}",
            "-Dwith_cxx_api=ON",
            "-DENABLE_LTDL=ON",
            "-DWITH_EXPAT=ON",
            "-DWITH_GVEDIT=OFF",
            "-DWITH_ZLIB=ON",
            "--warn-uninitialized",
            "-Werror=dev",
            "..",
        ],
        build,
        build_env,
        log,
    )
    run(
        ["cmake", "--build", ".", "--config", options.configuration],
        build,
        build_env,
        log,
    )
    run(["cpack", "-C", options.configuration], build, build_env, log)

    # report warning count
    warning_count = log.getvalue().count(" warning ")
    metrics = Path("metrics.txt")
    summary = f"{os.environ['CI_JOB_NAME']}-warnings {warning_count}"
    print(summary, flush=True)
    metrics.write_text(f"{summary}\n", encoding="utf-8")

    # derive Graphviz version
    version_buffer = io.StringIO()
    run([sys.executable, "gen_version.py"], root, None, version_buffer)
    gv_version = version_buffer.getvalue().strip()

    # find the installer
    installers = list(build.glob("Graphviz*.exe"))
    assert len(installers) == 1, "failed to find Graphviz installer"
    installer = build / installers[0]

    # install Graphviz
    install_dir = "C:\\Graphviz"
    run([installer, "/S", f"/D={install_dir}"], root, None)

    # which Windows interface are we targeting?
    if options.platform == "x64":
        api = "win64"
    else:
        api = "win32"

    # move the installer to the location expected by CI archiving steps
    dst = build / f"graphviz-install-{gv_version}-{api}.exe"
    shutil.move(installer, dst)

    # an environment we will use during testing
    test_env = os.environ.copy()

    test_env["PATH"] = f"{install_dir}\\bin;{test_env.get('PATH', '')}"
    test_env["CFLAGS"] = f"{test_env.get('CFLAGS', '')} -I{install_dir}\\include"
    test_env["LIB"] = f"{test_env.get('LIB', '')};{install_dir}\\lib"
    test_env["graphviz_ROOT"] = install_dir

    # run the test suite
    run(
        [
            sys.executable,
            "-m",
            "pytest",
            "-m",
            "not slow",
            "-n",
            "auto",
            "--junit-xml=report.xml",
            "ci/tests.py",
            "tests",
        ],
        root,
        test_env,
    )

    # create artifacts to archive
    prefix = f"windows_10_cmake_{os.environ['configuration']}_"
    packages = root / "Packages" / os.environ["CI_JOB_NAME"]
    packages.mkdir(parents=True)
    for src in itertools.chain(build.glob("*.exe"), build.glob("*.zip")):
        dst = packages / f"{prefix}{src.name}"
        print(f"+ mv {shlex.join(str(a) for a in [src, dst])}", flush=True)
        shutil.move(src, dst)

    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))