Vorlage fuer eigene Ableger-Installationen: Website + CMS-Code
Bereinigt von Pilot-Spezifika (echte Inhalte, Erzbistum-Hamburg-Bezuege, Domain-Werte) - install.env und hugo.toml [params] mit generischen Platzhaltern. docs/ komplett entfernt: Konzept, Manifest, Installations- anleitungen leben jetzt auf der Projekt-Website statt redundant im Repo, README verweist dorthin. Decap-CMS-Version von einer floatenden ^3.0.0 auf ein festes 3.15.1 gepinnt.
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env ruby
|
||||
# Small, permanently running service for the whole "write" area (/admin/*,
|
||||
# gated by the "write" oauth2-proxy instance, see
|
||||
# the installation guide on the project website): normally serves the same static files as its
|
||||
# former file:// upstream (Decap CMS, admin/status/), AND additionally
|
||||
# answers the two dynamic endpoints below. A single upstream instead of two
|
||||
# - oauth2-proxy 7.15.3 did not resolve the multiple, path-distinguished
|
||||
# upstreams (file:// + http://) via URL fragment in the simple
|
||||
# "upstreams = [...]" list form as documented (both ended up on path "/",
|
||||
# "upstream ids must be unique"/"upstream paths must be unique" on start) -
|
||||
# hence a WEBrick file handler here for the rest instead.
|
||||
#
|
||||
# This script itself does not check authorization, that is handled entirely
|
||||
# by the oauth2-proxy gate in front of it.
|
||||
#
|
||||
# STATUS_FILE is written by the deploy hook itself (~/repos/ableger.git/
|
||||
# hooks/post-receive on the server, not part of this repo - see
|
||||
# the installation guide on the project website), not by this script.
|
||||
require 'webrick'
|
||||
require 'json'
|
||||
|
||||
# Small install.env parser instead of a dotenv gem dependency - install.env
|
||||
# deliberately has a simple KEY="value" format (see there), not YAML.
|
||||
def load_install_env(pfad)
|
||||
werte = {}
|
||||
File.readlines(pfad).each do |zeile|
|
||||
zeile = zeile.strip
|
||||
next if zeile.empty? || zeile.start_with?('#')
|
||||
schluessel, wert = zeile.split('=', 2)
|
||||
werte[schluessel] = wert.to_s.sub(/\A"/, '').sub(/"\z/, '')
|
||||
end
|
||||
werte
|
||||
end
|
||||
|
||||
INSTALL_ENV = load_install_env(File.expand_path('../install.env', __dir__))
|
||||
|
||||
STATUS_FILE = File.expand_path('~/deploy/status.json')
|
||||
# Bare repo name (see the installation guide on the project website, Abschnitt 4) is derived from
|
||||
# the website repo name, not maintained separately.
|
||||
HOOK = File.expand_path("~/repos/#{INSTALL_ENV.fetch('WEBSITE_REPO').split('/').last}.git/hooks/post-receive")
|
||||
DOCROOT = INSTALL_ENV.fetch('DEPLOY_DOCROOT')
|
||||
PORT = INSTALL_ENV.fetch('STATUS_SERVER_PORT').to_i
|
||||
|
||||
def status_body
|
||||
File.exist?(STATUS_FILE) ? File.read(STATUS_FILE) : { error: 'noch kein Deploy-Status vorhanden' }.to_json
|
||||
end
|
||||
|
||||
server = WEBrick::HTTPServer.new(Port: PORT, BindAddress: '0.0.0.0', DocumentRoot: DOCROOT, Logger: WEBrick::Log.new($stdout), AccessLog: [[$stdout, WEBrick::AccessLog::COMBINED_LOG_FORMAT]])
|
||||
|
||||
server.mount_proc '/admin/status/api/data.json' do |req, res|
|
||||
res['Content-Type'] = 'application/json; charset=utf-8'
|
||||
res.body = status_body
|
||||
end
|
||||
|
||||
server.mount_proc '/admin/status/api/trigger' do |req, res|
|
||||
res['Content-Type'] = 'application/json; charset=utf-8'
|
||||
if req.request_method != 'POST'
|
||||
res.status = 405
|
||||
res.body = { error: 'nur POST erlaubt' }.to_json
|
||||
next
|
||||
end
|
||||
# Runs synchronously - the hook itself protects against an already
|
||||
# running cron/trigger run with a non-blocking flock (see hook script):
|
||||
# if one is already running, this call aborts immediately with a
|
||||
# corresponding message in the status instead of waiting or duplicating -
|
||||
# just click again shortly after.
|
||||
system(HOOK)
|
||||
res.body = status_body
|
||||
end
|
||||
|
||||
trap('INT') { server.shutdown }
|
||||
trap('TERM') { server.shutdown }
|
||||
server.start
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env ruby
|
||||
# Translates the form field "veroeffentlicht" (Decap, positive polarity: on
|
||||
# = published) into Hugo's native draft field (inverted: draft: true =
|
||||
# unpublished) - only in the local _content copy (not in the content repo),
|
||||
# before every Hugo build. Decap cannot write a boolean field inverted into
|
||||
# a differently named frontmatter field, hence this translation step
|
||||
# instead of a direct CMS mapping. Must run before
|
||||
# compute-methoden-sichtbarkeit.rb, which in turn reads the draft field set
|
||||
# here for variants (that script aborts if it still finds untranslated
|
||||
# "veroeffentlicht" fields, see there).
|
||||
require_relative 'lib/frontmatter'
|
||||
|
||||
root = File.expand_path('..', __dir__)
|
||||
varianten_dir = File.join(root, '_content', 'varianten')
|
||||
|
||||
changed = 0
|
||||
if Dir.exist?(varianten_dir)
|
||||
Dir.glob(File.join(varianten_dir, '*', 'index.md')).each do |file|
|
||||
result = Frontmatter.read(file)
|
||||
next unless result
|
||||
fm, body = result
|
||||
|
||||
# Missing "veroeffentlicht" (e.g. a variant committed directly via the
|
||||
# PR path, bypassing Decap's boolean widget with its "default: false")
|
||||
# must translate to unpublished, not be skipped untranslated - a
|
||||
# missing "draft" frontmatter key defaults to visible in Hugo, so
|
||||
# skipping this file entirely would publish it unintentionally.
|
||||
veroeffentlicht = fm.key?('veroeffentlicht') ? fm.delete('veroeffentlicht') == true : false
|
||||
fm['draft'] = !veroeffentlicht
|
||||
Frontmatter.write(file, fm, body, feldreihenfolge: Frontmatter::VARIANTEN_FELDER)
|
||||
changed += 1
|
||||
end
|
||||
end
|
||||
|
||||
puts "veroeffentlicht -> draft übersetzt: #{changed} Variante(n)"
|
||||
Executable
+71
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env ruby
|
||||
# Sets draft: true in the LOCAL copy of every method (_content/methoden/*/index.md)
|
||||
# whose variants are all still drafts (or has none) - not in the content repo
|
||||
# itself, only in the working copy freshly fetched on every sync (see sync-methoden.sh).
|
||||
#
|
||||
# Methods deliberately no longer have their own draft field
|
||||
# (admin/config.template.yml): publication is derived from the variants - as
|
||||
# soon as at least one variant is published, the method is too. This can't
|
||||
# be modeled as a Decap field (no access to other collections while saving),
|
||||
# hence this preprocessing step before the Hugo build. Hugo's own draft
|
||||
# mechanism then reliably takes care of the rest (e.g. automatic exclusion
|
||||
# from the homepage/search/taxonomies, not just the detail page itself) -
|
||||
# more robust than rebuilding a custom visibility check in the templates.
|
||||
#
|
||||
# Assumes apply-veroeffentlicht.rb has already run (see sync-methoden.sh) -
|
||||
# otherwise variants would still have "veroeffentlicht" instead of "draft",
|
||||
# published_methoden would stay empty, and EVERY method would be incorrectly
|
||||
# marked as draft without anything reporting the error. Hence this safeguard
|
||||
# here (Befund G/Schritt 6, see the project website (background/analysis notes)): instead of
|
||||
# silently accepting that, the script aborts loudly as soon as it finds a
|
||||
# variant with a still-untranslated "veroeffentlicht".
|
||||
require_relative 'lib/frontmatter'
|
||||
require 'set'
|
||||
|
||||
root = File.expand_path('..', __dir__)
|
||||
content = File.join(root, '_content')
|
||||
methoden_dir = File.join(content, 'methoden')
|
||||
varianten_dir = File.join(content, 'varianten')
|
||||
|
||||
published_methoden = Set.new
|
||||
if Dir.exist?(varianten_dir)
|
||||
Dir.glob(File.join(varianten_dir, '*', 'index.md')).each do |file|
|
||||
result = Frontmatter.read(file)
|
||||
next unless result
|
||||
fm, = result
|
||||
if fm.key?('veroeffentlicht')
|
||||
warn "compute-methoden-sichtbarkeit.rb: #{file} hat noch 'veroeffentlicht' statt 'draft' - apply-veroeffentlicht.rb muss vorher laufen (siehe sync-methoden.sh)"
|
||||
exit 1
|
||||
end
|
||||
next unless fm['draft'] == false
|
||||
methode = fm['methode']
|
||||
published_methoden << methode if methode
|
||||
end
|
||||
end
|
||||
|
||||
changed = 0
|
||||
Dir.glob(File.join(methoden_dir, '*', 'index.md')).each do |file|
|
||||
result = Frontmatter.read(file)
|
||||
next unless result
|
||||
fm, body = result
|
||||
kennung = fm['kennung']
|
||||
should_be_visible = published_methoden.include?(kennung)
|
||||
# fm['draft'] == true instead of fm.key?('draft'): methods used to have
|
||||
# their own draft field (since removed, see admin/config.template.yml) -
|
||||
# so a file may still contain a leftover old "draft: false" value.
|
||||
# Checking only for the key's presence would incorrectly treat that as
|
||||
# "currently hidden".
|
||||
currently_draft = fm['draft'] == true
|
||||
|
||||
if should_be_visible == currently_draft
|
||||
if should_be_visible
|
||||
fm.delete('draft')
|
||||
else
|
||||
fm['draft'] = true
|
||||
end
|
||||
Frontmatter.write(file, fm, body, feldreihenfolge: Frontmatter::METHODEN_FELDER)
|
||||
changed += 1
|
||||
end
|
||||
end
|
||||
|
||||
puts "Methoden-Sichtbarkeit aktualisiert: #{published_methoden.size} mit veröffentlichter Variante, #{changed} Datei(en) angepasst"
|
||||
Executable
+130
@@ -0,0 +1,130 @@
|
||||
#!/bin/bash
|
||||
# Generates admin/config.yml from admin/config.template.yml, AND
|
||||
# hugo/hugo.toml from hugo/hugo.template.toml (see below) - both share the
|
||||
# same "{{VARIABLE}}" substitution step, filled from install.env.
|
||||
#
|
||||
# admin/config.yml specifically has a second, independent substitution:
|
||||
# fields between "# VOKABULAR:<field>:START/END" markers are replaced by a
|
||||
# closed selection list if a vocabulary entry for <field> exists in the
|
||||
# content repo under _content/ableger.yml - otherwise the block from the
|
||||
# template stays unchanged (fallback: free text as before). See the
|
||||
# Manifest chapter on the project website Teil C, vokabular/README.md and
|
||||
# install.env.
|
||||
#
|
||||
# Runs both locally and in deploy (see the installation guide on the
|
||||
# project website), AFTER sync-methoden.sh (which fetches
|
||||
# _content/ableger.yml in the first place). Both admin/config.yml and
|
||||
# hugo/hugo.toml are generated and not versioned (see .gitignore) -
|
||||
# admin/config.template.yml and hugo/hugo.template.toml are the files to
|
||||
# maintain.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
TEMPLATE="$ROOT/admin/config.template.yml"
|
||||
OUT="$ROOT/admin/config.yml"
|
||||
ABLEGER_YML="$ROOT/_content/ableger.yml"
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
source "$ROOT/install.env"
|
||||
export GITEA_DOMAIN METHODEN_REPO OAUTH_CLIENT_ID WEBSITE_DOMAIN
|
||||
|
||||
# hugo.toml only needs the plain "{{VARIABLE}}" substitution, no VOKABULAR
|
||||
# blocks - a plain sed pass is enough, no need for the Python step below.
|
||||
HUGO_TEMPLATE="$ROOT/hugo/hugo.template.toml"
|
||||
HUGO_OUT="$ROOT/hugo/hugo.toml"
|
||||
sed -e "s|{{GITEA_DOMAIN}}|$GITEA_DOMAIN|g" \
|
||||
-e "s|{{METHODEN_REPO}}|$METHODEN_REPO|g" \
|
||||
-e "s|{{WEBSITE_DOMAIN}}|$WEBSITE_DOMAIN|g" \
|
||||
"$HUGO_TEMPLATE" > "$HUGO_OUT"
|
||||
echo "hugo.toml generiert: $HUGO_OUT"
|
||||
|
||||
# Export the vocabulary from ableger.yml (content repo) into a temporary
|
||||
# directory with one text file per field (one allowed value per line) - this
|
||||
# way the rest of the already-proven logic below (Python, reads from text
|
||||
# files) stays unchanged. Ruby instead of Python for YAML parsing, since
|
||||
# PyYAML isn't guaranteed to be available here, whereas Ruby's yaml library
|
||||
# (standard library) is already used elsewhere in the project (see
|
||||
# scripts/validate.rb).
|
||||
VOKABULAR="$(mktemp -d)"
|
||||
trap 'rm -rf "$VOKABULAR"' EXIT
|
||||
|
||||
if [ -f "$ABLEGER_YML" ]; then
|
||||
ruby -ryaml -e '
|
||||
daten = YAML.load_file(ARGV[0]) || {}
|
||||
vokabular = daten["vokabular"] || {}
|
||||
vokabular.each do |feld, werte|
|
||||
File.write(File.join(ARGV[1], "#{feld}.txt"), Array(werte).join("\n") + "\n")
|
||||
end
|
||||
' "$ABLEGER_YML" "$VOKABULAR"
|
||||
fi
|
||||
|
||||
python3 - "$TEMPLATE" "$OUT" "$VOKABULAR" <<'PYEOF'
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
template_path, out_path, vokabular_dir = sys.argv[1:4]
|
||||
text = Path(template_path).read_text()
|
||||
vokabular_dir = Path(vokabular_dir)
|
||||
|
||||
# Always replace "{{VARIABLE}}" placeholders (see install.env), independent
|
||||
# of the VOKABULAR mechanism below - no fallback logic needed, install.env
|
||||
# (unlike _content/ableger.yml) is always versioned in this repo.
|
||||
for feld in ("GITEA_DOMAIN", "METHODEN_REPO", "OAUTH_CLIENT_ID", "WEBSITE_DOMAIN"):
|
||||
text = text.replace("{{" + feld + "}}", os.environ[feld])
|
||||
|
||||
def render_field(feld, indent, values):
|
||||
lines = [f'{indent}- label: "{feld_labels.get(feld, feld)}"',
|
||||
f'{indent} name: "{feld}"',
|
||||
f'{indent} widget: "select"']
|
||||
# ONLY multi_fields determines multi-select - "more than one option to
|
||||
# choose from" (len(values) > 1) is not the same as "multiple values
|
||||
# selectable at once" and must not be conflated. Found live: "lizenz"
|
||||
# has 3 options, but exactly ONE applies per entry - the earlier
|
||||
# condition "len(values) > 1 or feld in multi_fields" incorrectly set
|
||||
# multiple: true as soon as a second vocabulary value was added. Decap
|
||||
# then stored lizenz as a list ("- CC0") instead of a plain string as
|
||||
# soon as someone made a selection in the CMS - unnoticed until a value
|
||||
# was actually changed.
|
||||
if feld in multi_fields:
|
||||
lines.append(f'{indent} multiple: true')
|
||||
lines.append(f'{indent} options:')
|
||||
for wert in values:
|
||||
lines.append(f'{indent} - "{wert}"')
|
||||
return "\n".join(lines)
|
||||
|
||||
feld_labels = {
|
||||
"zielgruppe": "Zielgruppe",
|
||||
"kategorie": "Kategorie",
|
||||
"lizenz": "Lizenz",
|
||||
"tags": "Tags",
|
||||
}
|
||||
multi_fields = {"zielgruppe", "kategorie", "tags"}
|
||||
|
||||
def replace_block(match):
|
||||
feld = match.group("feld")
|
||||
indent = match.group("indent")
|
||||
vokabular_file = vokabular_dir / f"{feld}.txt"
|
||||
start = match.group("start")
|
||||
end = match.group("end")
|
||||
if not vokabular_file.exists():
|
||||
return match.group(0)
|
||||
values = [line.strip() for line in vokabular_file.read_text().splitlines() if line.strip()]
|
||||
if not values:
|
||||
return match.group(0)
|
||||
block = render_field(feld, indent, values)
|
||||
return f"{indent}{start}\n{block}\n{indent}{end}"
|
||||
|
||||
pattern = re.compile(
|
||||
r'(?P<indent>[ \t]*)(?P<start># VOKABULAR:(?P<feld>\w+):START)\n'
|
||||
r'.*?\n'
|
||||
r'[ \t]*(?P<end># VOKABULAR:(?P=feld):END)',
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
result = pattern.sub(replace_block, text)
|
||||
Path(out_path).write_text(result)
|
||||
PYEOF
|
||||
|
||||
echo "config.yml generiert: $OUT"
|
||||
Executable
+62
@@ -0,0 +1,62 @@
|
||||
#!/bin/bash
|
||||
# Generates hugo/data/methoden.json and hugo/data/varianten.json: creation
|
||||
# and last-modified date per method/variant, determined from the git
|
||||
# history of _content/.
|
||||
#
|
||||
# Hugo's enableGitInfo/.GitInfo only looks for git history in the repo that
|
||||
# contains the Hugo page root (ableger_demo/ableger) - but _content/ is a
|
||||
# separate git repo (ableger_demo/ableger_methoden) mounted via
|
||||
# module.mounts and is not recognized there (.GitInfo stays nil, no error,
|
||||
# just silently empty). This has affected "last modified" ever since the
|
||||
# repo split, unnoticed, because Hugo doesn't warn about it.
|
||||
# For "created" there would be no Hugo-native equivalent anyway, see
|
||||
# https://github.com/gohugoio/hugo/issues/11810 (open).
|
||||
#
|
||||
# So both dates are read here uniformly from git history ourselves, instead
|
||||
# of relying on .GitInfo. Recomputed fresh on every sync rather than
|
||||
# maintained (see sync-methoden.sh, which calls this script automatically) -
|
||||
# no manual date field, git stays the single source of truth.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
CONTENT_REPO="$ROOT/_content"
|
||||
|
||||
dates_for_path() {
|
||||
local relpath="$1"
|
||||
local history erstellt geaendert
|
||||
# One "git log --follow" call instead of two: with the full (not -1)
|
||||
# history for this path, the first line (newest) is "geaendert" and the
|
||||
# last line (oldest, following through renames) is "erstellt" - no need
|
||||
# for a second, separately filtered/unfollowed call to get either.
|
||||
history="$(git -C "$CONTENT_REPO" log --follow --format=%aI -- "$relpath")"
|
||||
geaendert="$(echo "$history" | head -1)"
|
||||
erstellt="$(echo "$history" | tail -1)"
|
||||
[ -n "$erstellt" ] && [ -n "$geaendert" ] || return 1
|
||||
jq -n --arg erstellt "$erstellt" --arg geaendert "$geaendert" '{erstellt: $erstellt, geaendert: $geaendert}'
|
||||
}
|
||||
|
||||
# Both methods and variants are one folder per entry with content in
|
||||
# index.md (Hugo page bundle) - variants ever since attachments moved from
|
||||
# the method to the respective variant, see admin/config.template.yml.
|
||||
generate_bundle_dates() {
|
||||
local name="$1"
|
||||
local dir="$CONTENT_REPO/$name"
|
||||
local out="$ROOT/hugo/data/$name.json"
|
||||
mkdir -p "$(dirname "$out")"
|
||||
local entries="{}"
|
||||
if [ -d "$dir" ]; then
|
||||
for entry_dir in "$dir"/*/; do
|
||||
local slug
|
||||
slug="$(basename "$entry_dir")"
|
||||
[ -f "$entry_dir/index.md" ] || continue
|
||||
local dates
|
||||
dates="$(dates_for_path "$name/$slug/index.md")" || continue
|
||||
entries="$(echo "$entries" | jq --arg slug "$slug" --argjson dates "$dates" '. + {($slug): $dates}')"
|
||||
done
|
||||
fi
|
||||
echo "$entries" > "$out"
|
||||
echo "$name.json aktualisiert: $(echo "$entries" | jq 'length') Einträge"
|
||||
}
|
||||
|
||||
generate_bundle_dates "methoden"
|
||||
generate_bundle_dates "varianten"
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
# Generates hugo/data/website.json: the current commit (short hash + date)
|
||||
# of THIS website/CMS-code repo itself - shown in the footer next to the
|
||||
# Manifest version (see baseof.html) so an installation can tell at a
|
||||
# glance which code state it's actually running, independent of whether
|
||||
# it's still identical to the template or has since been developed further
|
||||
# on its own. Deliberately NOT a frozen "forked from template version X"
|
||||
# marker - once a fork's own commits land, this reflects those, not the
|
||||
# template's history.
|
||||
#
|
||||
# Unlike hugo/data/methoden.json/varianten.json (generate-dates.sh), this
|
||||
# reads the website repo's own git history directly - no separate
|
||||
# module.mounts repo involved, Hugo's enableGitInfo/.GitInfo would actually
|
||||
# work here, but a plain "git log" call keeps this consistent with the
|
||||
# same approach already used for methoden/varianten dates.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
OUT="$ROOT/hugo/data/website.json"
|
||||
mkdir -p "$(dirname "$OUT")"
|
||||
|
||||
commit="$(git -C "$ROOT" rev-parse --short HEAD)"
|
||||
datum="$(git -C "$ROOT" log -1 --format=%aI)"
|
||||
|
||||
jq -n --arg commit "$commit" --arg datum "$datum" '{commit: $commit, datum: $datum}' > "$OUT"
|
||||
echo "website.json aktualisiert: $commit ($datum)"
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env ruby
|
||||
# Generates vorlagen-manifest.json in the given templates folder - lists all
|
||||
# .docx/.odt files found there so the methoden-set tool (methoden-set/, see
|
||||
# the Methoden-Set chapter on the project website) can offer them automatically as template choices,
|
||||
# including files someone copied manually straight onto the server (not
|
||||
# just the ones from this repo). Runs in the deploy hook AFTER the rsync of
|
||||
# methoden-set/ into the docroot (see the installation guide on the project website) and
|
||||
# therefore deliberately scans the docroot itself, not the git worktree -
|
||||
# rsync runs there without --delete, so manually added files survive
|
||||
# across deploys and show up here too.
|
||||
require 'json'
|
||||
|
||||
verzeichnis = ARGV[0] or abort "Verwendung: #{$0} <vorlagen-verzeichnis>"
|
||||
|
||||
dateien = Dir.glob(File.join(verzeichnis, '*.{docx,odt}')).map { |pfad| File.basename(pfad) }.sort
|
||||
|
||||
# Derive the label from the filename (without extension, hyphens/
|
||||
# underscores turned into spaces, each word capitalized) - no additional
|
||||
# metadata field to maintain, the filename itself is the only source.
|
||||
eintraege = dateien.map do |datei|
|
||||
format = File.extname(datei).delete_prefix('.')
|
||||
name = File.basename(datei, '.*')
|
||||
label = name.gsub(/[-_]+/, ' ').strip.split(' ').map { |w| w.empty? ? w : w[0].upcase + w[1..] }.join(' ')
|
||||
{ 'datei' => datei, 'format' => format, 'label' => label }
|
||||
end
|
||||
|
||||
File.write(File.join(verzeichnis, 'vorlagen-manifest.json'), JSON.pretty_generate(eintraege))
|
||||
puts "vorlagen-manifest.json geschrieben: #{eintraege.length} Vorlage(n)"
|
||||
@@ -0,0 +1,59 @@
|
||||
# Shared helpers for reading/writing YAML frontmatter in method and variant
|
||||
# files - previously each script (validate.rb, apply-veroeffentlicht.rb,
|
||||
# compute-methoden-sichtbarkeit.rb) had its own copy of
|
||||
# read_frontmatter/write_frontmatter.
|
||||
#
|
||||
# More important than the duplication itself: a fixed field order when
|
||||
# writing (Befund G, see the project website (background/analysis notes) Teil 5, Schritt 6).
|
||||
# Ruby hashes preserve insertion order - a field that was deleted and
|
||||
# re-set (e.g. "draft" after fm.delete/fm[]=) used to move to the end,
|
||||
# creating unnecessary diff noise. Fields outside the canonical order are
|
||||
# not discarded but appended at the end unchanged (in their previous
|
||||
# order) - a script that doesn't know a field should still not silently
|
||||
# lose it.
|
||||
require 'yaml'
|
||||
require 'date'
|
||||
|
||||
module Frontmatter
|
||||
# Order per the Manifest chapter on the project website Teil C (field catalog), "draft" added: a
|
||||
# derived field that never appears in the content repo (see Regel 12),
|
||||
# only in the local copy translated for Hugo (see compute-methoden-
|
||||
# sichtbarkeit.rb).
|
||||
METHODEN_FELDER = %w[
|
||||
kennung titel kurzbeschreibung verwendungsmoeglichkeit zielgruppe
|
||||
kompetenzbereich kategorie tags lernchancen herkunft initiatoren draft
|
||||
].freeze
|
||||
|
||||
# "draft" replaces "veroeffentlicht" at the same position in the local
|
||||
# copy translated for Hugo (see apply-veroeffentlicht.rb) - the two sit
|
||||
# next to each other in the canonical order, but only one of them ever
|
||||
# appears in a given committed resp. translated file.
|
||||
VARIANTEN_FELDER = %w[
|
||||
kennung methode untertitel varianten_beschreibung veroeffentlicht draft dauer_minuten
|
||||
gruppengroesse_min gruppengroesse_max material autoren lizenz quellen
|
||||
anhaenge
|
||||
].freeze
|
||||
|
||||
def self.read(path)
|
||||
parse(File.read(path, encoding: 'UTF-8'))
|
||||
end
|
||||
|
||||
# Same split+parse as read(), but for text already in memory (e.g. from
|
||||
# `git show`) instead of a file on disk - see scripts/validate.rb,
|
||||
# vorherige_kennung.
|
||||
def self.parse(text)
|
||||
return nil unless text.start_with?("---\n")
|
||||
parts = text.split(/^---\s*$/, 3)
|
||||
return nil unless parts.length == 3
|
||||
fm = YAML.safe_load(parts[1], permitted_classes: [Date, Time]) || {}
|
||||
[fm, parts[2]]
|
||||
end
|
||||
|
||||
def self.write(path, fm, body, feldreihenfolge:)
|
||||
geordnet = {}
|
||||
feldreihenfolge.each { |feld| geordnet[feld] = fm[feld] if fm.key?(feld) }
|
||||
(fm.keys - feldreihenfolge).each { |feld| geordnet[feld] = fm[feld] }
|
||||
yaml = YAML.dump(geordnet).sub(/\A---\n/, '')
|
||||
File.write(path, "---\n#{yaml}---#{body}", encoding: 'UTF-8')
|
||||
end
|
||||
end
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
#!/bin/bash
|
||||
# Fetches the current state of the separate methods repo
|
||||
# (ableger_demo/ableger_methoden) into ./_content - for local development and
|
||||
# in the deploy hook on Uberspace. _content/ is deliberately not part of this
|
||||
# repo (see .gitignore) and is freshly fetched here on every call instead of
|
||||
# being pinned as a submodule. Hugo mounts _content/methoden (see
|
||||
# hugo/hugo.toml) - the content repo itself contains a methoden/ subfolder,
|
||||
# not just the methods directly at its root (Decap CMS workaround, see
|
||||
# admin/config.yml).
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
# shellcheck source=/dev/null
|
||||
source "$ROOT/install.env"
|
||||
|
||||
# ABLEGER_METHODEN_URL completely overrides this fallback in the deploy hook
|
||||
# (a local filesystem path on the same Uberspace account, see
|
||||
# the installation guide on the project website) - the SSH fallback built here from install.env is
|
||||
# only needed for local development without that environment variable set.
|
||||
REPO_URL="${ABLEGER_METHODEN_URL:-ssh://${GITEA_SSH_USER}@${GITEA_DOMAIN}:${GITEA_SSH_PORT}/${METHODEN_REPO}.git}"
|
||||
TARGET="$ROOT/_content"
|
||||
|
||||
if [ -d "$TARGET/.git" ]; then
|
||||
# "remote set-url" ALWAYS before the fetch, not only on first clone: an
|
||||
# already existing worktree otherwise keeps the remote URL from its
|
||||
# original clone time, even if REPO_URL has changed since (e.g. after a
|
||||
# repo rename/transfer to a different organization). This broke live
|
||||
# exactly this way: after transferring ableger_methoden to the
|
||||
# "ableger_demo" organization, the worktree already present on the server
|
||||
# kept pointing at the old path (tobias/ableger_methoden.git), and the
|
||||
# cron job then failed on every run (every 10 minutes) until this was
|
||||
# fixed manually.
|
||||
git -C "$TARGET" remote set-url origin "$REPO_URL"
|
||||
git -C "$TARGET" fetch origin main
|
||||
git -C "$TARGET" reset --hard origin/main
|
||||
else
|
||||
rm -rf "$TARGET"
|
||||
git clone "$REPO_URL" "$TARGET"
|
||||
fi
|
||||
|
||||
echo "_content/ aktuell: $(git -C "$TARGET" rev-parse --short HEAD)"
|
||||
|
||||
# Validate against the Manifest chapter on the project website (website repo) BEFORE
|
||||
# apply-veroeffentlicht.rb and compute-methoden-sichtbarkeit.rb translate the
|
||||
# state for Hugo - the validation script needs the real, committed state
|
||||
# (with "veroeffentlicht", without Hugo's "draft"), otherwise its own rules
|
||||
# (e.g. Regel 12: no derived fields stored) could never be satisfiable
|
||||
# against its own translation. set -e above ensures that an error (exit
|
||||
# code 1) here aborts the entire sync/build before a broken reference or
|
||||
# similar goes live unnoticed (see the project website (background/analysis notes), Befund A/B) -
|
||||
# warnings (exit code 0) deliberately do not block.
|
||||
ruby "$(dirname "${BASH_SOURCE[0]}")/validate.rb"
|
||||
|
||||
# Recompute creation dates from the freshly fetched history.
|
||||
"$(dirname "${BASH_SOURCE[0]}")/generate-dates.sh"
|
||||
|
||||
# Translate the variants' "veroeffentlicht" field (positive polarity) into
|
||||
# Hugo's native draft field - must run before compute-methoden-
|
||||
# sichtbarkeit.rb, which reads that draft field. See
|
||||
# admin/config.template.yml and the script's own comments.
|
||||
ruby "$(dirname "${BASH_SOURCE[0]}")/apply-veroeffentlicht.rb"
|
||||
|
||||
# Mark methods without a published variant as draft, locally (not in the
|
||||
# content repo) - see admin/config.template.yml and the script's own comment.
|
||||
ruby "$(dirname "${BASH_SOURCE[0]}")/compute-methoden-sichtbarkeit.rb"
|
||||
Executable
+299
@@ -0,0 +1,299 @@
|
||||
#!/usr/bin/env ruby
|
||||
# Validates _content/ against the rules from the Manifest chapter on the project website, Teil D. Runs
|
||||
# BEFORE apply-veroeffentlicht.rb and compute-methoden-sichtbarkeit.rb (see
|
||||
# sync-methoden.sh) - so it checks the real, committed state in the content
|
||||
# repo (with "veroeffentlicht", without Hugo's translated "draft"), not the
|
||||
# copy translated for the Hugo build.
|
||||
#
|
||||
# Two severity levels:
|
||||
# FEHLER (error) - structural (broken reference, duplicate/changed
|
||||
# kennung, wrong folder name) - aborts the run with exit code
|
||||
# 1; the deploy hook (sync-methoden.sh) must treat this as a
|
||||
# build stop, otherwise e.g. a method with a broken variant
|
||||
# reference could go live unnoticed (see the project website,
|
||||
# background/analysis notes, Befund A - exactly this class of error).
|
||||
# WARNUNG (warning) - content-related (missing required field, vocabulary
|
||||
# violation) - is reported but does not block: a single
|
||||
# incomplete entry shouldn't take down the whole site.
|
||||
#
|
||||
# Deliberately NO rule "a method needs at least one variant" - a normal
|
||||
# in-progress state while creating an entry, not a violation (see Manifest
|
||||
# Teil D).
|
||||
#
|
||||
# The required-field list below still duplicates admin/config.template.yml
|
||||
# (website repo) - the vocabulary (Regel 9) has read from ableger.yml
|
||||
# (content repo) since Schritt 5 (see the project website (background/analysis notes), Befund C),
|
||||
# but the required-field list itself stays hardcoded here for now.
|
||||
require_relative 'lib/frontmatter'
|
||||
require 'set'
|
||||
|
||||
root = File.expand_path('..', __dir__)
|
||||
content = File.join(root, '_content')
|
||||
methoden_dir = File.join(content, 'methoden')
|
||||
varianten_dir = File.join(content, 'varianten')
|
||||
|
||||
fehler = []
|
||||
warnungen = []
|
||||
|
||||
def read_frontmatter(path)
|
||||
Frontmatter.read(path)
|
||||
rescue Psych::SyntaxError => e
|
||||
[{ '__parse_error__' => e.message }, '']
|
||||
end
|
||||
|
||||
def kennung_pattern
|
||||
# Underscore allowed (e.g. "sinnesparcours-fur-senior_innen" - our
|
||||
# gender-inclusive spelling "Senior_innen"), otherwise identical to the
|
||||
# pattern in admin/config.template.yml.
|
||||
/\A[a-z0-9_]+(-[a-z0-9_]+)*\z/
|
||||
end
|
||||
|
||||
# Reads the previous kennung of the same file from git history (the prior
|
||||
# commit touching this path) - not the very first commit, since "kennung"
|
||||
# was introduced later and older commits don't know the field yet (no
|
||||
# comparison possible, no false positive wanted).
|
||||
def vorherige_kennung(rel_path, content_dir)
|
||||
# --follow is crucial here: when the kennung changes, the folder is
|
||||
# usually renamed along with it (Decap does this automatically, since
|
||||
# the folder name is derived from the kennung - see slug in
|
||||
# admin/config.template.yml). Without --follow, "git log -- <path>" stops
|
||||
# right at that rename and only finds the one new commit - the actual
|
||||
# violation would go undetected. Verified live against our own test case
|
||||
# (git mv + kennung changed, without --follow: no warning).
|
||||
# --name-only together with --follow, to get the historical path of the
|
||||
# commit under which "git show" needs to read the content.
|
||||
# Output format is "<hash>\n\n<path>" per commit, WITHOUT a blank line
|
||||
# between <path> and the next <hash> - so split flatly by lines and read
|
||||
# in pairs (hash, path, hash, path, ...), not block-wise by blank lines
|
||||
# (verified live, initially produced mismatched pairs).
|
||||
zeilen = `cd #{content_dir} && git log --follow --format=%H --name-only -- #{rel_path}`.split("\n").reject(&:empty?)
|
||||
return nil if zeilen.length < 4
|
||||
|
||||
voriger_hash, voriger_pfad = zeilen[2], zeilen[3]
|
||||
|
||||
vorheriger_inhalt = `cd #{content_dir} && git show #{voriger_hash}:#{voriger_pfad} 2>/dev/null`.force_encoding('UTF-8')
|
||||
return nil if vorheriger_inhalt.empty?
|
||||
result = Frontmatter.parse(vorheriger_inhalt)
|
||||
return nil unless result
|
||||
fm, = result
|
||||
fm['kennung']
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
|
||||
def vokabular(daten, name)
|
||||
werte = (daten['vokabular'] || {})[name]
|
||||
werte && Array(werte)
|
||||
end
|
||||
|
||||
methoden_pflichtfelder = %w[kennung titel kurzbeschreibung verwendungsmoeglichkeit zielgruppe kompetenzbereich kategorie lernchancen initiatoren]
|
||||
varianten_pflichtfelder = %w[veroeffentlicht methode kennung untertitel varianten_beschreibung dauer_minuten gruppengroesse_min gruppengroesse_max material lizenz autoren]
|
||||
|
||||
# --- Regel 14: protokoll_version, also the source of the vocabulary (Regel 9) ---
|
||||
ableger_yml = File.join(content, 'ableger.yml')
|
||||
ableger_daten = {}
|
||||
if File.exist?(ableger_yml)
|
||||
ableger_daten = YAML.load_file(ableger_yml) || {}
|
||||
version = ableger_daten['protokoll_version']
|
||||
fehler << "ableger.yml: protokoll_version fehlt" unless version
|
||||
fehler << "ableger.yml: protokoll_version #{version.inspect} wird von diesem Skript nicht unterstützt (bekannt: 1)" if version && version != 1
|
||||
else
|
||||
fehler << "ableger.yml fehlt an der Repo-Wurzel (Regel 14)"
|
||||
end
|
||||
|
||||
# --- Read methods ---
|
||||
methoden_kennungen = Set.new
|
||||
methoden_by_kennung = {}
|
||||
|
||||
Dir.glob(File.join(methoden_dir, '*')).select { |d| File.directory?(d) }.each do |dir|
|
||||
ordner = File.basename(dir)
|
||||
index = File.join(dir, 'index.md')
|
||||
|
||||
# Regel 7
|
||||
unless File.exist?(index)
|
||||
fehler << "methoden/#{ordner}/: kein index.md gefunden (Regel 7)"
|
||||
next
|
||||
end
|
||||
|
||||
fm, body = read_frontmatter(index)
|
||||
if fm.nil? || fm.key?('__parse_error__')
|
||||
fehler << "methoden/#{ordner}/index.md: YAML-Frontmatter ungültig#{fm ? " (#{fm['__parse_error__']})" : ''}"
|
||||
next
|
||||
end
|
||||
|
||||
kennung = fm['kennung']
|
||||
rel_path = "methoden/#{ordner}/index.md"
|
||||
|
||||
# Regel 5
|
||||
if kennung && !kennung_pattern.match?(kennung)
|
||||
fehler << "#{rel_path}: kennung #{kennung.inspect} passt nicht zum Muster a-z/0-9/- (Regel 5)"
|
||||
end
|
||||
|
||||
# Regel 3
|
||||
if kennung && kennung != ordner
|
||||
fehler << "#{rel_path}: Ordnername '#{ordner}' entspricht nicht der Kennung '#{kennung}' (Regel 3)"
|
||||
end
|
||||
|
||||
# Regel 2 (method kennungen unique)
|
||||
if kennung
|
||||
if methoden_kennungen.include?(kennung)
|
||||
fehler << "#{rel_path}: Kennung '#{kennung}' ist nicht eindeutig (Regel 2)"
|
||||
end
|
||||
methoden_kennungen << kennung
|
||||
methoden_by_kennung[kennung] = fm
|
||||
end
|
||||
|
||||
# Regel 6 (immutability)
|
||||
if kennung
|
||||
vorher = vorherige_kennung(rel_path, content)
|
||||
if vorher && vorher != kennung
|
||||
fehler << "#{rel_path}: Kennung wurde von '#{vorher}' zu '#{kennung}' geändert (Regel 6)"
|
||||
end
|
||||
end
|
||||
|
||||
# Regel 11 (document body empty)
|
||||
unless body.strip.empty?
|
||||
warnungen << "#{rel_path}: Dokumentkörper ist nicht leer, gehört bei Methoden aber zur Variante (Regel 11)"
|
||||
end
|
||||
|
||||
# Regel 12 (no derived fields)
|
||||
%w[draft dauer_minuten gruppengroesse_min gruppengroesse_max material lizenz erstellt geaendert].each do |feld|
|
||||
warnungen << "#{rel_path}: enthält abgeleitetes/verschobenes Feld '#{feld}', gehört nicht (mehr) zur Methode (Regel 12)" if fm.key?(feld)
|
||||
end
|
||||
|
||||
# Regel 8 (required fields)
|
||||
methoden_pflichtfelder.each do |feld|
|
||||
wert = fm[feld]
|
||||
leer = wert.nil? || (wert.respond_to?(:empty?) && wert.empty?)
|
||||
warnungen << "#{rel_path}: Pflichtfeld '#{feld}' fehlt oder ist leer (Regel 8)" if leer
|
||||
end
|
||||
|
||||
# Regel 9 (vocabulary)
|
||||
# lizenz has not been a method field since the field move, see below under variants.
|
||||
{ 'zielgruppe' => vokabular(ableger_daten, 'zielgruppe'), 'kompetenzbereich' => vokabular(ableger_daten, 'kompetenzbereich') }.each do |feld, erlaubt|
|
||||
next unless erlaubt
|
||||
werte = Array(fm[feld])
|
||||
werte.each do |w|
|
||||
warnungen << "#{rel_path}: Wert '#{w}' bei '#{feld}' steht nicht im Vokabular (Regel 9)" unless erlaubt.include?(w)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# --- Read variants ---
|
||||
varianten_kennungen_je_methode = Hash.new { |h, k| h[k] = Set.new }
|
||||
|
||||
Dir.glob(File.join(varianten_dir, '*')).select { |d| File.directory?(d) }.each do |dir|
|
||||
ordner = File.basename(dir)
|
||||
index = File.join(dir, 'index.md')
|
||||
|
||||
unless File.exist?(index)
|
||||
fehler << "varianten/#{ordner}/: kein index.md gefunden (Regel 7)"
|
||||
next
|
||||
end
|
||||
|
||||
fm, _body = read_frontmatter(index)
|
||||
if fm.nil? || fm.key?('__parse_error__')
|
||||
fehler << "varianten/#{ordner}/index.md: YAML-Frontmatter ungültig#{fm ? " (#{fm['__parse_error__']})" : ''}"
|
||||
next
|
||||
end
|
||||
|
||||
rel_path = "varianten/#{ordner}/index.md"
|
||||
methode_kennung = fm['methode']
|
||||
eigene_kennung = fm['kennung']
|
||||
|
||||
# Regel 1
|
||||
if methode_kennung.nil? || !methoden_kennungen.include?(methode_kennung)
|
||||
fehler << "#{rel_path}: methode '#{methode_kennung.inspect}' verweist auf keine existierende Methoden-Kennung (Regel 1)"
|
||||
end
|
||||
|
||||
# Regel 5
|
||||
if eigene_kennung && !kennung_pattern.match?(eigene_kennung)
|
||||
fehler << "#{rel_path}: kennung #{eigene_kennung.inspect} passt nicht zum Muster a-z/0-9/- (Regel 5)"
|
||||
end
|
||||
|
||||
# Regel 4
|
||||
erwarteter_ordner = "#{methode_kennung}--#{eigene_kennung}"
|
||||
if methode_kennung && eigene_kennung && ordner != erwarteter_ordner
|
||||
fehler << "#{rel_path}: Ordnername '#{ordner}' entspricht nicht '<methode>--<kennung>' ('#{erwarteter_ordner}') (Regel 4)"
|
||||
end
|
||||
|
||||
# Regel 2 (variant kennungen unique per method)
|
||||
if methode_kennung && eigene_kennung
|
||||
if varianten_kennungen_je_methode[methode_kennung].include?(eigene_kennung)
|
||||
fehler << "#{rel_path}: Kennung '#{eigene_kennung}' ist bei Methode '#{methode_kennung}' nicht eindeutig (Regel 2)"
|
||||
end
|
||||
varianten_kennungen_je_methode[methode_kennung] << eigene_kennung
|
||||
end
|
||||
|
||||
# Regel 6 (immutability)
|
||||
if eigene_kennung
|
||||
vorher = vorherige_kennung(rel_path, content)
|
||||
if vorher && vorher != eigene_kennung
|
||||
fehler << "#{rel_path}: Kennung wurde von '#{vorher}' zu '#{eigene_kennung}' geändert (Regel 6)"
|
||||
end
|
||||
end
|
||||
|
||||
# Regel 12 (no derived fields)
|
||||
%w[draft erstellt geaendert].each do |feld|
|
||||
warnungen << "#{rel_path}: enthält abgeleitetes Feld '#{feld}' - das übernimmt apply-veroeffentlicht.rb/generate-dates.sh selbst (Regel 12)" if fm.key?(feld)
|
||||
end
|
||||
|
||||
# Regel 8 (required fields)
|
||||
varianten_pflichtfelder.each do |feld|
|
||||
wert = fm[feld]
|
||||
leer = wert.nil? || (wert.respond_to?(:empty?) && wert.empty?) || (feld == 'veroeffentlicht' && wert.nil?)
|
||||
warnungen << "#{rel_path}: Pflichtfeld '#{feld}' fehlt oder ist leer (Regel 8)" if leer && feld != 'veroeffentlicht'
|
||||
end
|
||||
|
||||
# Regel 10
|
||||
gmin, gmax = fm['gruppengroesse_min'], fm['gruppengroesse_max']
|
||||
if gmin && gmax && gmin > gmax
|
||||
fehler << "#{rel_path}: gruppengroesse_min (#{gmin}) > gruppengroesse_max (#{gmax}) (Regel 10)"
|
||||
end
|
||||
|
||||
# lizenz must be a plain string, not a list - found live: a bug in
|
||||
# generate-config.sh (website repo) incorrectly set multiple: true for
|
||||
# "lizenz" as soon as the vocabulary had more than one value. Decap then
|
||||
# saved e.g. "- CC0" instead of "CC0" as soon as someone made a selection
|
||||
# in the CMS. This type error is structural (Regel 8 wouldn't recognize
|
||||
# it as "empty" at all, since a non-empty list is not an empty value) and
|
||||
# is therefore handled separately here as an ERROR, not as a vocabulary
|
||||
# warning.
|
||||
if fm['lizenz'].is_a?(Array)
|
||||
fehler << "#{rel_path}: 'lizenz' ist eine Liste (#{fm['lizenz'].inspect}) statt eines einzelnen Werts - Formularfehler beim Speichern, siehe scripts/generate-config.sh"
|
||||
else
|
||||
# Regel 9 (vocabulary)
|
||||
erlaubt = vokabular(ableger_daten, 'lizenz')
|
||||
if erlaubt && fm['lizenz']
|
||||
warnungen << "#{rel_path}: Wert '#{fm['lizenz']}' bei 'lizenz' steht nicht im Vokabular (Regel 9)" unless erlaubt.include?(fm['lizenz'])
|
||||
end
|
||||
end
|
||||
|
||||
# Regel 13 (attachments exist)
|
||||
Array(fm['anhaenge']).each do |anhang|
|
||||
next unless anhang.is_a?(Hash) && anhang['datei']
|
||||
pfad = File.join(dir, anhang['datei'])
|
||||
fehler << "#{rel_path}: Anhang '#{anhang['datei']}' existiert nicht im selben Ordner (Regel 13)" unless File.exist?(pfad)
|
||||
end
|
||||
end
|
||||
|
||||
# --- Ausgabe ---
|
||||
unless warnungen.empty?
|
||||
puts "Warnungen (#{warnungen.size}):"
|
||||
warnungen.each { |w| puts " ⚠ #{w}" }
|
||||
puts
|
||||
end
|
||||
|
||||
unless fehler.empty?
|
||||
puts "Fehler (#{fehler.size}):"
|
||||
fehler.each { |f| puts " ✗ #{f}" }
|
||||
puts
|
||||
end
|
||||
|
||||
if fehler.empty?
|
||||
puts "Prüfung bestanden#{warnungen.empty? ? '' : " (#{warnungen.size} Warnung(en))"}."
|
||||
exit 0
|
||||
else
|
||||
puts "Prüfung fehlgeschlagen: #{fehler.size} Fehler."
|
||||
exit 1
|
||||
end
|
||||
Reference in New Issue
Block a user