latexrun 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2013, 2014 Austin Clements
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. # The above copyright notice and this permission notice shall be included in
  10. # all copies or substantial portions of the Software.
  11. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. # THE SOFTWARE.
  18. import sys
  19. import os
  20. import errno
  21. import argparse
  22. import shlex
  23. import json
  24. import subprocess
  25. import re
  26. import collections
  27. import hashlib
  28. import shutil
  29. import curses
  30. import filecmp
  31. import io
  32. import traceback
  33. import time
  34. try:
  35. import fcntl
  36. except ImportError:
  37. # Non-UNIX platform
  38. fcntl = None
  39. def debug(string, *args):
  40. if debug.enabled:
  41. print(string.format(*args), file=sys.stderr)
  42. debug.enabled = False
  43. def debug_exc():
  44. if debug.enabled:
  45. traceback.print_exc()
  46. def main():
  47. # Parse command-line
  48. arg_parser = argparse.ArgumentParser(
  49. description='''A 21st century LaTeX wrapper,
  50. %(prog)s runs latex (and bibtex) the right number of times so you
  51. don't have to,
  52. strips the log spew to make errors visible,
  53. and plays well with standard build tools.''')
  54. arg_parser.add_argument(
  55. '-o', metavar='FILE', dest='output', default=None,
  56. help='Output file name (default: derived from input file)')
  57. arg_parser.add_argument(
  58. '--latex-cmd', metavar='CMD', default='pdflatex',
  59. help='Latex command (default: %(default)s)')
  60. arg_parser.add_argument(
  61. '--latex-args', metavar='ARGS', type=arg_parser_shlex,
  62. help='Additional command-line arguments for latex.'
  63. ' This will be parsed and split using POSIX shell rules.')
  64. arg_parser.add_argument(
  65. '--bibtex-cmd', metavar='CMD', default='bibtex',
  66. help='Bibtex command (default: %(default)s)')
  67. arg_parser.add_argument(
  68. '--bibtex-args', metavar='ARGS', type=arg_parser_shlex,
  69. help='Additional command-line arguments for bibtex')
  70. arg_parser.add_argument(
  71. '--max-iterations', metavar='N', type=int, default=10,
  72. help='Max number of times to run latex before giving up'
  73. ' (default: %(default)s)')
  74. arg_parser.add_argument(
  75. '-W', metavar='(no-)CLASS',
  76. action=ArgParserWarnAction, dest='nowarns', default=set(['underfull']),
  77. help='Enable/disable warning from CLASS, which can be any package name, '
  78. 'LaTeX warning class (e.g., font), bad box type '
  79. '(underfull, overfull, loose, tight), or "all"')
  80. arg_parser.add_argument(
  81. '-O', metavar='DIR', dest='obj_dir', default='latex.out',
  82. help='Directory for intermediate files and control database '
  83. '(default: %(default)s)')
  84. arg_parser.add_argument(
  85. '--color', choices=('auto', 'always', 'never'), default='auto',
  86. help='When to colorize messages')
  87. arg_parser.add_argument(
  88. '--verbose-cmds', action='store_true', default=False,
  89. help='Print commands as they are executed')
  90. arg_parser.add_argument(
  91. '--debug', action='store_true',
  92. help='Enable detailed debug output')
  93. actions = arg_parser.add_argument_group('actions')
  94. actions.add_argument(
  95. '--clean-all', action='store_true', help='Delete output files')
  96. actions.add_argument(
  97. 'file', nargs='?', help='.tex file to compile')
  98. args = arg_parser.parse_args()
  99. if not any([args.clean_all, args.file]):
  100. arg_parser.error('at least one action is required')
  101. args.latex_args = args.latex_args or []
  102. args.bibtex_args = args.bibtex_args or []
  103. verbose_cmd.enabled = args.verbose_cmds
  104. debug.enabled = args.debug
  105. # A note about encodings: POSIX encoding is a mess; TeX encoding
  106. # is a disaster. Our goal is to make things no worse, so we want
  107. # byte-accurate round-tripping of TeX messages. Since TeX
  108. # messages are *basically* text, we use strings and
  109. # surrogateescape'ing for both input and output. I'm not fond of
  110. # setting surrogateescape globally, but it's far easier than
  111. # dealing with every place we pass TeX output through.
  112. # Conveniently, JSON can round-trip surrogateescape'd strings, so
  113. # our control database doesn't need special handling.
  114. sys.stdout = io.TextIOWrapper(
  115. sys.stdout.buffer, encoding=sys.stdout.encoding,
  116. errors='surrogateescape', line_buffering=sys.stdout.line_buffering)
  117. sys.stderr = io.TextIOWrapper(
  118. sys.stderr.buffer, encoding=sys.stderr.encoding,
  119. errors='surrogateescape', line_buffering=sys.stderr.line_buffering)
  120. Message.setup_color(args.color)
  121. # Open control database.
  122. dbpath = os.path.join(args.obj_dir, '.latexrun.db')
  123. if not os.path.exists(dbpath) and os.path.exists('.latexrun.db'):
  124. # The control database used to live in the source directory.
  125. # Support this for backwards compatibility.
  126. dbpath = '.latexrun.db'
  127. try:
  128. db = DB(dbpath)
  129. except (ValueError, OSError) as e:
  130. print('error opening {}: {}'.format(e.filename if hasattr(e, 'filename')
  131. else dbpath, e),
  132. file=sys.stderr)
  133. debug_exc()
  134. sys.exit(1)
  135. # Clean
  136. if args.clean_all:
  137. try:
  138. db.do_clean(args.obj_dir)
  139. except OSError as e:
  140. print(e, file=sys.stderr)
  141. debug_exc()
  142. sys.exit(1)
  143. # Build
  144. if not args.file:
  145. return
  146. task_commit = None
  147. try:
  148. task_latex = LaTeX(db, args.file, args.latex_cmd, args.latex_args,
  149. args.obj_dir, args.nowarns)
  150. task_commit = LaTeXCommit(db, task_latex, args.output)
  151. task_bibtex = BibTeX(db, task_latex, args.bibtex_cmd, args.bibtex_args,
  152. args.nowarns, args.obj_dir)
  153. tasks = [task_latex, task_commit, task_bibtex]
  154. stable = run_tasks(tasks, args.max_iterations)
  155. # Print final task output and gather exit status
  156. status = 0
  157. for task in tasks:
  158. status = max(task.report(), status)
  159. if not stable:
  160. print('error: files are still changing after {} iterations; giving up'
  161. .format(args.max_iterations), file=sys.stderr)
  162. status = max(status, 1)
  163. except TaskError as e:
  164. print(str(e), file=sys.stderr)
  165. debug_exc()
  166. status = 1
  167. # Report final status, if interesting
  168. fstatus = 'There were errors' if task_commit is None else task_commit.status
  169. if fstatus:
  170. output = args.output
  171. if output is None:
  172. if task_latex.get_outname() is not None:
  173. output = os.path.basename(task_latex.get_outname())
  174. else:
  175. output = 'output'
  176. if Message._color:
  177. terminfo.send('bold', ('setaf', 1))
  178. print('{}; {} not updated'.format(fstatus, output))
  179. if Message._color:
  180. terminfo.send('sgr0')
  181. sys.exit(status)
  182. def arg_parser_shlex(string):
  183. """Argument parser for shell token lists."""
  184. try:
  185. return shlex.split(string)
  186. except ValueError as e:
  187. raise argparse.ArgumentTypeError(str(e)) from None
  188. class ArgParserWarnAction(argparse.Action):
  189. def __call__(self, parser, namespace, value, option_string=None):
  190. nowarn = getattr(namespace, self.dest)
  191. if value == 'all':
  192. nowarn.clear()
  193. elif value.startswith('no-'):
  194. nowarn.add(value[3:])
  195. else:
  196. nowarn.discard(value)
  197. setattr(namespace, self.dest, nowarn)
  198. def verbose_cmd(args, cwd=None, env=None):
  199. if verbose_cmd.enabled:
  200. cmd = ' '.join(map(shlex.quote, args))
  201. if cwd is not None:
  202. cmd = '(cd {} && {})'.format(shlex.quote(cwd), cmd)
  203. if env is not None:
  204. for k, v in env.items():
  205. if os.environ.get(k) != v:
  206. cmd = '{}={} {}'.format(k, shlex.quote(v), cmd)
  207. print(cmd, file=sys.stderr)
  208. verbose_cmd.enabled = False
  209. def mkdir_p(path):
  210. try:
  211. os.makedirs(path)
  212. except OSError as exc:
  213. if exc.errno == errno.EEXIST and os.path.isdir(path):
  214. pass
  215. else: raise
  216. class DB:
  217. """A latexrun control database."""
  218. _VERSION = 'latexrun-db-v2'
  219. def __init__(self, filename):
  220. self.__filename = filename
  221. # Make sure database directory exists
  222. if os.path.dirname(self.__filename):
  223. os.makedirs(os.path.dirname(self.__filename), exist_ok=True)
  224. # Lock the database if possible. We don't release this lock
  225. # until the process exits.
  226. lockpath = self.__filename + '.lock'
  227. if fcntl is not None:
  228. lockfd = os.open(lockpath, os.O_CREAT|os.O_WRONLY|os.O_CLOEXEC, 0o666)
  229. # Note that this is actually an fcntl lock, not a lockf
  230. # lock. Don't be fooled.
  231. fcntl.lockf(lockfd, fcntl.LOCK_EX, 1)
  232. try:
  233. fp = open(filename, 'r')
  234. except FileNotFoundError:
  235. debug('creating new database')
  236. self.__val = {'version': DB._VERSION}
  237. else:
  238. debug('loading database')
  239. self.__val = json.load(fp)
  240. if 'version' not in self.__val:
  241. raise ValueError('file exists, but does not appear to be a latexrun database'.format(filename))
  242. if self.__val['version'] != DB._VERSION:
  243. raise ValueError('unknown database version {!r}'
  244. .format(self.__val['version']))
  245. def commit(self):
  246. debug('committing database')
  247. # Atomically commit database
  248. tmp_filename = self.__filename + '.tmp'
  249. with open(tmp_filename, 'w') as fp:
  250. json.dump(self.__val, fp, indent=2, separators=(',', ': '))
  251. fp.flush()
  252. os.fsync(fp.fileno())
  253. os.rename(tmp_filename, self.__filename)
  254. def get_summary(self, task_id):
  255. """Return the recorded summary for the given task or None."""
  256. return self.__val.get('tasks', {}).get(task_id)
  257. def set_summary(self, task_id, summary):
  258. """Set the summary for the given task."""
  259. self.__val.setdefault('tasks', {})[task_id] = summary
  260. def add_clean(self, filename):
  261. """Add an output file to be cleaned.
  262. Unlike the output files recorded in the task summaries,
  263. cleanable files strictly accumulate until a clean is
  264. performed.
  265. """
  266. self.__val.setdefault('clean', {})[filename] = hash_cache.get(filename)
  267. def do_clean(self, obj_dir=None):
  268. """Remove output files and delete database.
  269. If obj_dir is not None and it is empty after all files are
  270. removed, it will also be removed.
  271. """
  272. for f, want_hash in self.__val.get('clean', {}).items():
  273. have_hash = hash_cache.get(f)
  274. if have_hash is not None:
  275. if want_hash == have_hash:
  276. debug('unlinking {}', f)
  277. hash_cache.invalidate(f)
  278. os.unlink(f)
  279. else:
  280. print('warning: {} has changed; not removing'.format(f),
  281. file=sys.stderr)
  282. self.__val = {'version': DB._VERSION}
  283. try:
  284. os.unlink(self.__filename)
  285. except FileNotFoundError:
  286. pass
  287. if obj_dir is not None:
  288. try:
  289. os.rmdir(obj_dir)
  290. except OSError:
  291. pass
  292. class HashCache:
  293. """Cache of file hashes.
  294. As latexrun reaches fixed-point, it hashes the same files over and
  295. over, many of which never change. Since hashing is somewhat
  296. expensive, we keep a simple cache of these hashes.
  297. """
  298. def __init__(self):
  299. self.__cache = {}
  300. def get(self, filename):
  301. """Return the hash of filename, or * if it was clobbered."""
  302. try:
  303. with open(filename, 'rb') as fp:
  304. st = os.fstat(fp.fileno())
  305. key = (st.st_dev, st.st_ino)
  306. if key in self.__cache:
  307. return self.__cache[key]
  308. debug('hashing {}', filename)
  309. h = hashlib.sha256()
  310. while True:
  311. block = fp.read(256*1024)
  312. if not len(block):
  313. break
  314. h.update(block)
  315. self.__cache[key] = h.hexdigest()
  316. return self.__cache[key]
  317. except (FileNotFoundError, IsADirectoryError):
  318. return None
  319. def clobber(self, filename):
  320. """If filename's hash is not known, record an invalid hash.
  321. This can be used when filename was overwritten before we were
  322. necessarily able to obtain its hash. filename must exist.
  323. """
  324. st = os.stat(filename)
  325. key = (st.st_dev, st.st_ino)
  326. if key not in self.__cache:
  327. self.__cache[key] = '*'
  328. def invalidate(self, filename):
  329. try:
  330. st = os.stat(filename)
  331. except OSError as e:
  332. # Pessimistically wipe the whole cache
  333. debug('wiping hash cache ({})', e)
  334. self.__cache.clear()
  335. else:
  336. key = (st.st_dev, st.st_ino)
  337. if key in self.__cache:
  338. del self.__cache[key]
  339. hash_cache = HashCache()
  340. class _Terminfo:
  341. def __init__(self):
  342. self.__tty = os.isatty(sys.stdout.fileno())
  343. if self.__tty:
  344. curses.setupterm()
  345. self.__ti = {}
  346. def __ensure(self, cap):
  347. if cap not in self.__ti:
  348. if not self.__tty:
  349. string = None
  350. else:
  351. string = curses.tigetstr(cap)
  352. if string is None or b'$<' in string:
  353. # Don't have this capability or it has a pause
  354. string = None
  355. self.__ti[cap] = string
  356. return self.__ti[cap]
  357. def has(self, *caps):
  358. return all(self.__ensure(cap) is not None for cap in caps)
  359. def send(self, *caps):
  360. # Flush TextIOWrapper to the binary IO buffer
  361. sys.stdout.flush()
  362. for cap in caps:
  363. # We should use curses.putp here, but it's broken in
  364. # Python3 because it writes directly to C's buffered
  365. # stdout and there's no way to flush that.
  366. if isinstance(cap, tuple):
  367. s = curses.tparm(self.__ensure(cap[0]), *cap[1:])
  368. else:
  369. s = self.__ensure(cap)
  370. sys.stdout.buffer.write(s)
  371. terminfo = _Terminfo()
  372. class Progress:
  373. _enabled = None
  374. def __init__(self, prefix):
  375. self.__prefix = prefix
  376. if Progress._enabled is None:
  377. Progress._enabled = (not debug.enabled) and \
  378. terminfo.has('cr', 'el', 'rmam', 'smam')
  379. def __enter__(self):
  380. self.last = ''
  381. self.update('')
  382. return self
  383. def __exit__(self, typ, value, traceback):
  384. if Progress._enabled:
  385. # Beginning of line and clear
  386. terminfo.send('cr', 'el')
  387. sys.stdout.flush()
  388. def update(self, msg):
  389. if not Progress._enabled:
  390. return
  391. out = '[' + self.__prefix + ']'
  392. if msg:
  393. out += ' ' + msg
  394. if out != self.last:
  395. # Beginning of line, clear line, disable wrap
  396. terminfo.send('cr', 'el', 'rmam')
  397. sys.stdout.write(out)
  398. # Enable wrap
  399. terminfo.send('smam')
  400. self.last = out
  401. sys.stdout.flush()
  402. class Message(collections.namedtuple(
  403. 'Message', 'typ filename lineno msg')):
  404. def emit(self):
  405. if self.filename:
  406. if self.filename.startswith('./'):
  407. finfo = self.filename[2:]
  408. else:
  409. finfo = self.filename
  410. else:
  411. finfo = '<no file>'
  412. if self.lineno is not None:
  413. finfo += ':' + str(self.lineno)
  414. finfo += ': '
  415. if self._color:
  416. terminfo.send('bold')
  417. sys.stdout.write(finfo)
  418. if self.typ != 'info':
  419. if self._color:
  420. terminfo.send(('setaf', 5 if self.typ == 'warning' else 1))
  421. sys.stdout.write(self.typ + ': ')
  422. if self._color:
  423. terminfo.send('sgr0')
  424. sys.stdout.write(self.msg + '\n')
  425. @classmethod
  426. def setup_color(cls, state):
  427. if state == 'never':
  428. cls._color = False
  429. elif state == 'always':
  430. cls._color = True
  431. elif state == 'auto':
  432. cls._color = terminfo.has('setaf', 'bold', 'sgr0')
  433. else:
  434. raise ValueError('Illegal color state {:r}'.format(state))
  435. ##################################################################
  436. # Task framework
  437. #
  438. terminate_task_loop = False
  439. start_time = time.time()
  440. def run_tasks(tasks, max_iterations):
  441. """Execute tasks in round-robin order until all are stable.
  442. This will also exit if terminate_task_loop is true. Tasks may use
  443. this to terminate after a fatal error (even if that fatal error
  444. doesn't necessarily indicate stability; as long as re-running the
  445. task will never eliminate the fatal error).
  446. Return True if fixed-point is reached or terminate_task_loop is
  447. set within max_iterations iterations.
  448. """
  449. global terminate_task_loop
  450. terminate_task_loop = False
  451. nstable = 0
  452. for iteration in range(max_iterations):
  453. for task in tasks:
  454. if task.stable():
  455. nstable += 1
  456. if nstable == len(tasks):
  457. debug('fixed-point reached')
  458. return True
  459. else:
  460. task.run()
  461. nstable = 0
  462. if terminate_task_loop:
  463. debug('terminate_task_loop set')
  464. return True
  465. debug('fixed-point not reached')
  466. return False
  467. class TaskError(Exception):
  468. pass
  469. class Task:
  470. """A deterministic computation whose inputs and outputs can be captured."""
  471. def __init__(self, db, task_id):
  472. self.__db = db
  473. self.__task_id = task_id
  474. def __debug(self, string, *args):
  475. if debug.enabled:
  476. debug('task {}: {}', self.__task_id, string.format(*args))
  477. def stable(self):
  478. """Return True if running this task will not affect system state.
  479. Functionally, let f be the task, and s be the system state.
  480. Then s' = f(s). If it must be that s' == s (that is, f has
  481. reached a fixed point), then this function must return True.
  482. """
  483. last_summary = self.__db.get_summary(self.__task_id)
  484. if last_summary is None:
  485. # Task has never run, so running it will modify system
  486. # state
  487. changed = 'never run'
  488. else:
  489. # If any of the inputs have changed since the last run of
  490. # this task, the result may change, so re-run the task.
  491. # Also, it's possible something else changed an output
  492. # file, in which case we also want to re-run the task, so
  493. # check the outputs, too.
  494. changed = self.__summary_changed(last_summary)
  495. if changed:
  496. self.__debug('unstable (changed: {})', changed)
  497. return False
  498. else:
  499. self.__debug('stable')
  500. return True
  501. def __summary_changed(self, summary):
  502. """Test if any inputs changed from summary.
  503. Returns a string describing the changed input, or None.
  504. """
  505. for dep in summary['deps']:
  506. fn, args, val = dep
  507. method = getattr(self, '_input_' + fn, None)
  508. if method is None:
  509. return 'unknown dependency method {}'.format(fn)
  510. if method == self._input_unstable or method(*args) != val:
  511. return '{}{}'.format(fn, tuple(args))
  512. return None
  513. def _input(self, name, *args):
  514. """Register an input for this run.
  515. This calls self._input_<name>(*args) to get the value of this
  516. input. This function should run quickly and return some
  517. projection of system state that affects the result of this
  518. computation.
  519. Both args and the return value must be JSON serializable.
  520. """
  521. method = getattr(self, '_input_' + name)
  522. val = method(*args)
  523. if [name, args, val] not in self.__deps:
  524. self.__deps.append([name, args, val])
  525. return val
  526. def run(self):
  527. # Before we run the task, pre-hash any files that were output
  528. # files in the last run. These may be input by this run and
  529. # then clobbered, at which point it will be too late to get an
  530. # input hash. Ideally we would only hash files that were
  531. # *both* input and output files, but latex doesn't tell us
  532. # about input files that didn't exist, so if we start from a
  533. # clean slate, we often require an extra run because we don't
  534. # know a file is input/output until after the second run.
  535. last_summary = self.__db.get_summary(self.__task_id)
  536. if last_summary is not None:
  537. for io_filename in last_summary['output_files']:
  538. self.__debug('pre-hashing {}', io_filename)
  539. hash_cache.get(io_filename)
  540. # Run the task
  541. self.__debug('running')
  542. self.__deps = []
  543. result = self._execute()
  544. # Clear cached output file hashes
  545. for filename in result.output_filenames:
  546. hash_cache.invalidate(filename)
  547. # If the output files change, then the computation needs to be
  548. # re-run, so record them as inputs
  549. for filename in result.output_filenames:
  550. self._input('file', filename)
  551. # Update task summary in database
  552. self.__db.set_summary(self.__task_id,
  553. self.__make_summary(self.__deps, result))
  554. del self.__deps
  555. # Add output files to be cleaned
  556. for f in result.output_filenames:
  557. self.__db.add_clean(f)
  558. try:
  559. self.__db.commit()
  560. except OSError as e:
  561. raise TaskError('error committing control database {}: {}'.format(
  562. getattr(e, 'filename', '<unknown path>'), e)) from e
  563. def __make_summary(self, deps, run_result):
  564. """Construct a new task summary."""
  565. return {
  566. 'deps': deps,
  567. 'output_files': {f: hash_cache.get(f)
  568. for f in run_result.output_filenames},
  569. 'extra': run_result.extra,
  570. }
  571. def _execute(self):
  572. """Abstract: Execute this task.
  573. Subclasses should implement this method to execute this task.
  574. This method must return a RunResult giving the inputs that
  575. were used by the task and the outputs it produced.
  576. """
  577. raise NotImplementedError('Task._execute is abstract')
  578. def _get_result_extra(self):
  579. """Return the 'extra' result from the previous run, or None."""
  580. summary = self.__db.get_summary(self.__task_id)
  581. if summary is None:
  582. return None
  583. return summary['extra']
  584. def report(self):
  585. """Report the task's results to stdout and return exit status.
  586. This may be called when the task has never executed.
  587. Subclasses should override this. The default implementation
  588. reports nothing and returns 0.
  589. """
  590. return 0
  591. # Standard input functions
  592. def _input_env(self, var):
  593. return os.environ.get(var)
  594. def _input_file(self, path):
  595. return hash_cache.get(path)
  596. def _input_unstable(self):
  597. """Mark this run as unstable, regardless of other inputs."""
  598. return None
  599. def _input_unknown_input(self):
  600. """An unknown input that may change after latexrun exits.
  601. This conservatively marks some unknown input that definitely
  602. won't change while latexrun is running, but may change before
  603. the user next runs latexrun. This allows the task to
  604. stabilize during this invocation, but will cause the task to
  605. re-run on the next invocation.
  606. """
  607. return start_time
  608. class RunResult(collections.namedtuple(
  609. 'RunResult', 'output_filenames extra')):
  610. """The result of a single task execution.
  611. This captures all files written by the task, and task-specific
  612. results that need to be persisted between runs (for example, to
  613. enable reporting of a task's results).
  614. """
  615. pass
  616. ##################################################################
  617. # LaTeX task
  618. #
  619. def normalize_input_path(path):
  620. # Resolve the directory of the input path, but leave the file
  621. # component alone because it affects TeX's behavior.
  622. head, tail = os.path.split(path)
  623. npath = os.path.join(os.path.realpath(head), tail)
  624. return os.path.relpath(path)
  625. class LaTeX(Task):
  626. def __init__(self, db, tex_filename, cmd, cmd_args, obj_dir, nowarns):
  627. super().__init__(db, 'latex::' + normalize_input_path(tex_filename))
  628. self.__tex_filename = tex_filename
  629. self.__cmd = cmd
  630. self.__cmd_args = cmd_args
  631. self.__obj_dir = obj_dir
  632. self.__nowarns = nowarns
  633. self.__pass = 0
  634. def _input_args(self):
  635. # If filename starts with a character the tex command-line
  636. # treats specially, then tweak it so it doesn't.
  637. filename = self.__tex_filename
  638. if filename.startswith(('-', '&', '\\')):
  639. filename = './' + filename
  640. # XXX Put these at the beginning in case the provided
  641. # arguments are malformed. Might want to do a best-effort
  642. # check for incompatible user-provided arguments (note:
  643. # arguments can be given with one or two dashes and those with
  644. # values can use an equals or a space).
  645. return [self.__cmd] + self.__cmd_args + \
  646. ['-interaction', 'nonstopmode', '-recorder',
  647. '-output-directory', self.__obj_dir, filename]
  648. def _execute(self):
  649. # Run latex
  650. self.__pass += 1
  651. args = self._input('args')
  652. debug('running {}', args)
  653. try:
  654. os.makedirs(self.__obj_dir, exist_ok=True)
  655. except OSError as e:
  656. raise TaskError('failed to create %s: ' % self.__obj_dir + str(e)) \
  657. from e
  658. try:
  659. verbose_cmd(args)
  660. p = subprocess.Popen(args,
  661. stdin=subprocess.DEVNULL,
  662. stdout=subprocess.PIPE,
  663. stderr=subprocess.STDOUT)
  664. stdout, has_errors, missing_includes = self.__feed_terminal(p.stdout)
  665. status = p.wait()
  666. except OSError as e:
  667. raise TaskError('failed to execute latex task: ' + str(e)) from e
  668. # Register environment variable inputs
  669. for env_var in ['TEXMFOUTPUT', 'TEXINPUTS', 'TEXFORMATS', 'TEXPOOL',
  670. 'TFMFONTS', 'PATH']:
  671. self._input('env', env_var)
  672. jobname, outname = self.__parse_jobname(stdout)
  673. inputs, outputs = self.__parse_recorder(jobname)
  674. # LaTeX overwrites its own inputs. Mark its output files as
  675. # clobbered before we hash its input files.
  676. for path in outputs:
  677. # In some abort cases (e.g., >=100 errors), LaTeX claims
  678. # output files that don't actually exist.
  679. if os.path.exists(path):
  680. hash_cache.clobber(path)
  681. # Depend on input files. Task.run pre-hashed outputs from the
  682. # previous run, so if this isn't the first run and as long as
  683. # the set of outputs didn't change, we'll be able to get the
  684. # input hashes, even if they were clobbered.
  685. for path in inputs:
  686. self._input('file', path)
  687. if missing_includes:
  688. # Missing \includes are tricky. Ideally we'd depend on
  689. # the absence of some file, but in fact we'd have to
  690. # depend on the failure of a whole kpathsea lookup.
  691. # Rather than try to be clever, just mark this as an
  692. # unknown input so we'll run at least once on the next
  693. # invocation.
  694. self._input('unknown_input')
  695. if not self.__create_outdirs(stdout) and has_errors:
  696. # LaTeX reported unrecoverable errors (other than output
  697. # directory errors, which we just fixed). We could
  698. # continue to stabilize the document, which may change
  699. # some of the other problems reported (but not the
  700. # unrecoverable errors), or we can just abort now and get
  701. # back to the user quickly with the major errors. We opt
  702. # for the latter.
  703. global terminate_task_loop
  704. terminate_task_loop = True
  705. # This error could depend on something we failed to track.
  706. # It would be really confusing if we continued to report
  707. # the error after the user fixed it, so be conservative
  708. # and force a re-run next time.
  709. self._input('unknown_input')
  710. return RunResult(outputs,
  711. {'jobname': jobname, 'outname': outname,
  712. 'status': status})
  713. def __feed_terminal(self, stdout):
  714. prefix = 'latex'
  715. if self.__pass > 1:
  716. prefix += ' ({})'.format(self.__pass)
  717. with Progress(prefix) as progress:
  718. buf = []
  719. filt = LaTeXFilter()
  720. while True:
  721. # Use os.read to read only what's available on the pipe,
  722. # without waiting to fill a buffer
  723. data = os.read(stdout.fileno(), 4096)
  724. if not data:
  725. break
  726. # See "A note about encoding" above
  727. data = data.decode('ascii', errors='surrogateescape')
  728. buf.append(data)
  729. filt.feed(data)
  730. file_stack = filt.get_file_stack()
  731. if file_stack:
  732. tos = file_stack[-1]
  733. if tos.startswith('./'):
  734. tos = tos[2:]
  735. progress.update('>' * len(file_stack) + ' ' + tos)
  736. else:
  737. progress.update('')
  738. # Were there unrecoverable errors?
  739. has_errors = any(msg.typ == 'error' for msg in filt.get_messages())
  740. return ''.join(buf), has_errors, filt.has_missing_includes()
  741. def __parse_jobname(self, stdout):
  742. """Extract the job name and output name from latex's output.
  743. We get these from latex because they depend on complicated
  744. file name parsing rules, are affected by arguments like
  745. -output-directory, and may be just "texput" if things fail
  746. really early. The output name may be None if there were no
  747. pages of output.
  748. """
  749. jobname = outname = None
  750. for m in re.finditer(r'^Transcript written on "?(.*)\.log"?\.$', stdout,
  751. re.MULTILINE | re.DOTALL):
  752. jobname = m.group(1).replace('\n', '')
  753. if jobname is None:
  754. print(stdout, file=sys.stderr)
  755. raise TaskError('failed to extract job name from latex log')
  756. for m in re.finditer(r'^Output written on "?(.*\.[^ ."]+)"? \([0-9]+ page',
  757. stdout, re.MULTILINE | re.DOTALL):
  758. outname = m.group(1).replace('\n', '')
  759. if outname is None and not \
  760. re.search(r'^No pages of output\.$|^! Emergency stop\.$'
  761. r'|^! ==> Fatal error occurred, no output PDF file produced!$',
  762. stdout, re.MULTILINE):
  763. print(stdout, file=sys.stderr)
  764. raise TaskError('failed to extract output name from latex log')
  765. # LuaTeX (0.76.0) doesn't include the output directory in the
  766. # logged transcript or output file name.
  767. if os.path.basename(jobname) == jobname and \
  768. os.path.exists(os.path.join(self.__obj_dir, jobname + '.log')):
  769. jobname = os.path.join(self.__obj_dir, jobname)
  770. if outname is not None:
  771. outname = os.path.join(self.__obj_dir, outname)
  772. return jobname, outname
  773. def __parse_recorder(self, jobname):
  774. """Parse file recorder output."""
  775. # XXX If latex fails because a file isn't found, that doesn't
  776. # go into the .fls file, but creating that file will affect
  777. # the computation, so it should be included as an input.
  778. # Though it's generally true that files can be added earlier
  779. # in search paths and will affect the output without us knowing.
  780. #
  781. # XXX This is a serious problem for bibtex, since the first
  782. # run won't depend on the .bbl file! But maybe the .aux file
  783. # will always cause a re-run, at which point the .bbl will
  784. # exist?
  785. filename = jobname + '.fls'
  786. try:
  787. recorder = open(filename)
  788. except OSError as e:
  789. raise TaskError('failed to open file recorder output: ' + str(e)) \
  790. from e
  791. pwd, inputs, outputs = '', set(), set()
  792. for linenum, line in enumerate(recorder):
  793. parts = line.rstrip('\n').split(' ', 1)
  794. if parts[0] == 'PWD':
  795. pwd = parts[1]
  796. elif parts[0] in ('INPUT', 'OUTPUT'):
  797. if parts[1].startswith('/'):
  798. path = parts[1]
  799. else:
  800. # Try to make "nice" paths, especially for clean
  801. path = os.path.relpath(os.path.join(pwd, parts[1]))
  802. if parts[0] == 'INPUT':
  803. inputs.add(path)
  804. else:
  805. outputs.add(path)
  806. else:
  807. raise TaskError('syntax error on line {} of {}'
  808. .format(linenum, filename))
  809. # Ironically, latex omits the .fls file itself
  810. outputs.add(filename)
  811. return inputs, outputs
  812. def __create_outdirs(self, stdout):
  813. # In some cases, such as \include'ing a file from a
  814. # subdirectory, TeX will attempt to create files in
  815. # subdirectories of the output directory that don't exist.
  816. # Detect this, create the output directory, and re-run.
  817. m = re.search('^! I can\'t write on file `(.*)\'\\.$', stdout, re.M)
  818. if m and m.group(1).find('/') > 0 and '../' not in m.group(1):
  819. debug('considering creating output sub-directory for {}'.
  820. format(m.group(1)))
  821. subdir = os.path.dirname(m.group(1))
  822. newdir = os.path.join(self.__obj_dir, subdir)
  823. if os.path.isdir(subdir) and not os.path.isdir(newdir):
  824. debug('creating output subdirectory {}'.format(newdir))
  825. try:
  826. mkdir_p(newdir)
  827. except OSError as e:
  828. raise TaskError('failed to create output subdirectory: ' +
  829. str(e)) from e
  830. self._input('unstable')
  831. return True
  832. def report(self):
  833. extra = self._get_result_extra()
  834. if extra is None:
  835. return 0
  836. # Parse the log
  837. logfile = open(extra['jobname'] + '.log', 'rt', errors='surrogateescape')
  838. for msg in self.__clean_messages(
  839. LaTeXFilter(self.__nowarns).feed(
  840. logfile.read(), True).get_messages()):
  841. msg.emit()
  842. # Return LaTeX's exit status
  843. return extra['status']
  844. def __clean_messages(self, msgs):
  845. """Make some standard log messages more user-friendly."""
  846. have_undefined_reference = False
  847. for msg in msgs:
  848. if msg.msg == '==> Fatal error occurred, no output PDF file produced!':
  849. msg = msg._replace(typ='info',
  850. msg='Fatal error (no output file produced)')
  851. if msg.msg.startswith('[LaTeX] '):
  852. # Strip unnecessary package name
  853. msg = msg._replace(msg=msg.msg.split(' ', 1)[1])
  854. if re.match(r'Reference .* undefined', msg.msg):
  855. have_undefined_reference = True
  856. if have_undefined_reference and \
  857. re.match(r'There were undefined references', msg.msg):
  858. # LaTeX prints this at the end so the user knows it's
  859. # worthwhile looking back at the log. Since latexrun
  860. # makes the earlier messages obvious, this is
  861. # redundant.
  862. continue
  863. yield msg
  864. def get_tex_filename(self):
  865. return self.__tex_filename
  866. def get_jobname(self):
  867. extra = self._get_result_extra()
  868. if extra is None:
  869. return None
  870. return extra['jobname']
  871. def get_outname(self):
  872. extra = self._get_result_extra()
  873. if extra is None:
  874. return None
  875. return extra['outname']
  876. def get_status(self):
  877. extra = self._get_result_extra()
  878. if extra is None:
  879. return None
  880. return extra['status']
  881. class LaTeXCommit(Task):
  882. def __init__(self, db, latex_task, output_path):
  883. super().__init__(db, 'latex_commit::' +
  884. normalize_input_path(latex_task.get_tex_filename()))
  885. self.__latex_task = latex_task
  886. self.__output_path = output_path
  887. self.status = 'There were errors'
  888. def _input_latex(self):
  889. return self.__latex_task.get_status(), self.__latex_task.get_outname()
  890. def _execute(self):
  891. self.status = 'There were errors'
  892. # If latex succeeded with output, atomically commit the output
  893. status, outname = self._input('latex')
  894. if status != 0 or outname is None:
  895. debug('not committing (status {}, outname {})', status, outname)
  896. if outname is None:
  897. self.status = 'No pages of output'
  898. return RunResult([], None)
  899. commit = self.__output_path or os.path.basename(outname)
  900. if os.path.abspath(commit) == os.path.abspath(outname):
  901. debug('skipping commit (outname is commit name)')
  902. self.status = None
  903. return RunResult([], None)
  904. try:
  905. if os.path.exists(commit) and filecmp.cmp(outname, commit):
  906. debug('skipping commit ({} and {} are identical)',
  907. outname, commit)
  908. # To avoid confusion, touch the output file
  909. open(outname, 'r+b').close()
  910. else:
  911. debug('commiting {} to {}', outname, commit)
  912. shutil.copy(outname, outname + '~')
  913. os.rename(outname + '~', commit)
  914. except OSError as e:
  915. raise TaskError('error committing latex output: {}'.format(e)) from e
  916. self._input('file', outname)
  917. self.status = None
  918. return RunResult([commit], None)
  919. class LaTeXFilter:
  920. TRACE = False # Set to enable detailed parse tracing
  921. def __init__(self, nowarns=[]):
  922. self.__data = ''
  923. self.__restart_pos = 0
  924. self.__restart_file_stack = []
  925. self.__restart_messages_len = 0
  926. self.__messages = []
  927. self.__first_file = None
  928. self.__fatal_error = False
  929. self.__missing_includes = False
  930. self.__pageno = 1
  931. self.__restart_pageno = 1
  932. self.__suppress = {cls: 0 for cls in nowarns}
  933. def feed(self, data, eof=False):
  934. """Feed LaTeX log data to the parser.
  935. The log data can be from LaTeX's standard output, or from the
  936. log file. If there will be no more data, set eof to True.
  937. """
  938. self.__data += data
  939. self.__data_complete = eof
  940. # Reset to last known-good restart point
  941. self.__pos = self.__restart_pos
  942. self.__file_stack = self.__restart_file_stack.copy()
  943. self.__messages = self.__messages[:self.__restart_messages_len]
  944. self.__lstart = self.__lend = -1
  945. self.__pageno = self.__restart_pageno
  946. # Parse forward
  947. while self.__pos < len(self.__data):
  948. self.__noise()
  949. # Handle suppressed warnings
  950. if eof:
  951. msgs = ['%d %s warning%s' % (count, cls, "s" if count > 1 else "")
  952. for cls, count in self.__suppress.items() if count]
  953. if msgs:
  954. self.__message('info', None,
  955. '%s not shown (use -Wall to show them)' %
  956. ', '.join(msgs), filename=self.__first_file)
  957. if eof and len(self.__file_stack) and not self.__fatal_error:
  958. # Fatal errors generally cause TeX to "succumb" without
  959. # closing the file stack, so don't complain in that case.
  960. self.__message('warning', None,
  961. "unbalanced `(' in log; file names may be wrong")
  962. return self
  963. def get_messages(self):
  964. """Return a list of warning and error Messages."""
  965. return self.__messages
  966. def get_file_stack(self):
  967. """Return the file stack for the data that has been parsed.
  968. This results a list from outermost file to innermost file.
  969. The list may be empty.
  970. """
  971. return self.__file_stack
  972. def has_missing_includes(self):
  973. """Return True if the log reported missing \\include files."""
  974. return self.__missing_includes
  975. def __save_restart_point(self):
  976. """Save the current state as a known-good restart point.
  977. On the next call to feed, the parser will reset to this point.
  978. """
  979. self.__restart_pos = self.__pos
  980. self.__restart_file_stack = self.__file_stack.copy()
  981. self.__restart_messages_len = len(self.__messages)
  982. self.__restart_pageno = self.__pageno
  983. def __message(self, typ, lineno, msg, cls=None, filename=None):
  984. if cls is not None and cls in self.__suppress:
  985. self.__suppress[cls] += 1
  986. return
  987. filename = filename or (self.__file_stack[-1] if self.__file_stack
  988. else self.__first_file)
  989. self.__messages.append(Message(typ, filename, lineno, msg))
  990. def __ensure_line(self):
  991. """Update lstart and lend."""
  992. if self.__lstart <= self.__pos < self.__lend:
  993. return
  994. self.__lstart = self.__data.rfind('\n', 0, self.__pos) + 1
  995. self.__lend = self.__data.find('\n', self.__pos) + 1
  996. if self.__lend == 0:
  997. self.__lend = len(self.__data)
  998. @property
  999. def __col(self):
  1000. """The 0-based column number of __pos."""
  1001. self.__ensure_line()
  1002. return self.__pos - self.__lstart
  1003. @property
  1004. def __avail(self):
  1005. return self.__pos < len(self.__data)
  1006. def __lookingat(self, needle):
  1007. return self.__data.startswith(needle, self.__pos)
  1008. def __lookingatre(self, regexp, flags=0):
  1009. return re.compile(regexp, flags=flags).match(self.__data, self.__pos)
  1010. def __skip_line(self):
  1011. self.__ensure_line()
  1012. self.__pos = self.__lend
  1013. def __consume_line(self, unwrap=False):
  1014. self.__ensure_line()
  1015. data = self.__data[self.__pos:self.__lend]
  1016. self.__pos = self.__lend
  1017. if unwrap:
  1018. # TeX helpfully wraps all terminal output at 79 columns
  1019. # (max_print_line). If requested, unwrap it. There's
  1020. # simply no way to do this perfectly, since there could be
  1021. # a line that happens to be 79 columns.
  1022. #
  1023. # We check for >=80 because a bug in LuaTeX causes it to
  1024. # wrap at 80 columns instead of 79 (LuaTeX #900).
  1025. while self.__lend - self.__lstart >= 80:
  1026. if self.TRACE: print('<{}> wrapping'.format(self.__pos))
  1027. self.__ensure_line()
  1028. data = data[:-1] + self.__data[self.__pos:self.__lend]
  1029. self.__pos = self.__lend
  1030. return data
  1031. # Parser productions
  1032. def __noise(self):
  1033. # Most of TeX's output is line noise that combines error
  1034. # messages, warnings, file names, user errors and warnings,
  1035. # and echos of token lists and other input. This attempts to
  1036. # tease these apart, paying particular attention to all of the
  1037. # places where TeX echos input so that parens in the input do
  1038. # not confuse the file name scanner. There are three
  1039. # functions in TeX that echo input: show_token_list (used by
  1040. # runaway and show_context, which is used by print_err),
  1041. # short_display (used by overfull/etc h/vbox), and show_print
  1042. # (used in issue_message and the same places as
  1043. # show_token_list).
  1044. lookingat, lookingatre = self.__lookingat, self.__lookingatre
  1045. if self.__col == 0:
  1046. # The following messages are always preceded by a newline
  1047. if lookingat('! '):
  1048. return self.__errmessage()
  1049. if lookingat('!pdfTeX error: '):
  1050. return self.__pdftex_fail()
  1051. if lookingat('Runaway '):
  1052. return self.__runaway()
  1053. if lookingatre(r'(Overfull|Underfull|Loose|Tight) \\[hv]box \('):
  1054. return self.__bad_box()
  1055. if lookingatre('(Package |Class |LaTeX |pdfTeX )?(\w+ )?warning: ', re.I):
  1056. return self.__generic_warning()
  1057. if lookingatre('No file .*\\.tex\\.$', re.M):
  1058. # This happens with \includes of missing files. For
  1059. # whatever reason, LaTeX doesn't consider this even
  1060. # worth a warning, but I do!
  1061. self.__message('warning', None,
  1062. self.__simplify_message(
  1063. self.__consume_line(unwrap=True).strip()))
  1064. self.__missing_includes = True
  1065. return
  1066. # Other things that are common and irrelevant
  1067. if lookingatre(r'(Package|Class|LaTeX) (\w+ )?info: ', re.I):
  1068. return self.__generic_info()
  1069. if lookingatre(r'(Document Class|File|Package): '):
  1070. # Output from "\ProvidesX"
  1071. return self.__consume_line(unwrap=True)
  1072. if lookingatre(r'\\\w+=\\[a-z]+\d+\n'):
  1073. # Output from "\new{count,dimen,skip,...}"
  1074. return self.__consume_line(unwrap=True)
  1075. # print(self.__data[self.__lstart:self.__lend].rstrip())
  1076. # self.__pos = self.__lend
  1077. # return
  1078. # Now that we've substantially reduced the spew and hopefully
  1079. # eliminated all input echoing, we're left with the file name
  1080. # stack, page outs, and random other messages from both TeX
  1081. # and various packages. We'll assume at this point that all
  1082. # parentheses belong to the file name stack or, if they're in
  1083. # random other messages, they're at least balanced and nothing
  1084. # interesting happens between them. For page outs, ship_out
  1085. # prints a space if not at the beginning of a line, then a
  1086. # "[", then the page number being shipped out (this is
  1087. # usually, but not always, followed by "]").
  1088. m = re.compile(r'[(){}\n]|(?<=[\n ])\[\d+', re.M).\
  1089. search(self.__data, self.__pos)
  1090. if m is None:
  1091. self.__pos = len(self.__data)
  1092. return
  1093. self.__pos = m.start() + 1
  1094. ch = self.__data[m.start()]
  1095. if ch == '\n':
  1096. # Save this as a known-good restart point for incremental
  1097. # parsing, since we definitely didn't match any of the
  1098. # known message types above.
  1099. self.__save_restart_point()
  1100. elif ch == '[':
  1101. # This is printed at the end of a page, so we're beginning
  1102. # page n+1.
  1103. self.__pageno = int(self.__lookingatre(r'\d+').group(0)) + 1
  1104. elif ((self.__data.startswith('`', m.start() - 1) or
  1105. self.__data.startswith('`\\', m.start() - 2)) and
  1106. self.__data.startswith('\'', m.start() + 1)):
  1107. # (, ), {, and } sometimes appear in TeX's error
  1108. # descriptions, but they're always in `'s (and sometimes
  1109. # backslashed)
  1110. return
  1111. elif ch == '(':
  1112. # XXX Check that the stack doesn't drop to empty and then re-grow
  1113. first = self.__first_file is None and self.__col == 1
  1114. filename = self.__filename()
  1115. self.__file_stack.append(filename)
  1116. if first:
  1117. self.__first_file = filename
  1118. if self.TRACE:
  1119. print('<{}>{}enter {}'.format(
  1120. m.start(), ' '*len(self.__file_stack), filename))
  1121. elif ch == ')':
  1122. if len(self.__file_stack):
  1123. if self.TRACE:
  1124. print('<{}>{}exit {}'.format(
  1125. m.start(), ' '*len(self.__file_stack),
  1126. self.__file_stack[-1]))
  1127. self.__file_stack.pop()
  1128. else:
  1129. self.__message('warning', None,
  1130. "extra `)' in log; file names may be wrong ")
  1131. elif ch == '{':
  1132. # TeX uses this for various things we want to ignore, like
  1133. # file names and print_mark. Consume up to the '}'
  1134. epos = self.__data.find('}', self.__pos)
  1135. if epos != -1:
  1136. self.__pos = epos + 1
  1137. else:
  1138. self.__message('warning', None,
  1139. "unbalanced `{' in log; file names may be wrong")
  1140. elif ch == '}':
  1141. self.__message('warning', None,
  1142. "extra `}' in log; file names may be wrong")
  1143. def __filename(self):
  1144. initcol = self.__col
  1145. first = True
  1146. name = ''
  1147. # File names may wrap, but if they do, TeX will always print a
  1148. # newline before the open paren
  1149. while first or (initcol == 1 and self.__lookingat('\n')
  1150. and self.__col >= 79):
  1151. if not first:
  1152. self.__pos += 1
  1153. m = self.__lookingatre(r'[^(){} \n]*')
  1154. name += m.group()
  1155. self.__pos = m.end()
  1156. first = False
  1157. return name
  1158. def __simplify_message(self, msg):
  1159. msg = re.sub(r'^(?:Package |Class |LaTeX |pdfTeX )?([^ ]+) (?:Error|Warning): ',
  1160. r'[\1] ', msg, flags=re.I)
  1161. msg = re.sub(r'\.$', '', msg)
  1162. msg = re.sub(r'has occurred (while \\output is active)', r'\1', msg)
  1163. return msg
  1164. def __errmessage(self):
  1165. # Procedure print_err (including \errmessage, itself used by
  1166. # LaTeX's \GenericError and all of its callers), as well as
  1167. # fatal_error. Prints "\n! " followed by error text
  1168. # ("Emergency stop" in the case of fatal_error). print_err is
  1169. # always followed by a call to error, which prints a period,
  1170. # and a newline...
  1171. msg = self.__consume_line(unwrap=True)[1:].strip()
  1172. is_fatal_error = (msg == 'Emergency stop.')
  1173. msg = self.__simplify_message(msg)
  1174. # ... and then calls show_context, which prints the input
  1175. # stack as pairs of lines giving the context. These context
  1176. # lines are truncated so they never wrap. Each pair of lines
  1177. # will start with either "<something> " if the context is a
  1178. # token list, "<*> " for terminal input (or command line),
  1179. # "<read ...>" for stream reads, something like "\macroname
  1180. # #1->" for macros (though everything after \macroname is
  1181. # subject to being elided as "..."), or "l.[0-9]+ " if it's a
  1182. # file. This is followed by the errant input with a line
  1183. # break where the error occurred.
  1184. lineno = None
  1185. found_context = False
  1186. stack = []
  1187. while self.__avail:
  1188. m1 = self.__lookingatre(r'<([a-z ]+|\*|read [^ >]*)> |\\.*(->|...)')
  1189. m2 = self.__lookingatre('l\.[0-9]+ ')
  1190. if m1:
  1191. found_context = True
  1192. pre = self.__consume_line().rstrip('\n')
  1193. stack.append(pre)
  1194. elif m2:
  1195. found_context = True
  1196. pre = self.__consume_line().rstrip('\n')
  1197. info, rest = pre.split(' ', 1)
  1198. lineno = int(info[2:])
  1199. stack.append(rest)
  1200. elif found_context:
  1201. # Done with context
  1202. break
  1203. if found_context:
  1204. # Consume the second context line
  1205. post = self.__consume_line().rstrip('\n')
  1206. # Clean up goofy trailing ^^M TeX sometimes includes
  1207. post = re.sub(r'\^\^M$', '', post)
  1208. if post[:len(pre)].isspace() and not post.isspace():
  1209. stack.append(len(stack[-1]))
  1210. stack[-2] += post[len(pre):]
  1211. else:
  1212. # If we haven't found the context, skip the line.
  1213. self.__skip_line()
  1214. stack_msg = ''
  1215. for i, trace in enumerate(stack):
  1216. stack_msg += ('\n ' + (' ' * trace) + '^'
  1217. if isinstance(trace, int) else
  1218. '\n at ' + trace.rstrip() if i == 0 else
  1219. '\n from ' + trace.rstrip())
  1220. if is_fatal_error:
  1221. # fatal_error always prints one additional line of message
  1222. info = self.__consume_line().strip()
  1223. if info.startswith('*** '):
  1224. info = info[4:]
  1225. msg += ': ' + info.lstrip('(').rstrip(')')
  1226. self.__message('error', lineno, msg + stack_msg)
  1227. self.__fatal_error = True
  1228. def __pdftex_fail(self):
  1229. # Procedure pdftex_fail. Prints "\n!pdfTeX error: ", the
  1230. # message, and a newline. Unlike print_err, there's never
  1231. # context.
  1232. msg = self.__consume_line(unwrap=True)[1:].strip()
  1233. msg = self.__simplify_message(msg)
  1234. self.__message('error', None, msg)
  1235. def __runaway(self):
  1236. # Procedure runaway. Prints "\nRunaway ...\n" possibly
  1237. # followed by token list (user text). Always followed by a
  1238. # call to print_err, so skip lines until we see the print_err.
  1239. self.__skip_line() # Skip "Runaway ...\n"
  1240. if not self.__lookingat('! ') and self.__avail:
  1241. # Skip token list, which is limited to one line
  1242. self.__skip_line()
  1243. def __bad_box(self):
  1244. # Function hpack and vpack. hpack prints a warning, a
  1245. # newline, then a short_display of the offending text.
  1246. # Unfortunately, there's nothing indicating the end of the
  1247. # offending text, but it should be on one (possible wrapped)
  1248. # line. vpack prints a warning and then, *unless output is
  1249. # active*, a newline. The missing newline is probably a bug,
  1250. # but it sure makes our lives harder.
  1251. origpos = self.__pos
  1252. msg = self.__consume_line()
  1253. m = re.search(r' in (?:paragraph|alignment) at lines ([0-9]+)--([0-9]+)', msg) or \
  1254. re.search(r' detected at line ([0-9]+)', msg)
  1255. if m:
  1256. # Sometimes TeX prints crazy line ranges like "at lines
  1257. # 8500--250". The lower number seems roughly sane, so use
  1258. # that. I'm not sure what causes this, but it may be
  1259. # related to shipout routines messing up line registers.
  1260. lineno = min(int(m.group(1)), int(m.groups()[-1]))
  1261. msg = msg[:m.start()]
  1262. else:
  1263. m = re.search(r' while \\output is active', msg)
  1264. if m:
  1265. lineno = None
  1266. msg = msg[:m.end()]
  1267. else:
  1268. self.__message('warning', None,
  1269. 'malformed bad box message in log')
  1270. return
  1271. # Back up to the end of the known message text
  1272. self.__pos = origpos + m.end()
  1273. if self.__lookingat('\n'):
  1274. # We have a newline, so consume it and look for the
  1275. # offending text.
  1276. self.__pos += 1
  1277. # If there is offending text, it will start with a font
  1278. # name, which will start with a \.
  1279. if 'hbox' in msg and self.__lookingat('\\'):
  1280. self.__consume_line(unwrap=True)
  1281. msg = self.__simplify_message(msg) + ' (page {})'.format(self.__pageno)
  1282. cls = msg.split(None, 1)[0].lower()
  1283. self.__message('warning', lineno, msg, cls=cls)
  1284. def __generic_warning(self):
  1285. # Warnings produced by LaTeX's \GenericWarning (which is
  1286. # called by \{Package,Class}Warning and \@latex@warning),
  1287. # warnings produced by pdftex_warn, and other random warnings.
  1288. msg, cls = self.__generic_info()
  1289. # Most warnings include an input line emitted by \on@line
  1290. m = re.search(' on input line ([0-9]+)', msg)
  1291. if m:
  1292. lineno = int(m.group(1))
  1293. msg = msg[:m.start()]
  1294. else:
  1295. lineno = None
  1296. msg = self.__simplify_message(msg)
  1297. self.__message('warning', lineno, msg, cls=cls)
  1298. def __generic_info(self):
  1299. # Messages produced by LaTeX's \Generic{Error,Warning,Info}
  1300. # and things that look like them
  1301. msg = self.__consume_line(unwrap=True).strip()
  1302. # Package and class messages are continued with lines
  1303. # containing '(package name) '
  1304. pkg_name = msg.split(' ', 2)[1]
  1305. prefix = '(' + pkg_name + ') '
  1306. while self.__lookingat(prefix):
  1307. # Collect extra lines. It's important that we keep these
  1308. # because they may contain context information like line
  1309. # numbers.
  1310. extra = self.__consume_line(unwrap=True)
  1311. msg += ' ' + extra[len(prefix):].strip()
  1312. return msg, pkg_name.lower()
  1313. ##################################################################
  1314. # BibTeX task
  1315. #
  1316. class BibTeX(Task):
  1317. def __init__(self, db, latex_task, cmd, cmd_args, nowarns, obj_dir):
  1318. super().__init__(db, 'bibtex::' + normalize_input_path(
  1319. latex_task.get_tex_filename()))
  1320. self.__latex_task = latex_task
  1321. self.__cmd = cmd
  1322. self.__cmd_args = cmd_args
  1323. self.__obj_dir = obj_dir
  1324. def stable(self):
  1325. # If bibtex doesn't have its inputs, then it's stable because
  1326. # it has no effect on system state.
  1327. jobname = self.__latex_task.get_jobname()
  1328. if jobname is None:
  1329. # We don't know where the .aux file is until latex has run
  1330. return True
  1331. if not os.path.exists(jobname + '.aux'):
  1332. # Input isn't ready, so bibtex will simply fail without
  1333. # affecting system state. Hence, this task is trivially
  1334. # stable.
  1335. return True
  1336. if not self.__find_bib_cmds(os.path.dirname(jobname), jobname + '.aux'):
  1337. # The tex file doesn't refer to any bibliographic data, so
  1338. # don't run bibtex.
  1339. return True
  1340. return super().stable()
  1341. def __find_bib_cmds(self, basedir, auxname, stack=()):
  1342. debug('scanning for bib commands in {}'.format(auxname))
  1343. if auxname in stack:
  1344. raise TaskError('.aux file loop')
  1345. stack = stack + (auxname,)
  1346. try:
  1347. aux_data = open(auxname, errors='surrogateescape').read()
  1348. except FileNotFoundError:
  1349. # The aux file may not exist if latex aborted
  1350. return False
  1351. if re.search(r'^\\bibstyle\{', aux_data, flags=re.M) or \
  1352. re.search(r'^\\bibdata\{', aux_data, flags=re.M):
  1353. return True
  1354. if re.search(r'^\\abx@aux@cite\{', aux_data, flags=re.M):
  1355. # biber citation
  1356. return True
  1357. # Recurse into included aux files (see aux_input_command), in
  1358. # case \bibliography appears in an \included file.
  1359. for m in re.finditer(r'^\\@input\{([^}]*)\}', aux_data, flags=re.M):
  1360. if self.__find_bib_cmds(basedir, os.path.join(basedir, m.group(1)),
  1361. stack):
  1362. return True
  1363. return False
  1364. def _input_args(self):
  1365. if self.__is_biber():
  1366. aux_name = os.path.basename(self.__latex_task.get_jobname())
  1367. else:
  1368. aux_name = os.path.basename(self.__latex_task.get_jobname()) + '.aux'
  1369. return [self.__cmd] + self.__cmd_args + [aux_name]
  1370. def _input_cwd(self):
  1371. return os.path.dirname(self.__latex_task.get_jobname())
  1372. def _input_auxfile(self, auxname):
  1373. # We don't consider the .aux files regular inputs.
  1374. # Instead, we extract just the bit that BibTeX cares about
  1375. # and depend on that. See get_aux_command_and_process in
  1376. # bibtex.web.
  1377. debug('hashing filtered aux file {}', auxname)
  1378. try:
  1379. with open(auxname, 'rb') as aux:
  1380. h = hashlib.sha256()
  1381. for line in aux:
  1382. if line.startswith((b'\\citation{', b'\\bibdata{',
  1383. b'\\bibstyle{', b'\\@input{',
  1384. b'\\abx@aux@cite{')):
  1385. h.update(line)
  1386. return h.hexdigest()
  1387. except FileNotFoundError:
  1388. debug('{} does not exist', auxname)
  1389. return None
  1390. def __path_join(self, first, rest):
  1391. if rest is None:
  1392. # Append ':' to keep the default search path
  1393. return first + ':'
  1394. return first + ':' + rest
  1395. def __is_biber(self):
  1396. return "biber" in self.__cmd
  1397. def _execute(self):
  1398. # This gets complicated when \include is involved. \include
  1399. # switches to a different aux file and records its path in the
  1400. # main aux file. However, BibTeX does not consider this path
  1401. # to be relative to the location of the main aux file, so we
  1402. # have to run BibTeX *in the output directory* for it to
  1403. # follow these includes (there's no way to tell BibTeX other
  1404. # locations to search). Unfortunately, this means BibTeX will
  1405. # no longer be able to find local bib or bst files, but so we
  1406. # tell it where to look by setting BIBINPUTS and BSTINPUTS
  1407. # (luckily we can control this search). We have to pass this
  1408. # same environment down to Kpathsea when we resolve the paths
  1409. # in BibTeX's log.
  1410. args, cwd = self._input('args'), self._input('cwd')
  1411. debug('running {} in {}', args, cwd)
  1412. env = os.environ.copy()
  1413. env['BIBINPUTS'] = self.__path_join(os.getcwd(), env.get('BIBINPUTS'))
  1414. env['BSTINPUTS'] = self.__path_join(os.getcwd(), env.get('BSTINPUTS'))
  1415. try:
  1416. verbose_cmd(args, cwd, env)
  1417. p = subprocess.Popen(args, cwd=cwd, env=env,
  1418. stdin=subprocess.DEVNULL,
  1419. stdout=subprocess.PIPE,
  1420. stderr=subprocess.STDOUT)
  1421. stdout = self.__feed_terminal(p.stdout)
  1422. status = p.wait()
  1423. except OSError as e:
  1424. raise TaskError('failed to execute bibtex task: ' + str(e)) from e
  1425. inputs, auxnames, outbase = self.__parse_inputs(stdout, cwd, env)
  1426. if not inputs and not auxnames:
  1427. # BibTeX failed catastrophically.
  1428. print(stdout, file=sys.stderr)
  1429. raise TaskError('failed to execute bibtex task')
  1430. # Register environment variable inputs
  1431. for env_var in ['TEXMFOUTPUT', 'BSTINPUTS', 'BIBINPUTS', 'PATH']:
  1432. self._input('env', env_var)
  1433. # Register file inputs
  1434. for path in auxnames:
  1435. self._input('auxfile', path)
  1436. for path in inputs:
  1437. self._input('file', path)
  1438. if self.__is_biber():
  1439. outbase = os.path.join(cwd, outbase)
  1440. outputs = [outbase + '.bbl', outbase + '.blg']
  1441. return RunResult(outputs, {'outbase': outbase, 'status': status,
  1442. 'inputs': inputs})
  1443. def __feed_terminal(self, stdout):
  1444. with Progress('bibtex') as progress:
  1445. buf, linebuf = [], ''
  1446. while True:
  1447. data = os.read(stdout.fileno(), 4096)
  1448. if not data:
  1449. break
  1450. # See "A note about encoding" above
  1451. data = data.decode('ascii', errors='surrogateescape')
  1452. buf.append(data)
  1453. linebuf += data
  1454. while '\n' in linebuf:
  1455. line, _, linebuf = linebuf.partition('\n')
  1456. if line.startswith('Database file'):
  1457. progress.update(line.split(': ', 1)[1])
  1458. return ''.join(buf)
  1459. def __parse_inputs(self, log, cwd, env):
  1460. # BibTeX conveniently logs every file that it opens, and its
  1461. # log is actually sensible (see calls to a_open_in in
  1462. # bibtex.web.) The only trick is that these file names are
  1463. # pre-kpathsea lookup and may be relative to the directory we
  1464. # ran BibTeX in.
  1465. #
  1466. # Because BibTeX actually depends on very little in the .aux
  1467. # file (and it's likely other things will change in the .aux
  1468. # file), we don't count the whole .aux file as an input, but
  1469. # instead depend only on the lines that matter to BibTeX.
  1470. kpathsea = Kpathsea('bibtex')
  1471. inputs = []
  1472. auxnames = []
  1473. outbase = None
  1474. for line in log.splitlines():
  1475. m = re.match('(?:The top-level auxiliary file:'
  1476. '|A level-[0-9]+ auxiliary file:) (.*)', line)
  1477. if m:
  1478. auxnames.append(os.path.join(cwd, m.group(1)))
  1479. continue
  1480. m = re.match('(?:(The style file:)|(Database file #[0-9]+:)) (.*)',
  1481. line)
  1482. if m:
  1483. filename = m.group(3)
  1484. if m.group(1):
  1485. filename = kpathsea.find_file(filename, 'bst', cwd, env)
  1486. elif m.group(2):
  1487. filename = kpathsea.find_file(filename, 'bib', cwd, env)
  1488. # If this path is relative to the source directory,
  1489. # clean it up for error reporting and portability of
  1490. # the dependency DB
  1491. if filename.startswith('/'):
  1492. relname = os.path.relpath(filename)
  1493. if '../' not in relname:
  1494. filename = relname
  1495. inputs.append(filename)
  1496. # biber output
  1497. m = re.search("Found BibTeX data source '(.*?)'",
  1498. line)
  1499. if m:
  1500. filename = m.group(1)
  1501. inputs.append(filename)
  1502. m = re.search("Logfile is '(.*?)'", line)
  1503. if m:
  1504. outbase = m.group(1)[:-4]
  1505. if outbase is None:
  1506. outbase = auxnames[0][:-4]
  1507. return inputs, auxnames, outbase
  1508. def report(self):
  1509. extra = self._get_result_extra()
  1510. if extra is None:
  1511. return 0
  1512. # Parse and pretty-print the log
  1513. log = open(extra['outbase'] + '.blg', 'rt').read()
  1514. inputs = extra['inputs']
  1515. for msg in BibTeXFilter(log, inputs).get_messages():
  1516. msg.emit()
  1517. # BibTeX exits with 1 if there are warnings, 2 if there are
  1518. # errors, and 3 if there are fatal errors (sysdep.h).
  1519. # Translate to a normal UNIX exit status.
  1520. if extra['status'] >= 2:
  1521. return 1
  1522. return 0
  1523. class BibTeXFilter:
  1524. def __init__(self, data, inputs):
  1525. self.__inputs = inputs
  1526. self.__key_locs = None
  1527. self.__messages = []
  1528. prev_line = ''
  1529. for line in data.splitlines():
  1530. msg = self.__process_line(prev_line, line)
  1531. if msg is not None:
  1532. self.__messages.append(Message(*msg))
  1533. prev_line = line
  1534. def get_messages(self):
  1535. """Return a list of warning and error Messages."""
  1536. # BibTeX reports most errors in no particular order. Sort by
  1537. # file and line.
  1538. return sorted(self.__messages,
  1539. key=lambda msg: (msg.filename or '', msg.lineno or 0))
  1540. def __process_line(self, prev_line, line):
  1541. m = None
  1542. def match(regexp):
  1543. nonlocal m
  1544. m = re.match(regexp, line)
  1545. return m
  1546. # BibTeX has many error paths, but luckily the set is closed,
  1547. # so we can find all of them. This first case is the
  1548. # workhorse format.
  1549. #
  1550. # AUX errors: aux_err/aux_err_return/aux_err_print
  1551. #
  1552. # BST errors: bst_ln_num_print/bst_err/
  1553. # bst_err_print_and_look_for_blank_line_return/
  1554. # bst_warn_print/bst_warn/
  1555. # skip_token/skip_token_print/
  1556. # bst_ext_warn/bst_ext_warn_print/
  1557. # bst_ex_warn/bst_ex_warn_print/
  1558. # bst_mild_ex_warn/bst_mild_ex_warn_print/
  1559. # bst_string_size_exceeded
  1560. #
  1561. # BIB errors: bib_ln_num_print/
  1562. # bib_err_print/bib_err/
  1563. # bib_warn_print/bib_warn/
  1564. # bib_one_of_two_expected_err/macro_name_warning/
  1565. if match('(.*?)---?line ([0-9]+) of file (.*)'):
  1566. # Sometimes the real error is printed on the previous line
  1567. if m.group(1) == 'while executing':
  1568. # bst_ex_warn. The real message is on the previous line
  1569. text = prev_line
  1570. else:
  1571. text = m.group(1) or prev_line
  1572. typ, msg = self.__canonicalize(text)
  1573. return (typ, m.group(3), int(m.group(2)), msg)
  1574. # overflow/print_overflow
  1575. if match('Sorry---you\'ve exceeded BibTeX\'s (.*)'):
  1576. return ('error', None, None, 'capacity exceeded: ' + m.group(1))
  1577. # confusion/print_confusion
  1578. if match('(.*)---this can\'t happen$'):
  1579. return ('error', None, None, 'internal error: ' + m.group(1))
  1580. # aux_end_err
  1581. if match('I found (no .*)---while reading file (.*)'):
  1582. return ('error', m.group(2), None, m.group(1))
  1583. # bad_cross_reference_print/
  1584. # nonexistent_cross_reference_error/
  1585. # @<Complain about a nested cross reference@>
  1586. #
  1587. # This is split across two lines. Match the second.
  1588. if match('^refers to entry "'):
  1589. typ, msg = self.__canonicalize(prev_line + ' ' + line)
  1590. msg = re.sub('^a (bad cross reference)', '\\1', msg)
  1591. # Try to give this key a location
  1592. filename = lineno = None
  1593. m2 = re.search(r'--entry "[^"]"', prev_line)
  1594. if m2:
  1595. filename, lineno = self.__find_key(m2.group(1))
  1596. return (typ, filename, lineno, msg)
  1597. # print_missing_entry
  1598. if match('Warning--I didn\'t find a database entry for (".*")'):
  1599. return ('warning', None, None,
  1600. 'no database entry for ' + m.group(1))
  1601. # x_warning
  1602. if match('Warning--(.*)'):
  1603. # Most formats give warnings about "something in <key>".
  1604. # Try to match it up.
  1605. filename = lineno = None
  1606. for m2 in reversed(list(re.finditer(r' in ([^, \t\n]+)\b', line))):
  1607. if m2:
  1608. filename, lineno = self.__find_key(m2.group(1))
  1609. if filename:
  1610. break
  1611. return ('warning', filename, lineno, m.group(1))
  1612. # @<Clean up and leave@>
  1613. if match('Aborted at line ([0-9]+) of file (.*)'):
  1614. return ('info', m.group(2), int(m.group(1)), 'aborted')
  1615. # biber type errors
  1616. if match('^.*> WARN - (.*)$'):
  1617. print ('warning', None, None, m.group(1))
  1618. m2 = re.match("(.*) in file '(.*?)', skipping ...", m.group(1))
  1619. if m2:
  1620. return ('warning', m2.group(2), "0", m2.group(1))
  1621. return ('warning', None, None, m.group(1))
  1622. if match('^.*> ERROR - (.*)$'):
  1623. m2 = re.match("BibTeX subsystem: (.*?), line (\d+), (.*)$", m.group(1))
  1624. if m2:
  1625. return ('error', m2.group(1), m2.group(2), m2.group(3))
  1626. return ('error', None, None, m.group(1))
  1627. def __canonicalize(self, msg):
  1628. if msg.startswith('Warning'):
  1629. msg = re.sub('^Warning-*', '', msg)
  1630. typ = 'warning'
  1631. else:
  1632. typ = 'error'
  1633. msg = re.sub('^I(\'m| was)? ', '', msg)
  1634. msg = msg[:1].lower() + msg[1:]
  1635. return typ, msg
  1636. def __find_key(self, key):
  1637. if self.__key_locs is None:
  1638. p = BibTeXKeyParser()
  1639. self.__key_locs = {}
  1640. for filename in self.__inputs:
  1641. data = open(filename, 'rt', errors='surrogateescape').read()
  1642. for pkey, lineno in p.parse(data):
  1643. self.__key_locs.setdefault(pkey, (filename, lineno))
  1644. return self.__key_locs.get(key, (None, None))
  1645. class BibTeXKeyParser:
  1646. """Just enough of a BibTeX parser to find keys."""
  1647. def parse(self, data):
  1648. IDENT_RE = '(?![0-9])([^\x00-\x20\x80-\xff \t"#%\'(),={}]+)'
  1649. self.__pos, self.__data = 0, data
  1650. # Find the next entry
  1651. while self.__consume('[^@]*@[ \t\n]*'):
  1652. # What type of entry?
  1653. if not self.__consume(IDENT_RE + '[ \t\n]*'):
  1654. continue
  1655. typ = self.__m.group(1)
  1656. if typ == 'comment':
  1657. continue
  1658. start = self.__pos
  1659. if not self.__consume('([{(])[ \t\n]*'):
  1660. continue
  1661. closing, key_re = {'{' : ('}', '([^, \t\n}]*)'),
  1662. '(' : (')', '([^, \t\n]*)')}[self.__m.group(1)]
  1663. if typ not in ('preamble', 'string'):
  1664. # Regular entry; get key
  1665. if self.__consume(key_re):
  1666. yield self.__m.group(1), self.__lineno()
  1667. # Consume body of entry
  1668. self.__pos = start
  1669. self.__balanced(closing)
  1670. def __consume(self, regexp):
  1671. self.__m = re.compile(regexp).match(self.__data, self.__pos)
  1672. if self.__m:
  1673. self.__pos = self.__m.end()
  1674. return self.__m
  1675. def __lineno(self):
  1676. return self.__data.count('\n', 0, self.__pos) + 1
  1677. def __balanced(self, closing):
  1678. self.__pos += 1
  1679. level = 0
  1680. skip = re.compile('[{}' + closing + ']')
  1681. while True:
  1682. m = skip.search(self.__data, self.__pos)
  1683. if not m:
  1684. break
  1685. self.__pos = m.end()
  1686. ch = m.group(0)
  1687. if level == 0 and ch == closing:
  1688. break
  1689. elif ch == '{':
  1690. level += 1
  1691. elif ch == '}':
  1692. level -= 1
  1693. class Kpathsea:
  1694. def __init__(self, program_name):
  1695. self.__progname = program_name
  1696. def find_file(self, name, format, cwd=None, env=None):
  1697. """Return the resolved path of 'name' or None."""
  1698. args = ['kpsewhich', '-progname', self.__progname, '-format', format,
  1699. name]
  1700. try:
  1701. verbose_cmd(args, cwd, env)
  1702. path = subprocess.check_output(
  1703. args, cwd=cwd, env=env, universal_newlines=True).strip()
  1704. except subprocess.CalledProcessError as e:
  1705. if e.returncode != 1:
  1706. raise
  1707. return None
  1708. if cwd is None:
  1709. return path
  1710. return os.path.join(cwd, path)
  1711. if __name__ == "__main__":
  1712. main()