Skip to content

Commit 89c35f7

Browse files
srgizhbagasme
andcommitted
Refactor book:build task
progit/progit2#1598 Co-authored-by: Bagas Sanjaya <[email protected]>
1 parent 6846ed8 commit 89c35f7

File tree

2 files changed

+141
-37
lines changed

2 files changed

+141
-37
lines changed

README.asc

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,13 @@ image:https://travis-ci.org/progit/progit2-ru.svg?branch=master["Build Status",
1010

1111
С момента публикации первого издания многое изменилось.
1212
Для начала, мы перешли с Markdown на AsciiDoc -- вот краткий справочник по синтаксису https://asciidoctor.org/docs/asciidoc-syntax-quick-reference/[AsciiDoc].
13-
К тому же мы теперь используем https://atlas.oreilly.com[Atlas] от О'Рейли для постоянной сборки книги, так что все основные форматы всегда в наличии.
1413

1514
Еще мы убрали переводы из подразделов английского языка в отдельные репозитории.
1615
Подробнее в пункте про переводы.
1716

1817
== Участие
1918

20-
Чтобы исправить ошибку или добавить что-то новое в этот репозиторий, вам нужно открыть пулл-реквест на GitHub.
19+
Чтобы исправить ошибку или добавить что-то новое в этот репозиторий, вам нужно открыть запрос на изменение (Pull Request) на GitHub.
2120

2221
Несмотря на то, что в английской версии просят воздержаться от стилистических изменений на больших участках текста, русский перевод профессиональные редакторы не просматривали, будем рады вашим правкам.
2322

@@ -27,10 +26,11 @@ image:https://travis-ci.org/progit/progit2-ru.svg?branch=master["Build Status",
2726

2827
Самый простой -- поручить это нам. Робот реагирует на изменения в ветке `master` репозитория и автоматически собирает книгу во всех форматах.
2928

30-
Текущую сборку можно найти на https://git-scm.com/book/ru/v2.
29+
Текущую сборку можно найти по адресу https://git-scm.com/book/ru/v2.
3130

32-
Другой способ получить кнугу -- собрать её самостоятельно с помощью Asciidoctor.
33-
Используя команды ниже, вы сможете получить HTML, Epub, Mobi и PDF файлы:
31+
Другой способ получить книгу -- собрать её самостоятельно с помощью Asciidoctor.
32+
Раньше мы могли собирать файлы .mobi (Kindle), но сейчас не можем, см. https://github.com/progit/progit2/issues/1496[#1496] для получения дополнительной информации.
33+
Используя команды ниже, вы сможете получить HTML, Epub и PDF-файлы:
3434

3535
----
3636
$ bundle install
@@ -39,14 +39,32 @@ Converting to HTML...
3939
-- HTML output at progit.html
4040
Converting to EPub...
4141
-- Epub output at progit.epub
42-
Converting to Mobi (kf8)...
43-
-- Mobi output at progit.mobi
4442
Converting to PDF...
45-
-- PDF output at progit.pdf
43+
-- PDF output at progit.pdf
4644
----
4745

4846
Здесь используются проекты `asciidoctor`, `asciidoctor-pdf` и `asciidoctor-epub`.
4947

48+
Также возможно собрать отдельно в одном из поддерживаемых форматов (HTML, EPUB или PDF).
49+
50+
Сборка только в HTML:
51+
52+
----
53+
$ bundle exec rake book:build_html
54+
----
55+
56+
Сборка только в EPUB:
57+
58+
----
59+
$ bundle exec rake book:build_epub
60+
----
61+
62+
Сборка только в PDF:
63+
64+
----
65+
$ bundle exec rake book:build_pdf
66+
----
67+
5068
По умолчанию, `bundle install` устанавливает зависимости глобально в систему.
5169
Чтобы этого избежать, следует сконфигурировать менеджер пакетов перед установкой зависимостей с помощью следующей команды:
5270

Rakefile

Lines changed: 115 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -8,51 +8,102 @@ namespace :book do
88
end
99
end
1010

11-
desc 'build basic book formats'
12-
task :build do
11+
lang = "ru"
12+
begin
13+
locale_file = "attributes-#{lang}.adoc"
14+
locale_file_url = "https://raw.githubusercontent.com/asciidoctor/asciidoctor/master/data/locale/#{locale_file}"
1315

14-
begin
15-
lang = "ru"
16-
begin
17-
locale_file = "attributes-#{lang}.adoc"
18-
locale_file_url = "https://raw.githubusercontent.com/asciidoctor/asciidoctor/master/data/locale/#{locale_file}"
19-
20-
if not File.exist?(locale_file)
21-
puts "Downloading locale attributes file #{locale_file_url} ..."
22-
l10n_text = URI.open(locale_file_url).read
23-
File.open(locale_file, 'w') { |file| file.puts l10n_text }
24-
else
25-
puts "Use existing file with locale attributes #{locale_file}"
26-
end
27-
rescue
28-
puts "[ERROR] Can not download attributes list for language #{lang}"
29-
end
16+
if not File.exist?(locale_file)
17+
puts "Downloading locale attributes file #{locale_file_url} ..."
18+
l10n_text = URI.open(locale_file_url).read
19+
File.open(locale_file, 'w') { |file| file.puts l10n_text }
20+
else
21+
puts "Use existing file with locale attributes #{locale_file}"
22+
end
23+
rescue
24+
puts "[ERROR] Can not download attributes list for language #{lang}"
25+
end
26+
27+
# Variables referenced for build
28+
version_string = ENV['TRAVIS_TAG'] || `git describe --tags`.chomp
29+
if version_string.empty?
30+
version_string = '0'
31+
end
32+
33+
date_string = Time.now.strftime("%d.%m.%Y")
34+
params = "--attribute revnumber='#{version_string}' --attribute revdate='#{date_string}' --attribute lang='#{lang}'"
35+
36+
header_hash = `git rev-parse --short HEAD`.strip
37+
38+
# Check contributors list
39+
# This checks commit hash stored in the header of list against current HEAD
40+
def check_contrib
41+
if File.exist?('book/contributors.txt')
42+
current_head_hash = `git rev-parse --short HEAD`.strip
43+
header = `head -n 1 book/contributors.txt`.strip
44+
# Match regex, then coerce resulting array to string by join
45+
header_hash = header.scan(/[a-f0-9]{7,}/).join
3046

31-
version_string = ENV['TRAVIS_TAG'] || `git describe --tags`.chomp
32-
if version_string.empty?
33-
version_string = '0'
47+
if header_hash == current_head_hash
48+
puts "Hash on header of contributors list (#{header_hash}) matches the current HEAD (#{current_head_hash})"
49+
else
50+
puts "Hash on header of contributors list (#{header_hash}) does not match the current HEAD (#{current_head_hash}), refreshing"
51+
`rm book/contributors.txt`
52+
# Reenable and invoke task again
53+
Rake::Task['book/contributors.txt'].reenable
54+
Rake::Task['book/contributors.txt'].invoke
3455
end
56+
end
57+
end
58+
59+
desc 'build basic book formats'
60+
task :build => [:build_html, :build_epub, :build_pdf] do
61+
begin
62+
# Run check
63+
Rake::Task['book:check'].invoke
3564

36-
date_string = Time.now.strftime("%d.%m.%Y")
37-
params = "--attribute revnumber='#{version_string}' --attribute revdate='#{date_string}' --attribute lang=#{lang} "
65+
# Rescue to ignore checking errors
66+
rescue => e
67+
puts e.message
68+
puts "Error when checking books (ignored)"
69+
end
70+
end
3871

72+
desc 'build basic book formats (for ci)'
73+
task :ci => [:build_html, :build_epub, :build_pdf] do
74+
# Run check, but don't ignore any errors
75+
Rake::Task['book:check'].invoke
76+
end
77+
78+
desc 'generate contributors list'
79+
file 'book/contributors.txt' do
3980
puts "Generating contributors list"
40-
`git shortlog -s | grep -v -E "(Straub|Chacon|dependabot)" | cut -f 2- | column -c 96 > book/contributors.txt`
81+
`echo "Contributors as of #{header_hash}:\n" > book/contributors.txt`
82+
`git shortlog -s | grep -v -E "(Straub|Chacon|dependabot)" | cut -f 2- | column -x -c 48 >> book/contributors.txt`
83+
end
84+
85+
desc 'build HTML format'
86+
task :build_html => 'book/contributors.txt' do
87+
check_contrib()
4188

4289
puts "Converting to HTML..."
4390
`bundle exec asciidoctor #{params} -a data-uri progit.asc`
4491
puts " -- HTML output at progit.html"
4592

46-
puts " -- Validate HTML file progit.html"
47-
exec_or_raise('htmlproofer --check-html progit.html')
93+
end
94+
95+
desc 'build Epub format'
96+
task :build_epub => 'book/contributors.txt' do
97+
check_contrib()
4898

4999
puts "Converting to EPub..."
50100
`bundle exec asciidoctor-epub3 #{params} progit.asc`
51101
puts " -- Epub output at progit.epub"
52102

53-
puts " -- Validate Epub output file progit.epub"
54-
exec_or_raise('epubcheck progit.epub')
55-
103+
end
104+
105+
desc 'build Mobi format'
106+
task :build_mobi => 'book/contributors.txt' do
56107
# Commented out the .mobi file creation because the kindlegen dependency is not available.
57108
# For more information on this see: #1496.
58109
# This is a (hopefully) temporary fix until upstream asciidoctor-epub3 is fixed and we can offer .mobi files again.
@@ -61,9 +112,44 @@ namespace :book do
61112
# `bundle exec asciidoctor-epub3 #{params} -a ebook-format=kf8 progit.asc`
62113
# puts " -- Mobi output at progit.mobi"
63114

115+
# FIXME: If asciidoctor-epub3 supports Mobi again, uncomment these lines below
116+
puts "Converting to Mobi isn't supported yet."
117+
puts "For more information see issue #1496 at https://github.com/progit/progit2/issues/1496."
118+
exit(127)
119+
end
120+
121+
desc 'build PDF format'
122+
task :build_pdf => 'book/contributors.txt' do
123+
check_contrib()
124+
64125
puts "Converting to PDF... (this one takes a while)"
65126
`bundle exec asciidoctor-pdf #{params} progit.asc 2>/dev/null`
66127
puts " -- PDF output at progit.pdf"
128+
end
129+
130+
desc 'Check generated books'
131+
task :check => [:build_html, :build_epub] do
132+
puts "Checking generated books"
133+
134+
exec_or_raise('htmlproofer --check-html progit.html')
135+
exec_or_raise('epubcheck progit.epub')
136+
end
137+
138+
desc 'Clean all generated files'
139+
task :clean do
140+
begin
141+
puts "Removing generated files"
142+
143+
FileList['book/contributors.txt', 'progit.html', 'progit.epub', 'progit.pdf'].each do |file|
144+
rm file
145+
146+
# Rescue if file not found
147+
rescue Errno::ENOENT => e
148+
begin
149+
puts e.message
150+
puts "Error removing files (ignored)"
151+
end
152+
end
67153
end
68154
end
69155
end

0 commit comments

Comments
 (0)