4 # USAGE: mass-link.py [--prepend-suffix SUFFIX] symbolic | hard SOURCEDIR DESTDIR FILES
6 # create hard or symbolic links to SOURCEDIR/FILES in DESTDIR
8 # If symbolic or hard links are not provided by the operating system,
9 # copies will be made instead. However, if the operating system
10 # support symbolic or hard links, then this program expects to
11 # operate on a filesystem which supports them too.
13 # If --prepend-suffix is specified, link to foo.bar will be called
14 # fooSUFFIX.bar. Shell wildcards expansion is performed on FILES.
16 # No check is performed on FILES type; in particular, if FILES
17 # expansions contain a directory and hard links are requested,
18 # this program may fail non-gracefully.
20 # Attempts to make hard links across different filesystems are
21 # caught and replaced by copies.
29 optlist, args = getopt.getopt (sys.argv[1:], '', ['prepend-suffix='])
30 link_type, source_dir, dest_dir = args[0:3]
33 source_dir = os.path.normpath (source_dir)
34 dest_dir = os.path.normpath (dest_dir)
38 if x[0] == '--prepend-suffix':
39 prepended_suffix = x[1]
42 def insert_suffix (p):
45 l[-2] += prepended_suffix
47 return p + prepended_suffix
49 insert_suffix = lambda p: p
51 if link_type == 'symbolic':
52 if hasattr (os, 'symlink'):
56 elif link_type == 'hard':
57 if hasattr (os, 'link'):
62 sys.stderr.write(sys.argv[0] + ': ' + link_type + ": wrong argument, expected 'symbolic' or 'hard'\n")
67 sourcefiles += (glob.glob (os.path.join (source_dir, pattern)))
69 def relative_path (f):
72 return f[len (source_dir) + 1:]
74 destfiles = [os.path.join (dest_dir, insert_suffix (relative_path (f))) for f in sourcefiles]
76 destdirs = set ([os.path.dirname (dest) for dest in destfiles])
77 [os.makedirs (d) for d in destdirs if not os.path.exists (d)]
79 def force_link (src,dest):
80 if os.path.exists (dest):
84 except OSError, e: # can't use "as" because GUB has python 2.4.5.
86 shutil.copy (src, dest)
91 map (force_link, sourcefiles, destfiles)