pythonwise / unpack

#!/usr/bin/env python
'''Unpack compressed files'''

__author__ = "Miki Tebeka <miki.tebeka@gmail.com>"

from os import system
from os.path import splitext, isfile
from sys import stderr, version_info
if float("%s.%s" % version_info[:2]) < 2.3:
    raise SystemExit("need at least Python 2.3 to run")

from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] FILE[s]")
parser.add_option("-f", "--find", help="just find program, don't unpack",
    dest="find", action="store_true", default=0)

opts, args = parser.parse_args()
if not args:
    parser.error("wrong number of arguments") # Will exit

def _stdout(cmd, file):
    return "%s \"%s\" > %s" % (cmd, file, splitext(file)[0])

def bz(file):
    return _stdout("bzip2 -d -c", file)

def gz(file):
    return _stdout("gunzip -c", file)

EXTS = []
def register(func, *extensions):
    for ext in extensions:
        EXTS.append((ext.lower(), func))

register("tar -xzvf", ".tar.gz", ".tgz", ".tar.Z")
register("tar -xjvf", ".tar.bz", ".tar.bz2", ".tbz")
register(bz, ".bz", ".bz2")
register("tar -xvf", ".tar")
register("unzip", ".zip", "jar", "egg")
register("unarj", ".arj")
register(gz, ".gz", ".Z")
register("unrar x", ".rar")
register("7za x", ".7z")

# We sort by length of extension, longest first
EXTS.sort(lambda e1, e2: cmp(len(e2[0]), len(e1[0])))

err = 0
for file in args:
    if (not opts.find) and (not isfile(file)):
        print >> stderr, "error: can't find", file
        err = 1
        continue
    fl = file.lower()
    for ext, cmd in EXTS:
        if fl.endswith(ext):
            if callable(cmd):
                cmd = cmd(file)
            else:
                cmd = "%s \"%s\"" % (cmd, file)
            if opts.find:
                print "%s: %s" % (file, cmd)
            else:
                if system(cmd) != 0:
                    err = 1
            break
    else:
        print "error: can't find a program to extract", file
        err = 1

raise SystemExit(err)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.