-
Notifications
You must be signed in to change notification settings - Fork 0
/
glossary_preproc.rb
executable file
·68 lines (55 loc) · 2.4 KB
/
glossary_preproc.rb
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
#!/usr/bin/env ruby
# frozen_string_literal: true
# This script will take a post filename as the first and only argument
# What it will do is loop through all files in _glossary/ and replace
# mentions in the post with links to the glossary page. This script aims to
# produce idempotent results.
#
require 'front_matter_parser'
require 'yaml'
require 'active_support/core_ext/string/inflections'
DEBUG = true
# just one glossary item
class GlossaryItem
attr_reader :fname, :title, :link_part, :slug
def initialize(fname)
return unless File.exist? fname
@fname = fname
fcontent = YAML.load_file(fname)
# Slug is the file name without extension, e.g. "Volo"
@slug = fname.gsub('_skt_glossary/', '')\
.gsub(/\.md$/, '')\
.gsub('_', ' ')\
.titleize
# Title is e.g. "Volothamp Geddarm". This is optional and defaults to @slug
@title = fcontent['title'] ||= @slug
# Link part is the hash part in /glossary/ for this glossary item,
# i.e. #volothamp+geddarm
@link_part = "##{@title.downcase.gsub(' ', '+')}"
end
end
all_glossary_items = Dir.glob('_skt_glossary/*.md').map do |item_fname|
puts "[DEBUG] reading #{item_fname}" if DEBUG
GlossaryItem.new(item_fname)
end
puts '[DEBUG] DONE reading glossary items' if DEBUG
markdown_fname = ARGV.first
markdown_file = FrontMatterParser::Parser.parse_file(markdown_fname)
all_glossary_items.each do |glossary_term|
puts "[DEBUG] substituting #{glossary_term.title} in #{markdown_fname}..." if DEBUG
count = 0
# We must only replace full words that are not enclosed in quotes
markdown_file.content.gsub!(/(?!<{%.*?)\b#{glossary_term.title}\b(?!.*?%})/) { |m| count +=1; m.replace("{% include glossary_link.html title=\"#{glossary_term.title}\" %}")}
markdown_file.content.gsub!(/(?!<{%.*?)\b#{glossary_term.slug}\b(?!.*?%})/) { |m| count +=1; m.replace("{% include glossary_link.html title=\"#{glossary_term.slug}\" name=\"#{glossary_term.title}\" %}")}
if DEBUG
puts "[DEBUG] ... #{count} times!" unless count.zero?
end
end
File.open(markdown_fname, 'w') do |output_file|
puts "[DEBUG] writing changes to #{markdown_fname}" if DEBUG
# We're writing this out step by step because FrontMaterParser.to_yaml
# does not reproduce the original input
output_file.write(markdown_file.front_matter.to_yaml)
output_file.write("---\n\n")
output_file.write(markdown_file.content)
end