notex-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- notex/__init__.py +52 -0
- notex/cli.py +403 -0
- notex/scaffold.py +87 -0
- notex/sessions.py +177 -0
- notex/templates/LICENSE +674 -0
- notex/templates/cols-formulae/letterfonts.tex +6 -0
- notex/templates/cols-formulae/macros.tex +40 -0
- notex/templates/cols-formulae/preamble.tex +23 -0
- notex/templates/cols-formulae/template.tex +14 -0
- notex/templates/grand/bibliography.bib +0 -0
- notex/templates/grand/chapters/ch1.tex +5 -0
- notex/templates/grand/letterfonts.tex +6 -0
- notex/templates/grand/macros.tex +33 -0
- notex/templates/grand/preamble.tex +161 -0
- notex/templates/grand/template.tex +27 -0
- notex/templates/note/letterfonts.tex +6 -0
- notex/templates/note/macros.tex +33 -0
- notex/templates/note/preamble.tex +163 -0
- notex/templates/note/template.tex +28 -0
- notex/templates/problems/letterfonts.tex +6 -0
- notex/templates/problems/macros.tex +46 -0
- notex/templates/problems/preamble.tex +143 -0
- notex/templates/problems/template.tex +28 -0
- notex/templates/single-formulae/letterfonts.tex +6 -0
- notex/templates/single-formulae/macros.tex +40 -0
- notex/templates/single-formulae/preamble.tex +22 -0
- notex/templates/single-formulae/template.tex +13 -0
- notex/terminal.py +195 -0
- notex_cli-0.1.0.dist-info/METADATA +141 -0
- notex_cli-0.1.0.dist-info/RECORD +34 -0
- notex_cli-0.1.0.dist-info/WHEEL +4 -0
- notex_cli-0.1.0.dist-info/entry_points.txt +5 -0
- notex_cli-0.1.0.dist-info/licenses/LICENSE +674 -0
- notex_cli-0.1.0.dist-info/licenses/notex/templates/LICENSE +674 -0
notex/__init__.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Dated note folders for university terms, optionally started from LaTeX templates.
|
|
2
|
+
|
|
3
|
+
`__all__` is the API: scanning and naming session folders (`sessions`), creating one, empty or
|
|
4
|
+
from a template (`scaffold`). Both are pure: no printing, no exit, no environment.
|
|
5
|
+
|
|
6
|
+
`cli` and `terminal` are the application: they ask, print and may exit, so they stay out of
|
|
7
|
+
the API.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from importlib import metadata as _metadata
|
|
11
|
+
|
|
12
|
+
from notex.scaffold import TEMPLATE_MAIN_FILE, create_session, latex_escape
|
|
13
|
+
from notex.sessions import (
|
|
14
|
+
SESSION_DATE_FORMAT,
|
|
15
|
+
SUBJECT_DEPTH,
|
|
16
|
+
TERM_DEPTH,
|
|
17
|
+
Session,
|
|
18
|
+
explicit_counter,
|
|
19
|
+
find_sessions,
|
|
20
|
+
kind_names,
|
|
21
|
+
newest_term,
|
|
22
|
+
next_session_name,
|
|
23
|
+
session_date,
|
|
24
|
+
term_folders,
|
|
25
|
+
visible_subdirectories,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
'SESSION_DATE_FORMAT',
|
|
30
|
+
'SUBJECT_DEPTH',
|
|
31
|
+
'TEMPLATE_MAIN_FILE',
|
|
32
|
+
'TERM_DEPTH',
|
|
33
|
+
'Session',
|
|
34
|
+
'create_session',
|
|
35
|
+
'explicit_counter',
|
|
36
|
+
'find_sessions',
|
|
37
|
+
'kind_names',
|
|
38
|
+
'latex_escape',
|
|
39
|
+
'newest_term',
|
|
40
|
+
'next_session_name',
|
|
41
|
+
'session_date',
|
|
42
|
+
'term_folders',
|
|
43
|
+
'visible_subdirectories',
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
# This is what the version reads when used from a checkout that was not installed.
|
|
47
|
+
_UNKNOWN_VERSION = '0+unknown'
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
__version__ = _metadata.version('notex-cli')
|
|
51
|
+
except _metadata.PackageNotFoundError:
|
|
52
|
+
__version__ = _UNKNOWN_VERSION
|
notex/cli.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""The notex application: the argument parser, the commands new / ls / go, and main().
|
|
2
|
+
|
|
3
|
+
Main reads the environment (root, templates, placeholder values) and asks for anything an
|
|
4
|
+
argument left out; a program that makes note folders wants `notex` instead.
|
|
5
|
+
|
|
6
|
+
NO_COLOR and TERM belong to `terminal`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import datetime
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from notex import __version__, scaffold, sessions, terminal
|
|
19
|
+
|
|
20
|
+
__all__ = ['main']
|
|
21
|
+
|
|
22
|
+
_DEFAULT_ROOT = '~/uni'
|
|
23
|
+
|
|
24
|
+
# The picker entry that means "no template"; also accepted by -t.
|
|
25
|
+
_NO_TEMPLATE = 'none'
|
|
26
|
+
|
|
27
|
+
# The picker entry that means "the subject folder itself", as opposed to a kind folder.
|
|
28
|
+
_NO_KIND = '.'
|
|
29
|
+
|
|
30
|
+
# How the date of the newest session is shown in the overview, e.g. 14 Nov 2026.
|
|
31
|
+
_OVERVIEW_DATE_FORMAT = '%d %b %Y'
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _root_dir() -> Path:
|
|
35
|
+
"""Return the notes root: $NOTEX_ROOT, or ~/uni."""
|
|
36
|
+
return Path(os.environ.get('NOTEX_ROOT', _DEFAULT_ROOT)).expanduser()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _templates_dir() -> Path:
|
|
40
|
+
"""Return the folder holding the templates: $NOTEX_TEMPLATES, or the one bundled."""
|
|
41
|
+
configured = os.environ.get('NOTEX_TEMPLATES')
|
|
42
|
+
if configured:
|
|
43
|
+
return Path(configured)
|
|
44
|
+
return Path(__file__).resolve().parent / 'templates'
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _author_name() -> str:
|
|
48
|
+
"""Return the name for the template's author line.
|
|
49
|
+
|
|
50
|
+
$NOTEX_AUTHOR if set, else git's user.name, else the login name.
|
|
51
|
+
"""
|
|
52
|
+
configured = os.environ.get('NOTEX_AUTHOR')
|
|
53
|
+
if configured:
|
|
54
|
+
return configured
|
|
55
|
+
return _git_user_name() or os.environ.get('USER', '')
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _git_user_name() -> str:
|
|
59
|
+
"""Return git's user.name, or an empty string if there is none or git is missing."""
|
|
60
|
+
try:
|
|
61
|
+
result = subprocess.run(
|
|
62
|
+
['git', 'config', 'user.name'],
|
|
63
|
+
capture_output=True,
|
|
64
|
+
text=True,
|
|
65
|
+
encoding='utf-8',
|
|
66
|
+
check=False,
|
|
67
|
+
)
|
|
68
|
+
except OSError:
|
|
69
|
+
return ''
|
|
70
|
+
|
|
71
|
+
return result.stdout.strip()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
75
|
+
"""Build the argument parser with its three subcommands."""
|
|
76
|
+
parser = argparse.ArgumentParser(prog='notex', description='Dated LaTeX note folders.')
|
|
77
|
+
parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
|
|
78
|
+
|
|
79
|
+
# the destination is called cmd because argparse names it in its error messages
|
|
80
|
+
commands = parser.add_subparsers(dest='cmd', required=True)
|
|
81
|
+
|
|
82
|
+
help_text = 'create a session folder (prints its path)'
|
|
83
|
+
new = commands.add_parser('new', help=help_text, description=help_text)
|
|
84
|
+
new.add_argument(
|
|
85
|
+
'subject',
|
|
86
|
+
nargs='?',
|
|
87
|
+
help='subject folder, used as typed and created if missing; omit it to be asked',
|
|
88
|
+
)
|
|
89
|
+
new.add_argument(
|
|
90
|
+
'-T',
|
|
91
|
+
'--term',
|
|
92
|
+
help='term dir relative to ROOT (created if missing); default: the term with '
|
|
93
|
+
'the newest session',
|
|
94
|
+
)
|
|
95
|
+
new.add_argument(
|
|
96
|
+
'-t',
|
|
97
|
+
'--template',
|
|
98
|
+
help='template to start from, a folder in the templates directory; '
|
|
99
|
+
f'{_NO_TEMPLATE!r} for an empty folder',
|
|
100
|
+
)
|
|
101
|
+
new.add_argument(
|
|
102
|
+
'-k',
|
|
103
|
+
'--kind',
|
|
104
|
+
help='folder inside the subject to put the session in, e.g. lecture; '
|
|
105
|
+
f'{_NO_KIND!r} for the subject itself',
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
help_text = 'list subjects, or sessions of matching subjects'
|
|
109
|
+
ls = commands.add_parser('ls', help=help_text, description=help_text)
|
|
110
|
+
ls.add_argument(
|
|
111
|
+
'-T',
|
|
112
|
+
'--term',
|
|
113
|
+
help='term dir relative to ROOT; default: the term with the newest session',
|
|
114
|
+
)
|
|
115
|
+
ls.add_argument(
|
|
116
|
+
'subject',
|
|
117
|
+
nargs='?',
|
|
118
|
+
help='list the sessions of subjects whose name contains this text',
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
help_text = 'pick a session or subject dir (prints its path)'
|
|
122
|
+
go = commands.add_parser('go', help=help_text, description=help_text)
|
|
123
|
+
go.add_argument(
|
|
124
|
+
'query',
|
|
125
|
+
nargs='?',
|
|
126
|
+
help='start the picker with this text; fzf takes a single match without asking',
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
return parser
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _command_new(arguments: argparse.Namespace, root: Path, templates: Path) -> None:
|
|
133
|
+
"""Create the next session folder for a subject and print its path.
|
|
134
|
+
|
|
135
|
+
Without a subject argument the subject, the kind folder and the template are picked
|
|
136
|
+
interactively (unless -k or -t already gave them). With one, nothing is asked.
|
|
137
|
+
"""
|
|
138
|
+
term = _resolve_term(root, arguments.term)
|
|
139
|
+
interactive = arguments.subject is None
|
|
140
|
+
subject = _choose_subject(arguments.subject, term)
|
|
141
|
+
subject_folder = term / subject
|
|
142
|
+
messages = _new_folder_messages(root, term, subject_folder, arguments.term)
|
|
143
|
+
|
|
144
|
+
kind = _choose_kind(arguments.kind, subject_folder, interactive=interactive)
|
|
145
|
+
template = _choose_template(arguments.template, templates, interactive=interactive)
|
|
146
|
+
# pathlib drops '.', so _NO_KIND means the subject folder itself
|
|
147
|
+
session_folder = _next_session_folder(subject_folder / kind, template)
|
|
148
|
+
template_folder = None if template is None else templates / template
|
|
149
|
+
|
|
150
|
+
_create_session_folder(root, session_folder, template_folder, subject)
|
|
151
|
+
_report_created(root, session_folder, messages)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _command_ls(arguments: argparse.Namespace, root: Path) -> None:
|
|
155
|
+
"""List the subjects of a term with their sessions, or the sessions of matching subjects."""
|
|
156
|
+
term = _resolve_term(root, arguments.term)
|
|
157
|
+
if not term.is_dir():
|
|
158
|
+
terminal.die(f'no such term: {term.relative_to(root)}')
|
|
159
|
+
if arguments.subject:
|
|
160
|
+
_print_session_list(root, term, arguments.subject)
|
|
161
|
+
else:
|
|
162
|
+
_print_overview_table(root, term)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _command_go(arguments: argparse.Namespace, root: Path) -> None:
|
|
166
|
+
"""Let the user pick any session or subject folder and print its path."""
|
|
167
|
+
terms = sessions.term_folders(root)
|
|
168
|
+
choices = _sessions_newest_first(root, terms) + _subjects(root, terms)
|
|
169
|
+
chosen = terminal.pick('go> ', choices, arguments.query or '')
|
|
170
|
+
path = root / chosen
|
|
171
|
+
if not path.is_dir():
|
|
172
|
+
terminal.die(f'not a directory: {path}')
|
|
173
|
+
if not _inside_root(root, path):
|
|
174
|
+
terminal.die(f'not inside {root}: {path}')
|
|
175
|
+
|
|
176
|
+
print(path.absolute())
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
180
|
+
"""Run notex with `argv`, or with the command line arguments; no arguments means `new`."""
|
|
181
|
+
if argv is None:
|
|
182
|
+
argv = sys.argv[1:] or ['new']
|
|
183
|
+
|
|
184
|
+
arguments = _build_parser().parse_args(argv)
|
|
185
|
+
root = _root_dir()
|
|
186
|
+
|
|
187
|
+
if arguments.cmd == 'new':
|
|
188
|
+
_command_new(arguments, root, _templates_dir())
|
|
189
|
+
elif arguments.cmd == 'ls':
|
|
190
|
+
_command_ls(arguments, root)
|
|
191
|
+
else:
|
|
192
|
+
_command_go(arguments, root)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _resolve_term(root: Path, requested: str | None) -> Path:
|
|
196
|
+
"""Return the term named by -T, or else the term with the newest session."""
|
|
197
|
+
if requested:
|
|
198
|
+
return _term_inside_root(root, requested)
|
|
199
|
+
term = sessions.newest_term(root)
|
|
200
|
+
if term is None:
|
|
201
|
+
terminal.die(f'no */*_term dirs under {root}')
|
|
202
|
+
return term
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _term_inside_root(root: Path, requested: str) -> Path:
|
|
206
|
+
"""Return ROOT/<requested>, refusing a path that leads out of the root."""
|
|
207
|
+
term = root / requested
|
|
208
|
+
if not _inside_root(root, term):
|
|
209
|
+
terminal.die(f'term {requested!r} is outside {root}')
|
|
210
|
+
return term
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _inside_root(root: Path, path: Path) -> bool:
|
|
214
|
+
"""Tell whether `path` is a strict descendant of `root`, links resolved."""
|
|
215
|
+
return root.resolve() in path.resolve().parents
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _choose_subject(requested: str | None, term: Path) -> str:
|
|
219
|
+
"""Return the subject from the command line, or ask for one among those in the term."""
|
|
220
|
+
if requested is None:
|
|
221
|
+
subject_names = [folder.name for folder in sessions.visible_subdirectories(term)]
|
|
222
|
+
requested = terminal.pick('subject> ', subject_names)
|
|
223
|
+
return _require_folder_name(requested, 'subject')
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _choose_kind(requested: str | None, subject_folder: Path, *, interactive: bool) -> str:
|
|
227
|
+
"""Return the kind folder (lecture, labs, ...) to put the session in.
|
|
228
|
+
|
|
229
|
+
Only a subject that already has kind folders is worth asking about.
|
|
230
|
+
"""
|
|
231
|
+
if requested is None:
|
|
232
|
+
kinds = sessions.kind_names(subject_folder)
|
|
233
|
+
if not (interactive and kinds):
|
|
234
|
+
return _NO_KIND
|
|
235
|
+
requested = terminal.pick('where> ', [_NO_KIND, *kinds])
|
|
236
|
+
|
|
237
|
+
if requested == _NO_KIND:
|
|
238
|
+
return _NO_KIND
|
|
239
|
+
return _require_folder_name(requested, 'kind')
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _choose_template(requested: str | None, templates: Path, *, interactive: bool) -> str | None:
|
|
243
|
+
"""Return the name of the template to use, or None for an empty folder."""
|
|
244
|
+
available = [folder.name for folder in sessions.visible_subdirectories(templates)]
|
|
245
|
+
if requested is None and interactive:
|
|
246
|
+
requested = terminal.pick('template> ', [_NO_TEMPLATE, *available])
|
|
247
|
+
|
|
248
|
+
if not requested or requested == _NO_TEMPLATE: # no -t, -t '' or -t none
|
|
249
|
+
return None
|
|
250
|
+
if requested not in available:
|
|
251
|
+
listed = ', '.join(available) or '(none)'
|
|
252
|
+
terminal.die(f'unknown template {requested!r}; available: {listed}')
|
|
253
|
+
return requested
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _next_session_folder(parent: Path, template: str | None) -> Path:
|
|
257
|
+
"""Return the path of the next session folder in `parent`, which must not exist yet."""
|
|
258
|
+
name = sessions.next_session_name(parent, template, datetime.date.today())
|
|
259
|
+
session_folder = parent / name
|
|
260
|
+
if session_folder.exists():
|
|
261
|
+
terminal.die(f'{session_folder} already exists')
|
|
262
|
+
return session_folder
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _create_session_folder(
|
|
266
|
+
root: Path, session_folder: Path, template_folder: Path | None, subject: str
|
|
267
|
+
) -> None:
|
|
268
|
+
"""Create the session folder, turning a filesystem failure into a clean error."""
|
|
269
|
+
try:
|
|
270
|
+
values: dict[str, str] = {}
|
|
271
|
+
if template_folder is not None:
|
|
272
|
+
# inside the try: git's user.name may not decode as UTF-8 (UnicodeError)
|
|
273
|
+
values = _placeholder_values(subject)
|
|
274
|
+
|
|
275
|
+
scaffold.create_session(session_folder, template_folder, values)
|
|
276
|
+
except (OSError, UnicodeError) as error:
|
|
277
|
+
terminal.die(f'cannot create {session_folder.relative_to(root)}: {error}')
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _new_folder_messages(
|
|
281
|
+
root: Path, term: Path, subject_folder: Path, requested_term: str | None
|
|
282
|
+
) -> list[str]:
|
|
283
|
+
"""Return the messages telling that a term or subject is about to be created.
|
|
284
|
+
|
|
285
|
+
Asked before the session is created, while the folders do not exist yet. A term only
|
|
286
|
+
counts as new when -T asked for it: the term found by itself always exists.
|
|
287
|
+
"""
|
|
288
|
+
messages = []
|
|
289
|
+
if requested_term and not term.is_dir():
|
|
290
|
+
messages.append(f'new term {term.relative_to(root)}')
|
|
291
|
+
if not subject_folder.is_dir():
|
|
292
|
+
messages.append(f'new subject {subject_folder.relative_to(root)}')
|
|
293
|
+
return messages
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _report_created(root: Path, session_folder: Path, messages: Sequence[str]) -> None:
|
|
297
|
+
"""Tell what was created on stderr and print the session folder's path on stdout."""
|
|
298
|
+
for message in messages:
|
|
299
|
+
terminal.info(message)
|
|
300
|
+
parent = session_folder.parent.relative_to(root)
|
|
301
|
+
terminal.ok(f'created {parent}/{terminal.emphasise(session_folder.name)}')
|
|
302
|
+
print(session_folder.absolute())
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _placeholder_values(subject: str) -> dict[str, str]:
|
|
306
|
+
"""Return what the template placeholders are filled with."""
|
|
307
|
+
return {
|
|
308
|
+
'title': re.sub(r'[-_]', ' ', subject),
|
|
309
|
+
'name': _author_name(),
|
|
310
|
+
# spelled like this in the templates themselves
|
|
311
|
+
'afilliation': os.environ.get('NOTEX_AFFILIATION', ''),
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _require_folder_name(value: str, what: str) -> str:
|
|
316
|
+
"""Return `value` if it is a single folder name, else exit with an error.
|
|
317
|
+
|
|
318
|
+
Names come from the command line and the picker, and end up in paths, so nothing that
|
|
319
|
+
could lead out of the folder they are meant for gets through.
|
|
320
|
+
"""
|
|
321
|
+
# os.sep is a backslash on Windows, where a slash is not the only separator
|
|
322
|
+
if not value or value in ('.', '..') or '/' in value or os.sep in value:
|
|
323
|
+
terminal.die(f'invalid {what} {value!r}: must be a single folder name')
|
|
324
|
+
return value
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _print_session_list(root: Path, term: Path, subject_text: str) -> None:
|
|
328
|
+
"""Print the sessions of every subject in the term whose name contains `subject_text`."""
|
|
329
|
+
found: list[sessions.Session] = []
|
|
330
|
+
for subject in sessions.visible_subdirectories(term):
|
|
331
|
+
if subject_text in subject.name:
|
|
332
|
+
found.extend(sessions.find_sessions(subject))
|
|
333
|
+
|
|
334
|
+
if not found:
|
|
335
|
+
terminal.warn(
|
|
336
|
+
f'no sessions in subjects matching {subject_text!r} in {term.relative_to(root)}'
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
for session in sorted(found):
|
|
340
|
+
terminal.print_path(str(session.path.relative_to(root)))
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _print_overview_table(root: Path, term: Path) -> None:
|
|
344
|
+
"""Print the term's name, then a table of its subjects: sessions and last session."""
|
|
345
|
+
terminal.print_heading(str(term.relative_to(root)))
|
|
346
|
+
|
|
347
|
+
subjects = sessions.visible_subdirectories(term)
|
|
348
|
+
sessions_by_subject = [list(sessions.find_sessions(subject)) for subject in subjects]
|
|
349
|
+
newest_in_term = max(
|
|
350
|
+
(session.date for found in sessions_by_subject for session in found), default=None
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
rows = [[terminal.Cell(title, terminal.BOLD) for title in ('SUBJECT', 'SESSIONS', 'LAST')]]
|
|
354
|
+
for subject, found in zip(subjects, sessions_by_subject, strict=True):
|
|
355
|
+
rows.append(_overview_row(subject.name, found, newest_in_term))
|
|
356
|
+
|
|
357
|
+
terminal.print_table(rows, right_aligned_column=1) # SESSIONS
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _overview_row(
|
|
361
|
+
subject_name: str, found: list[sessions.Session], newest: datetime.date | None
|
|
362
|
+
) -> list[terminal.Cell]:
|
|
363
|
+
"""Return the overview row of one subject.
|
|
364
|
+
|
|
365
|
+
A subject without sessions is dimmed. The date is green on the subject whose last
|
|
366
|
+
session is the newest in the term, dim on the others.
|
|
367
|
+
"""
|
|
368
|
+
if not found:
|
|
369
|
+
return [
|
|
370
|
+
terminal.Cell(subject_name, terminal.DIM),
|
|
371
|
+
terminal.Cell('0', terminal.DIM),
|
|
372
|
+
terminal.Cell('-', terminal.DIM),
|
|
373
|
+
]
|
|
374
|
+
|
|
375
|
+
last = max(session.date for session in found)
|
|
376
|
+
date_colour = terminal.GREEN if last == newest else terminal.DIM
|
|
377
|
+
return [
|
|
378
|
+
terminal.Cell(subject_name),
|
|
379
|
+
terminal.Cell(str(len(found))),
|
|
380
|
+
terminal.Cell(last.strftime(_OVERVIEW_DATE_FORMAT), date_colour),
|
|
381
|
+
]
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _sessions_newest_first(root: Path, terms: Sequence[Path]) -> list[str]:
|
|
385
|
+
"""Return the paths, relative to the root, of every session in the terms, newest first."""
|
|
386
|
+
found: list[sessions.Session] = []
|
|
387
|
+
for term in terms:
|
|
388
|
+
found.extend(sessions.find_sessions(term, sessions.TERM_DEPTH))
|
|
389
|
+
found.sort(reverse=True)
|
|
390
|
+
return [str(session.path.relative_to(root)) for session in found]
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _subjects(root: Path, terms: Sequence[Path]) -> list[str]:
|
|
394
|
+
"""Return the paths, relative to the root, of every subject in the terms."""
|
|
395
|
+
paths: list[str] = []
|
|
396
|
+
for term in terms:
|
|
397
|
+
subjects = sessions.visible_subdirectories(term)
|
|
398
|
+
paths.extend(str(subject.relative_to(root)) for subject in subjects)
|
|
399
|
+
return paths
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
if __name__ == '__main__':
|
|
403
|
+
main()
|
notex/scaffold.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Creating a session folder, empty or started from a LaTeX template.
|
|
2
|
+
|
|
3
|
+
Copies the template, renames its main file to `<template>.tex` and fills the placeholders.
|
|
4
|
+
Paths and values come in as arguments; nothing prints, exits or reads the environment.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
__all__ = ['TEMPLATE_MAIN_FILE', 'create_session', 'latex_escape']
|
|
13
|
+
|
|
14
|
+
# The file in every template that holds the document and its placeholders.
|
|
15
|
+
TEMPLATE_MAIN_FILE = 'template.tex'
|
|
16
|
+
|
|
17
|
+
# Placeholders in the main file look like <nTeX>[title]; the word between the brackets is
|
|
18
|
+
# the key into the values passed to create_session.
|
|
19
|
+
_PLACEHOLDER_PATTERN = re.compile(r'<nTeX>\[(\w+)\]')
|
|
20
|
+
|
|
21
|
+
# Characters LaTeX treats as commands. Those in _LATEX_NAMED_ESCAPES have no `\x` form and
|
|
22
|
+
# need a command; the rest are escaped with a backslash.
|
|
23
|
+
_LATEX_SPECIAL_CHARACTERS = re.compile(r'[\\&%$#_{}~^]')
|
|
24
|
+
_LATEX_NAMED_ESCAPES = {
|
|
25
|
+
'\\': r'\textbackslash{}',
|
|
26
|
+
'~': r'\textasciitilde{}',
|
|
27
|
+
'^': r'\textasciicircum{}',
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def create_session(folder: Path, template: Path | None, values: Mapping[str, str]) -> None:
|
|
32
|
+
"""Create the session `folder`: empty, or copied from the `template` directory.
|
|
33
|
+
|
|
34
|
+
The values fill the placeholders of the template's main file. An existing folder is
|
|
35
|
+
refused rather than emptied, and a failed attempt leaves nothing behind, so the caller
|
|
36
|
+
sees what went wrong and keeps whatever was already on disk.
|
|
37
|
+
"""
|
|
38
|
+
if folder.exists():
|
|
39
|
+
raise FileExistsError(f'{folder} already exists')
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
if template is None:
|
|
43
|
+
folder.mkdir(parents=True)
|
|
44
|
+
else:
|
|
45
|
+
_copy_template(template, folder, values)
|
|
46
|
+
except (OSError, UnicodeError):
|
|
47
|
+
shutil.rmtree(folder, ignore_errors=True)
|
|
48
|
+
raise
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def latex_escape(text: str) -> str:
|
|
52
|
+
"""Escape the characters LaTeX treats as commands, so `text` is typeset as written."""
|
|
53
|
+
return _LATEX_SPECIAL_CHARACTERS.sub(_escape_character, text)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _copy_template(template: Path, folder: Path, values: Mapping[str, str]) -> None:
|
|
57
|
+
"""Copy the template into `folder`, name its main file after it and fill that file in."""
|
|
58
|
+
# a copied template must not drag its own .git along
|
|
59
|
+
shutil.copytree(template, folder, ignore=shutil.ignore_patterns('.git'))
|
|
60
|
+
|
|
61
|
+
unnamed_main_file = folder / TEMPLATE_MAIN_FILE
|
|
62
|
+
main_file = folder / f'{template.name}.tex'
|
|
63
|
+
if unnamed_main_file.exists():
|
|
64
|
+
unnamed_main_file.rename(main_file)
|
|
65
|
+
if main_file.exists():
|
|
66
|
+
_fill_placeholders(main_file, values)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _fill_placeholders(main_file: Path, values: Mapping[str, str]) -> None:
|
|
70
|
+
"""Replace the known placeholders in a file, escaped for LaTeX; others stay as they are."""
|
|
71
|
+
text = main_file.read_text(encoding='utf-8')
|
|
72
|
+
filled = _PLACEHOLDER_PATTERN.sub(lambda match: _value_for(match, values), text)
|
|
73
|
+
main_file.write_text(filled, encoding='utf-8')
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _value_for(placeholder: re.Match[str], values: Mapping[str, str]) -> str:
|
|
77
|
+
"""Return the escaped value for a placeholder, or the placeholder itself if unknown."""
|
|
78
|
+
key = placeholder[1]
|
|
79
|
+
if key not in values:
|
|
80
|
+
return placeholder[0]
|
|
81
|
+
return latex_escape(values[key])
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _escape_character(match: re.Match[str]) -> str:
|
|
85
|
+
"""Return the LaTeX spelling of one special character."""
|
|
86
|
+
character = match[0]
|
|
87
|
+
return _LATEX_NAMED_ESCAPES.get(character, '\\' + character)
|