Skip to content

Instantly share code, notes, and snippets.

@jcarletto27
Last active August 15, 2024 02:01
Show Gist options
  • Save jcarletto27/2a3f0e959aac919998d1e8a5b314aea0 to your computer and use it in GitHub Desktop.
Save jcarletto27/2a3f0e959aac919998d1e8a5b314aea0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# python script to search a folder for directories beginning with a string pattern
# and create a symlink, I use this for splitting out my Libation audible accounts
# for different libraries on AudioBookShelf
# can be used standalone or from the companion shell script proc_library.sh
import os
import sys
import subprocess
def create_symlink(source, target):
try:
# Ensure the source path exists
if not os.path.exists(source):
print(f"Source directory {source} does not exist.")
return
# Create a symbolic link at the target location pointing to the source
if not os.path.exists(target):
subprocess.run(["cp", "-asr", source, target], check=True)
print(f"Created symlink: {target} -> {source}")
return
except subprocess.CalledProcessError as e:
print(f"Failed to create symlink: {e}")
def find_pattern_dirs(root_dir, pattern):
pattern_dirs = []
for root, dirs, files in os.walk(root_dir):
for dir_name in dirs:
if dir_name.startswith(pattern):
pattern_dirs.append(os.path.join(root, dir_name))
return pattern_dirs
def create_directory(dir_path):
try:
# Check if the directory already exists
if not os.path.exists(dir_path):
# Create the directory if it does not exist
os.makedirs(dir_path)
print(f"Directory {dir_path} created.")
except OSError as e:
print(f"Error creating directory {dir_path}: {e}")
def main():
if len(sys.argv) != 4:
print(
"Usage: python script.py <source_directory> <target_directory> <trigger pattern>"
)
sys.exit(1)
source_dir = sys.argv[1]
target_dir = sys.argv[2]
pattern = sys.argv[3]
create_directory(target_dir)
pattern_dirs = find_pattern_dirs(source_dir, pattern)
for src in pattern_dirs:
relative_path = os.path.relpath(src, source_dir)
target_path = os.path.join(target_dir, os.path.basename(relative_path))
create_symlink(src, target_path)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment