http://scons.tigris.org/issues/show_bug.cgi?id=2329
[scons.git] / bin / scons-unzip.py
1 #!/usr/bin/env python
2 #
3 # A quick script to unzip a .zip archive and put the files in a
4 # subdirectory that matches the basename of the .zip file.
5 #
6 # This is actually generic functionality, it's not SCons-specific, but
7 # I'm using this to make it more convenient to manage working on multiple
8 # changes on Windows, where I don't have access to my Aegis tools.
9 #
10
11 import getopt
12 import os.path
13 import sys
14 import zipfile
15
16 helpstr = """\
17 Usage: scons-unzip.py [-o outdir] zipfile
18 Options:
19   -o DIR, --out DIR           Change output directory name to DIR
20   -v, --verbose               Print file names when extracting
21 """
22
23 opts, args = getopt.getopt(sys.argv[1:],
24                            "o:v",
25                            ['out=', 'verbose'])
26
27 outdir = None
28 printname = lambda x: x
29
30 for o, a in opts:
31     if o == '-o' or o == '--out':
32         outdir = a
33     elif o == '-v' or o == '--verbose':
34         def printname(x):
35             print x
36
37 if len(args) != 1:
38     sys.stderr.write("scons-unzip.py:  \n")
39     sys.exit(1)
40
41 zf = zipfile.ZipFile(str(args[0]), 'r')
42
43 if outdir is None:
44     outdir, _ = os.path.splitext(os.path.basename(args[0]))
45
46 def outname(n, outdir=outdir):
47     l = []
48     while True:
49         n, tail = os.path.split(n)
50         if not n:
51             break
52         l.append(tail)
53     l.append(outdir)
54     l.reverse()
55     return os.path.join(*l)
56
57 for name in zf.namelist():
58     dest = outname(name)
59     dir = os.path.dirname(dest)
60     try:
61         os.makedirs(dir)
62     except:
63         pass
64     printname(dest)
65     # if the file exists, then delete it before writing
66     # to it so that we don't end up trying to write to a symlink:
67     if os.path.isfile(dest) or os.path.islink(dest):
68         os.unlink(dest)
69     if not os.path.isdir(dest):
70         open(dest, 'w').write(zf.read(name))
71
72 # Local Variables:
73 # tab-width:4
74 # indent-tabs-mode:nil
75 # End:
76 # vim: set expandtab tabstop=4 shiftwidth=4: