Minor code cleanup master
authorMichael Petch <mpetch@capp-sysware.com>
Mon, 17 Aug 2015 18:17:02 +0000 (12:17 -0600)
committerMichael Petch <mpetch@capp-sysware.com>
Mon, 17 Aug 2015 18:17:02 +0000 (12:17 -0600)
extractxgdata.py
xgimport.py
xgutils.py
xgzarc.py

index 7811fb4..3724bc2 100755 (executable)
@@ -19,9 +19,6 @@
 #
 
 from __future__ import with_statement
-import sys
-import struct
-import uuid
 import os
 import argparse
 import xgimport
@@ -29,20 +26,19 @@ import xgzarc
 import xgstruct
 import pprint
 
-def parseoptsegments(parser, segments):
 
+def parseoptsegments(segparser, segments):
     segmentlist = segments.split(',')
-    for segment in segmentlist:
-        if segment not in ['all', 'comments', 'gdhdr', 'thumb', 'gameinfo',
-                           'gamefile', 'rollouts', 'idx']:
-            parser.error("%s is not a recognized segment" % segment)
+    for seg in segmentlist:
+        if seg not in ['all', 'comments', 'gdhdr', 'thumb', 'gameinfo',
+                       'gamefile', 'rollouts', 'idx']:
+            segparser.error("%s is not a recognized segment" % seg)
     return segmentlist
 
 
-def directoryisvalid(parser, dir):
-
-    if not os.path.isdir(dir):
-        parser.error("directory path '%s' doesn't exist" % dir)
+def directoryisvalid(dirparser, filedir):
+    if not os.path.isdir(filedir):
+        dirparser.error("directory path '%s' doesn't exist" % filedir)
     return dir
 
 
@@ -53,9 +49,9 @@ if __name__ == '__main__':
         formatter_class=argparse.RawTextHelpFormatter)
     parser.add_argument("-d", metavar='DIR', dest="outdir",
                         help="Directory to write segments to "
-                        "(Default is same directory as the import file)\n",
-                        type=lambda dir:
-                        directoryisvalid(parser, dir), default=None)
+                             "(Default is same directory as the import file)\n",
+                        type=lambda filedir:
+                        directoryisvalid(parser, filedir), default=None)
     parser.add_argument('files', metavar='FILE', type=str, nargs='+',
                         help='An XG file to import')
     args = parser.parse_args()
@@ -64,38 +60,38 @@ if __name__ == '__main__':
         xgbasepath = os.path.dirname(xgfilename)
         xgbasefile = os.path.basename(xgfilename)
         xgext = os.path.splitext(xgfilename)
-        if (args.outdir is not None):
+        if args.outdir is not None:
             xgbasepath = args.outdir
 
         try:
             xgobj = xgimport.Import(xgfilename)
-            print ('Processing file: %s' % xgfilename)
+            print('Processing file: %s' % xgfilename)
             fileversion = -1
             # To do: move this code to XGImport where it belongs
-            for segment in xgobj.getfilesegment():
+            for segment in xgobj.getfilesegment:
                 segment.copyto(os.path.abspath(
-                        os.path.join(xgbasepath,
-                        xgbasefile[:-len(xgext[1])] + segment.ext)))
+                    os.path.join(xgbasepath,
+                                 xgbasefile[:-len(xgext[1])] + segment.ext)))
 
                 if segment.type == xgimport.Import.Segment.XG_GAMEFILE:
                     segment.fd.seek(os.SEEK_SET, 0)
                     while True:
                         rec = xgstruct.GameFileRecord(
-                                version=fileversion).fromstream(segment.fd)
+                            version=fileversion).fromstream(segment.fd)
                         if rec is None:
                             break
                         if isinstance(rec, xgstruct.HeaderMatchEntry):
                             fileversion = rec.Version
                         elif isinstance(rec, xgstruct.UnimplementedEntry):
                             continue
-                        pprint.pprint (rec,width=160)
+                        pprint.pprint(rec, width=160)
                 elif segment.type == xgimport.Import.Segment.XG_ROLLOUTS:
                     segment.fd.seek(os.SEEK_SET, 0)
                     while True:
                         rec = xgstruct.RolloutFileRecord().fromstream(segment.fd)
                         if rec is None:
                             break
-                        pprint.pprint (rec,width=160)
+                        pprint.pprint(rec, width=160)
 
         except (xgimport.Error, xgzarc.Error) as e:
-            print (e.value)
+            print(e.value)
index a0ffc94..be23ed8 100644 (file)
 from __future__ import with_statement as _with
 import tempfile as _tempfile
 import shutil as _shutil
-import struct as _struct
 import os as _os
-import xgutils as _xgutils
+
 import xgzarc as _xgzarc
 import xgstruct as _xgstruct
 
 
 class Import(object):
-
     class Segment(object):
         GDF_HDR, GDF_IMAGE, XG_GAMEHDR, XG_GAMEFILE, XG_ROLLOUTS, XG_COMMENT, \
             ZLIBARC_IDX, XG_UNKNOWN = range(8)
         EXTENSIONS = ['_gdh.bin', '.jpg', '_gamehdr.bin', '_gamefile.bin',
                       '_rollouts.bin', '_comments.bin', '_idx.bin', None]
-        GDF_HDR_EXT, GDF_IMAGE_EXT, XG_GAMEHDR_EXT, XG_GAMEFILE_EXT, \
-            XG_ROLLOUTS_EXT, XG_COMMENTS_EXT, \
-            XG_IDX_EXT, XG_UNKNOWN = EXTENSIONS
+        GDF_HDR_EXT, GDF_IMAGE_EXT, XG_GAMEHDR_EXT, XG_GAMEFILE_EXT, XG_ROLLOUTS_EXT, \
+            XG_COMMENTS_EXT, XG_IDX_EXT, XG_UNKNOWN_EXT = EXTENSIONS
         XG_FILEMAP = {'temp.xgi': XG_GAMEHDR, 'temp.xgr': XG_ROLLOUTS,
                       'temp.xgc': XG_COMMENT, 'temp.xg': XG_GAMEFILE}
 
@@ -71,12 +68,12 @@ class Import(object):
                 if self.__autodelete and self.filename is not None and \
                         _os.path.exists(self.filename):
                     try:
-                        _os.unlink(self.filename)
+                        _os.unlink(str(self.filename))
                     finally:
                         self.filename = None
 
         def copyto(self, fileto):
-            _shutil.copy(self.filename, fileto)
+            _shutil.copy(str(self.filename), fileto)
 
         def createtempfile(self, mode="w+b"):
             self.fd, self.filename = _tempfile.mkstemp(prefix=self.__prefix)
@@ -86,15 +83,16 @@ class Import(object):
     def __init__(self, filename):
         self.filename = filename
 
+    @property
     def getfilesegment(self):
         with open(self.filename, "rb") as xginfile:
             # Extract the uncompressed Game Data Header (GDH)
             # Note: MS Windows Vista feature
             gdfheader = \
-                    _xgstruct.GameDataFormatHdrRecord().fromstream(xginfile)
+                _xgstruct.GameDataFormatHdrRecord().fromstream(xginfile)
             if gdfheader is None:
                 raise Error("Not a game data format file", self.filename)
-            
+
             # Extract the Game Format Header to a temporary file
             with Import.Segment(type=Import.Segment.GDF_HDR) as segment:
                 xginfile.seek(0)
@@ -104,7 +102,7 @@ class Import(object):
                 yield segment
 
             # Extract the uncompressed thumbnail JPEG from the GDF hdr
-            if (gdfheader.ThumbnailSize > 0):
+            if gdfheader.ThumbnailSize > 0:
                 with Import.Segment(type=Import.Segment.GDF_IMAGE) as segment:
                     xginfile.seek(gdfheader.ThumbnailOffset, _os.SEEK_CUR)
                     imgbuf = xginfile.read(gdfheader.ThumbnailSize)
@@ -132,8 +130,8 @@ class Import(object):
                 # the magic number to ensure it is valid
                 if xg_filetype == Import.Segment.XG_GAMEFILE:
                     segment_file.seek(Import.Segment.XG_GAMEHDR_LEN)
-                    magicStr = bytearray(segment_file.read(4)).decode('ascii')
-                    if magicStr != 'DMLI':
+                    magicstr = bytearray(segment_file.read(4)).decode('ascii')
+                    if magicstr != 'DMLI':
                         raise Error("Not a valid XG gamefile", self.filename)
 
                 yield xg_filesegment
@@ -145,7 +143,6 @@ class Import(object):
 
 
 class Error(Exception):
-
     def __init__(self, error, filename):
         self.value = "XG Import Error processing '%s': %s" % \
                      (filename, str(error))
index fecb618..e6c20bc 100644 (file)
@@ -67,7 +67,7 @@ def utf16intarraytostr3x(intarray):
             break
         newstr += [chr(intval).encode('utf-8')]
 
-    return (b''.join([x for x in newstr]))
+    return b''.join([x for x in newstr])
 
 
 def utf16intarraytostr2x(intarray):
@@ -82,6 +82,8 @@ def utf16intarraytostr2x(intarray):
 
     return ''.join(newstr)
 
+
+
 def delphidatetimeconv(delphi_datetime):
     """Convert a double float Delphi style timedate object to a Python
     datetime object. Delphi uses the number of days since
@@ -115,4 +117,3 @@ else:
         utf16intarraytostr = utf16intarraytostr3x
     else:
         utf16intarraytostr = utf16intarraytostr2x
-
index 961d98d..5a005c0 100644 (file)
--- a/xgzarc.py
+++ b/xgzarc.py
@@ -190,10 +190,10 @@ class ZlibArchive(object):
 
     def __getarchiveindex(self):
 
+        curstreampos = self.stream.tell()
         try:
             # Advance to the archive record at the end and retrieve it
             filerecords = []
-            curstreampos = self.stream.tell()
 
             self.stream.seek(-ArchiveRecord.SIZEOFREC, _os.SEEK_END)
             self.endofarcdata = self.stream.tell()