Debian Codegraph @

lib/dbtexmf/core/txtparser.py

raw
1 #
2 # DbTex configuration parser. Maybe we could use or extend ConfigParser.
3 #
4 import os
5 import re
6 from io import open
7
8 #
9 # Functions used by the config parsers and by the dbtex command parser
10 #
11 def texinputs_parse(strpath, basedir=None):
12 """
13 Transform the TEXINPUTS string to absolute normalized paths,
14 but keep intact the '//' suffix if any. The absolute paths are
15 computed from current one or from <basedir> when specified.
16 """
17 paths = []
18 for p in strpath.split(os.pathsep):
19 if not(os.path.isabs(p)):
20 if not(basedir):
21 d = os.path.realpath(p)
22 else:
23 d = os.path.normpath(os.path.join(basedir, p))
24 else:
25 d = os.path.normpath(p)
26 if p.endswith("//"):
27 d += "//"
28 paths.append(d)
29 return paths
30
31 def texstyle_parse(texstyle):
32 sty = os.path.basename(texstyle)
33 dir = os.path.dirname(texstyle)
34 if sty.endswith(".sty"):
35 path = os.path.realpath(dir)
36 sty = sty[:-4]
37 if not(os.path.isfile(texstyle)):
38 raise ValueError("Latex style '%s' not found" % texstyle)
39 elif (dir):
40 raise ValueError("Invalid latex style path: missing .sty")
41 else:
42 path = ""
43 return ("latex.style=%s" % sty, path)
44
45
46
47 class OptMap:
48 def __init__(self, option):
49 self.option = option
50
51 def format(self, dir, value):
52 return ["%s=%s" % (self.option, value)]
53
54 class PathMap(OptMap):
55 def format(self, dir, value):
56 if not(os.path.isabs(value)):
57 value = os.path.normpath(os.path.join(dir, value))
58 return OptMap.format(self, dir, value)
59
60 class TexMap(OptMap):
61 def format(self, dir, value):
62 paths = texinputs_parse(value, basedir=dir)
63 return OptMap.format(self, dir, ":".join(paths))
64
65 class NoneMap(OptMap):
66 def format(self, dir, value):
67 return value.split()
68
69
70 class TextConfig:
71 conf_mapping = {
72 'TexInputs' : TexMap('--texinputs'),
73 #'PdfInputs' : OptMap('--pdfinputs'),
74 'TexPost' : PathMap('--texpost'),
75 'FigPath' : PathMap('--fig-path'),
76 'XslParam' : PathMap('--xsl-user'),
77 'TexStyle' : OptMap('--texstyle'),
78 'Options' : NoneMap('')
79 }
80
81 def __init__(self):
82 self._options = []
83 self.reparam = re.compile(r"^\s*([^:=\s]+)\s*:\s*(.*)")
84
85 def options(self):
86 return self._options
87
88 def fromfile(self, file):
89 dir = os.path.dirname(os.path.realpath(file))
90 f = open(file, "rt")
91
92 for line in f:
93 # Remove the comment
94 line = line.split("#")[0]
95 m = self.reparam.match(line)
96 if not(m):
97 continue
98 key = m.group(1)
99 value = m.group(2).strip()
100 if key not in self.conf_mapping:
101 continue
102 o = self.conf_mapping[key]
103
104 # The paths can be relative to the config file
105 self._options += o.format(dir, value)
106
107 f.close()
108