File: deploy.py

package info (click to toggle)
graphviz 14.1.1-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 139,440 kB
  • sloc: ansic: 142,129; cpp: 11,960; python: 7,770; makefile: 4,043; yacc: 3,030; xml: 2,972; tcl: 2,495; sh: 1,388; objc: 1,159; java: 560; lex: 423; perl: 243; awk: 156; pascal: 139; php: 58; ruby: 49; cs: 31; sed: 1
file content (286 lines) | stat: -rw-r--r-- 8,919 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env python3

"""
steps for deploying a new release (see ../.gitlab-ci.yml)

This is based on Gitlab’s generic package example,
https://gitlab.com/gitlab-org/release-cli/-/tree/master/docs/examples/release-assets-as-generic-package
"""

import hashlib
import json
import logging
import os
import re
import shutil
import stat
import subprocess
import sys
from pathlib import Path
from typing import Optional

# logging output stream, setup in main()
log = None


def upload(dry_run: bool, version: str, path: Path, name: Optional[str] = None) -> str:
    """
    upload a file to the Graphviz generic package with the given version
    """

    # use the path as the name if no other was given
    if name is None:
        name = str(path)

    # Gitlab upload file_name field only allows letters, numbers, dot, dash, and
    # underscore
    safe = re.sub(r"[^a-zA-Z0-9.\-]", "_", name)
    log.info(f"escaped name {name} to {safe}")

    target = (
        f'{os.environ["CI_API_V4_URL"]}/projects/'
        f'{os.environ["CI_PROJECT_ID"]}/packages/generic/graphviz-releases/'
        f"{version}/{safe}"
    )

    if dry_run:
        log.info("skipping upload due to 'dry_run' flag")
        return target

    log.info(f"uploading {path} to {target}")
    # calling Curl is not the cleanest way to achieve this, but Curl takes care of
    # encodings, headers and part splitting for us
    proc = subprocess.run(
        [
            "curl",
            "--silent",  # no progress bar
            "--include",  # include HTTP response headers in output
            "--verbose",  # more connection details
            "--retry",
            "3",  # retry on transient errors
            "--header",
            f'JOB-TOKEN: {os.environ["CI_JOB_TOKEN"]}',
            "--upload-file",
            path,
            target,
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        check=False,
        text=True,
    )
    log.info("Curl response:")
    for i, line in enumerate(proc.stdout.split("\n"), 1):
        log.info(f" {i:3}: {line}")
    proc.check_returncode()

    resp = proc.stdout.split("\n")[-1]
    if json.loads(resp)["message"] != "201 Created":
        raise RuntimeError(f"upload failed: {resp}")

    return target


def checksum(path: Path) -> Path:
    """generate checksum for the given file"""

    assert path.exists()

    log.info(f"SHA256 summing {path}")
    check = Path(f"{path}.sha256")
    data = path.read_bytes()
    check.write_text(f"{hashlib.sha256(data).hexdigest()}  {path}\n", encoding="utf-8")
    return check


def is_macos_artifact(path: Path) -> bool:
    """is this a deployment artifact for macOS?"""
    return re.search(r"\bDarwin\b", str(path)) is not None


def is_windows_artifact(path: Path) -> bool:
    """is this a deployment artifact for Windows?"""
    return re.search(r"\bwindows\b", str(path)) is not None


def get_format(path: Path) -> str:
    """a human readable description of the format of this file"""
    if path.suffix[1:].lower() == "exe":
        return "EXE installer"
    if path.suffix[1:].lower() == "zip":
        return "ZIP archive"
    if ".tar." in str(path):
        return "".join(path.suffixes[-2:])[1:].lower()
    return path.suffix[1:].lower()


def main() -> int:
    """entry point"""

    # setup logging to print to stderr
    global log
    ch = logging.StreamHandler()
    log = logging.getLogger("deploy.py")
    log.addHandler(ch)
    log.setLevel(logging.INFO)

    if os.environ.get("CI") is None:
        log.error("CI environment variable unset; refusing to run")
        return -1

    # echo some useful things for debugging
    log.info(f"os.uname(): {os.uname()}")
    if Path("/etc/os-release").exists():
        with open("/etc/os-release", "rt", encoding="utf-8") as f:
            log.info("/etc/os-release:")
            for i, line in enumerate(f, 1):
                log.info(f" {i}: {line[:-1]}")

    # bail out early if we do not have release-cli to avoid uploading assets that
    # become orphaned when we fail to create the release
    if not shutil.which("release-cli"):
        log.error("release-cli not found")
        return -1

    # retrieve version name left by prior CI tasks
    log.info("deriving Graphviz version")
    root = Path(__file__).resolve().parents[1]
    version = subprocess.check_output(
        [sys.executable, "gen_version.py"], cwd=root, text=True
    ).strip()
    log.info(f"Graphviz version == {version}")

    # the generic package version has to be \d+.\d+.\d+ but it does not need to
    # correspond to the release version (which may not conform to this pattern if
    # this is a dev release)
    if re.match(r"\d+\.\d+\.\d+$", version) is None:
        # generate a compliant version
        package_version = f'0.0.{int(os.environ["CI_COMMIT_SHA"], 16)}'
    else:
        # we can use a version corresponding to the release version
        package_version = version
    log.info(f"using generic package version {package_version}")

    # we only create Gitlab releases for stable version numbers
    skip_release = re.match(r"\d+\.\d+\.\d+$", version) is None

    # list of assets we have uploaded
    assets: list[str] = []

    # 0-pad major version to 2 digits, to sort versions properly
    vparts = version.split(".")
    assert len(vparts) > 0, "Malformed version string"
    vparts[0] = f"{int(vparts[0]):02d}"

    # data for the website’s download page
    webdata = {
        "name": f"graphviz-{version}",
        "version": ".".join(vparts),
        "sources": [],
        "windows": [],
    }

    for tarball in (
        Path(f"graphviz-{version}.tar.gz"),
        Path(f"graphviz-{version}.tar.xz"),
    ):
        if not tarball.exists():
            log.error(f"source {tarball} not found")
            return -1

        # accrue the source tarball and accompanying checksum
        url = upload(skip_release, package_version, tarball)
        assets.append(url)
        webentry = {"format": get_format(tarball), "url": url}
        check = checksum(tarball)
        url = upload(skip_release, package_version, check)
        assets.append(url)
        webentry[check.suffix[1:]] = url

        webdata["sources"].append(webentry)

    for stem, _, leaves in os.walk("Packages"):
        for leaf in leaves:
            path = Path(stem) / leaf

            # get existing permissions
            mode = path.stat().st_mode

            # fixup permissions, o-rwx g-wx
            path.chmod(mode & ~stat.S_IRWXO & ~stat.S_IWGRP & ~stat.S_IXGRP)

            url = upload(
                skip_release, package_version, path, str(path)[len("Packages/") :]
            )
            assets.append(url)

            webentry = {
                "format": get_format(path),
                "url": url,
            }
            if "win32" in str(path):
                webentry["bits"] = 32
            elif "win64" in str(path):
                webentry["bits"] = 64

            # if this is a standalone Windows or macOS package, also provide
            # checksum(s)
            if is_macos_artifact(path) or is_windows_artifact(path):
                c = checksum(path)
                url = upload(
                    skip_release, package_version, c, str(c)[len("Packages/") :]
                )
                assets.append(url)
                webentry[c.suffix[1:]] = url

            # only expose a subset of the Windows artifacts
            if "/windows/10/cmake/Release/" in str(path):
                webdata["windows"].append(webentry)

    # various release pages truncate the viewable artifacts to 100 or even 50
    if len(assets) > 50:
        log.error(
            f"upload has {len(assets)} assets, which will result in some of "
            f"them being unviewable in web page lists: {assets}"
        )
        return -1

    assert len(webdata["windows"]) > 0, "no Windows artifacts found"

    if skip_release:
        log.warning(
            f"skipping release creation because {version} is not "
            "of the form \\d+.\\d+.\\d+"
        )
        return 0

    # construct a command to create the release itself
    cmd = [
        "release-cli",
        "create",
        "--name",
        version,
        "--tag-name",
        version,
        "--description",
        "See the [CHANGELOG](https://gitlab.com/"
        "graphviz/graphviz/-/blob/main/CHANGELOG.md).",
    ]
    for a in assets:
        name = os.path.basename(a)
        url = a
        cmd += ["--assets-link", json.dumps({"name": name, "url": url})]

    # create the release
    subprocess.check_call(cmd)

    # output JSON data for the website
    log.info(f"dumping {webdata} to graphviz-{version}.json")
    with open(f"graphviz-{version}.json", "wt", encoding="utf-8") as f:
        json.dump(webdata, f, indent=2)

    return 0


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