forked from graalvm/graalvm-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
process_front_matter.rb
99 lines (86 loc) 路 2.44 KB
/
process_front_matter.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
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
#!/usr/bin/env ruby
require 'yaml'
add_title = false
version_permalinks = false
add_redirects = false
folders = []
ARGV.each do |arg|
case arg
when '--add-title'
add_title = true
when '--version-permalinks'
version_permalinks = true
when '--add-redirects'
add_redirects = true
when /^-/
raise "Unknown option: #{arg}"
else
folders << arg
end
end
folders.each do |folder|
Dir.glob("#{folder}/**/*.md") do |file|
puts file if $VERBOSE
lines = File.readlines(file)
lines = lines.drop(1)
last_yaml_line = lines.index { |line|
line.strip == "---"
}
unless last_yaml_line
warn "No YAML header in #{file} !"
next
end
yaml = lines[0...last_yaml_line].join
body = lines[last_yaml_line+1..-1].join
begin
header = YAML.load yaml
rescue Psych::SyntaxError => e
warn "Could not parse the YAML header in #{file}:\n#{e.inspect}"
next
end
unless header.is_a?(Hash)
warn "Unexpected YAML header in #{file}:\n#{header.inspect}"
exit(1)
end
next if %w[redirected docs_landing].include? header["layout"]
if add_title
# Add title:
unless header.include?('title')
title = body[/^##?\s+(\S.+)$/, 1]
if title
header['title'] = title
elsif title = header['link_title']
warn "No h1/h2 in #{file}, using link_title instead"
header['title'] = title
else
warn "Could not find title in #{file}"
end
end
end
if version_permalinks
# Add version in permalink:
# Updates
# permalink: /foo => permalink: "/$version/foo"
# Does not change:
# permalink: "/$version/foo"
if permalink = header['permalink']
permalink = permalink[1...-1] if permalink.start_with?('"')
versioned_permalink = if permalink.start_with?('/$version')
permalink
else
"/$version#{permalink}"
end
header['permalink'] = versioned_permalink
end
end
# Add redirect_from: for unversioned URLs
if add_redirects and permalink
redirects = Array(header['redirect_from'])
redirect_to_latest_release = permalink.sub('/$version', '')
redirects << redirect_to_latest_release unless redirects.include?(redirect_to_latest_release)
header['redirect_from'] = redirects
end
contents = "#{YAML.dump(header).chomp}\n---\n#{body}"
File.write(file, contents)
end
end