Last active
August 29, 2015 14:13
-
-
Save n6g7/9f3627c077b947a33610 to your computer and use it in GitHub Desktop.
Recursive file linker
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/python | |
import argparse | |
import os | |
parser = argparse.ArgumentParser() | |
parser.add_argument('dir', help='source directory') | |
parser.add_argument('-e', '--ext', help='extensions to link', nargs='+', default='mp4') | |
parser.add_argument('-s', '--sym', help='use symlinks instead of hard links', action="store_true") | |
parser.add_argument('-i', '--interactive', help='use interactive mode', action='store_true') | |
parser.add_argument('-v', '--verbose', help='output verbosity', type=int, choices = [0,1,2,3], default=1) | |
def link(root, name, sym=False, verbose=False): | |
"""Links the file at root/name to the current directory. | |
Supports hard and symlinks. Optional verbosity. | |
""" | |
source = os.path.join(root, name) | |
if sym: | |
os.symlink(source, name) | |
else: | |
os.link(source, name) | |
if verbose: | |
print 'Linked %s' % os.path.relpath(source) | |
if __name__ == '__main__': | |
args = parser.parse_args() | |
cnt = 0 | |
source_dir = os.path.abspath(args.dir) | |
detailed_count = {} | |
for root, dirs, files in os.walk(source_dir): | |
detailed_count[root] = 0 | |
inter_printed_cdir = False | |
for name in files: | |
if args.interactive: | |
for e in args.ext: | |
if name.endswith(e): | |
if not inter_printed_cdir: | |
print root | |
inter_printed_cdir = True | |
res = raw_input(' %s ' % name) | |
if res is 'y': | |
link(root, name, sym=args.sym, verbose=args.verbose >= 3) | |
detailed_count[root] += 1 | |
else: | |
for e in args.ext: | |
if name.endswith(e): | |
link(root, name, sym=args.sym, verbose=args.verbose >= 3) | |
detailed_count[root] += 1 | |
break | |
cnt += detailed_count[root] | |
if args.verbose >= 1: | |
if args.verbose >= 3 or args.interactive: print '------' | |
print 'Linked %s files from %s' % (cnt, source_dir) | |
if args.verbose >= 2: | |
for root in detailed_count: | |
if detailed_count[root] > 0: | |
print ' %s : %s' % (os.path.relpath(root), detailed_count[root]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment