Add new script link_directory

This commit is contained in:
2024-04-03 21:59:26 +08:00
parent abd4a19573
commit ef12172c7b
4 changed files with 109 additions and 1 deletions

40
link_directory.py Normal file
View File

@@ -0,0 +1,40 @@
from argparse import ArgumentParser
from os.path import exists, isdir, join
from os import makedirs, listdir, link
p = ArgumentParser(description='Link files in a directory to another directory.') # noqa: E501
p.add_argument('-a', '--all', help='Include all files.', action='store_true') # noqa: E501
p.add_argument('input', help='The path to the input directory.')
p.add_argument('output', help='The path to the output directory.')
def hardlink_files(input: str, output: str, all: bool):
if exists(input) and not isdir(input):
raise ValueError(f"{input} is not a directory.")
if exists(output) and not isdir(output):
raise ValueError(f"{output} is not a directory.")
if not exists(output):
makedirs(output)
for f in listdir(input):
if not all and f.startswith('.'):
continue
src = join(input, f)
dst = join(output, f)
if isdir(src):
hardlink_files(src, dst, all)
continue
if exists(dst):
print(f"{dst} already exists.")
continue
print(f"Linking {src} to {dst}.")
link(src, dst)
def main(args=None):
arg = p.parse_intermixed_args(args)
hardlink_files(arg.input, arg.output, arg.all)
if __name__ == '__main__':
main()