Last active
October 29, 2024 21:10
-
-
Save gabrielfeo/3f7d1b363920c875415184531fae9bfa to your computer and use it in GitHub Desktop.
Adds relative symlinks in the given directory, pointing to the specified files in the current directory. Useful to add symlinks to a nested Gradle build in order to open it separately in an IntelliJ IDE (but prefer making it an included build)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# pylint: disable=missing-function-docstring,invalid-name | |
""" | |
Adds relative symlinks in the given directory, pointing to the specified | |
files in the current directory. | |
For example, add symlinks to a nested Gradle build in order to open in | |
separately in an IntelliJ IDE: | |
$ ./add-relative-symlinks.py --dir ./tools/nested-gradle-build/ | |
./gradlew* ./gradle ./.idea/codeStyles | |
""" | |
from pathlib import Path | |
import argparse | |
import logging | |
from typing import List | |
def symlink_all(source_paths: List[Path], target_dir: Path, overwrite: bool): | |
for source in source_paths: | |
symlink(source, target_dir / source.name, overwrite) | |
def symlink(source_path: Path, link_path: Path, overwrite: bool): | |
try: | |
if overwrite: | |
link_path.unlink(missing_ok=True) | |
link_dir = link_path.parent.resolve() | |
source_path = source_path.resolve() | |
source_path = source_path.relative_to(link_dir, walk_up=True) | |
link_path.symlink_to( | |
target=source_path, | |
target_is_directory=source_path.is_dir(), | |
) | |
logging.info("Created symlink: %s -> %s", link_path, source_path) | |
except FileExistsError: | |
logging.warning("Symlink exists: %s (--overwrite?)", link_path) | |
except FileNotFoundError: | |
logging.error("File not found: %s", source_path) | |
def main(): | |
parser = argparse.ArgumentParser(description=__doc__) | |
parser.add_argument( | |
"--dir", | |
required=True, | |
type=Path, | |
help="The directory in which to create the symlinks", | |
) | |
parser.add_argument( | |
"paths", | |
nargs="+", | |
type=Path, | |
help="The target paths to create symlinks for", | |
) | |
parser.add_argument( | |
"--overwrite", | |
default=False, | |
action="store_true", | |
help="Overwrite existing symlinks", | |
) | |
args = parser.parse_args() | |
symlink_all(args.paths, args.dir, overwrite=args.overwrite) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment