xref: /aosp_15_r20/external/bazelbuild-rules_python/gazelle/manifest/copy_to_source.py (revision 60517a1edbc8ecf509223e9af94a7adec7d736b8)
1"""Copy a generated file to the source tree.
2
3Run like:
4    copy_to_source path/to/generated_file path/to/source_file_to_overwrite
5"""
6
7import os
8import shutil
9import stat
10import sys
11from pathlib import Path
12
13
14def copy_to_source(generated_relative_path: Path, target_relative_path: Path) -> None:
15    """Copy the generated file to the target file path.
16
17    Expands the relative paths by looking at Bazel env vars to figure out which absolute paths to use.
18    """
19    # This script normally gets executed from the runfiles dir, so find the absolute path to the generated file based on that.
20    generated_absolute_path = Path.cwd() / generated_relative_path
21
22    # Similarly, the target is relative to the source directory.
23    target_absolute_path = os.getenv("BUILD_WORKSPACE_DIRECTORY") / target_relative_path
24
25    print(f"Copying {generated_absolute_path} to {target_absolute_path}")
26    target_absolute_path.parent.mkdir(parents=True, exist_ok=True)
27    shutil.copy(generated_absolute_path, target_absolute_path)
28
29    target_absolute_path.chmod(0o664)
30
31
32if __name__ == "__main__":
33    if len(sys.argv) != 3:
34        sys.exit("Usage: copy_to_source <generated_file> <target_file>")
35
36    copy_to_source(Path(sys.argv[1]), Path(sys.argv[2]))
37