-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathgenerate.rb
More file actions
370 lines (317 loc) · 10.3 KB
/
generate.rb
File metadata and controls
370 lines (317 loc) · 10.3 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
class GitScribe
module Generate
# generate the new media
def gen(args = [])
@done = {} # what we've generated already
type = first_arg(args) || 'all'
prepare_output_dir
gather_and_process
types = type == 'all' ? OUTPUT_TYPES : [type]
ret = false
output = []
Dir.chdir("output") do
types.each do |out_type|
call = 'do_' + out_type
if self.respond_to? call
ret = self.send call
else
die "NOT A THING: #{call}"
end
end
# clean up
`rm #{BOOK_FILE}`
ret
end
end
def prepare_output_dir
Dir.mkdir('output') rescue nil
Dir.chdir('output') do
Dir.mkdir('stylesheets') rescue nil
from_stdir = File.join(SCRIBE_ROOT, 'stylesheets')
FileUtils.cp_r from_stdir, '.'
end
end
def a2x(type)
"a2x -f #{type} -d book --no-xmllint "
end
def a2x_wss(type)
a2x(type) + " --stylesheet=stylesheets/scribe.css"
end
def do_docbook
return true if @done['docbook']
info "GENERATING DOCBOOK"
if ex("asciidoc -b docbook #{BOOK_FILE}")
@done['docbook'] = true
'book.xml'
end
end
def do_pdf
info "GENERATING PDF"
do_docbook
java_options = {
'callout.graphics' => 0,
'navig.graphics' => 0,
'admon.textlabel' => 1,
'admon.graphics' => 0,
}
run_xslt "-o #{local('book.fo')} #{local('book.xml')} #{base('docbook-xsl/fo.xsl')}", java_options
ex "fop -fo #{local('book.fo')} -pdf #{local('book.pdf')}"
if $?.success?
'book.pdf'
end
end
def do_epub
info "GENERATING EPUB"
# TODO: look for custom stylesheets
cmd = "#{a2x_wss('epub')} -v #{BOOK_FILE}"
if ex(cmd)
'book.epub'
end
end
def do_mobi
do_html
info "GENERATING MOBI"
generate_toc_files
# generate book.opf
cmd = "kindlegen -verbose book.opf -o book.mobi"
if ex(cmd)
'book.mobi'
end
end
def do_html
return true if @done['html']
info "GENERATING HTML"
# TODO: look for custom stylesheets
stylesheet = local('stylesheets') + '/scribe.css'
cmd = "asciidoc -a stylesheet=#{stylesheet} #{BOOK_FILE}"
if ex(cmd)
@done['html'] == true
'book.html'
end
end
def do_site
info "GENERATING SITE"
# TODO: check if html was already done
ex "asciidoc -b docbook #{BOOK_FILE}"
run_xslt "book.xml #{base('docbook-xsl/xhtml/chunk.xsl')}", "html.stylesheet" => 1
source = File.read('index.html')
html = Nokogiri::HTML.parse(source, nil, 'utf-8')
sections = []
c = -1
# each chapter
html.css('.toc > dl').each do |section|
section.children.each do |item|
if item.name == 'dt' # section
c += 1
sections[c] ||= {'number' => c}
link = item.css('a').first
sections[c]['title'] = title = link.text
sections[c]['href'] = href = link['href']
clean_title = title.downcase.gsub(/[^a-z0-9\-_]+/, '_') + '.html'
sections[c]['link'] = clean_title
if href[0, 10] == 'index.html'
sections[c]['link'] = 'title.html'
end
sections[c]['sub'] = []
end
if item.name == 'dd' # subsection
item.css('dt').each do |sub|
link = sub.css('a').first
data = {}
data['title'] = title = link.text
data['href'] = href = link['href']
data['link'] = sections[c]['link'] + '#' + href.split('#').last
sections[c]['sub'] << data
end
end
end
end
book_title = html.css('head > title').text
content = html.css('body > div')[1]
content.css('.toc').first.remove
content = content.inner_html
sections.each do |s|
content.gsub!(s['href'], s['link'])
end
template_dir = File.join(SCRIBE_ROOT, 'site', 'default')
# copy the template files in
files = Dir.glob(template_dir + '/*')
FileUtils.cp_r files, '.'
index_template = liquid_template('index.html')
page_template = liquid_template('page.html')
# write the index page
main_data = {
'book_title' => book_title,
'sections' => sections
}
File.open('index.html', 'w+') do |f|
f.puts index_template.render( main_data )
end
# write the title page
File.open('title.html', 'w+') do |f|
data = {
'title' => sections.first['title'],
'sub' => sections.first['sub'],
'prev' => {'link' => 'index.html', 'title' => "Main"},
'home' => {'link' => 'index.html', 'title' => "Home"},
'next' => sections[1],
'content' => content
}
data.merge!(main_data)
f.puts page_template.render( data )
end
# write the other pages
sections.each_with_index do |section, i|
if i > 0 # skip title page
source = File.read(section['href'])
html = Nokogiri::HTML.parse(source, nil, 'utf-8')
content = html.css('body > div')[1].to_html
sections.each do |s|
content.gsub!(s['href'], s['link'])
end
File.open(section['link'], 'w+') do |f|
next_section = nil
if i <= sections.size
next_section = sections[i+1]
end
data = {
'title' => section['title'],
'sub' => section['sub'],
'prev' => sections[i-1],
'home' => {'link' => 'index.html', 'title' => "Home"},
'next' => next_section,
'content' => content
}
data.merge!(main_data)
f.puts page_template.render( data )
end
#File.unlink(section['href'])
info i
info section['title']
info section['href']
info section['link']
end
#File.unlink
end
sections
end
def generate_toc_files
# read book table of contents
toc = []
source = File.read("book.html")
# get the book title
book_title = 'Title'
if t = /\<title>(.*?)<\/title\>/.match(source)
book_title = t[0]
end
source.scan(/\<h([2|3]) id=\"(.*?)\"\>(.*?)\<\/h[2|3]\>/).each do |header|
sec = {'id' => header[1], 'name' => header[2]}
if header[0] == '2'
toc << {'section' => sec, 'subsections' => []}
else
toc[toc.size - 1]['subsections'] << sec
end
end
# write ncx table of contents
ncx = File.open('book.ncx', 'w+')
ncx.puts('<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN"
"http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en-US">
<head>
<meta name="dtb:depth" content="2"/>
<meta name="dtb:totalPageCount" content="0"/>
<meta name="dtb:maxPageNumber" content="0"/>
</head>
<docTitle><text>Title</text></docTitle>
<docAuthor><text>Author</text></docAuthor>
<navMap>
<navPoint class="toc" id="toc" playOrder="1">
<navLabel>
<text>Table of Contents</text>
</navLabel>
<content src="toc.html"/>
</navPoint>')
chapters = 0
toc.each do |section|
chapters += 1
ch = section['section']
ncx.puts('<navPoint class="chapter" id="chapter_' + chapters.to_s + '" playOrder="' + (chapters + 1).to_s + '">')
ncx.puts('<navLabel><text>' + ch['name'].to_s + '</text></navLabel>')
ncx.puts('<content src="book.html#' + ch['id'].to_s + '"/>')
ncx.puts('</navPoint>')
end
ncx.puts('</navMap></ncx>')
ncx.close
# build html toc
# write ncx table of contents
html = File.open('toc.html', 'w+')
html.puts('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Table of Contents</title></head><body>
<div><h1><b>TABLE OF CONTENTS</b></h1><br/>')
chapters = 0
toc.each do |section|
chapters += 1
ch = section['section']
html.puts('<h3><b>Chapter ' + chapters.to_s + '<br/>')
html.puts('<a href="book.html#' + ch['id'] + '">' + ch['name'] + '</a></b></h3><br/>')
section['subsections'].each do |sub|
html.puts('<a href="book.html#' + sub['id'] + '"><b>' + sub['name'] + '</b></a><br/>')
end
end
html.puts('<h1 class="centered">* * *</h1></div></body></html>')
html.close
# build book.opf file
opf_template = liquid_template('book.opf')
File.open('book.opf', 'w+') do |f|
lang = @config['language'] || 'en'
author = @config['author'] || 'Author'
cover = @config['cover'] || 'images/cover.jpg'
data = {'title' => book_title,
'language' => lang,
'author' => author,
'pubdate' => Time.now.strftime("%Y-%m-%d"),
'cover_image' => cover}
f.puts opf_template.render( data )
end
end
def liquid_template(file)
template_dir = File.join(SCRIBE_ROOT, 'site', 'default')
Liquid::Template.parse(File.read(File.join(template_dir, file)))
end
# create a new file by concatenating all the ones we find
def gather_and_process
files = Dir.glob("book/*")
FileUtils.cp_r files, 'output', :remove_destination => true
if OVERRIDE_NAME != ""
FileUtils.mv "output/#{OVERRIDE_NAME}", "output/book.asc"
end
end
def ex(command)
out = `#{command} 2>&1`
info out
$?.success?
end
private
def windows?
RbConfig::CONFIG['host_os'] =~ /mswin|windows|mingw|cygwin/i
end
def classpath_delimiter
if windows?
";"
else
":"
end
end
def run_xslt(jar_arguments, java_options)
ex <<-SH
java -cp "#{base('vendor/saxon.jar')}#{classpath_delimiter}#{base('vendor/xslthl-2.0.2.jar')}" \
-Dxslthl.config=file://"#{base('docbook-xsl/highlighting/xslthl-config.xml')}" \
#{java_options.map { |k, v| "-D#{k}=#{v}" }.join(' ')} \
com.icl.saxon.StyleSheet \
#{jar_arguments}
SH
end
end
end