Debian Codegraph @

texk/texlive/linked_scripts/spix/spix.py

raw
1 #!/usr/bin/env python3
2
3 # Copyright 2020-2022 Louis Paternault
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17
18 """Compile a `.tex` file, executing commands that are set inside the file itself."""
19
20 import argparse
21 import logging
22 import os
23 import pathlib
24 import re
25 import subprocess
26 import sys
27
28 NAME = "SpiX"
29 VERSION = "1.3.0"
30
31 RE_EMPTY = re.compile("^ *$")
32 RE_COMMENT = re.compile("^ *%")
33 RE_COMMAND = re.compile(r"^%\$ ?(.*)$")
34
35
36 class SpixError(Exception):
37 """Exception that should be catched and nicely displayed to user."""
38
39
40 def parse_lines(lines):
41 """Parse line to find code snippets.
42
43 :param iterable lines: Lines to parte (typically ``open("foo.tex").readlines()``.
44 :return: Iterator over snippets (as strings).
45 """
46 snippet = None
47 for line in lines:
48 line = line.rstrip("\n")
49 if RE_COMMAND.match(line):
50 match = RE_COMMAND.match(line)
51 if snippet is None:
52 snippet = ""
53 else:
54 snippet += "\n"
55 snippet += match.groups()[0]
56 elif RE_EMPTY.match(line) or RE_COMMENT.match(line):
57 if snippet is not None:
58 yield snippet
59 snippet = None
60 else:
61 break
62 if snippet is not None:
63 yield snippet
64
65
66 def compiletex(filename, *, dryrun=False):
67 """Read commands from file, and execute them.
68
69 :param str filename: File to process.
70 :param bool dryrun: If ``True``, print commands to run, but do not execute them.
71 """
72 env = os.environ
73 filename = pathlib.Path(filename)
74 env["texname"] = filename.name
75 env["basename"] = filename.stem
76
77 try:
78 # pylint: disable=unspecified-encoding
79 with open(filename, errors="ignore") as file:
80 for snippet in parse_lines(file.readlines()):
81 print(snippet)
82 sys.stdout.flush()
83 if dryrun:
84 continue
85
86 subprocess.check_call(
87 ["sh", "-c", snippet, NAME, filename.name],
88 cwd=(pathlib.Path.cwd() / filename).parent,
89 env=env,
90 )
91 except subprocess.CalledProcessError as error:
92 raise SpixError() from error
93 except IsADirectoryError as error:
94 raise SpixError(str(error)) from error
95
96
97 def commandline_parser():
98 """Return a command line parser.
99
100 :rtype: argparse.ArgumentParser
101 """
102 parser = argparse.ArgumentParser(
103 prog="spix",
104 description=(
105 "Compile a `.tex` file, "
106 "executing commands that are set inside the file itself."
107 ),
108 )
109 parser.add_argument(
110 "-n",
111 "--dry-run",
112 action="store_true",
113 help="Print the commands that would be executed, but do not execute them.",
114 )
115 parser.add_argument(
116 "--version",
117 help="Show version and exit.",
118 action="version",
119 version=f"{NAME} {VERSION}",
120 )
121 parser.add_argument("FILE", nargs=1, help="File to process.")
122
123 return parser
124
125
126 def main():
127 """Main function."""
128 arguments = commandline_parser().parse_args()
129
130 if os.path.exists(arguments.FILE[0]):
131 arguments.FILE = arguments.FILE[0]
132 elif os.path.exists(f"{arguments.FILE[0]}.tex"):
133 arguments.FILE = f"{arguments.FILE[0]}.tex"
134 else:
135 logging.error("""File not found: "%s".""", arguments.FILE[0])
136 sys.exit(1)
137
138 try:
139 compiletex(arguments.FILE, dryrun=arguments.dry_run)
140 except SpixError as error:
141 if str(error):
142 logging.error(error)
143 sys.exit(1)
144
145
146 if __name__ == "__main__":
147 main()