summaryrefslogtreecommitdiffstats
path: root/pkgs/simple/cgit-about-filter/cgit-about-filter.lua
blob: 7b3622618f0456452a9444fe87eb874e4b7e342a (plain)
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
local function resolve(base, relative)
    if relative:sub(1, 1) == "/" then
        return relative
    end

    local combined = base .. "/" .. relative

    local segments = {}
    for segment in combined:gmatch("[^/]+") do
        if segment == ".." then
            if #segments > 0 and segments[#segments] ~= ".." then
                table.remove(segments)
            else
                table.insert(segments, "..")
            end
        elseif segment ~= "." and segment ~= "" then
            table.insert(segments, segment)
        end
    end

    local prefix = (base:sub(1, 1) == "/" or relative:sub(1, 1) == "/") and "/" or ""
    return prefix .. table.concat(segments, "/")
end

-- The branch from the query string (?h=...), or nil.  cgit doesn't pass it
-- to filters, but Lua filters run in cgit's process, which has the CGI
-- environment.
local function query_head()
    local query = os.getenv("QUERY_STRING") or ""
    for key, value in query:gmatch("([^&=]+)=([^&]*)") do
        if key == "h" then
            value = value:gsub("%+", " "):gsub("%%(%x%x)", function(hex)
                return string.char(tonumber(hex, 16))
            end)
            if value ~= "" then
                return value
            end
        end
    end
    return nil
end

local function url_escape(s)
    return (s:gsub("[^%w._~/-]", function(c)
        return string.format("%%%02X", c:byte())
    end))
end

-- cgit provides html() to Lua filters.  It writes in order with cgit's own
-- output, which io.write's buffered stdout doesn't.  io.write is for running
-- the filter outside of cgit.
local emit = html or io.write

-- Run a shell command with input on stdin and return its output.
local function run(command, input)
    local name = os.tmpname()
    local file = assert(io.open(name, "w"))
    file:write(input)
    file:close()
    local handle = io.popen(command .. " < " .. name, "r")
    local output = handle and handle:read("*a")
    if handle then
        handle:close()
    end
    os.remove(name)
    return output
end

local function md2html(markdown)
    return run("@md2html@ --github", markdown)
end

local function shell_quote(s)
    return "'" .. s:gsub("'", "'\\''") .. "'"
end

-- The files that exist in rev, as a set.
local function existing_files(rev, files)
    local found = {}
    if #files == 0 then
        return found
    end
    local input = {}
    for i, file in ipairs(files) do
        input[i] = rev .. ":" .. file .. "\n"
    end
    local git_dir = shell_quote(os.getenv("CGIT_REPO_PATH") or ".")
    local output = run("@git@ --git-dir=" .. git_dir .. " cat-file --batch-check", table.concat(input)) or ""
    local i = 0
    for line in output:gmatch("[^\n]*\n") do
        i = i + 1
        if line:match("^%x+ blob ") then
            found[files[i]] = true
        end
    end
    return found
end

-- The files the filter renders: README.md, and Markdown files in docs/.
local function renderable(file)
    return file:sub(-3) == ".md"
end

local table_style = [[
<style>
div#cgit div#summary table {
	width: 100%;
	table-layout: fixed;
	margin: 1em 0;
	border-collapse: collapse;
}
div#cgit div#summary th,
div#cgit div#summary td {
	padding: 0.35em 0.6em;
	text-align: left;
	vertical-align: top;
}
div#cgit div#summary thead th {
	border-bottom: 2px solid #888;
}
div#cgit div#summary tbody td {
	border-bottom: 1px solid #ddd;
}
div#cgit div#summary tbody tr:nth-child(even) {
	background: #f7f7f7;
}
div#cgit div#summary th + th,
div#cgit div#summary td + td {
	border-left: 1px solid #eee;
}
</style>
]]

-- Column widths, shared by all tables with the same header.  A column's
-- weight is the larger of its longest word and its average cell length, in
-- characters; code counts more, as monospace is wider.  Narrow columns get a
-- fixed width, the others a share of what's left.
local code_weight = 1.25
local narrow = 12

local function length(s)
    s = s:gsub("&#?%w+;", "x")
    return select(2, s:gsub("[^\128-\191]", ""))
end

local function cell_weights(cell)
    local longest, total = 0, 0
    local function add(text, factor)
        for word in text:gmatch("%S+") do
            local n = length(word) * factor
            longest = math.max(longest, n)
            total = total + n + 1
        end
    end
    for code in cell:gmatch("<code>(.-)</code>") do
        add((code:gsub("<[^>]+>", "")), code_weight)
    end
    add((cell:gsub("<code>.-</code>", " "):gsub("<[^>]+>", " ")), 1)
    return longest, math.max(total - 1, 0)
end

local function cells(row)
    local result = {}
    for cell in row:gmatch("<t[hd][^>]*>(.-)</t[hd]>") do
        table.insert(result, cell)
    end
    return result
end

local function header(tbl)
    return table.concat(cells(tbl:match("<tr>(.-)</tr>") or ""), "\0")
end

local function column_widths(output)
    local stats = {}
    for tbl in output:gmatch("<table>.-</table>") do
        local key = header(tbl)
        stats[key] = stats[key] or { rows = 0, longest = {}, total = {} }
        local s = stats[key]
        for row in tbl:gmatch("<tr>(.-)</tr>") do
            s.rows = s.rows + 1
            for i, cell in ipairs(cells(row)) do
                local longest, total = cell_weights(cell)
                s.longest[i] = math.max(s.longest[i] or 0, longest)
                s.total[i] = (s.total[i] or 0) + total
            end
        end
    end
    local widths = {}
    for key, s in pairs(stats) do
        local weights, wide = {}, 0
        for i = 1, #s.longest do
            weights[i] = math.max(s.longest[i], s.total[i] / s.rows)
            if weights[i] > narrow then
                wide = wide + weights[i]
            end
        end
        local cols = {}
        for i, weight in ipairs(weights) do
            if weight > narrow then
                cols[i] = string.format('<col style="width:%.1f%%">', 100 * weight / wide)
            else
                cols[i] = string.format('<col style="width:calc(%dch + 1.2em)">', math.ceil(weight) + 1)
            end
        end
        widths[key] = "<colgroup>" .. table.concat(cols) .. "</colgroup>"
    end
    return widths
end

-- Add the column widths, and let code break after underscores.
local function layout_tables(output)
    local widths = column_widths(output)
    return (output:gsub("<table>.-</table>", function(tbl)
        local key = header(tbl)
        tbl = tbl:gsub("<code>(.-)</code>", function(code)
            return "<code>" .. code:gsub("_", "_<wbr>") .. "</code>"
        end)
        return "<table>" .. widths[key] .. tbl:sub(#"<table>" + 1)
    end))
end

-- A heading's id, the way GitHub makes it: the text in lower case, without
-- punctuation, and with a hyphen for each space.
local function slug(content)
    local text = content:gsub("<[^>]*>", ""):gsub("&[^;]*;", "")
    return (text:lower():gsub("[^%w%s_%-\128-\255]", ""):gsub("%s", "-"))
end

-- Headings link to themselves, underlined on hover by cgit.css.  Clicking
-- the heading that is the #fragment removes the fragment again.  Setting
-- location.hash is what makes :target forget the heading;
-- history.replaceState alone doesn't.
local heading_links = [[
<style>
div#summary a.anchor { color: inherit; }
</style>
<script>
  document.addEventListener("click", event => {
    const link = event.target.closest("a.anchor");
    if (link && link.hash === location.hash && event.button === 0 &&
        !(event.ctrlKey || event.metaKey || event.shiftKey || event.altKey)) {
      event.preventDefault();
      const x = scrollX, y = scrollY;
      location.hash = "";
      scrollTo(x, y);
      history.replaceState(null, "", location.pathname + location.search);
    }
  });
</script>
]]

-- Give headings ids, so links to #fragments work.  A repeated id gets -1,
-- -2, etc., and so do ids cgit uses on the about page itself.
local function heading_ids(output)
    local seen = { cgit = 0, header = 0, summary = 0 }
    return (output:gsub("<h([1-6])>(.-)</h%1>", function(level, content)
        local id = slug(content)
        if id == "" then
            return nil
        end
        if seen[id] then
            seen[id] = seen[id] + 1
            id = id .. "-" .. seen[id]
        else
            seen[id] = 0
        end
        if not content:find("<a ", 1, true) then
            content = string.format('<a class="anchor" href="#%s">%s</a>', id, content)
        end
        return string.format('<h%s id="%s">%s</h%s>', level, id, content, level)
    end))
end

-- Highlight the heading a #fragment points to.
local target_style = [[
<style>
div#summary :is(h1, h2, h3, h4, h5, h6):target { background-color: #ffffcc; }
</style>
]]

-- Render ```mermaid code blocks in the browser.
local mermaid_script = [[
<script type="module">
  const codeBlocks = document.querySelectorAll("pre code.language-mermaid");
  try {
    const { default: mermaid } = await import("https://esm.run/mermaid@12.3.0");

    // Text as large as the page's, diagrams at their natural size.
    const style = getComputedStyle(document.querySelector("div#summary") || document.body);
    const fontSize = parseFloat(style.fontSize);
    mermaid.initialize({
      startOnLoad: false,
      theme: "default",
      fontFamily: style.fontFamily,
      fontSize,
      themeVariables: {
        fontFamily: style.fontFamily,
        fontSize: style.fontSize,
        edgeLabelBackground: "#ffffff"
      },
      flowchart: {
        wrappingWidth: 300
      },
      sequence: {
        actorFontSize: fontSize,
        messageFontSize: fontSize,
        noteFontSize: fontSize
      }
    });

    for (let i = 0; i < codeBlocks.length; i++) {
      const codeBlock = codeBlocks[i];
      const preBlock = codeBlock.parentElement;
      const diagramText = codeBlock.textContent;
      const id = "mermaid-diagram-" + i;

      try {
        const { svg } = await mermaid.render(id, diagramText);
        preBlock.outerHTML = `<div class="mermaid-container" style="overflow-x: auto; margin: 1em 0;">${svg}</div>`;
        // Mermaid shrinks wide diagrams to fit; scroll them instead.
        const rendered = document.getElementById(id);
        const box = rendered.viewBox.baseVal;
        rendered.style.maxWidth = "none";
        rendered.setAttribute("width", box.width);
        rendered.setAttribute("height", box.height);
      } catch (error) {
        console.error("Mermaid rendering failed for block " + i, error);
        codeBlock.textContent += "\n\n[Mermaid Render Error: See console for details]";
      }
    }
  } catch (importError) {
    console.error("Failed to dynamically load Mermaid module", importError);
  }
</script>
]]

local buffer = ""
local should_render = true
local current_dir = "" -- Stores the directory prefix of the file being processed
local current_file = ""

local function open(...)
    local args = {...}
    current_file = args[1] or ""

    if current_file == "" then
        current_file = "README.md"
    end

    if renderable(current_file) then
        should_render = true

        -- Extract directory context (e.g., "docs/ops.md" -> "docs/")
        -- If it's the root README.md, current_dir stays an empty string ""
        if current_file ~= "README.md" then
            current_dir = current_file:match("(.*/)") or ""
        else
            current_dir = ""
        end
    else
        should_render = false
    end

    buffer = ""
end

local function write(str)
    if should_render then
        buffer = buffer .. str
    end
end

local function close()
    if not should_render then
        emit("<p><em>Error: Access Denied. Only README.md and documentation markdown files are viewable here.</em></p>")
        return
    end

    local repo = os.getenv("CGIT_REPO_URL") or ""

    local head = query_head()
    local query = ""
    if head and head ~= os.getenv("CGIT_REPO_DEFBRANCH") then
        query = "?h=" .. url_escape(head)
    end

    local link = "%[([^%]]+)%]%(([^:)]+)%)"

    -- A link's path, resolved, and its fragment; nil for protocols (http,
    -- https, etc.), absolute paths (/), and anchors (#).
    local function target(path)
        if path:sub(1, 1) == "/" or path:sub(1, 1) == "#" or path:match("^%w+:") then
            return nil
        end
        local fragment
        path, fragment = path:match("^([^#]*)(.*)$")
        return resolve(current_dir, path), fragment
    end

    -- The README.md of a linked directory, if the filter renders it.
    local function readme(path)
        local file = (path == "" and "" or path .. "/") .. "README.md"
        return renderable(file) and file or nil
    end

    local readmes = {}
    for _, path in buffer:gmatch(link) do
        path = target(path)
        if path and readme(path) then
            table.insert(readmes, readme(path))
        end
    end
    local existing = existing_files(head or os.getenv("CGIT_REPO_DEFBRANCH") or "HEAD", readmes)

    local processed = buffer:gsub(link, function(text, path)
        local fragment
        path, fragment = target(path)
        if not path then
            return nil
        end

        if existing[readme(path)] then
            path = readme(path)
        end

        if path:sub(-3) == ".md" then
          return string.format("[%s](/%s/about/%s%s%s)", text, repo, path, query, fragment)
        else
          return string.format("[%s](/%s/tree/%s%s%s)", text, repo, path, query, fragment)
        end
    end)

    local output = md2html(processed)
    if output then
        output = heading_ids(output)
        if output:find('<h%d id="') then
            emit(target_style)
            emit(heading_links)
        end
        if output:find("<table>", 1, true) then
            emit(table_style)
            output = layout_tables(output)
        end
        emit(output)
        if output:find('<code class="language-mermaid">', 1, true) then
            emit(mermaid_script)
        end
    else
        emit("<p>Error: Could not execute md2html.</p>")
    end
end

-- cgit hooks its output into the filter while the filter is open, so the
-- error page of a Lua error in here would end up in the buffer, and the
-- response would end without a word.  Show the error instead.
local err

local function try(f, ...)
    if not err then
        local ok, e = xpcall(f, debug.traceback, ...)
        if not ok then
            err = e
        end
    end
end

function filter_open(...)
    err = nil
    try(open, ...)
end

function filter_write(str)
    try(write, str)
end

function filter_close()
    try(close)
    if err then
        emit("<pre>")
        ;(html_txt or io.write)(err)
        emit("</pre>")
    end
end