# 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 # Reorders fm's keys to the canonical order (fields outside it appended # unchanged at the end, see module comment) without writing anything - # shared by write() below and generate-verlauf.rb, which reorders both # sides of a historical comparison the same way before diffing so a # field merely sitting at a different position (e.g. Decap CMS moving # "tags" to the end) doesn't itself look like a change. def self.geordnet(fm, feldreihenfolge) ergebnis = {} feldreihenfolge.each { |feld| ergebnis[feld] = fm[feld] if fm.key?(feld) } (fm.keys - feldreihenfolge).each { |feld| ergebnis[feld] = fm[feld] } ergebnis end def self.write(path, fm, body, feldreihenfolge:) yaml = YAML.dump(geordnet(fm, feldreihenfolge)).sub(/\A---\n/, '') File.write(path, "---\n#{yaml}---#{body}", encoding: 'UTF-8') end end