# sapdbUnpack.py import sys import string import re import os def outfileName (options, fname): if options.outfile: return options.outfile base = os.path.basename (fname) if base [-1] == 'c': result = base + '.c' elif base [-1] == 'a': if os.name == 'unix': result = base + '.s' else: result = base + '.asm' else: result = base + '.pas' return os.path.join (options.outdir, result) startBlock = '\n' + r'\s*%s\s*:' endBlock = '[.]CM [*]-END-[*] %s -------' defineStartRE = re.compile (startBlock % 'define', re.I) defineEndRE = re.compile (endBlock % 'define', re.I) codeStartRE = re.compile (startBlock % 'code', re.I) codeEndRE = re.compile (endBlock % 'code', re.I) def extractBlock (source, startRE, endRE): match = startRE.search (source) if not match: return '' blockStart = match.end () match = endRE.search (source, blockStart) assert match blockEnd = match.start () return source [blockStart:blockEnd] def sapdbUnpack (options, fname): outfile = outfileName (options, fname) data = open (fname, 'rt').read () definition = extractBlock (data, defineStartRE, defineEndRE) code = extractBlock (data, codeStartRE, codeEndRE) print fname, '=>', outfile open (outfile, 'wt').write (definition + code) def patchOptions (options): if os.path.isdir (options.output): options.outdir = options.output options.outfile = None else: options.outdir = '.' options.outfile = options.output def main (options, args): """extract source from module frame Unless specified with -o, the name of the output file is given the proper extension """ patchOptions (options) rc = 0 for arg in args: if not os.path.exists (arg): sys.stderr.write (arg + ' does not exist\n') rc = 1 continue ext = os.path.splitext (arg) [1] if ext: sys.stderr.write (arg + ' skipped\n') continue sapdbUnpack (options, arg) sys.exit (rc) def _options (): return [ # (optstring, varname, typechar, default, help) ('o', 'output', ':', '.', 'output file or output dir'), ] if __name__ == '__main__': import optlib optlib.optMain2 (main, _options ())