~aleteoryx/gloss

ref: cebd9a4d78455b80e35e6cdc905936bde678dc2e gloss/gloss.py -rwxr-xr-x 7.8 KiB
cebd9a4dAleteoryx rewrite markup language in C 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/bin/env python3

import html
import re
from datetime import datetime
from os import stat, system
from glob import glob
from typing import List, Optional, Union, Dict, Set, Tuple
from dataclasses import dataclass
from sys import argv, stderr, exit
from pathlib import Path
from subprocess import Popen, PIPE, run as runcmd

usage = f'''
usage: {argv[0]} <SRCDIR> <OUTDIR>

For each .gls file in SRCDIR, creates a matching .html file in OUTDIR.

If SRCDIR/template.html exists, it will be used. Templates are
interpolated as in str.format, and the following keys are provided:

	{{title}} - The first name for an article.
	{{slug}} - The name of the output file, minus '.html'.
	{{body}} - The HTML content of an article.
	{{modtime}} - The datetime of the article's last edit.
'''[1:]

def die(why, code=1):
	print(why, file=stderr)
	exit(code)


### TYPES ###

@dataclass
class Block:
	ty: str
	text: str
	meta: str

@dataclass
class GlsFile:
	slug: str
	title: str
	names: Set[str]
	blocks: List[Block]
	see_also: Optional[List[str]]


### PARSING ###

def readlines(fp):
	return filter(
		lambda x: not x.startswith(';'), 
		map(
			lambda x: x.strip(), 
			fp.readlines() ) )

def first_pass(slug, fp):
	lines = readlines(fp)

	names = set()
	title = None
	for name in lines:
		if len(name) == 0 and len(names) != 0:			# section end
			break
		if title is None:
			title = name.strip();
		names.add(name.strip())
	
	if len(names) == 0:
		print(f'Empty file: {slug}.gls', file=stderr)
		return None
	
	do_see_also = False
	block_type = None
	block_text = None
	block_meta = ''
	blocks = []
	for line in lines:
		if len(line) == 0 and block_type is not None:		# block end
			blocks.append(Block(block_type, block_text, block_meta))
			block_type = None
			block_text = None
			block_meta = ''
			continue
		if line.startswith('***') and block_type is None:	# see also section
			do_see_also = True
			break

		if line.startswith('~'):
			block_meta = line[1:].strip()
		elif block_type is None:
			if len(line) == 0:
				continue
			if line.startswith('>'):
				block_type = 'quote'
				block_text = line[1:].strip()
				continue
			
			if line.startswith("\\>") or line.startswith("\\~") or line.startswith("\\***") or line == "\\":
				line = line[1:]
			block_type = 'para'
			block_text = line
		elif block_type == 'quote':
			if line.startswith('>'):
				line = line[1:].strip()
			block_text += "\n" + line
		elif block_type == 'para':
			block_text += ' ' + line
	
	see_also = None
	if do_see_also:
		see_also = [*filter(len, lines)]
	elif block_type is not None:
		blocks.append(Block(block_type, block_text, block_meta))
	
	return GlsFile(slug, title, [*names], blocks, see_also)

class Markup:
	def __init__(self, where, *, cfile='markup.c', bfile='markup'):
		self.cfile = str(Path(where, cfile))
		self.bfile = str(Path(where, bfile))

		if stat(self.cfile).st_mtime > stat(self.bfile).st_mtime:
			print("recompiling markup subsystem...")
			runcmd(['cc', self.cfile, '-DDEBUG', '-o', self.bfile, '-Wall'], check=True)
			print("recompiled!")
		
		self.proc = Popen([self.bfile, 'convert'], stdin=PIPE, stdout=PIPE, text=True)
	
	def process(self, text):
		print(f'{text=}')
		self.proc.stdin.write(text+"\n")
		self.proc.stdin.flush()

		segments = []
		while (line := self.proc.stdout.readline()) != '':
			ty = line[0:4]
			if ty == 'NEXT':
				break

			length = int(line[5:9])
			ltext = line[12:12+length]
			print(f'{ltext=}')

			if ty == 'HTML':
				segments.append((ltext,))
			elif ty == 'IESC':
				segments.append((html.escape(ltext),))
			elif ty == 'TEXT':
				segments.append(ltext)
			else:
				print(f'read in unknown type "{ty}" from markup subprocess', file=stderr)
		
		print(segments)
		return segments
			

quote_pat = re.compile("((?:(?!@@)(?!//).)*)(?:@@((?:(?!//).)+))?(?://(.+))?")


### GENERATION ###

def link_repl(mat):
	url, name = map(lambda x: x if x is None else html.escape(x.strip()), mat.groups())
	if name is not None and len(name) != 0:
		return f'<a href="{url}">{name}</a>'
	else:
		return f'<a href="{url}">&lt;{url}&gt;</a>'

@dataclass(init=False)
class Indexes:
	by_slug: Dict[str, GlsFile]
	by_name: Dict[str, GlsFile]
	names_sorted: List[Tuple[str, re.Pattern]]

	def __init__(self, files):
		self.by_slug = {}
		self.by_name = {}
		self.names_sorted = []
		
		for file in files:
			self.by_slug[file.slug] = file
			for name in file.names:
				if name in self.by_name:
					die(f'Redefinition of "{name}": occurs in {self.by_name[name].slug}.gls and {file.slug}.gls')
				self.by_name[name] = file
				
				pattern = re.compile(f"((?<=\\W)|^){re.escape(name)}((?=\\W)|$)", re.IGNORECASE)
				self.names_sorted.append((name, pattern))
		
		sorted(self.names_sorted, key=lambda x: len(x[0]))
			
def gen_inner_html(fmt, file, idx):
	for block in file.blocks:		# format text, listify it
		block.text = fmt.process(block.text)

	blacklist = set()
	for name, pat in idx.names_sorted:	# populate local links
		if name in file.names:		# ...but not to the same file
			continue
		if name in blacklist:		# ...and don't repeat!
			continue
		for block in file.blocks:
			for i in range(len(block.text)):
				seg = block.text[i]
				if type(seg) != str:
					continue
				m = pat.search(seg)
				if m is None:
					continue

				s, e = m.span()
				block.text.pop(i)
				block.text.insert(i, seg[e:])
				block.text.insert(i, (f'<a href="{html.escape(idx.by_name[name].slug)}.html">{seg[s:e]}</a>',))
				block.text.insert(i, seg[:s])
				break
	
	content = f"<h1>{html.escape(file.title)}</h1>"
	for block in file.blocks:		# ok generate the html
		text = ''.join(map(lambda x: html.escape(x) if type(x) == str else x[0], block.text))
		if block.ty == 'para':
			content += f"\n<p>{text}</p>"
		elif block.ty == 'quote':
			if block.meta is not None and len(block.meta):
				sauce, date, url = map(
					lambda x: x if x is None else html.escape(x.strip()),
					quote_pat.match(block.meta).groups() )
			else:
				sauce = date = url = None

			content += "\n<div>\n\t<blockquote" + ('' if url is None else f' cite="{url}"') + '>'
			content += text
			content += '</blockquote>'
			
			if sauce is not None:
				content += "\n\t<p>&mdash; <cite>" + (sauce if url is None else f'<a href="{url}">{sauce}</a>') + "</cite>"
				if date is not None:
					content += f', {date}'
				content += '</p>'
			content +='\n</div>'
	
	if file.see_also is not None and len(file.see_also) != 0:
		content += "\n<hr>\n<h3>See Also:</h3>\n<ul>"
		for what in file.see_also:
			if what in idx.by_slug:
				page = idx.by_slug[what]
				href = page.slug
				name = page.title
			elif what in idx.by_name:
				page = idx.by_name[what]
				href = page.slug
				name = page.title
			else:
				if '|' in what:
					href, name = what.split('|', 1)
				else:
					href = name = what
			content += f"\n\t<li><a href=\"{html.escape(href)}.html\">{html.escape(name)}</a></li>"
		content += "\n</ul>"
	
	return content


### ENTRYPOINT ###

if __name__ == '__main__':
	argv = argv[1:]
	if len(argv) != 2 or argv[0][0] == '-' or argv[1][0] == '-':
		die(usage)

	srcdir = argv[0]
	outdir = argv[1]

	try:
		with open('{srcdir}/template.html', 'rt') as fp:
			template = fp.read()
	except Exception:
		template = \
'''<!doctype html>
<html>
<head>
	<meta encoding='utf-8'>
	<title>{title}</title>
</head>
<body>
<main>
{body}
</main>
<footer>File last modified {modtime:%a, %Y-%d-%M %H:%M:%S %Z}</footer>
</body>
</html>
'''

	fmt = Markup(Path(__file__).parent)

	files = []
	for fn in glob('*.gls', root_dir=srcdir):
		with open(f'{srcdir}/{fn}', 'rt') as fp:
			data = first_pass(fn[:-4], fp)
			if data is not None:
				files.append(data)
	
	indexes = Indexes(files)
	for file in files:
		with open(f'{outdir}/{file.slug}.html', 'wt') as fp:
			ctx = {
				'title': html.escape(file.title),
				'slug': html.escape(file.slug),
				'body': gen_inner_html(fmt, file, indexes),
				'modtime': datetime.fromtimestamp(stat(f'{srcdir}/{file.slug}.gls').st_mtime)
			}
			fp.write(template.format(**ctx))