Welcome to mirror list, hosted at ThFree Co, Russian Federation.

make_source_archive.py « utils « build_files - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: befd6d845340955e069b39f78337aae311685267 (plain)
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
287
288
289
290
291
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later

import argparse
import dataclasses
import os
import re
import subprocess
from pathlib import Path
from typing import Iterable, TextIO, Optional, Any, Union

# This script can run from any location,
# output is created in the $CWD
#
# NOTE: while the Python part of this script is portable,
# it relies on external commands typically found on GNU/Linux.
# Support for other platforms could be added by moving GNU `tar` & `md5sum` use to Python.

SKIP_NAMES = {
    ".gitignore",
    ".gitmodules",
    ".arcconfig",
    ".svn",
}


def main() -> None:
    blender_srcdir = Path(__file__).absolute().parent.parent.parent

    cli_parser = argparse.ArgumentParser(
        description=f"Create a tarball of the Blender sources, optionally including sources of dependencies.",
        epilog="This script is intended to be run by `make source_archive_complete`.",
    )
    cli_parser.add_argument(
        "-p",
        "--include-packages",
        type=Path,
        default=None,
        metavar="PACKAGE_PATH",
        help="Include all source files from the given package directory as well.",
    )

    cli_args = cli_parser.parse_args()

    print(f"Source dir: {blender_srcdir}")

    curdir = blender_srcdir.parent
    os.chdir(curdir)
    blender_srcdir = blender_srcdir.relative_to(curdir)

    print(f"Output dir: {curdir}")

    version = parse_blender_version(blender_srcdir)
    tarball = tarball_path(curdir, version, cli_args)
    manifest = manifest_path(tarball)
    packages_dir = packages_path(curdir, cli_args)

    create_manifest(version, manifest, blender_srcdir, packages_dir)
    create_tarball(version, tarball, manifest, blender_srcdir, packages_dir)
    create_checksum_file(tarball)
    cleanup(manifest)
    print("Done!")


@dataclasses.dataclass
class BlenderVersion:
    version: int  # 293 for 2.93.1
    patch: int  # 1 for 2.93.1
    cycle: str  # 'alpha', 'beta', 'release', maybe others.

    @property
    def is_release(self) -> bool:
        return self.cycle == "release"

    def __str__(self) -> str:
        """Convert to version string.

        >>> str(BlenderVersion(293, 1, "alpha"))
        '2.93.1-alpha'
        >>> str(BlenderVersion(327, 0, "release"))
        '3.27.0'
        """
        version_major = self.version // 100
        version_minor = self.version % 100
        as_string = f"{version_major}.{version_minor}.{self.patch}"
        if self.is_release:
            return as_string
        return f"{as_string}-{self.cycle}"


def parse_blender_version(blender_srcdir: Path) -> BlenderVersion:
    version_path = blender_srcdir / "source/blender/blenkernel/BKE_blender_version.h"

    version_info = {}
    line_re = re.compile(r"^#define (BLENDER_VERSION[A-Z_]*)\s+([0-9a-z]+)$")

    with version_path.open(encoding="utf-8") as version_file:
        for line in version_file:
            match = line_re.match(line.strip())
            if not match:
                continue
            version_info[match.group(1)] = match.group(2)

    return BlenderVersion(
        int(version_info["BLENDER_VERSION"]),
        int(version_info["BLENDER_VERSION_PATCH"]),
        version_info["BLENDER_VERSION_CYCLE"],
    )


def tarball_path(output_dir: Path, version: BlenderVersion, cli_args: Any) -> Path:
    extra = ""
    if cli_args.include_packages:
        extra = "-with-libraries"

    return output_dir / f"blender{extra}-{version}.tar.xz"


def manifest_path(tarball: Path) -> Path:
    """Return the manifest path for the given tarball path.

    >>> from pathlib import Path
    >>> tarball = Path("/home/sybren/workspace/blender-git/blender-test.tar.gz")
    >>> manifest_path(tarball).as_posix()
    '/home/sybren/workspace/blender-git/blender-test-manifest.txt'
    """
    # ".tar.gz" is seen as two suffixes.
    without_suffix = tarball.with_suffix("").with_suffix("")
    name = without_suffix.name
    return without_suffix.with_name(f"{name}-manifest.txt")


def packages_path(current_directory: Path, cli_args: Any) -> Optional[Path]:
    if not cli_args.include_packages:
        return None

    abspath = cli_args.include_packages.absolute()

    # os.path.relpath() can return paths like "../../packages", where
    # Path.relative_to() will not go up directories (so its return value never
    # has "../" in there).
    relpath = os.path.relpath(abspath, current_directory)

    return Path(relpath)

# -----------------------------------------------------------------------------
# Manifest creation


def create_manifest(
    version: BlenderVersion,
    outpath: Path,
    blender_srcdir: Path,
    packages_dir: Optional[Path],
) -> None:
    print(f'Building manifest of files:  "{outpath}"...', end="", flush=True)
    with outpath.open("w", encoding="utf-8") as outfile:
        main_files_to_manifest(blender_srcdir, outfile)
        submodules_to_manifest(blender_srcdir, version, outfile)

        if packages_dir:
            packages_to_manifest(outfile, packages_dir)
    print("OK")


def main_files_to_manifest(blender_srcdir: Path, outfile: TextIO) -> None:
    assert not blender_srcdir.is_absolute()
    for path in git_ls_files(blender_srcdir):
        print(path, file=outfile)


def submodules_to_manifest(
    blender_srcdir: Path, version: BlenderVersion, outfile: TextIO
) -> None:
    skip_addon_contrib = version.is_release
    assert not blender_srcdir.is_absolute()

    for line in git_command("-C", blender_srcdir, "submodule"):
        submodule = line.split()[1]

        # Don't use native slashes as GIT for MS-Windows outputs forward slashes.
        if skip_addon_contrib and submodule == "release/scripts/addons_contrib":
            continue

        for path in git_ls_files(blender_srcdir / submodule):
            print(path, file=outfile)


def packages_to_manifest(outfile: TextIO, packages_dir: Path) -> None:
    for path in packages_dir.glob("*"):
        if not path.is_file():
            continue
        if path.name in SKIP_NAMES:
            continue
        print(path, file=outfile)


# -----------------------------------------------------------------------------
# Higher-level functions


def create_tarball(
    version: BlenderVersion, tarball: Path, manifest: Path, blender_srcdir: Path, packages_dir: Optional[Path]
) -> None:
    print(f'Creating archive:            "{tarball}" ...', end="", flush=True)
    command = ["tar"]

    # Requires GNU `tar`, since `--transform` is used.
    if packages_dir:
        command += ["--transform", f"s,{packages_dir}/,packages/,g"]

    command += [
        "--transform",
        f"s,^{blender_srcdir.name}/,blender-{version}/,g",
        "--use-compress-program=xz -9",
        "--create",
        f"--file={tarball}",
        f"--files-from={manifest}",
        # Without owner/group args, extracting the files as root will
        # use ownership from the tar archive:
        "--owner=0",
        "--group=0",
    ]

    subprocess.run(command, check=True, timeout=3600)
    print("OK")


def create_checksum_file(tarball: Path) -> None:
    md5_path = tarball.with_name(tarball.name + ".md5sum")
    print(f'Creating checksum:           "{md5_path}" ...', end="", flush=True)
    command = [
        "md5sum",
        # The name is enough, as the tarball resides in the same dir as the MD5
        # file, and that's the current working directory.
        tarball.name,
    ]
    md5_cmd = subprocess.run(
        command, stdout=subprocess.PIPE, check=True, text=True, timeout=300
    )
    with md5_path.open("w", encoding="utf-8") as outfile:
        outfile.write(md5_cmd.stdout)
    print("OK")


def cleanup(manifest: Path) -> None:
    print("Cleaning up ...", end="", flush=True)
    if manifest.exists():
        manifest.unlink()
    print("OK")


# -----------------------------------------------------------------------------
# Low-level commands


def git_ls_files(directory: Path = Path(".")) -> Iterable[Path]:
    """Generator, yields lines of output from 'git ls-files'.

    Only lines that are actually files (so no directories, sockets, etc.) are
    returned, and never one from SKIP_NAMES.
    """
    for line in git_command("-C", str(directory), "ls-files"):
        path = directory / line
        if not path.is_file() or path.name in SKIP_NAMES:
            continue
        yield path


def git_command(*cli_args: Union[bytes, str, Path]) -> Iterable[str]:
    """Generator, yields lines of output from a Git command."""
    command = ("git", *cli_args)

    # import shlex
    # print(">", " ".join(shlex.quote(arg) for arg in command))

    git = subprocess.run(
        command, stdout=subprocess.PIPE, check=True, text=True, timeout=30
    )
    for line in git.stdout.split("\n"):
        if line:
            yield line


if __name__ == "__main__":
    import doctest

    if doctest.testmod().failed:
        raise SystemExit("ERROR: Self-test failed, refusing to run")

    main()