| 1 |
#!/usr/bin/env python3 |
| 2 |
# |
| 3 |
# Copyright (c) Facebook, Inc. and its affiliates. |
| 4 |
# |
| 5 |
import argparse |
| 6 |
import collections |
| 7 |
import errno |
| 8 |
import os |
| 9 |
import shutil |
| 10 |
import sys |
| 11 |
import tempfile |
| 12 |
import zipapp |
| 13 |
|
| 14 |
MANIFEST_SEPARATOR = " :: " |
| 15 |
MANIFEST_HEADER_V1 = "FBPY_MANIFEST 1\n" |
| 16 |
|
| 17 |
|
| 18 |
class UsageError(Exception): |
| 19 |
def __init__(self, message): |
| 20 |
self.message = message |
| 21 |
|
| 22 |
def __str__(self): |
| 23 |
return self.message |
| 24 |
|
| 25 |
|
| 26 |
class BadManifestError(UsageError): |
| 27 |
def __init__(self, path, line_num, message): |
| 28 |
full_msg = "%s:%s: %s" % (path, line_num, message) |
| 29 |
super().__init__(full_msg) |
| 30 |
self.path = path |
| 31 |
self.line_num = line_num |
| 32 |
self.raw_message = message |
| 33 |
|
| 34 |
|
| 35 |
PathInfo = collections.namedtuple( |
| 36 |
"PathInfo", ("src", "dest", "manifest_path", "manifest_line") |
| 37 |
) |
| 38 |
|
| 39 |
|
| 40 |
def parse_manifest(manifest, path_map): |
| 41 |
bad_prefix = ".." + os.path.sep |
| 42 |
manifest_dir = os.path.dirname(manifest) |
| 43 |
with open(manifest, "r") as f: |
| 44 |
line_num = 1 |
| 45 |
line = f.readline() |
| 46 |
if line != MANIFEST_HEADER_V1: |
| 47 |
raise BadManifestError( |
| 48 |
manifest, line_num, "Unexpected manifest file header" |
| 49 |
) |
| 50 |
|
| 51 |
for line in f: |
| 52 |
line_num += 1 |
| 53 |
if line.startswith("#"): |
| 54 |
continue |
| 55 |
line = line.rstrip("\n") |
| 56 |
parts = line.split(MANIFEST_SEPARATOR) |
| 57 |
if len(parts) != 2: |
| 58 |
msg = "line must be of the form SRC %s DEST" % MANIFEST_SEPARATOR |
| 59 |
raise BadManifestError(manifest, line_num, msg) |
| 60 |
src, dest = parts |
| 61 |
dest = os.path.normpath(dest) |
| 62 |
if dest.startswith(bad_prefix): |
| 63 |
msg = "destination path starts with %s: %s" % (bad_prefix, dest) |
| 64 |
raise BadManifestError(manifest, line_num, msg) |
| 65 |
|
| 66 |
if not os.path.isabs(src): |
| 67 |
src = os.path.normpath(os.path.join(manifest_dir, src)) |
| 68 |
|
| 69 |
if dest in path_map: |
| 70 |
prev_info = path_map[dest] |
| 71 |
msg = ( |
| 72 |
"multiple source paths specified for destination " |
| 73 |
"path %s. Previous source was %s from %s:%s" |
| 74 |
% ( |
| 75 |
dest, |
| 76 |
prev_info.src, |
| 77 |
prev_info.manifest_path, |
| 78 |
prev_info.manifest_line, |
| 79 |
) |
| 80 |
) |
| 81 |
raise BadManifestError(manifest, line_num, msg) |
| 82 |
|
| 83 |
info = PathInfo( |
| 84 |
src=src, |
| 85 |
dest=dest, |
| 86 |
manifest_path=manifest, |
| 87 |
manifest_line=line_num, |
| 88 |
) |
| 89 |
path_map[dest] = info |
| 90 |
|
| 91 |
|
| 92 |
def populate_install_tree(inst_dir, path_map): |
| 93 |
os.mkdir(inst_dir) |
| 94 |
dest_dirs = {"": False} |
| 95 |
|
| 96 |
def make_dest_dir(path): |
| 97 |
if path in dest_dirs: |
| 98 |
return |
| 99 |
parent = os.path.dirname(path) |
| 100 |
make_dest_dir(parent) |
| 101 |
abs_path = os.path.join(inst_dir, path) |
| 102 |
os.mkdir(abs_path) |
| 103 |
dest_dirs[path] = False |
| 104 |
|
| 105 |
def install_file(info): |
| 106 |
dir_name, base_name = os.path.split(info.dest) |
| 107 |
make_dest_dir(dir_name) |
| 108 |
if base_name == "__init__.py": |
| 109 |
dest_dirs[dir_name] = True |
| 110 |
abs_dest = os.path.join(inst_dir, info.dest) |
| 111 |
shutil.copy2(info.src, abs_dest) |
| 112 |
|
| 113 |
# Copy all of the destination files |
| 114 |
for info in path_map.values(): |
| 115 |
install_file(info) |
| 116 |
|
| 117 |
# Create __init__ files in any directories that don't have them. |
| 118 |
for dir_path, has_init in dest_dirs.items(): |
| 119 |
if has_init: |
| 120 |
continue |
| 121 |
init_path = os.path.join(inst_dir, dir_path, "__init__.py") |
| 122 |
with open(init_path, "w"): |
| 123 |
pass |
| 124 |
|
| 125 |
|
| 126 |
def build_zipapp(args, path_map): |
| 127 |
"""Create a self executing python binary using Python 3's built-in |
| 128 |
zipapp module. |
| 129 |
|
| 130 |
This type of Python binary is relatively simple, as zipapp is part of the |
| 131 |
standard library, but it does not support native language extensions |
| 132 |
(.so/.dll files). |
| 133 |
""" |
| 134 |
dest_dir = os.path.dirname(args.output) |
| 135 |
with tempfile.TemporaryDirectory(prefix="make_fbpy.", dir=dest_dir) as tmpdir: |
| 136 |
inst_dir = os.path.join(tmpdir, "tree") |
| 137 |
populate_install_tree(inst_dir, path_map) |
| 138 |
|
| 139 |
tmp_output = os.path.join(tmpdir, "output.exe") |
| 140 |
zipapp.create_archive( |
| 141 |
inst_dir, target=tmp_output, interpreter=args.python, main=args.main |
| 142 |
) |
| 143 |
os.replace(tmp_output, args.output) |
| 144 |
|
| 145 |
|
| 146 |
def create_main_module(args, inst_dir, path_map): |
| 147 |
if not args.main: |
| 148 |
assert "__main__.py" in path_map |
| 149 |
return |
| 150 |
|
| 151 |
dest_path = os.path.join(inst_dir, "__main__.py") |
| 152 |
main_module, main_fn = args.main.split(":") |
| 153 |
main_contents = """\ |
| 154 |
#!{python} |
| 155 |
|
| 156 |
if __name__ == "__main__": |
| 157 |
import {main_module} |
| 158 |
{main_module}.{main_fn}() |
| 159 |
""".format( |
| 160 |
python=args.python, main_module=main_module, main_fn=main_fn |
| 161 |
) |
| 162 |
with open(dest_path, "w") as f: |
| 163 |
f.write(main_contents) |
| 164 |
os.chmod(dest_path, 0o755) |
| 165 |
|
| 166 |
|
| 167 |
def build_install_dir(args, path_map): |
| 168 |
"""Create a directory that contains all of the sources, with a __main__ |
| 169 |
module to run the program. |
| 170 |
""" |
| 171 |
# Populate a temporary directory first, then rename to the destination |
| 172 |
# location. This ensures that we don't ever leave a halfway-built |
| 173 |
# directory behind at the output path if something goes wrong. |
| 174 |
dest_dir = os.path.dirname(args.output) |
| 175 |
with tempfile.TemporaryDirectory(prefix="make_fbpy.", dir=dest_dir) as tmpdir: |
| 176 |
inst_dir = os.path.join(tmpdir, "tree") |
| 177 |
populate_install_tree(inst_dir, path_map) |
| 178 |
create_main_module(args, inst_dir, path_map) |
| 179 |
os.rename(inst_dir, args.output) |
| 180 |
|
| 181 |
|
| 182 |
def ensure_directory(path): |
| 183 |
try: |
| 184 |
os.makedirs(path) |
| 185 |
except OSError as ex: |
| 186 |
if ex.errno != errno.EEXIST: |
| 187 |
raise |
| 188 |
|
| 189 |
|
| 190 |
def install_library(args, path_map): |
| 191 |
"""Create an installation directory a python library.""" |
| 192 |
out_dir = args.output |
| 193 |
out_manifest = args.output + ".manifest" |
| 194 |
|
| 195 |
install_dir = args.install_dir |
| 196 |
if not install_dir: |
| 197 |
install_dir = out_dir |
| 198 |
|
| 199 |
os.makedirs(out_dir) |
| 200 |
with open(out_manifest, "w") as manifest: |
| 201 |
manifest.write(MANIFEST_HEADER_V1) |
| 202 |
for info in path_map.values(): |
| 203 |
abs_dest = os.path.join(out_dir, info.dest) |
| 204 |
ensure_directory(os.path.dirname(abs_dest)) |
| 205 |
print("copy %r --> %r" % (info.src, abs_dest)) |
| 206 |
shutil.copy2(info.src, abs_dest) |
| 207 |
installed_dest = os.path.join(install_dir, info.dest) |
| 208 |
manifest.write("%s%s%s\n" % (installed_dest, MANIFEST_SEPARATOR, info.dest)) |
| 209 |
|
| 210 |
|
| 211 |
def parse_manifests(args): |
| 212 |
# Process args.manifest_separator to help support older versions of CMake |
| 213 |
if args.manifest_separator: |
| 214 |
manifests = [] |
| 215 |
for manifest_arg in args.manifests: |
| 216 |
split_arg = manifest_arg.split(args.manifest_separator) |
| 217 |
manifests.extend(split_arg) |
| 218 |
args.manifests = manifests |
| 219 |
|
| 220 |
path_map = {} |
| 221 |
for manifest in args.manifests: |
| 222 |
parse_manifest(manifest, path_map) |
| 223 |
|
| 224 |
return path_map |
| 225 |
|
| 226 |
|
| 227 |
def check_main_module(args, path_map): |
| 228 |
# Translate an empty string in the --main argument to None, |
| 229 |
# just to allow the CMake logic to be slightly simpler and pass in an |
| 230 |
# empty string when it really wants the default __main__.py module to be |
| 231 |
# used. |
| 232 |
if args.main == "": |
| 233 |
args.main = None |
| 234 |
|
| 235 |
if args.type == "lib-install": |
| 236 |
if args.main is not None: |
| 237 |
raise UsageError("cannot specify a --main argument with --type=lib-install") |
| 238 |
return |
| 239 |
|
| 240 |
main_info = path_map.get("__main__.py") |
| 241 |
if args.main: |
| 242 |
if main_info is not None: |
| 243 |
msg = ( |
| 244 |
"specified an explicit main module with --main, " |
| 245 |
"but the file listing already includes __main__.py" |
| 246 |
) |
| 247 |
raise BadManifestError( |
| 248 |
main_info.manifest_path, main_info.manifest_line, msg |
| 249 |
) |
| 250 |
parts = args.main.split(":") |
| 251 |
if len(parts) != 2: |
| 252 |
raise UsageError( |
| 253 |
"argument to --main must be of the form MODULE:CALLABLE " |
| 254 |
"(received %s)" % (args.main,) |
| 255 |
) |
| 256 |
else: |
| 257 |
if main_info is None: |
| 258 |
raise UsageError( |
| 259 |
"no main module specified with --main, " |
| 260 |
"and no __main__.py module present" |
| 261 |
) |
| 262 |
|
| 263 |
|
| 264 |
BUILD_TYPES = { |
| 265 |
"zipapp": build_zipapp, |
| 266 |
"dir": build_install_dir, |
| 267 |
"lib-install": install_library, |
| 268 |
} |
| 269 |
|
| 270 |
|
| 271 |
def main(): |
| 272 |
ap = argparse.ArgumentParser() |
| 273 |
ap.add_argument("-o", "--output", required=True, help="The output file path") |
| 274 |
ap.add_argument( |
| 275 |
"--install-dir", |
| 276 |
help="When used with --type=lib-install, this parameter specifies the " |
| 277 |
"final location where the library where be installed. This can be " |
| 278 |
"used to generate the library in one directory first, when you plan " |
| 279 |
"to move or copy it to another final location later.", |
| 280 |
) |
| 281 |
ap.add_argument( |
| 282 |
"--manifest-separator", |
| 283 |
help="Split manifest arguments around this separator. This is used " |
| 284 |
"to support older versions of CMake that cannot supply the manifests " |
| 285 |
"as separate arguments.", |
| 286 |
) |
| 287 |
ap.add_argument( |
| 288 |
"--main", |
| 289 |
help="The main module to run, specified as <module>:<callable>. " |
| 290 |
"This must be specified if and only if the archive does not contain " |
| 291 |
"a __main__.py file.", |
| 292 |
) |
| 293 |
ap.add_argument( |
| 294 |
"--python", |
| 295 |
help="Explicitly specify the python interpreter to use for the " "executable.", |
| 296 |
) |
| 297 |
ap.add_argument( |
| 298 |
"--type", choices=BUILD_TYPES.keys(), help="The type of output to build." |
| 299 |
) |
| 300 |
ap.add_argument( |
| 301 |
"manifests", |
| 302 |
nargs="+", |
| 303 |
help="The manifest files specifying how to construct the archive", |
| 304 |
) |
| 305 |
args = ap.parse_args() |
| 306 |
|
| 307 |
if args.python is None: |
| 308 |
args.python = sys.executable |
| 309 |
|
| 310 |
if args.type is None: |
| 311 |
# In the future we might want different default output types |
| 312 |
# for different platforms. |
| 313 |
args.type = "zipapp" |
| 314 |
build_fn = BUILD_TYPES[args.type] |
| 315 |
|
| 316 |
try: |
| 317 |
path_map = parse_manifests(args) |
| 318 |
check_main_module(args, path_map) |
| 319 |
except UsageError as ex: |
| 320 |
print("error: %s" % (ex,), file=sys.stderr) |
| 321 |
sys.exit(1) |
| 322 |
|
| 323 |
build_fn(args, path_map) |
| 324 |
|
| 325 |
|
| 326 |
if __name__ == "__main__": |
| 327 |
main() |