• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2#
3# Copyright (C) 2021 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#   http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16"""A script to copy outputs from Bazel rules to a user specified dist directory.
17
18This script is only meant to be executed with `bazel run`. `bazel build <this
19script>` doesn't actually copy the files, you'd have to `bazel run` a
20copy_to_dist_dir target.
21
22This script copies files from Bazel's output tree into a directory specified by
23the user. It does not check if the dist dir already contains the file, and will
24simply overwrite it.
25
26One approach is to wipe the dist dir every time this script runs, but that may
27be overly destructive and best left to an explicit rm -rf call outside of this
28script.
29
30Another approach is to error out if the file being copied already exist in the
31dist dir, or perform some kind of content hash checking.
32"""
33
34import argparse
35import glob
36import os
37import shutil
38import sys
39import tarfile
40
41
42def files_to_dist(pattern):
43    # Assume that dist.bzl is in the same package as dist.py
44    runfiles_directory = os.path.dirname(__file__)
45    dist_manifests = glob.glob(
46        os.path.join(runfiles_directory, pattern))
47    if not dist_manifests:
48        print("Warning: could not find a file with pattern " + pattern +
49              " in the runfiles directory: %s" % runfiles_directory)
50    files_to_dist = []
51    for dist_manifest in dist_manifests:
52        with open(dist_manifest, "r") as f:
53            files_to_dist += [line.strip() for line in f]
54    return files_to_dist
55
56
57def copy_files_to_dist_dir(files, archives, dist_dir, flat, prefix,
58    archive_prefix):
59
60    for src in files:
61        src_relpath = os.path.basename(src) if flat else src
62        src_relpath = os.path.join(prefix, src_relpath)
63        src_abspath = os.path.abspath(src)
64
65        dst = os.path.join(dist_dir, src_relpath)
66        if os.path.isfile(src):
67            dst_dirname = os.path.dirname(dst)
68            print("[dist] Copying file: %s" % dst)
69            if not os.path.exists(dst_dirname):
70                os.makedirs(dst_dirname)
71
72            shutil.copyfile(src_abspath, dst, follow_symlinks=True)
73        elif os.path.isdir(src):
74            print("[dist] Copying dir: %s" % dst)
75            shutil.copytree(src_abspath, dst)
76
77    for archive in archives:
78        try:
79            with tarfile.open(archive) as tf:
80                dst_dirname = os.path.join(dist_dir, archive_prefix)
81                print("[dist] Extracting archive: {} -> {}".format(archive,
82                                                                   dst_dirname))
83                tf.extractall(dst_dirname)
84        except tarfile.TarError:
85            # toybox does not support creating empty tar files, hence the build
86            # system may use empty files as empty archives.
87            if os.path.getsize(archive) == 0:
88                print("Warning: skipping empty tar file: {}".format(archive))
89                continue
90             # re-raise if we do not know anything about this error
91            raise
92
93
94def main():
95    parser = argparse.ArgumentParser(
96        description="Dist Bazel output files into a custom directory.")
97    parser.add_argument(
98        "--dist_dir", required=True, help="""path to the dist dir.
99            If relative, it is interpreted as relative to Bazel workspace root
100            set by the BUILD_WORKSPACE_DIRECTORY environment variable, or
101            PWD if BUILD_WORKSPACE_DIRECTORY is not set.""")
102    parser.add_argument(
103        "--flat",
104        action="store_true",
105        help="ignore subdirectories in the manifest")
106    parser.add_argument(
107        "--prefix", default="",
108        help="path prefix to apply within dist_dir for copied files")
109    parser.add_argument(
110        "--archive_prefix", default="",
111        help="Path prefix to apply within dist_dir for extracted archives. " +
112             "Supported archives: tar.")
113
114    args = parser.parse_args(sys.argv[1:])
115
116    if not os.path.isabs(args.dist_dir):
117        # BUILD_WORKSPACE_DIRECTORY is the root of the Bazel workspace containing
118        # this binary target.
119        # https://docs.bazel.build/versions/main/user-manual.html#run
120        args.dist_dir = os.path.join(
121            os.environ.get("BUILD_WORKSPACE_DIRECTORY"), args.dist_dir)
122
123    files = files_to_dist("*_dist_manifest.txt")
124    archives = files_to_dist("*_dist_archives_manifest.txt")
125    copy_files_to_dist_dir(files, archives, **vars(args))
126
127
128if __name__ == "__main__":
129    main()
130