reclaimable 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. checksums.yaml +7 -0
  2. data/.claude/launch.json +11 -0
  3. data/.gitignore +11 -0
  4. data/.gitlab-ci.yml +16 -0
  5. data/AGENTS.md +88 -0
  6. data/CLAUDE.md +1 -0
  7. data/Gemfile +3 -0
  8. data/LICENSE +674 -0
  9. data/README.md +160 -0
  10. data/Rakefile +28 -0
  11. data/ai-skill/reclaimable/SKILL.md +94 -0
  12. data/benchmark/README.md +59 -0
  13. data/benchmark/experiments/lstat_scanner.rb +11 -0
  14. data/benchmark/experiments/ractor_scanner.rb +92 -0
  15. data/benchmark/experiments/verify_bulk_list.rb +34 -0
  16. data/benchmark/lib/fixture.rb +104 -0
  17. data/benchmark/lib/results.rb +62 -0
  18. data/benchmark/reports/00-baseline.md +75 -0
  19. data/benchmark/reports/01-jit.md +70 -0
  20. data/benchmark/reports/02-ractor.md +58 -0
  21. data/benchmark/reports/03-getattrlistbulk.md +84 -0
  22. data/benchmark/reports/04-others.md +52 -0
  23. data/benchmark/reports/05-outside-root.md +56 -0
  24. data/benchmark/reports/06-round2-discussion.md +374 -0
  25. data/benchmark/reports/06-round2.md +194 -0
  26. data/benchmark/reports/README.md +46 -0
  27. data/benchmark/results/baseline.yml +126 -0
  28. data/benchmark/results/bulk-list.yml +126 -0
  29. data/benchmark/results/final-yjit.yml +126 -0
  30. data/benchmark/results/final.yml +126 -0
  31. data/benchmark/results/ractor-exp.yml +38 -0
  32. data/benchmark/results/round2-after.yml +126 -0
  33. data/benchmark/results/round2-before.yml +126 -0
  34. data/benchmark/results/src-baseline.yml +32 -0
  35. data/benchmark/results/src-bulk-list.yml +32 -0
  36. data/benchmark/results/src-pair-none1.yml +38 -0
  37. data/benchmark/results/src-pair-none2.yml +38 -0
  38. data/benchmark/results/src-pair-yjit1.yml +38 -0
  39. data/benchmark/results/src-pair-yjit2.yml +38 -0
  40. data/benchmark/results/src-ractor-exp.yml +32 -0
  41. data/benchmark/results/src-round2-after1.yml +52 -0
  42. data/benchmark/results/src-round2-after2.yml +52 -0
  43. data/benchmark/results/src-round2-before1.yml +52 -0
  44. data/benchmark/results/src-round2-before2.yml +52 -0
  45. data/benchmark/results/yjit.yml +126 -0
  46. data/benchmark/results/zjit.yml +126 -0
  47. data/benchmark/run.rb +149 -0
  48. data/bin/reclaimable +10 -0
  49. data/doc/performance.md +179 -0
  50. data/lib/reclaimable/ai_skill.rb +138 -0
  51. data/lib/reclaimable/bulk_list.rb +91 -0
  52. data/lib/reclaimable/cache_dump.rb +125 -0
  53. data/lib/reclaimable/cli.rb +168 -0
  54. data/lib/reclaimable/cloud_files.rb +33 -0
  55. data/lib/reclaimable/config.rb +100 -0
  56. data/lib/reclaimable/i18n.rb +24 -0
  57. data/lib/reclaimable/locations.rb +89 -0
  58. data/lib/reclaimable/output.rb +154 -0
  59. data/lib/reclaimable/paths.rb +36 -0
  60. data/lib/reclaimable/report.rb +504 -0
  61. data/lib/reclaimable/ruby_abi.rb +69 -0
  62. data/lib/reclaimable/scan_cache.rb +97 -0
  63. data/lib/reclaimable/scanner.rb +440 -0
  64. data/lib/reclaimable/util.rb +34 -0
  65. data/lib/reclaimable.rb +42 -0
  66. data/locale/ja/LC_MESSAGES/reclaimable.mo +0 -0
  67. data/man/reclaimable.1.ronn +302 -0
  68. data/man/reclaimable.en.1 +234 -0
  69. data/man/reclaimable.ja.1 +452 -0
  70. data/po/ja/reclaimable-docs.po +668 -0
  71. data/po/ja/reclaimable.po +510 -0
  72. data/rakelib/benchmark.rake +22 -0
  73. data/rakelib/docs/japanese.rb +132 -0
  74. data/rakelib/docs/man_page.rb +73 -0
  75. data/rakelib/docs/site.rb +187 -0
  76. data/rakelib/docs/sources.rb +94 -0
  77. data/rakelib/docs/translation.rb +157 -0
  78. data/rakelib/docs.rake +62 -0
  79. data/rakelib/gettext.rake +30 -0
  80. data/rakelib/i18n.rake +199 -0
  81. data/reclaimable.gemspec +56 -0
  82. data/site/index.md +142 -0
  83. data/site/layout.html.erb +60 -0
  84. data/site/style.css +82 -0
  85. metadata +231 -0
@@ -0,0 +1,73 @@
1
+ require_relative "japanese"
2
+ require_relative "sources"
3
+
4
+ module Docs
5
+ # man page 1 言語分。man page(roff)、サイトに載せる HTML の断片、AI 向けの Markdown を作る。
6
+ # 原稿は Sources から取る(英語以外は PO の訳から作る)
7
+ class ManPage
8
+ attr_reader :lang
9
+
10
+ # lang: "en" または "ja"
11
+ def initialize(lang:, version:)
12
+ require "ronn" # 開発用の依存なので、使うときにだけ読み込む
13
+ @lang = lang
14
+ @version = version
15
+ end
16
+
17
+ def ja? = @lang == "ja"
18
+
19
+ # 生成する roff のパス。gem man(gem-man)は man/ の直下しか見ないので、どの言語も直下に言語名を付けて置く
20
+ # (gem-man は「.数字」で終わるファイルを一覧にして選ばせる。reclaimable --man は言語で選んで開く)。
21
+ # Rake の file タスクを定義するときにも使うので、ronn-ng を読み込まずに済むクラスメソッドにしてある
22
+ def self.output(lang) = "man/reclaimable.#{lang}.1"
23
+
24
+ def output = self.class.output(lang)
25
+
26
+ # 原稿。日本語は文中の改行を取り除いておく(Japanese.join_lines を参照)
27
+ def markdown
28
+ @markdown ||= Sources.markdown(:manual, lang).then { ja? ? Japanese.join_lines(it) : it }
29
+ end
30
+
31
+ # 「reclaimable(1)」
32
+ def reference_name = document.reference_name
33
+
34
+ # 「reclaimable(1) -- ここ」の部分
35
+ def tagline = document.tagline
36
+
37
+ def roff
38
+ roff = document.to_roff
39
+ # ronn-ng はコードブロックを .IP で囲むが、macOS の man(mandoc)ではその前後に空行が 2 つずつ入るので、.RS で字下げし直す
40
+ roff = roff.gsub(%(.IP "" 4\n.nf\n), %(.sp\n.RS 4\n.nf\n)).gsub(%(.fi\n.IP "" 0\n), %(.fi\n.RE\n))
41
+ return roff unless ja?
42
+
43
+ Japanese.wrap_roff(roff.sub('.SH "NAME"', '.SH "名前"'))
44
+ end
45
+
46
+ def html
47
+ html = document.to_html_fragment(nil)
48
+ # ronn-ng は見出しの id から ASCII 以外の文字を落とすので(日本語の見出しはすべて「-」になる)、見出しの文字列を id にする
49
+ html = html.gsub(%r{<h2 id="[^"]*">(.*?)</h2>}) { %(<h2 id="#{heading_id($1)}">#{$1}</h2>) }
50
+ ja? ? html.sub(%(<h2 id="NAME">NAME</h2>), %(<h2 id="名前">名前</h2>)) : html
51
+ end
52
+
53
+ private
54
+
55
+ def heading_id(text) = text.gsub(/<[^>]*>/, "").strip.gsub(/\s+/, "-")
56
+
57
+ # ronn-ng はパスから名前と章を取るので、ファイルは無くても生成先に合わせたパスを渡す
58
+ def document
59
+ @document ||= Ronn::Document.new("#{output}.ronn", { date:, organization: "reclaimable #{@version}" }) { markdown }
60
+ end
61
+
62
+ # man page の日付。原稿(訳は PO も)がコミット済みなら最後のコミットの日時、手元で変更中なら今日
63
+ # (ファイルの更新日時は、CI では clone した時刻になってしまうので使わない)
64
+ def date
65
+ files = Sources.date_sources(:manual, lang)
66
+ changed = IO.popen(["git", "status", "--porcelain", "--", *files], err: File::NULL, &:read)
67
+ committed = IO.popen(["git", "log", "-1", "--format=%ct", "--", *files], err: File::NULL, &:read).strip
68
+ changed.empty? && !committed.empty? ? Time.at(committed.to_i) : Time.now
69
+ rescue SystemCallError
70
+ Time.now
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,187 @@
1
+ require "cgi"
2
+ require "erb"
3
+ require "fileutils"
4
+ require "json"
5
+ require "pathname"
6
+ require "yaml"
7
+ require_relative "japanese"
8
+ require_relative "man_page"
9
+ require_relative "sources"
10
+
11
+ module Docs
12
+ # GitLab Pages に置くサイトを組み立てる。
13
+ # 英語をサイトの直下、日本語を ja/ に置き、同じ内容のページどうしを hreflang で結ぶ。
14
+ # 人向けの HTML のほかに、AI 向けに各ページの Markdown と llms.txt も置く
15
+ class Site
16
+ DEFAULT_URL = "https://kitaitimakoto.gitlab.io/reclaimable/"
17
+
18
+ # prefix: サイト内での置き場所。locale: OGP 用
19
+ LANGS = {
20
+ "en" => { prefix: "", locale: "en_US", name: "English" },
21
+ "ja" => { prefix: "ja/", locale: "ja_JP", name: "日本語" },
22
+ }.freeze
23
+
24
+ # key: 言語をまたいで同じ内容のページを結ぶための名前。path: サイト内の URL。md_path: Markdown 版の URL
25
+ Page = Data.define(:key, :lang, :path, :md_path, :title, :description, :html, :markdown, :kind) do
26
+ def file = path.empty? || path.end_with?("/") ? "#{path}index.html" : path
27
+ end
28
+
29
+ def initialize(base_url:, out_dir:, spec:)
30
+ require "kramdown" # 開発用の依存なので、使うときにだけ読み込む
31
+ require "kramdown-parser-gfm"
32
+ @base_url = base_url.end_with?("/") ? base_url : "#{base_url}/"
33
+ @out_dir = out_dir
34
+ @spec = spec
35
+ # LANG が未設定の環境でも日本語を扱えるよう、エンコーディングを明示して読む
36
+ @layout = ERB.new(File.read("site/layout.html.erb", encoding: "UTF-8"), trim_mode: "-")
37
+ end
38
+
39
+ def build
40
+ FileUtils.rm_rf(@out_dir)
41
+ pages = LANGS.keys.flat_map { [index_page(it), man_page(it)] }
42
+ pages.each do |page|
43
+ write(page.file, render(page, pages))
44
+ write(page.md_path, page.markdown)
45
+ end
46
+ write("404.html", render(not_found_page, []))
47
+ write("sitemap.xml", sitemap(pages))
48
+ write("llms.txt", llms_txt(pages))
49
+ FileUtils.cp("site/style.css", File.join(@out_dir, "style.css"))
50
+ end
51
+
52
+ # サイト内のパスを絶対 URL にする。レイアウトからも使う
53
+ def url(path) = "#{@base_url}#{path}"
54
+
55
+ # from のページから、サイト内の path へのリンク先。
56
+ # 公開前に file スキームで開いても辿れるよう、相対パスにし、フォルダーには index.html を付ける
57
+ # (file スキームではフォルダーを開いても index.html を表示しないため)。
58
+ # 404 のページはどの URL でも表示されるので、相対パスにできず絶対 URL にする
59
+ def href(from, path)
60
+ return url(path) if from.kind == :not_found
61
+
62
+ file = path.empty? || path.end_with?("/") ? "#{path}index.html" : path
63
+ Pathname(file).relative_path_from(Pathname(from.file).dirname).to_s
64
+ end
65
+
66
+ private
67
+
68
+ def write(path, content)
69
+ file = File.join(@out_dir, path)
70
+ FileUtils.mkdir_p(File.dirname(file))
71
+ File.write(file, content)
72
+ end
73
+
74
+ # 概要のページ。原稿は site/index.md(英語以外は PO の訳から作る)。先頭の front matter に title と description を書く
75
+ def index_page(lang)
76
+ text = Sources.markdown(:index, lang)
77
+ match = text.match(/\A---\n(.*?)\n---\n(.*)\z/m) or raise "front matter がない: #{lang}"
78
+ front, body = match.captures
79
+ meta = YAML.safe_load(front)
80
+ body = Japanese.join_lines(body) if lang == "ja"
81
+ html = Kramdown::Document.new(body, input: "GFM", hard_wrap: false, syntax_highlighter: nil).to_html
82
+ prefix = LANGS[lang][:prefix]
83
+ Page.new(key: :index, lang:, path: prefix, md_path: "#{prefix}index.md", title: meta.fetch("title"),
84
+ description: meta.fetch("description"), html:, markdown: body.lstrip, kind: :index)
85
+ end
86
+
87
+ def man_page(lang)
88
+ man = ManPage.new(lang:, version: @spec.version)
89
+ prefix = LANGS[lang][:prefix]
90
+ # man page には front matter がないので、検索結果に出す説明文はサイトの文言として持つ
91
+ Page.new(key: :manual, lang:, path: "#{prefix}reclaimable.1.html", md_path: "#{prefix}reclaimable.1.md",
92
+ title: "#{man.reference_name} — #{man.tagline}", description: Sources.string(:manual_description, lang),
93
+ html: %(<h1>#{CGI.escapeHTML(man.reference_name)}</h1>\n<div class="man">#{man.html}</div>),
94
+ markdown: man.markdown, kind: :manual)
95
+ end
96
+
97
+ # どの URL でも表示されるので、リンクはすべて絶対 URL にしてある(#href を参照)
98
+ def not_found_page
99
+ html = <<~HTML
100
+ <h1>Page not found</h1>
101
+ <p>The page you are looking for does not exist. <a href="#{url('')}">Go to the reclaimable overview</a>.</p>
102
+ <p lang="ja">お探しのページは見つかりませんでした。<a href="#{url('ja/')}">reclaimable の概要へ</a></p>
103
+ HTML
104
+ Page.new(key: :not_found, lang: "en", path: "404.html", md_path: nil, title: "Page not found — reclaimable",
105
+ description: nil, html:, markdown: nil, kind: :not_found)
106
+ end
107
+
108
+ def render(page, pages)
109
+ alternates = pages.select { it.key == page.key }
110
+ home = pages.find { it.key == :index && it.lang == page.lang }
111
+ manual = pages.find { it.key == :manual && it.lang == page.lang }
112
+ labels = Sources::STRINGS.keys.to_h { [it, Sources.string(it, page.lang)] }
113
+ @layout.result_with_hash(page:, alternates:, home:, manual:, labels:, langs: LANGS,
114
+ site: self, spec: @spec, json_ld: json_ld(page))
115
+ end
116
+
117
+ # 概要のページにだけ、ソフトウェアとしての構造化データを付ける
118
+ def json_ld(page)
119
+ return unless page.kind == :index
120
+
121
+ JSON.generate(
122
+ "@context" => "https://schema.org",
123
+ "@type" => "SoftwareApplication",
124
+ "name" => @spec.name,
125
+ "description" => page.description,
126
+ "url" => url(page.path),
127
+ "inLanguage" => page.lang,
128
+ "applicationCategory" => "DeveloperApplication",
129
+ "operatingSystem" => "macOS",
130
+ "softwareVersion" => @spec.version.to_s,
131
+ "softwareRequirements" => "Ruby #{@spec.required_ruby_version}",
132
+ "downloadUrl" => "https://rubygems.org/gems/#{@spec.name}",
133
+ "codeRepository" => @spec.metadata["source_code_uri"],
134
+ "author" => { "@type" => "Person", "name" => @spec.authors.first },
135
+ "offers" => { "@type" => "Offer", "price" => "0", "priceCurrency" => "USD" },
136
+ ).gsub("</", "<\\/") # <script> の中なので、</script> で閉じられないようにする
137
+ end
138
+
139
+ # 言語違いのページを xhtml:link で結んだ sitemap
140
+ def sitemap(pages)
141
+ entries = pages.map do |page|
142
+ links = pages.select { it.key == page.key }.map do
143
+ %( <xhtml:link rel="alternate" hreflang="#{it.lang}" href="#{CGI.escapeHTML(url(it.path))}"/>)
144
+ end
145
+ default = pages.find { it.key == page.key && it.lang == "en" }
146
+ links << %( <xhtml:link rel="alternate" hreflang="x-default" href="#{CGI.escapeHTML(url(default.path))}"/>)
147
+ " <url>\n <loc>#{CGI.escapeHTML(url(page.path))}</loc>\n#{links.join("\n")}\n </url>"
148
+ end
149
+ <<~XML
150
+ <?xml version="1.0" encoding="UTF-8"?>
151
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
152
+ #{entries.join("\n")}
153
+ </urlset>
154
+ XML
155
+ end
156
+
157
+ # https://llmstxt.org/ の形式。AI が最初に読む案内として、要約と Markdown 版へのリンクを並べる
158
+ def llms_txt(pages)
159
+ link = ->(key, lang, note) { pages.find { it.key == key && it.lang == lang }.then { "- [#{it.title}](#{url(it.md_path)}): #{note}" } }
160
+ en = pages.find { it.key == :index && it.lang == "en" }
161
+ <<~TEXT
162
+ # #{@spec.name}
163
+
164
+ > #{en.description}
165
+
166
+ - Install: `gem install #{@spec.name}`. Requires macOS and Ruby #{@spec.required_ruby_version}. Its only runtime gem dependency is gettext.
167
+ - It only reads. It never deletes, moves, or changes files, and never uses `sudo`.
168
+ - Messages and the report are in Japanese when the locale (LC_ALL, LC_MESSAGES, LANG) is Japanese, and in English otherwise.
169
+ - Read the manual in a terminal with `gem install gem-man` and then `gem man #{@spec.name}`.
170
+
171
+ ## Docs
172
+
173
+ #{link.(:index, 'en', Sources.string(:llms_index, 'en'))}
174
+ #{link.(:manual, 'en', Sources.string(:llms_manual, 'en'))}
175
+
176
+ ## Japanese
177
+
178
+ #{link.(:index, 'ja', Sources.string(:llms_index, 'ja'))}
179
+ #{link.(:manual, 'ja', Sources.string(:llms_manual, 'ja'))}
180
+
181
+ ## Optional
182
+
183
+ - [Source code](#{@spec.metadata['source_code_uri']})
184
+ TEXT
185
+ end
186
+ end
187
+ end
@@ -0,0 +1,94 @@
1
+ require_relative "translation"
2
+
3
+ module Docs
4
+ # ドキュメントの原稿。原稿は英語だけで、ほかの言語は po/<言語>/reclaimable-docs.po の訳から作る
5
+ module Sources
6
+ DOMAIN = "reclaimable-docs"
7
+ FILES = { manual: "man/reclaimable.1.ronn", index: "site/index.md" }.freeze
8
+
9
+ # Markdown の原稿の外にあるサイトの文言(ナビゲーション、検索結果に出す説明文、llms.txt の注記)。
10
+ # これも PO で訳す
11
+ STRINGS = {
12
+ home: "Overview",
13
+ manual: "Manual",
14
+ source: "Source code",
15
+ markdown: "Markdown version of this page",
16
+ manual_description: "Manual for reclaimable(1): options, report sections, files, and environment variables of " \
17
+ "reclaimable, a read-only command-line tool for macOS that finds what is eating disk space.",
18
+ llms_index: "what it finds, installation, usage, and FAQ",
19
+ llms_manual: "every option, report section, file, and environment variable",
20
+ }.freeze
21
+
22
+ module_function
23
+
24
+ def po_file(lang) = "po/#{lang}/#{DOMAIN}.po"
25
+
26
+ # サイトの文言(STRINGS)の lang での訳。訳がなければ英語
27
+ def string(key, lang)
28
+ english = STRINGS.fetch(key)
29
+ return english if lang == "en"
30
+
31
+ @translations ||= {}
32
+ (@translations[lang] ||= Translation.load(po_file(lang)))[english] || english
33
+ end
34
+
35
+ # lang の原稿(Markdown)。訳がない段落などは英語のまま残し、その旨を警告する
36
+ def markdown(key, lang)
37
+ english = File.read(FILES.fetch(key), encoding: "UTF-8")
38
+ return english if lang == "en"
39
+
40
+ translation = Translation.load(po_file(lang))
41
+ translation.translate(english).tap do
42
+ next if translation.missing.empty?
43
+
44
+ warn "warn: #{po_file(lang)} に訳がないので英語のままの箇所が #{translation.missing.size} 件(#{FILES[key]}):"
45
+ translation.missing.each { warn " #{FILES[key]}:#{it.line}: #{it.text[0, 70]}" }
46
+ end
47
+ end
48
+
49
+ # 原稿の日付を決めるのに使うファイル。訳した原稿は、英語の原稿と PO のどちらが変わっても新しくなる
50
+ def date_sources(key, lang) = [FILES.fetch(key), (po_file(lang) unless lang == "en")].compact
51
+
52
+ # 英語の原稿から翻訳の単位を抜き出した POT(訳の雛形)
53
+ def pot(version)
54
+ require "gettext/po"
55
+ po = GetText::PO.new
56
+ po[""] = header(version)
57
+ FILES.each_value do |file|
58
+ Translation.units(File.read(file, encoding: "UTF-8")).each do |unit|
59
+ po[unit.text] = "" unless po.has_key?(unit.text) # 同じ文が何度か出てくるときは 1 つにまとめる
60
+ entry = po[unit.text]
61
+ entry.references << "#{file}:#{unit.line}"
62
+ entry.extracted_comment ||= "type: #{unit.type}"
63
+ end
64
+ end
65
+ STRINGS.each do |key, english|
66
+ po[english] = "" unless po.has_key?(english)
67
+ po[english].references << "rakelib/docs/sources.rb"
68
+ po[english].extracted_comment ||= "type: site text (#{key})"
69
+ end
70
+ po.to_s(max_line_width: -1)
71
+ end
72
+
73
+ def header(version)
74
+ require "gettext/po_entry"
75
+ GetText::POEntry.new(:normal).tap do |entry|
76
+ entry.msgid = ""
77
+ entry.translator_comment = "Translations of the reclaimable documentation (man page and website).\n"
78
+ entry.flag = "fuzzy"
79
+ entry.msgstr = <<~HEADER
80
+ Project-Id-Version: reclaimable #{version}
81
+ Report-Msgid-Bugs-To:#{' '}
82
+ PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
83
+ Last-Translator: FULL NAME <EMAIL@ADDRESS>
84
+ Language-Team: LANGUAGE <LL@li.org>
85
+ Language:#{' '}
86
+ MIME-Version: 1.0
87
+ Content-Type: text/plain; charset=UTF-8
88
+ Content-Transfer-Encoding: 8bit
89
+ Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;
90
+ HEADER
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,157 @@
1
+ require "json"
2
+ require "yaml"
3
+
4
+ module Docs
5
+ # Markdown の原稿(英語)を翻訳の単位に分け、PO ファイルの訳で置き換えて別の言語の原稿を作る。
6
+ #
7
+ # 翻訳の単位は、段落・見出し・箇条書きの 1 項目・ronn の定義リストの項目名・``` のコードブロック・
8
+ # front matter の値。改行をまたぐ段落は 1 行にまとめて msgid にする(原稿の折り返し位置が変わっても訳が外れない)。
9
+ # 字下げしたコードブロック(コマンドの例)と、空行・``` の行・見出しの下線は訳さずにそのまま使う。
10
+ #
11
+ # 訳がない・あいまい(fuzzy)な単位は英語のまま残し、missing に記録する
12
+ class Translation
13
+ # kind: :raw(そのまま出す行)か :unit(翻訳の単位)。
14
+ # prefix: 1 行目の前に付ける字下げや記号(「## 」「 * 」など)。indent: 2 行目以降の字下げ
15
+ Segment = Data.define(:kind, :text, :prefix, :indent, :type, :line)
16
+
17
+ LIST_ITEM = /\A(\s*(?:[-*+]|\d+\.)\s+)(.*)\z/
18
+ HEADING = /\A(#+\s+)(.*)\z/
19
+ FENCE = /\A\s*```/
20
+ UNDERLINE = /\A(?:=+|-+)\s*\z/
21
+
22
+ # 原稿を Segment の配列に分ける
23
+ def self.parse(markdown)
24
+ lines = markdown.lines(chomp: true)
25
+ segments = []
26
+ raw = ->(text) { segments << Segment.new(kind: :raw, text:, prefix: "", indent: "", type: nil, line: nil) }
27
+ unit = lambda do |text, line:, type:, prefix: "", indent: ""|
28
+ segments << Segment.new(kind: :unit, text:, prefix:, indent:, type:, line:)
29
+ end
30
+ i = 0
31
+
32
+ # front matter(先頭の --- から --- まで)。値だけを訳す
33
+ if lines.first == "---" && (close = lines[1..].index("---"))
34
+ raw.("---")
35
+ lines[1..close].each.with_index(2) do |line, number|
36
+ if (m = line.match(/\A(\w+):\s*(.*)\z/))
37
+ unit.(YAML.safe_load(m[2]).to_s, line: number, type: "front matter: #{m[1]}", prefix: "#{m[1]}: ")
38
+ else
39
+ raw.(line)
40
+ end
41
+ end
42
+ raw.("---")
43
+ i = close + 2
44
+ end
45
+
46
+ after_blank = true
47
+ while i < lines.size
48
+ line = lines[i]
49
+ number = i + 1
50
+ if line.strip.empty?
51
+ raw.(line)
52
+ after_blank = true
53
+ i += 1
54
+ next
55
+ end
56
+
57
+ if line.match?(FENCE)
58
+ # ``` のコードブロック。中のコメントを訳せるよう、中身をまとめて 1 単位にする
59
+ close = (i + 1...lines.size).find { lines[it].match?(FENCE) } or raise "閉じていないコードブロック: #{number} 行目"
60
+ raw.(line)
61
+ unit.(lines[i + 1...close].join("\n"), line: number + 1, type: "code")
62
+ raw.(lines[close])
63
+ i = close + 1
64
+ elsif after_blank && line.match?(/\A {4,}\S/) && !line.match?(LIST_ITEM)
65
+ # 字下げしたコードブロック。空行までそのまま
66
+ while i < lines.size && !lines[i].strip.empty?
67
+ raw.(lines[i])
68
+ i += 1
69
+ end
70
+ elsif (m = line.match(HEADING))
71
+ unit.(m[2], line: number, type: "heading", prefix: m[1])
72
+ i += 1
73
+ elsif lines[i + 1]&.match?(UNDERLINE) && !line.match?(LIST_ITEM)
74
+ # 下線を引いた見出し(ronn の 1 行目など)。下線はそのまま
75
+ unit.(line, line: number, type: "title")
76
+ raw.(lines[i + 1])
77
+ i += 2
78
+ elsif (m = line.match(LIST_ITEM))
79
+ prefix = m[1]
80
+ indent = " " * prefix.size
81
+ if m[2].end_with?(":") && lines[i + 1]&.match?(/\A\s+\S/) && !lines[i + 1].match?(LIST_ITEM)
82
+ # ronn の定義リストの項目名(「 * `-n` <count>:」)。説明は次の行からの段落として別に訳す
83
+ unit.(m[2], line: number, type: "definition term", prefix:)
84
+ i += 1
85
+ else
86
+ text, i = gather(lines, i + 1, [m[2]])
87
+ unit.(text, line: number, type: "list item", prefix:, indent:)
88
+ end
89
+ else
90
+ indent = line[/\A\s*/]
91
+ text, i = gather(lines, i + 1, [line.strip])
92
+ unit.(text, line: number, type: "paragraph", prefix: indent, indent:)
93
+ end
94
+ after_blank = false
95
+ end
96
+ segments
97
+ end
98
+
99
+ # 段落の続きの行を集めて、空白でつないだ 1 行にする。空行・箇条書き・見出し・コードブロックの手前で止まる
100
+ def self.gather(lines, i, parts)
101
+ while i < lines.size
102
+ line = lines[i]
103
+ break if line.strip.empty? || line.match?(LIST_ITEM) || line.match?(HEADING) || line.match?(FENCE)
104
+
105
+ parts << line.strip
106
+ i += 1
107
+ end
108
+ [parts.join(" "), i]
109
+ end
110
+
111
+ # 翻訳の単位だけを取り出す
112
+ def self.units(markdown) = parse(markdown).select { it.kind == :unit }
113
+
114
+ attr_reader :missing
115
+
116
+ # translations: msgid => 訳 のハッシュ
117
+ def initialize(translations)
118
+ @translations = translations
119
+ @missing = []
120
+ end
121
+
122
+ # PO ファイルから作る。訳が空のもの・fuzzy のものは使わない
123
+ def self.load(po_file)
124
+ require "gettext/po_parser"
125
+ require "gettext/po"
126
+ po = GetText::POParser.new.tap { it.report_warning = false }.parse_file(po_file, GetText::PO.new)
127
+ new(po.each.reject { it.header? || it.fuzzy? || it.msgstr.to_s.empty? }.to_h { [it.msgid, it.msgstr] })
128
+ end
129
+
130
+ # 原文 1 つの訳。なければ nil
131
+ def [](msgid) = @translations[msgid]
132
+
133
+ # 英語の原稿を訳した原稿を返す
134
+ def translate(markdown)
135
+ Translation.parse(markdown).map do |segment|
136
+ next segment.text if segment.kind == :raw
137
+
138
+ text = @translations[segment.text]
139
+ if text.nil?
140
+ @missing << segment unless segment.type == "code" # コードは訳さなくてよいことが多い
141
+ text = segment.text
142
+ end
143
+ render(segment, text)
144
+ end.join("\n") + "\n"
145
+ end
146
+
147
+ private
148
+
149
+ def render(segment, text)
150
+ return "#{segment.prefix}#{text.to_json}" if segment.type.start_with?("front matter") # JSON の文字列は YAML としても読める
151
+ return text if segment.type == "code"
152
+
153
+ first, *rest = text.split("\n")
154
+ ["#{segment.prefix}#{first}", *rest.map { "#{segment.indent}#{it}" }].join("\n")
155
+ end
156
+ end
157
+ end
data/rakelib/docs.rake ADDED
@@ -0,0 +1,62 @@
1
+ # ドキュメントのタスク。原稿は英語の Markdown だけで、ほかの言語は PO の訳から作る。
2
+ # man/reclaimable.1.ronn → man/reclaimable.en.1、man/reclaimable.ja.1
3
+ # (roff。gem に入れて gem man や reclaimable --man で読む)
4
+ # gem man(gem-man)は man/ の直下しか見ないので、どの言語も直下に言語名を付けて置く
5
+ # site/index.md と上の man page の原稿 → public/(GitLab Pages のサイト)
6
+ # 訳は po/ja/reclaimable-docs.po(段落・見出し・箇条書きの項目などが 1 項目ずつ)
7
+ # ronn-ng・kramdown は開発用の依存なので、タスクの中でだけ読み込む
8
+
9
+ require "gettext/tools/task"
10
+ require_relative "docs/man_page"
11
+ require_relative "docs/site"
12
+ require_relative "docs/sources"
13
+
14
+ DOCS_LANGS = %w[en ja].freeze
15
+
16
+ # 生成した roff はリポジトリーに入れない。gem のパッケージの前提になっていて(Rakefile を参照)、
17
+ # 無いか古ければここの file タスクで作られる。
18
+ # 原稿・変換の処理・版(gemspec)が変わったときに作り直す。英語以外は訳の po にも依存し、
19
+ # その po は gettext の file タスクが英語の原稿から更新する
20
+ MAN_PAGES = DOCS_LANGS.map { Docs::ManPage.output(it) }
21
+
22
+ DOCS_LANGS.each do |lang|
23
+ sources = [Docs::Sources::FILES[:manual], "reclaimable.gemspec", *FileList["rakelib/docs/*.rb"]]
24
+ sources << Docs::Sources.po_file(lang) unless lang == "en"
25
+ file Docs::ManPage.output(lang) => sources do |t|
26
+ page = Docs::ManPage.new(lang:, version: Gem::Specification.load("reclaimable.gemspec").version)
27
+ File.write(t.name, page.roff)
28
+ puts "#{Docs::Sources::FILES[:manual]} (#{lang}) -> #{t.name}"
29
+ end
30
+ end
31
+
32
+ desc "man/reclaimable.1.ronn と訳から man page(roff)を作る(原稿や訳が変わったときだけ)"
33
+ task man: MAN_PAGES
34
+
35
+ desc "GitLab Pages に置くサイトを public/ に作る(公開先の URL は環境変数 SITE_URL で変える)"
36
+ task :site do
37
+ spec = Gem::Specification.load("reclaimable.gemspec")
38
+ Docs::Site.new(base_url: ENV.fetch("SITE_URL", Docs::Site::DEFAULT_URL), out_dir: "public", spec:).build
39
+ puts "public/ を作りました"
40
+ end
41
+
42
+ desc "man page とサイトの両方を作る"
43
+ task docs: %i[man site]
44
+
45
+ # 訳の更新は gettext の仕組みに乗せる(rake docs:po)。英語の原稿から po/reclaimable-docs.pot を作り、
46
+ # po/ja/reclaimable-docs.po に新しい文を加える。原稿の文が変わったところは fuzzy になり、直すまで英語のまま出る。
47
+ # 文言の .mo は使わないので、作るとしても gem に入らない tmp/ に置く
48
+ GetText::Tools::Task.define do |task|
49
+ task.domain = Docs::Sources::DOMAIN
50
+ task.namespace_prefix = "docs"
51
+ task.locales = DOCS_LANGS - ["en"]
52
+ task.files = [*Docs::Sources::FILES.values, "rakelib/docs/sources.rb"]
53
+ task.package_name = "reclaimable"
54
+ task.package_version = Gem::Specification.load("reclaimable.gemspec").version.to_s
55
+ task.mo_base_directory = "tmp/locale"
56
+ task.msgcat_options = ["--no-wrap"]
57
+ task.enable_description = false
58
+ task.pot_creator = ->(path) { path.write(Docs::Sources.pot(task.package_version)) }
59
+ end
60
+
61
+ desc "英語の原稿から訳の雛形を作り、po/ja/reclaimable-docs.po に新しい文を加える"
62
+ task "docs:po" => "docs:gettext:po:update"
@@ -0,0 +1,30 @@
1
+ # 画面・レポート・ログの文言の翻訳(gettext)のタスク。原文は英語で、ソースの _("...") などから抜き出す。
2
+ # rake gettext:po:update ソースから po/reclaimable.pot を作り、po/ja/reclaimable.po を更新する
3
+ # (新しい文言は msgstr が空で加わる。訳を書き込んだらもう一度 rake gettext)
4
+ # rake gettext po から locale/ja/LC_MESSAGES/reclaimable.mo を作る
5
+ # .mo はリポジトリーに入れない。gem のパッケージの前提になっていて(Rakefile を参照)、無いか古ければ
6
+ # gettext の file タスク(ソース → .pot → .edit.po → .po → .mo)で作られる。
7
+ # インストールせずに ruby -Ilib で動かすときは Rake を通らないので、日本語で見るには先に rake gettext を実行する
8
+
9
+ require "gettext/tools/task"
10
+
11
+ sources = nil
12
+ GetText::Tools::Task.define do |task|
13
+ task.spec = Gem::Specification.load("reclaimable.gemspec")
14
+ sources = task.files.sort
15
+ task.locales = ["ja"]
16
+ task.xgettext_options = ["--add-comments=TRANSLATORS:"]
17
+ task.msgcat_options = ["--no-wrap"] # 長い文言を途中で折り返さず、1 行で読めるようにする
18
+ end
19
+
20
+ # 抜き出し元のファイルの一覧が変わったら、.pot を作り直す。
21
+ # .pot の file タスクは、抜き出し元(gemspec の files、つまり git が追跡しているファイル)より古いときにしか動かない。
22
+ # そのため、前からあったファイルを後から git add したとき(.pot より古いので作り直されず、文言が抜き出されない)や、
23
+ # ファイルを消したとき(消えた文言が .pot に残る)に追従できない。
24
+ # 一覧をファイルに控えておき、変わったときだけ書き直して、.pot をそれに依存させる
25
+ sources_list = "tmp/gettext/sources.txt"
26
+ unless File.exist?(sources_list) && File.read(sources_list) == sources.join("\n")
27
+ FileUtils.mkdir_p(File.dirname(sources_list))
28
+ File.write(sources_list, sources.join("\n"))
29
+ end
30
+ file "po/reclaimable.pot" => sources_list