Bidirectional Rhqx

This commit is contained in:
Elliot Nunn 2019-08-18 21:44:46 +08:00
parent 7b25e03e64
commit 123cd3294e

View File

@ -1,22 +1,58 @@
import os
from os import path from os import path
import argparse import argparse
import macresources import macresources
from macresources import binhex from macresources import binhex
parser = argparse.ArgumentParser(description=''' parser = argparse.ArgumentParser(description='''
Convert a "rdump" file (provide base name) to hqx Supply base name to convert datafork+rdump+idump to HQX.
Supply base.hqx name to convert HQX to datafork+rdump+idump.
''') ''')
parser.add_argument('srcfile', help='base name (.rdump/.idump should be alongside)') parser.add_argument('srcfile', nargs='*', help='base or base.hqx')
args = parser.parse_args() args = parser.parse_args()
for srcfile in args.srcfile:
# Case 1: from BinHex
if path.splitext(path.basename(srcfile))[1].lower() == '.hqx':
hb = binhex.HexBin(srcfile)
base = path.splitext(srcfile)[0]
if hb.FInfo.Type == hb.FInfo.Creator == b'????':
try:
os.remove(base + '.idump')
except FileNotFoundError:
pass
else:
with open(base + '.idump', 'wb') as f:
f.write(hb.FInfo.Type + hb.FInfo.Creator)
data = hb.read()
if hb.FInfo.Type in [b'TEXT', b'ttro']:
data = data.replace(b'\r', b'\n').decode('mac_roman').encode('utf-8')
with open(base, 'wb') as f:
f.write(data)
rsrc = hb.read_rsrc()
if rsrc:
with open(base + '.rdump', 'wb') as f:
f.write(macresources.make_rez_code(macresources.parse_file(rsrc), ascii_clean=True))
else:
try:
os.remove(base + '.rdump')
except FileNotFoundError:
pass
# Case 2: to BinHex
else:
finfo = binhex.FInfo() finfo = binhex.FInfo()
finfo.Flags = 0 finfo.Flags = 0
try: try:
info = open(args.srcfile + '.idump', 'rb').read(8) info = open(srcfile + '.idump', 'rb').read(8)
assert len(info) == 8 assert len(info) == 8
finfo.Type = info[:4] finfo.Type = info[:4]
finfo.Creator = info[4:] finfo.Creator = info[4:]
@ -24,19 +60,19 @@ except:
pass pass
try: try:
data = open(args.srcfile, 'rb').read() data = open(srcfile, 'rb').read()
if finfo.Type in [b'TEXT', b'ttro']: if finfo.Type in [b'TEXT', b'ttro']:
data = data.decode('utf-8').encode('mac_roman') data = data.replace(b'\n', b'\r').decode('utf-8').encode('mac_roman')
except: except:
data = b'' data = b''
try: try:
rsrc = open(args.srcfile + '.rdump', 'rb').read() rsrc = open(srcfile + '.rdump', 'rb').read()
rsrc = macresources.make_file(macresources.parse_rez_code(rsrc)) rsrc = macresources.make_file(macresources.parse_rez_code(rsrc))
except: except:
rsrc = b'' rsrc = b''
bh = binhex.BinHex((path.basename(args.srcfile), finfo, len(data), len(rsrc)), args.srcfile + '.hqx') bh = binhex.BinHex((path.basename(srcfile), finfo, len(data), len(rsrc)), srcfile + '.hqx')
bh.write(data) bh.write(data)
bh.write_rsrc(rsrc) bh.write_rsrc(rsrc)