|
6 | 6 | import os
|
7 | 7 | import re
|
8 | 8 | import shlex
|
| 9 | +import shutil |
9 | 10 | import ssl
|
10 | 11 | import subprocess
|
11 | 12 | import sys
|
@@ -359,6 +360,40 @@ def extract_tar(tar_src: Path, dest: Path) -> None:
|
359 | 360 | tar_.extractall(dest)
|
360 | 361 |
|
361 | 362 |
|
| 363 | +def move_file(src_file: Path, dst_file: Path) -> Path: |
| 364 | + """Moves a file safely while avoiding potential semantic confusion: |
| 365 | +
|
| 366 | + 1. `dst_file` must point to the target filename, not a directory |
| 367 | + 2. `dst_file` will be overwritten if it already exists |
| 368 | + 3. any missing parent directories will be created |
| 369 | +
|
| 370 | + Returns the fully resolved Path of the resulting file. |
| 371 | +
|
| 372 | + Raises: |
| 373 | + NotADirectoryError: If any part of the intermediate path to `dst_file` is an existing file |
| 374 | + IsADirectoryError: If `dst_file` points directly to an existing directory |
| 375 | + """ |
| 376 | + |
| 377 | + # Importing here as logger needs various functions from util -> circular imports |
| 378 | + from .logger import log |
| 379 | + |
| 380 | + src_file = src_file.resolve() |
| 381 | + dst_file = dst_file.resolve() |
| 382 | + |
| 383 | + if dst_file.is_dir(): |
| 384 | + msg = "dst_file must be a valid target filename, not an existing directory." |
| 385 | + raise IsADirectoryError(msg) |
| 386 | + dst_file.unlink(missing_ok=True) |
| 387 | + dst_file.parent.mkdir(parents=True, exist_ok=True) |
| 388 | + |
| 389 | + # using shutil.move() as Path.rename() is not guaranteed to work across filesystem boundaries |
| 390 | + # explicit str() needed for Python 3.8 |
| 391 | + resulting_file = shutil.move(str(src_file), str(dst_file)) |
| 392 | + resulting_file = Path(resulting_file).resolve() |
| 393 | + log.notice(f"Moved {src_file} to {resulting_file}") |
| 394 | + return Path(resulting_file) |
| 395 | + |
| 396 | + |
362 | 397 | class DependencyConstraints:
|
363 | 398 | def __init__(self, base_file_path: Path):
|
364 | 399 | assert base_file_path.exists()
|
|
0 commit comments