Files
website/scripts/generate-verlauf.rb
T
tobias 782783ab64 Kommentar: Cache-Hinweis bei Skript-Änderungen ohne Content-Änderung
Der Skip-Cache erkennt nur Änderungen an _content/, nicht an diesem Skript
selbst - hat uns beim letzten Deploy einer Logik-Änderung überrascht
(Deploy lief durch, zeigte aber noch alte Werte, weil _content/'s HEAD
unverändert war). Kein Verhaltensfix, nur ein Hinweis für's nächste Mal.
2026-08-26 09:43:46 +02:00

198 lines
8.7 KiB
Ruby
Executable File

#!/usr/bin/env ruby
# Generates hugo/data/methoden.json and hugo/data/varianten.json: creation
# date, last-modified date, and a full chronological change history
# (verlauf, newest first) per method/variant - all derived from the git
# history of _content/. Replaces generate-dates.sh (same underlying reason
# for reading git history ourselves instead of relying on Hugo's
# enableGitInfo/.GitInfo, which doesn't see _content/'s separate git repo -
# see the installation guide on the project website. No Hugo-native
# "created" equivalent exists anyway, https://github.com/gohugoio/hugo/issues/11810).
#
# Recomputed fresh whenever _content/ actually changed, not maintained (see
# sync-methoden.sh, which calls this script automatically) - no manual
# date/history field, git stays the single source of truth (Manifest
# Prinzip 8). "Whenever actually changed", not "on every call": walking the
# full history of every entry (one "git show"-equivalent read per historical
# commit) is real, recurring cost on every deploy - skipped entirely via
# hugo/data/verlauf-cache.json when _content/'s HEAD hasn't moved since the
# last run, see skip_wenn_unveraendert below.
require_relative 'lib/frontmatter'
require 'json'
require 'fileutils'
require 'yaml'
ROOT = File.expand_path('..', __dir__)
CONTENT_REPO = File.join(ROOT, '_content')
CACHE_FILE = File.join(ROOT, 'hugo', 'data', 'verlauf-cache.json')
def content_head
`cd #{CONTENT_REPO} && git rev-parse HEAD`.strip
end
# Skips the whole run (both files untouched, left exactly as the last
# successful run produced them) when _content/'s current HEAD is the same
# commit as last time - a no-op sync/cron tick (by far the common case
# under the 10-minute cron) then costs one "git rev-parse" instead of
# walking the entire history of every method/variant again.
def skip_wenn_unveraendert
return false unless File.exist?(CACHE_FILE)
cache = JSON.parse(File.read(CACHE_FILE)) rescue nil
return false unless cache
return false unless cache['content_head'] == content_head
out_methoden = File.join(ROOT, 'hugo', 'data', 'methoden.json')
out_varianten = File.join(ROOT, 'hugo', 'data', 'varianten.json')
return false unless File.exist?(out_methoden) && File.exist?(out_varianten)
puts 'verlauf: _content/ unveraendert seit letztem Lauf, ueberspringe Neuberechnung.'
true
end
# Note for anyone changing this script itself (not _content/): the cache
# only tracks _content/'s HEAD, so it can't detect that the computation
# logic changed. After deploying such a change, delete the deployed
# hugo/data/verlauf-cache.json by hand (or just run this script once
# outside the normal deploy) - otherwise the next deploy silently skips
# recomputation and keeps serving output produced by the old logic.
# One combined "git log" call per file instead of one per commit - %x09 is
# a literal tab byte as field separator, safe against contents containing
# regular spaces/dashes. --name-only gives the historical path at each
# commit (needed for --follow across renames, same technique
# scripts/validate.rb's vorherige_kennung already uses for the single most
# recent rename). --no-merges: merge commits (e.g. from a regularly merged
# Pull Request against the content repo, see the "Ein Server oder
# zwei"/PR workflow docs) carry no file list under --name-only by default -
# left in, the fixed 2-lines-per-commit pairing below would desync at
# exactly that commit and misattribute every following entry. Excluding
# them is also correct on its own terms: a merge commit isn't itself a
# content edit, the actual edits are the commits it merges, which still
# appear individually here regardless.
def commits_for(relpath, content_dir)
raw = `cd #{content_dir} && git log --no-merges --follow --format='%H%x09%an%x09%aI' --name-only -- #{relpath}`
zeilen = raw.split("\n").reject(&:empty?)
commits = []
i = 0
while i < zeilen.length
hash, autor, datum = zeilen[i].split("\t")
pfad = zeilen[i + 1]
commits << { hash: hash, autor: autor, datum: datum, pfad: pfad }
i += 2
end
commits.reverse
end
def inhalt_bei(hash, pfad, content_dir)
text = `cd #{content_dir} && git show #{hash}:#{pfad} 2>/dev/null`.force_encoding('UTF-8')
return nil if text.empty?
Frontmatter.parse(text)
end
# Compares frontmatter key-by-key (simple value inequality, including for
# list-type fields - a reordered-but-unchanged list would show as
# "changed", accepted as a rare, harmless false positive rather than
# building element-level list diffing for this) plus the document body, for
# variants where the actual content (Vorbereitung/Ablauf/Hintergründe)
# lives.
def geaenderte_felder(vorher_fm, vorher_body, jetzt_fm, jetzt_body)
felder = (vorher_fm.keys | jetzt_fm.keys).select { |k| vorher_fm[k] != jetzt_fm[k] }
felder << 'inhalt' if vorher_body != jetzt_body
felder
end
# Longest-common-subsequence length between two line arrays - O(n*m)
# dynamic programming, fine here since inputs are frontmatter blocks/body
# text (tens to a few hundred lines), not full files.
def lcs_laenge(a, b)
tabelle = Array.new(a.length + 1) { Array.new(b.length + 1, 0) }
(1..a.length).each do |i|
(1..b.length).each do |j|
tabelle[i][j] = if a[i - 1] == b[j - 1]
tabelle[i - 1][j - 1] + 1
else
[tabelle[i - 1][j], tabelle[i][j - 1]].max
end
end
end
tabelle[a.length][b.length]
end
# Added+removed line count between two versions, analogous to "git diff
# --numstat"'s sum - but computed on normalized frontmatter instead of the
# raw committed text. Decap CMS rewrites a file's *entire* frontmatter in
# its own formatting style (list indent, quoting, prose line width, field
# order) the first time it saves a file that wasn't already in that style -
# diffing the raw git blobs would count that one-time reformatting as
# dozens of "changed" lines even when only a single field's value actually
# changed. Frontmatter.geordnet (same canonical order write() already
# enforces, see lib/frontmatter.rb) removes the field-order component of
# that noise before YAML.dump removes the indent/quoting/width component;
# the body (plain prose, not YAML-serialized) is compared as-is.
def normalisierte_zeilen(vorher_fm, vorher_body, jetzt_fm, jetzt_body, feldreihenfolge)
vorher_zeilen = (vorher_fm ? YAML.dump(Frontmatter.geordnet(vorher_fm, feldreihenfolge)).lines : []) + (vorher_body || '').lines
jetzt_zeilen = YAML.dump(Frontmatter.geordnet(jetzt_fm, feldreihenfolge)).lines + jetzt_body.lines
gemeinsam = lcs_laenge(vorher_zeilen, jetzt_zeilen)
(vorher_zeilen.length - gemeinsam) + (jetzt_zeilen.length - gemeinsam)
end
def verlauf_fuer(relpath, content_dir, feldreihenfolge)
commits = commits_for(relpath, content_dir)
return nil if commits.empty?
eintraege = []
vorher_fm = nil
vorher_body = nil
commits.each do |c|
parsed = inhalt_bei(c[:hash], c[:pfad], content_dir)
unless parsed
warn "verlauf: Konnte #{relpath} bei Commit #{c[:hash]} nicht lesen, uebersprungen."
next
end
fm, body = parsed
zeilen = normalisierte_zeilen(vorher_fm, vorher_body, fm, body, feldreihenfolge)
basis = { datum: c[:datum], autor: c[:autor], hash: c[:hash], zeilen: zeilen }
if vorher_fm.nil?
eintraege << basis.merge(typ: 'erstellt', felder: [])
else
felder = geaenderte_felder(vorher_fm, vorher_body, fm, body)
eintraege << basis.merge(typ: 'geaendert', felder: felder) unless felder.empty?
end
vorher_fm = fm
vorher_body = body
end
return nil if eintraege.empty?
eintraege = eintraege.reverse # newest first
{ erstellt: eintraege.last[:datum], geaendert: eintraege.first[:datum], verlauf: eintraege }
end
# Both methods and variants are one folder per entry with content in
# index.md (Hugo page bundle).
def generate_bundle_verlauf(name, feldreihenfolge)
dir = File.join(CONTENT_REPO, name)
out = File.join(ROOT, 'hugo', 'data', "#{name}.json")
FileUtils.mkdir_p(File.dirname(out))
entries = {}
if Dir.exist?(dir)
Dir.glob(File.join(dir, '*')).select { |d| File.directory?(d) }.each do |entry_dir|
slug = File.basename(entry_dir)
next unless File.exist?(File.join(entry_dir, 'index.md'))
daten = verlauf_fuer("#{name}/#{slug}/index.md", CONTENT_REPO, feldreihenfolge)
entries[slug] = daten if daten
end
end
File.write(out, JSON.pretty_generate(entries))
puts "#{name}.json aktualisiert: #{entries.length} Einträge"
end
exit if skip_wenn_unveraendert
generate_bundle_verlauf('methoden', Frontmatter::METHODEN_FELDER)
generate_bundle_verlauf('varianten', Frontmatter::VARIANTEN_FELDER)
FileUtils.mkdir_p(File.dirname(CACHE_FILE))
File.write(CACHE_FILE, JSON.pretty_generate({ content_head: content_head }))