#!/usr/bin/env python """ MPAK package handling utility Version 1.4 (Python-implementation) Copyright (c) 2008, Mika Halttunen. This command line tool allows creation and extraction of MPAK (.mpk) packages used in several of my games. MPAK is a simple WAD-like file format of mine, that allows storing the game data in one single .mpk file. I originally had a very crude command line program bit like this one (written in C++), and decided to write this Python-implementation as an Python-programming excercise. So, it's my first Python program. :) Version history: v1.4: The first Python version v1.0 -- v1.31: The original C++ implementation """ import getopt, sys import os import traceback import struct import binascii import fnmatch import shutil from ctypes import c_uint32 def usage(): """ Prints the program usage. """ print("MPAK package handling utility") print("Version 1.4 (Python-implementation)") print("Copyright (c) 2008, Mika Halttunen.") print("") print("Usage:", sys.argv[0],"[switch]","-f pakfile.mpk","[file1]","[file2]", "[...]", "[fileN]") print("where [switch] is one of the following:") print(" -f, --file=FILE Use package FILE") print(" -c, --create Create a new package with files 'file1' to 'fileN'") print(" -l, --list List the files from given package") print(" -e, --extract Extract all files (by default) from given package. If you") print(" want to only extract some specific files, you can name") print(" them individually, and/or use wildcards (i.e. *.png).") print(" You can supply path where to extract with -p.") print(" -p, --path=PATH Extract to PATH (created if doesn't exist)") print(" -h, --help Print this usage text") print("") def errorMsg(msg): """ Prints an error message and exits. """ try: pos = traceback.extract_stack(limit=2) if pos: print("ERROR: In %s:%s, line %d:" % (pos[0][0], pos[0][2], pos[0][1])) else: print("ERROR:") print("\t",msg) except: if __debug__: traceback.print_exc() pass sys.exit(2) def separator(): """ Prints the separator line. """ print("-"*75) def computeCRC(file, offset): """ Computes the CRC32 for the file, starting at given offset. """ f = open(file, "rb") f.seek(offset) crc = 0 # Compute a running CRC32 for the file in 16kb chunks while True: buffer = f.read(16384) if not buffer: break # End of file crc = binascii.crc32(buffer, crc) f.close() return crc def createPackage(pakFile, files): """ Creates a new MPAK package. This copies the given files into the new package file, writes the file table and closes the package. MPAK doesn't support adding new files to an existing package. """ print("Creating '%s'.." % pakFile) if len(files) < 1: errorMsg("No input files specified!") separator() # Open the package file for writing out = open(pakFile, "wb") # Write the header and reserve 4+4 bytes for CRC32 and file table offset out.write(b"MPK1") out.write(b"."*8) # Write each file package = { "fileNames": [], "fileOffsets": [] } count = 0 for file in files: # Get the basename filename = os.path.basename(file) print(" <%s..." % filename, end=' ') package["fileNames"].append(filename) # Get the file size in bytes stats = os.stat(file) # Store the current offset package["fileOffsets"].append(out.tell()) # Open the file and copy its contents f = open(file, "rb") shutil.copyfileobj(f, out, 16384) f.close() print("OK. (%.1f KB)" % (stats.st_size / 1024.0)) count = count + 1 separator() # Grab the file table offset and write the table ftOffset = out.tell() # Write the number of files out.write(struct.pack(" 0: for filter in filters: if fnmatch.fnmatch(package["fileNames"][i], filter): break else: continue print(" >%s..." % package["fileNames"][i], end=' ') # Seek to the correct offset f.seek(package["fileOffsets"][i]) # Open a new file for writing, and write the file out in 16kb chunks out = open(os.path.join(path, package["fileNames"][i]), "wb") bytesWritten = 0 bytesTotal = package["fileSizes"][i]; while True: # We have to watch not to write too much bytesLeft = bytesTotal - bytesWritten if bytesLeft > 16384: bytesLeft = 16384 buffer = f.read(bytesLeft) out.write(buffer) bytesWritten = bytesWritten + bytesLeft if bytesWritten == bytesTotal: break out.close() print("OK.") count = count + 1 f.close() separator() print("%d (of %d) files extracted to %s." % (count, package["numFiles"], path)) def main(): """ Main method. """ try: # Get the optiosn opts, args = getopt.getopt(sys.argv[1:], "f:clep:h", ["file=", "create", "list", "extract", "path=", "help"]) except getopt.GetoptError as err: # Print the program usage and exit print("ERROR: " + str(err)) usage() sys.exit(2) extractPath = os.getcwd() pakFile = None action = None # Handle the options for o, a in opts: if o in ("-f", "--file"): pakFile = a # Grab the pakfile elif o in ("-c", "--create"): action = "create" elif o in ("-l", "--list"): action = "list" elif o in ("-e", "--extract"): action = "extract" elif o in ("-p", "--path"): extractPath = a # Grab the path elif o in ("-h", "--help"): usage() sys.exit() else: assert False, "Unhandled option" # Check that we got a pakfile if pakFile == None: usage() sys.exit(2) if action == "create": createPackage(pakFile, args) elif action == "list": listPackage(pakFile) elif action == "extract": extractPackage(pakFile, extractPath, args) else: usage() sys.exit() if __name__ == "__main__": main()