]> Shamusworld >> Repos - ardour-manual-diverged/blob - build.rb
Little bit of cleaning up code
[ardour-manual-diverged] / build.rb
1 require 'pathname'
2 require 'fileutils'
3 require 'yaml'
4 require 'liquid'
5 require 'optparse'
6
7 CONFIG = {
8     pages_dir: '_manual',
9     layouts_dir: '_layouts',
10     static_dir: 'source',
11     output_dir: '_site'         # will get wiped!
12 }
13
14 def child_url?(a, b)
15     a.start_with?(b) && b.count('/') + 1 == a.count('/')
16 end
17
18 class Site
19     attr_reader :pages, :layouts
20
21     def initialize()
22         @pages = []
23         @layouts = {}
24     end
25     
26     def build()
27         print "Building... "
28
29         read_layouts()
30         read_pages()
31         copy_static()
32         process_pages()
33
34         puts "done."
35     end
36
37     def read_layouts()
38         Pathname.glob(layouts_dir + Pathname('*.html')) do |path|
39             next if !path.file?
40             layout = Layout.new(self, path)
41             layout.read
42             @layouts[path.basename('.html').to_s] = layout
43         end
44     end
45     
46     def read_pages()
47         pages_dir.find do |path|
48             if path.file? && path.extname == '.html'
49                 page = Page.new(self, path)
50                 page.read
51                 @pages << page
52             end
53         end
54     end
55
56     def process_pages()
57         @pages.each {|page| page.process}
58     end
59     
60     def copy_static()
61         `rsync -a --delete --exclude='*~' #{static_dir}/. #{output_dir}`
62     end
63     
64     def find_children(url)
65         sorted_pages.select { |p| child_url?(p.url, url) }
66     end
67     
68     def toplevel() @toplevel_memo ||= find_children('/') end
69     def sorted_pages() @sorted_pages_memo ||= @pages.sort_by{ |p| p.sort_url } end
70
71     def pages_dir() @pages_dir_memo ||= Pathname(CONFIG[:pages_dir]) end
72     def layouts_dir() @layouts_dir_memo ||= Pathname(CONFIG[:layouts_dir]) end
73     def static_dir() @static_dir_memo ||= Pathname(CONFIG[:static_dir]) end
74     def output_dir() @output_dir_memo ||= Pathname(CONFIG[:output_dir]) end
75 end
76
77 class Page
78     attr_reader :path, :out_path, :url, :sort_url
79
80     def initialize(site, path)
81         @site = site
82         @path = path
83
84         relative_path = @path.relative_path_from(@site.pages_dir);
85         a = relative_path.each_filename.map do |x|
86             x.sub(/^[0-9]*[-_]/, '')
87         end
88         a[-1].sub!(/\.html$/, '')
89         s = a.join('/')
90
91         @out_path = @site.output_dir + Pathname(s) + Pathname("index.html")
92         @url = "/#s/"
93         @sort_url = @path.to_s.sub(/\.html$/, '')
94     end
95
96     def related_to?(p)
97         # should we show p in the index on selfs page?
98         url.start_with?(p.url) || child_url?(url, p.url)
99     end
100
101     def title()
102         @page_context['title'] || ""
103     end
104
105     def menu_title()
106         @page_context['menu_title'] || title
107     end
108
109     def read()
110         content = @path.read
111         frontmatter, @content = split_frontmatter(content) || abort("File not well-formatted: #{@path}") 
112         @page_context = YAML.load(frontmatter)
113         @template = Liquid::Template.parse(@content)
114     end        
115
116     def split_frontmatter(txt)
117         @split_regex ||= /\A---[ \t\r]*\n(?<frontmatter>.*?)^---[ \t\r]*\n(?<content>.*)\z/m
118         match = @split_regex.match txt 
119         match ? [match['frontmatter'], match['content']] : nil
120     end
121     
122     def find_layout()
123         @site.layouts[@page_context['layout'] || 'default']
124     end
125
126     def children()
127         @children ||= @site.find_children(@url)
128     end
129     
130     def render()
131         registers = {page: self, site: @site}
132         context = {'page' => @page_context}
133         content = @template.render!(context, registers: registers)
134         find_layout.render(context.merge({'content' => content}), registers)
135     end
136     
137     def process()
138         path = out_path
139         path.dirname.mkpath
140         path.open('w') { |f| f.write(render) }
141     end
142 end
143
144 class Layout < Page
145     def render(context, registers)
146         context = context.dup
147         context['page'] = @page_context.merge(context['page'])
148         content = @template.render!(context, registers: registers)
149         if @page_context.has_key?('layout')
150             find_layout.render(context.merge({'content' => content}), registers)
151         else
152             content
153         end
154     end
155 end
156
157 class Tag_tree < Liquid::Tag
158     def join(children_html)
159         children_html.empty? ? "" : "<dl>\n" + children_html.join + "</dl>\n"
160     end
161
162     def render(context)
163         current = context.registers[:page]
164         site = context.registers[:site]
165
166         format_entry = lambda do |page|
167             children = page.children
168             
169             css = (page == current) ? ' class="active"' : ""
170             children_html = current.related_to?(page) ? join(children.map(&format_entry)) : ""
171             
172             %{
173           <dt#{css}>
174             <a href='#{page.url}'>#{page.menu_title}</a>
175           </dt>
176           <dd#{css}>
177             #{children_html}
178           </dd>
179         }
180         end
181
182         join(site.toplevel.map(&format_entry))
183     end
184 end
185
186 class Tag_children < Liquid::Tag
187     def render(context)
188         children = context.registers[:page].children
189         entries = children.map {|p| "<li><a href='#{p.url}'>#{p.title}</a></li>" }
190         
191         "<div id='subtopics'>
192         <h2>This chapter covers the following topics:</h2>
193         <ul>
194           #{entries.join}
195         </ul>
196         </div>
197       "
198     end
199 end
200
201 class Tag_prevnext < Liquid::Tag
202     def render(context)
203         current = context.registers[:page]
204         pages = context.registers[:site].sorted_pages
205         
206         index = pages.index { |page| page == current }
207         return '' if !index
208         
209         link = lambda do |p, cls, txt| 
210             "<li><a title='#{p.title}' href='#{p.url}' class='#{cls}'>#{txt}</a></li>"
211         end
212         prev_link = index > 0 ? link.call(pages[index-1], "previous", " &lt; Previous ") : ""
213         next_link = index < pages.length-1 ? link.call(pages[index+1], "next", " Next &gt; ") : ""
214         
215         "<ul class='pager'>#{prev_link}#{next_link}</ul>"
216     end
217 end
218
219 class Server
220     def start_watcher()
221         require 'listen'
222
223         listener = Listen.to(CONFIG[:pages_dir], wait_for_delay: 1.0, only: /.html$/) do |modified, added, removed|
224             Site.new.build
225         end
226         listener.start
227         listener
228     end
229
230     def run(options)
231         require 'webrick'
232         listener = options[:watch] && start_watcher
233             
234         puts "Serving at http://localhost:8000/ ..."
235         server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => CONFIG[:output_dir]
236         trap 'INT' do 
237             server.shutdown 
238         end
239         server.start
240         listener.stop if listener
241     end  
242 end
243
244 def main
245     Liquid::Template.register_tag('tree', Tag_tree)
246     Liquid::Template.register_tag('children', Tag_children)
247     Liquid::Template.register_tag('prevnext', Tag_prevnext)
248
249     if defined? Liquid::Template.error_mode
250         Liquid::Template.error_mode = :strict
251     end
252
253     options = {}
254     OptionParser.new do |opts| 
255         opts.on("--watch", "Watch for changes") { options[:watch] = true }
256     end.parse!
257
258     Site.new.build
259
260     if ARGV == ['serve']
261         Server.new.run(options)
262     end
263 end
264
265 main