|
| 1 | +import argparse |
| 2 | +import sysconfig |
| 3 | +import shutil |
| 4 | +import os |
| 5 | +import sys |
| 6 | + |
| 7 | +def add_rust_prefix(p): |
| 8 | + base, ext = os.path.splitext(p) |
| 9 | + return f"{base}-rust{ext}" |
| 10 | + |
| 11 | +def is_executable(p): |
| 12 | + """ Cross-platform check for executable files. """ |
| 13 | + if os.path.isfile(p) and os.access(p, os.X_OK): |
| 14 | + return True |
| 15 | + return os.name == "nt" and p.lower().endswith((".exe", ".bat", ".cmd", ".com")) |
| 16 | + |
| 17 | +def build(target_dir, python_bin_dir): |
| 18 | + |
| 19 | + if not os.path.exists(target_dir): |
| 20 | + print(f"Error: {target_dir} does not exist. Did you run `cargo build --release`?", file=sys.stderr) |
| 21 | + sys.exit(1) |
| 22 | + |
| 23 | + os.makedirs(python_bin_dir, exist_ok=True) |
| 24 | + |
| 25 | + for file_name in os.listdir(target_dir): |
| 26 | + src_file = os.path.join(target_dir, file_name) |
| 27 | + dst_file = add_rust_prefix(os.path.join(python_bin_dir, file_name)) |
| 28 | + |
| 29 | + if is_executable(src_file): |
| 30 | + shutil.copy(src_file, dst_file) |
| 31 | + |
| 32 | +def clean(target_dir, python_bin_dir): |
| 33 | + if not os.path.exists(python_bin_dir) or not os.path.exists(target_dir): |
| 34 | + return |
| 35 | + |
| 36 | + for file_name in os.listdir(target_dir): |
| 37 | + dst_file = add_rust_prefix(os.path.join(python_bin_dir, file_name)) |
| 38 | + if is_executable(dst_file): |
| 39 | + os.remove(dst_file) |
| 40 | + |
| 41 | +def main(args): |
| 42 | + |
| 43 | + python_bin_dir = sysconfig.get_path("scripts") |
| 44 | + |
| 45 | + if not python_bin_dir: |
| 46 | + python_bin_dir = os.path.dirname(sys.executable) |
| 47 | + |
| 48 | + if args.clean: |
| 49 | + clean(args.target_dir, python_bin_dir) |
| 50 | + else: |
| 51 | + build(args.target_dir, python_bin_dir) |
| 52 | + |
| 53 | +def parse_args(): |
| 54 | + parser = argparse.ArgumentParser() |
| 55 | + |
| 56 | + parser.add_argument("--clean", action='store_true', default=False) |
| 57 | + parser.add_argument("target_dir", type=str, default=os.path.join("target", "release"), nargs='?') |
| 58 | + |
| 59 | + return parser.parse_args() |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + args = parse_args() |
| 63 | + main(args) |
0 commit comments