| 1 |
# |
| 2 |
# Basic class handling osx() call. It tries to replace the entities by |
| 3 |
# the equivalent unicode characters. |
| 4 |
# |
| 5 |
import os |
| 6 |
import sys |
| 7 |
import re |
| 8 |
import logging |
| 9 |
from subprocess import call |
| 10 |
from io import open |
| 11 |
|
| 12 |
class Osx: |
| 13 |
def __init__(self): |
| 14 |
self.opts = ["-xlower", |
| 15 |
"-xno-nl-in-tag", |
| 16 |
"-xempty", |
| 17 |
"-xno-expand-internal", |
| 18 |
"-xid"] # To have id() working without a DTD |
| 19 |
self.log = logging.getLogger("dblatex") |
| 20 |
|
| 21 |
def replace_entities(self, entfile, mapfile, outfile=None): |
| 22 |
# Find out the SDATA entities to replace |
| 23 |
re_ent = re.compile(r'<!ENTITY +([^\s]+) +"?\[([^\s"]+) *\]"?>') |
| 24 |
f = open(entfile, "rt", encoding="latin-1") |
| 25 |
lines = f.readlines() |
| 26 |
f.close() |
| 27 |
|
| 28 |
# Trivial case where no entities to map |
| 29 |
if not(lines): |
| 30 |
return |
| 31 |
|
| 32 |
ents = [] |
| 33 |
for line in lines: |
| 34 |
ents += re_ent.findall(line) |
| 35 |
self.log.debug("Entities to map: %s" % ents) |
| 36 |
|
| 37 |
# Now, get their Unicode mapping |
| 38 |
entpat = r"^(%s)\s+[^\s]+\s+0(x[^\s]+)" % "|".join([x for x, y in ents]) |
| 39 |
re_map = re.compile(entpat) |
| 40 |
entmap = [] |
| 41 |
f = open(mapfile, "rt", encoding="latin-1") |
| 42 |
for line in f: |
| 43 |
entmap += re_map.findall(line.split("#")[0]) |
| 44 |
f.close() |
| 45 |
self.log.debug("Entity map: %s" % entmap) |
| 46 |
|
| 47 |
# Replace the entity definitions by their Unicode equivalent |
| 48 |
entdict = {} |
| 49 |
for ent, uval in entmap: |
| 50 |
entdict[ent] = \ |
| 51 |
(re.compile(r'<!ENTITY\s+%s\s+"?\[[^\]]+\]"?\s*>' % ent), |
| 52 |
'<!ENTITY %s "&#%s;">' % (ent, uval)) |
| 53 |
|
| 54 |
nlines = [] |
| 55 |
for line in lines: |
| 56 |
mapped = [] |
| 57 |
for ent in entdict: |
| 58 |
reg, rep = entdict[ent] |
| 59 |
line, n = reg.subn(rep, line) |
| 60 |
if n: |
| 61 |
mapped.append(ent) |
| 62 |
nlines.append(line) |
| 63 |
for ent in mapped: |
| 64 |
del entdict[ent] |
| 65 |
|
| 66 |
if not(outfile): outfile = entfile |
| 67 |
f = open(outfile, "wt", encoding="latin-1") |
| 68 |
f.writelines(nlines) |
| 69 |
f.close() |
| 70 |
|
| 71 |
def run(self, sgmlfile, xmlfile): |
| 72 |
errfile = "errors.osx" |
| 73 |
f = open(xmlfile, "wb") |
| 74 |
rc = call(["osx"] + self.opts + ["-f", errfile, sgmlfile], stdout=f) |
| 75 |
f.close() |
| 76 |
if rc != 0: |
| 77 |
i = 0 |
| 78 |
f = open(errfile, "rt") |
| 79 |
for line in f: |
| 80 |
sys.stderr.write(line) |
| 81 |
i += 1 |
| 82 |
if i == 10: break |
| 83 |
f.close() |
| 84 |
raise OSError("osx failed") |
| 85 |
|
| 86 |
# Now, replace the SDATA entities |
| 87 |
sgmlmap = os.path.join(os.path.dirname(__file__), "sgmlent.txt") |
| 88 |
self.replace_entities("intEntities.dtf", sgmlmap) |
| 89 |
|