wp2txt 2.4.0 → 2.5.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 (65) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +16 -1
  3. data/.github/workflows/publish-image.yml +8 -4
  4. data/.gitignore +0 -1
  5. data/CHANGELOG.md +23 -0
  6. data/DEVELOPMENT.md +62 -92
  7. data/DEVELOPMENT_ja.md +60 -92
  8. data/Dockerfile +1 -1
  9. data/README.md +54 -8
  10. data/README_ja.md +54 -8
  11. data/bin/wp2txt +23 -6
  12. data/lib/wp2txt/article.rb +1 -2
  13. data/lib/wp2txt/bz2_stream.rb +63 -0
  14. data/lib/wp2txt/cli.rb +48 -26
  15. data/lib/wp2txt/config.rb +2 -11
  16. data/lib/wp2txt/constants.rb +0 -1
  17. data/lib/wp2txt/corpus.rb +1 -21
  18. data/lib/wp2txt/data/template_aliases.json +3 -0
  19. data/lib/wp2txt/data/template_patterns.json +61643 -0
  20. data/lib/wp2txt/dump_snapshot.rb +99 -0
  21. data/lib/wp2txt/extraction_run.rb +272 -0
  22. data/lib/wp2txt/extractor.rb +476 -325
  23. data/lib/wp2txt/fts_index.rb +1 -1
  24. data/lib/wp2txt/index_cache.rb +144 -55
  25. data/lib/wp2txt/index_commands.rb +22 -19
  26. data/lib/wp2txt/link_counter.rb +1 -1
  27. data/lib/wp2txt/magic_words.rb +44 -28
  28. data/lib/wp2txt/metadata_index.rb +6 -13
  29. data/lib/wp2txt/multistream.rb +890 -824
  30. data/lib/wp2txt/output_writer.rb +3 -1
  31. data/lib/wp2txt/parser_functions.rb +23 -5
  32. data/lib/wp2txt/ractor_worker.rb +6 -4
  33. data/lib/wp2txt/regex.rb +24 -4
  34. data/lib/wp2txt/site_info.rb +123 -0
  35. data/lib/wp2txt/stream_store.rb +91 -0
  36. data/lib/wp2txt/template_args.rb +111 -0
  37. data/lib/wp2txt/template_expander.rb +92 -125
  38. data/lib/wp2txt/template_patterns.rb +182 -0
  39. data/lib/wp2txt/utils.rb +160 -125
  40. data/lib/wp2txt/version.rb +1 -1
  41. data/spec/auto_download_spec.rb +9 -6
  42. data/spec/category_fetcher_spec.rb +135 -463
  43. data/spec/cli_targeted_spec.rb +60 -0
  44. data/spec/config_spec.rb +2 -15
  45. data/spec/constants_spec.rb +0 -4
  46. data/spec/dump_fetch_spec.rb +293 -0
  47. data/spec/extraction_run_spec.rb +520 -0
  48. data/spec/index_build_spec.rb +113 -0
  49. data/spec/index_commands_version_spec.rb +17 -0
  50. data/spec/multistream_reader_spec.rb +140 -0
  51. data/spec/multistream_spec.rb +8 -214
  52. data/spec/output_integrity_spec.rb +45 -2
  53. data/spec/regex_spec.rb +30 -0
  54. data/spec/spec_helper.rb +3 -3
  55. data/spec/support/dump_status.rb +34 -0
  56. data/spec/support/multistream_fixture.rb +26 -8
  57. data/spec/template_args_spec.rb +133 -0
  58. data/spec/template_expander_spec.rb +29 -111
  59. data/spec/template_passthrough_spec.rb +17 -2
  60. data/spec/template_patterns_spec.rb +253 -0
  61. data/spec/tracked_paths_spec.rb +168 -0
  62. data/spec/utils_spec.rb +7 -1
  63. metadata +30 -5
  64. data/lib/wp2txt/category_cache.rb +0 -313
  65. data/spec/category_cache_spec.rb +0 -226
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "fileutils"
5
+ require "open3"
6
+ require "tmpdir"
7
+
8
+ # scripts/check_tracked_paths.rb and scripts/pre-push, run against a disposable
9
+ # copy of this repository's index: what it passes, and what it must stop.
10
+ RSpec.describe "tracked-path allow list" do
11
+ repo_root = File.expand_path("..", __dir__)
12
+
13
+ around do |example|
14
+ Dir.mktmpdir("wp2txt-paths-") do |dir|
15
+ @dir = dir
16
+ @repo = File.join(dir, "repo")
17
+ # Commits in the copy run no hooks but the one under test
18
+ @no_hooks = File.join(dir, "no-hooks")
19
+ Dir.mkdir(@no_hooks)
20
+ Dir.mkdir(@repo)
21
+ system("git", "-C", repo_root, "checkout-index", "-a", "-f", "--prefix=#{@repo}/", exception: true)
22
+ git("init", "-q", "-b", "master")
23
+ git("add", "-A")
24
+ commit("initial")
25
+ example.run
26
+ end
27
+ end
28
+
29
+ def git(*args, hooks: @no_hooks)
30
+ out, status = Open3.capture2e("git", "-c", "core.hooksPath=#{hooks}", "-c", "user.name=t",
31
+ "-c", "user.email=t@example.invalid", "-C", @repo, *args)
32
+ raise "git #{args.join(' ')} failed:\n#{out}" unless status.success?
33
+
34
+ out
35
+ end
36
+
37
+ def commit(message)
38
+ git("commit", "-q", "--allow-empty", "-m", message)
39
+ end
40
+
41
+ def put(path, content = "x\n", stage: true)
42
+ full = File.join(@repo, path)
43
+ FileUtils.mkdir_p(File.dirname(full))
44
+ File.write(full, content, mode: "a")
45
+ git("add", path) if stage
46
+ end
47
+
48
+ def check(*args)
49
+ out, status = Open3.capture2e(RbConfig.ruby, File.join(@repo, "scripts", "check_tracked_paths.rb"), *args)
50
+ [status.success?, out]
51
+ end
52
+
53
+ it "passes the files tracked now" do
54
+ expect(check).to match([true, /OK: every tracked file is allowed/])
55
+ end
56
+
57
+ it "stops an internal note, wherever it is placed" do
58
+ ["notes/plan.md", "PLAN.md", "README_plan.md", "docs/PLAN.md", "spec/notes.md"].each do |path|
59
+ put(path)
60
+ ok, out = check
61
+ expect([path, ok]).to eq([path, false])
62
+ expect(out).to include(" #{path}\n")
63
+ git("rm", "-q", "--cached", path)
64
+ end
65
+ end
66
+
67
+ it "stops logs, environment files, databases, and data in places not allowed" do
68
+ %w[debug.log .env data.sqlite3 dump.json lib/dump.json lib/wp2txt/data/dump.json spec/fixtures/dump.json].each do |path|
69
+ put(path)
70
+ expect(check.first).to be(false), "#{path} passed"
71
+ git("rm", "-q", "--cached", path)
72
+ end
73
+ end
74
+
75
+ it "stops an alternative that matches no tracked file" do
76
+ put("scripts/tracked_paths.allow", "image/*.{svg,png}\n")
77
+ ok, out = check
78
+ expect(ok).to be(false)
79
+ expect(out).to include("image/*.png (from image/*.{svg,png})")
80
+ end
81
+
82
+ it "judges by the staged list, not by an unstaged edit to it" do
83
+ put("notes/plan.md")
84
+ put("scripts/tracked_paths.allow", "notes/*.md\n", stage: false)
85
+ expect(check.first).to be(false)
86
+ end
87
+
88
+ it "judges a commit by the list inside that commit" do
89
+ put("notes/plan.md")
90
+ commit("add a note")
91
+ expect(check("--tree", "HEAD").first).to be(false)
92
+ expect(check("--tree", "HEAD~1").first).to be(true)
93
+ end
94
+
95
+ it "refuses to pass when it saw nothing" do
96
+ expect(check("--tree")).to match([false, /needs a revision/])
97
+ expect(check("--tree", "--other")).to match([false, /needs a revision/])
98
+ expect(check("--tree", "no-such-rev")).to match([false, /could not list/])
99
+ git("rm", "-q", "--cached", "scripts/tracked_paths.allow")
100
+ expect(check).to match([false, /has no scripts\/tracked_paths.allow/])
101
+
102
+ outside = File.join(@dir, "outside", "scripts")
103
+ FileUtils.mkdir_p(outside)
104
+ FileUtils.cp(File.join(@repo, "scripts", "check_tracked_paths.rb"), outside)
105
+ _out, status = Open3.capture2e(RbConfig.ruby, File.join(outside, "check_tracked_paths.rb"))
106
+ expect(status.success?).to be(false)
107
+
108
+ system("git", "init", "-q", File.join(@dir, "outside"), exception: true) # a checkout tracking nothing
109
+ out, status = Open3.capture2e(RbConfig.ruby, File.join(outside, "check_tracked_paths.rb"))
110
+ expect([status.success?, out]).to match([false, /could not list/])
111
+ end
112
+
113
+ describe "pre-push" do
114
+ before do
115
+ @remote = File.join(@dir, "remote.git")
116
+ system("git", "init", "-q", "--bare", @remote, exception: true)
117
+ git("remote", "add", "origin", @remote)
118
+ git("push", "-q", "origin", "master")
119
+ @hooks = File.join(@dir, "hooks")
120
+ Dir.mkdir(@hooks)
121
+ File.symlink(File.join(@repo, "scripts", "pre-push"), File.join(@hooks, "pre-push"))
122
+ end
123
+
124
+ def push
125
+ out, status = Open3.capture2e("git", "-c", "core.hooksPath=#{@hooks}", "-C", @repo, "push", "origin", "master")
126
+ [status.success?, out]
127
+ end
128
+
129
+ def remote_head
130
+ `git -C #{@remote} rev-parse master`.strip
131
+ end
132
+
133
+ it "lets allowed commits through and says how many it checked" do
134
+ put("lib/wp2txt/extra.rb")
135
+ commit("add a module")
136
+ expect(push).to match([true, /1 commit\(s\) checked/])
137
+ end
138
+
139
+ it "stops a push when only a commit in the middle of the range has an unallowed file" do
140
+ before = remote_head
141
+ put("debug.log")
142
+ commit("add a log")
143
+ git("rm", "-q", "debug.log")
144
+ commit("remove it again")
145
+ ok, out = push
146
+ expect(ok).to be(false)
147
+ expect(out).to include("debug.log")
148
+ expect(remote_head).to eq(before)
149
+ end
150
+
151
+ it "stops a new commit that carries no allow list" do
152
+ git("rm", "-q", "scripts/tracked_paths.allow")
153
+ commit("drop the list")
154
+ expect(push).to match([false, /without scripts\/tracked_paths.allow/])
155
+ end
156
+
157
+ it "checks every commit no remote has when pushing a new branch" do
158
+ git("switch", "-q", "-c", "topic")
159
+ put(".env")
160
+ commit("add env")
161
+ git("rm", "-q", ".env")
162
+ commit("remove env")
163
+ out, status = Open3.capture2e("git", "-c", "core.hooksPath=#{@hooks}", "-C", @repo, "push", "origin", "topic")
164
+ expect(status.success?).to be(false)
165
+ expect(out).to include(".env")
166
+ end
167
+ end
168
+ end
data/spec/utils_spec.rb CHANGED
@@ -352,6 +352,12 @@ RSpec.describe "Wp2txt Utils" do
352
352
  expect(b2).to eq "http://yohasebe.com"
353
353
  expect(c2).to eq "* Turkish: {{t+|tr|köken bilimi}}]], {{t+|tr|etimoloji}}"
354
354
  end
355
+
356
+ it "keeps a bracket that does not open with a URL as written" do
357
+ expect(process_external_links("Ким Уэстон[англ.] said [sic] it")).to eq "Ким Уэстон[англ.] said [sic] it"
358
+ expect(process_external_links("[//example.org Site] and [mailto:a@example.org mail]")).to eq "Site and mail"
359
+ expect(process_external_links("[wikipedia://en/Example entry]")).to eq "entry"
360
+ end
355
361
  end
356
362
 
357
363
  describe "correct_inline_template" do
@@ -366,7 +372,7 @@ RSpec.describe "Wp2txt Utils" do
366
372
  expect(correct_inline_template(str_before2)).to eq str_after2
367
373
 
368
374
  str_before3 = "{{a|b=c|d=f}}"
369
- str_after3 = "c"
375
+ str_after3 = ""
370
376
  expect(correct_inline_template(str_before3)).to eq str_after3
371
377
 
372
378
  str_before4 = "{{a|b|{{c|d|e}}}}"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: wp2txt
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.4.0
4
+ version: 2.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yoichiro Hasebe
@@ -221,8 +221,8 @@ files:
221
221
  - docs/INDEXES.md
222
222
  - lib/wp2txt.rb
223
223
  - lib/wp2txt/article.rb
224
+ - lib/wp2txt/bz2_stream.rb
224
225
  - lib/wp2txt/bz2_validator.rb
225
- - lib/wp2txt/category_cache.rb
226
226
  - lib/wp2txt/cli.rb
227
227
  - lib/wp2txt/cli_ui.rb
228
228
  - lib/wp2txt/config.rb
@@ -234,7 +234,10 @@ files:
234
234
  - lib/wp2txt/data/language_tiers.json
235
235
  - lib/wp2txt/data/mediawiki_aliases.json
236
236
  - lib/wp2txt/data/template_aliases.json
237
+ - lib/wp2txt/data/template_patterns.json
237
238
  - lib/wp2txt/data/wikipedia_entities.json
239
+ - lib/wp2txt/dump_snapshot.rb
240
+ - lib/wp2txt/extraction_run.rb
238
241
  - lib/wp2txt/extractor.rb
239
242
  - lib/wp2txt/file_utils.rb
240
243
  - lib/wp2txt/formatter.rb
@@ -256,9 +259,13 @@ files:
256
259
  - lib/wp2txt/ractor_worker.rb
257
260
  - lib/wp2txt/regex.rb
258
261
  - lib/wp2txt/section_extractor.rb
262
+ - lib/wp2txt/site_info.rb
259
263
  - lib/wp2txt/sql_dump_reader.rb
260
264
  - lib/wp2txt/stream_processor.rb
265
+ - lib/wp2txt/stream_store.rb
266
+ - lib/wp2txt/template_args.rb
261
267
  - lib/wp2txt/template_expander.rb
268
+ - lib/wp2txt/template_patterns.rb
262
269
  - lib/wp2txt/text_processing.rb
263
270
  - lib/wp2txt/utils.rb
264
271
  - lib/wp2txt/version.rb
@@ -266,21 +273,25 @@ files:
266
273
  - spec/article_spec.rb
267
274
  - spec/auto_download_spec.rb
268
275
  - spec/bz2_validator_spec.rb
269
- - spec/category_cache_spec.rb
270
276
  - spec/category_fetcher_spec.rb
271
277
  - spec/cleanup_spec.rb
272
278
  - spec/cli_options_spec.rb
273
279
  - spec/cli_spec.rb
280
+ - spec/cli_targeted_spec.rb
274
281
  - spec/config_spec.rb
275
282
  - spec/constants_spec.rb
276
283
  - spec/corpus_spec.rb
277
284
  - spec/docs_sync_spec.rb
285
+ - spec/dump_fetch_spec.rb
286
+ - spec/extraction_run_spec.rb
278
287
  - spec/file_utils_spec.rb
279
288
  - spec/fixtures/samples.rb
280
289
  - spec/formatter_sections_spec.rb
281
290
  - spec/fts_index_spec.rb
282
291
  - spec/global_data_cache_spec.rb
292
+ - spec/index_build_spec.rb
283
293
  - spec/index_cache_spec.rb
294
+ - spec/index_commands_version_spec.rb
284
295
  - spec/integration_spec.rb
285
296
  - spec/langlinks_importer_spec.rb
286
297
  - spec/lead_terms_edge_cases_spec.rb
@@ -290,6 +301,7 @@ files:
290
301
  - spec/memory_monitor_spec.rb
291
302
  - spec/metadata_index_spec.rb
292
303
  - spec/multi_dump_attach_spec.rb
304
+ - spec/multistream_reader_spec.rb
293
305
  - spec/multistream_spec.rb
294
306
  - spec/output_integrity_spec.rb
295
307
  - spec/output_writer_spec.rb
@@ -302,14 +314,18 @@ files:
302
314
  - spec/section_extractor_spec.rb
303
315
  - spec/spec_helper.rb
304
316
  - spec/stream_processor_spec.rb
317
+ - spec/support/dump_status.rb
305
318
  - spec/support/meta_db_fixture.rb
306
319
  - spec/support/multistream_fixture.rb
320
+ - spec/template_args_spec.rb
307
321
  - spec/template_data_spec.rb
308
322
  - spec/template_expander_spec.rb
309
323
  - spec/template_passthrough_spec.rb
324
+ - spec/template_patterns_spec.rb
310
325
  - spec/template_processing_spec.rb
311
326
  - spec/text_processing_spec.rb
312
327
  - spec/titles_output_path_spec.rb
328
+ - spec/tracked_paths_spec.rb
313
329
  - spec/utils_spec.rb
314
330
  - spec/wp2txt_spec.rb
315
331
  - wp2txt.gemspec
@@ -331,7 +347,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
331
347
  - !ruby/object:Gem::Version
332
348
  version: '0'
333
349
  requirements: []
334
- rubygems_version: 4.0.3
350
+ rubygems_version: 4.0.20
335
351
  specification_version: 4
336
352
  summary: A command-line toolkit to extract text content and category data from Wikipedia
337
353
  dump files
@@ -339,21 +355,25 @@ test_files:
339
355
  - spec/article_spec.rb
340
356
  - spec/auto_download_spec.rb
341
357
  - spec/bz2_validator_spec.rb
342
- - spec/category_cache_spec.rb
343
358
  - spec/category_fetcher_spec.rb
344
359
  - spec/cleanup_spec.rb
345
360
  - spec/cli_options_spec.rb
346
361
  - spec/cli_spec.rb
362
+ - spec/cli_targeted_spec.rb
347
363
  - spec/config_spec.rb
348
364
  - spec/constants_spec.rb
349
365
  - spec/corpus_spec.rb
350
366
  - spec/docs_sync_spec.rb
367
+ - spec/dump_fetch_spec.rb
368
+ - spec/extraction_run_spec.rb
351
369
  - spec/file_utils_spec.rb
352
370
  - spec/fixtures/samples.rb
353
371
  - spec/formatter_sections_spec.rb
354
372
  - spec/fts_index_spec.rb
355
373
  - spec/global_data_cache_spec.rb
374
+ - spec/index_build_spec.rb
356
375
  - spec/index_cache_spec.rb
376
+ - spec/index_commands_version_spec.rb
357
377
  - spec/integration_spec.rb
358
378
  - spec/langlinks_importer_spec.rb
359
379
  - spec/lead_terms_edge_cases_spec.rb
@@ -363,6 +383,7 @@ test_files:
363
383
  - spec/memory_monitor_spec.rb
364
384
  - spec/metadata_index_spec.rb
365
385
  - spec/multi_dump_attach_spec.rb
386
+ - spec/multistream_reader_spec.rb
366
387
  - spec/multistream_spec.rb
367
388
  - spec/output_integrity_spec.rb
368
389
  - spec/output_writer_spec.rb
@@ -375,13 +396,17 @@ test_files:
375
396
  - spec/section_extractor_spec.rb
376
397
  - spec/spec_helper.rb
377
398
  - spec/stream_processor_spec.rb
399
+ - spec/support/dump_status.rb
378
400
  - spec/support/meta_db_fixture.rb
379
401
  - spec/support/multistream_fixture.rb
402
+ - spec/template_args_spec.rb
380
403
  - spec/template_data_spec.rb
381
404
  - spec/template_expander_spec.rb
382
405
  - spec/template_passthrough_spec.rb
406
+ - spec/template_patterns_spec.rb
383
407
  - spec/template_processing_spec.rb
384
408
  - spec/text_processing_spec.rb
385
409
  - spec/titles_output_path_spec.rb
410
+ - spec/tracked_paths_spec.rb
386
411
  - spec/utils_spec.rb
387
412
  - spec/wp2txt_spec.rb
@@ -1,313 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "sqlite3"
4
- require "json"
5
- require "fileutils"
6
- require_relative "constants"
7
-
8
- module Wp2txt
9
- # SQLite-based cache for Wikipedia category hierarchy and members
10
- # Dramatically speeds up repeated category extraction operations
11
- class CategoryCache
12
- CACHE_VERSION = 1
13
- DEFAULT_CACHE_DIR = File.expand_path("~/.wp2txt/cache")
14
-
15
- attr_reader :lang, :cache_path, :expiry_days
16
-
17
- def initialize(lang, cache_dir: nil, expiry_days: nil)
18
- @lang = lang.to_s
19
- @cache_dir = cache_dir || DEFAULT_CACHE_DIR
20
- @expiry_days = expiry_days || DEFAULT_CATEGORY_CACHE_EXPIRY_DAYS
21
- @cache_path = File.join(@cache_dir, "categories_#{@lang}.sqlite3")
22
- @db = nil
23
- ensure_schema
24
- end
25
-
26
- # Check if a category is cached and fresh
27
- # @param category_name [String] Category name (without "Category:" prefix)
28
- # @return [Boolean]
29
- def cached?(category_name)
30
- open_db
31
- row = @db.get_first_row(
32
- "SELECT cached_at FROM categories WHERE name = ?",
33
- [normalize_name(category_name)]
34
- )
35
- return false unless row
36
-
37
- cached_at = row[0]
38
- return false unless cached_at
39
-
40
- # Check freshness
41
- Time.at(cached_at) > Time.now - (@expiry_days * SECONDS_PER_DAY)
42
- rescue SQLite3::Exception
43
- false
44
- end
45
-
46
- # Get category data from cache
47
- # @param category_name [String] Category name
48
- # @return [Hash, nil] { pages: [...], subcats: [...] } or nil if not cached
49
- def get(category_name)
50
- return nil unless cached?(category_name)
51
-
52
- name = normalize_name(category_name)
53
- open_db
54
-
55
- pages = []
56
- subcats = []
57
-
58
- # Get pages
59
- @db.execute(
60
- "SELECT page_title FROM category_pages WHERE category_name = ?",
61
- [name]
62
- ) do |row|
63
- pages << row[0]
64
- end
65
-
66
- # Get subcategories
67
- @db.execute(
68
- "SELECT child_name FROM category_hierarchy WHERE parent_name = ?",
69
- [name]
70
- ) do |row|
71
- subcats << row[0]
72
- end
73
-
74
- { pages: pages, subcats: subcats }
75
- rescue SQLite3::Exception
76
- nil
77
- end
78
-
79
- # Save category data to cache
80
- # @param category_name [String] Category name
81
- # @param pages [Array<String>] Article titles in this category
82
- # @param subcats [Array<String>] Subcategory names
83
- def save(category_name, pages, subcats)
84
- name = normalize_name(category_name)
85
- open_db
86
-
87
- @db.execute("BEGIN TRANSACTION")
88
-
89
- # Update or insert category
90
- @db.execute(
91
- "INSERT OR REPLACE INTO categories (name, page_count, subcat_count, cached_at) VALUES (?, ?, ?, ?)",
92
- [name, pages.size, subcats.size, Time.now.to_i]
93
- )
94
-
95
- # Clear old pages and hierarchy
96
- @db.execute("DELETE FROM category_pages WHERE category_name = ?", [name])
97
- @db.execute("DELETE FROM category_hierarchy WHERE parent_name = ?", [name])
98
-
99
- # Insert pages
100
- unless pages.empty?
101
- stmt = @db.prepare("INSERT INTO category_pages (category_name, page_title) VALUES (?, ?)")
102
- pages.each { |page| stmt.execute([name, page]) }
103
- stmt.close
104
- end
105
-
106
- # Insert subcategories
107
- unless subcats.empty?
108
- stmt = @db.prepare("INSERT INTO category_hierarchy (parent_name, child_name) VALUES (?, ?)")
109
- subcats.each { |subcat| stmt.execute([name, normalize_name(subcat)]) }
110
- stmt.close
111
- end
112
-
113
- @db.execute("COMMIT")
114
- rescue SQLite3::Exception => e
115
- @db&.execute("ROLLBACK") rescue nil
116
- warn "CategoryCache: Failed to save #{category_name}: #{e.message}"
117
- end
118
-
119
- # Get all pages in a category tree (recursive)
120
- # @param category_name [String] Root category name
121
- # @param max_depth [Integer] Maximum recursion depth (0 = no recursion)
122
- # @param visited [Set] Already visited categories (for cycle detection)
123
- # @return [Array<String>] All article titles
124
- def get_all_pages(category_name, max_depth: 0, visited: nil)
125
- visited ||= Set.new
126
- name = normalize_name(category_name)
127
- return [] if visited.include?(name)
128
-
129
- visited << name
130
- data = get(name)
131
- return [] unless data
132
-
133
- pages = data[:pages].dup
134
-
135
- if max_depth > 0
136
- data[:subcats].each do |subcat|
137
- pages.concat(get_all_pages(subcat, max_depth: max_depth - 1, visited: visited))
138
- end
139
- end
140
-
141
- pages.uniq
142
- end
143
-
144
- # Get category tree structure
145
- # @param category_name [String] Root category name
146
- # @param max_depth [Integer] Maximum recursion depth
147
- # @return [Hash] Tree structure with category info
148
- def get_tree(category_name, max_depth: 0)
149
- build_tree(category_name, max_depth, Set.new)
150
- end
151
-
152
- # Get statistics for all cached categories
153
- # @return [Hash] Statistics
154
- def stats
155
- open_db
156
-
157
- total_categories = @db.get_first_value("SELECT COUNT(*) FROM categories")
158
- total_pages = @db.get_first_value("SELECT COUNT(*) FROM category_pages")
159
- total_relations = @db.get_first_value("SELECT COUNT(*) FROM category_hierarchy")
160
-
161
- oldest_cache = @db.get_first_value("SELECT MIN(cached_at) FROM categories")
162
- newest_cache = @db.get_first_value("SELECT MAX(cached_at) FROM categories")
163
-
164
- {
165
- lang: @lang,
166
- cache_path: @cache_path,
167
- cache_size: File.exist?(@cache_path) ? File.size(@cache_path) : 0,
168
- total_categories: total_categories || 0,
169
- total_pages: total_pages || 0,
170
- total_relations: total_relations || 0,
171
- oldest_cache: oldest_cache ? Time.at(oldest_cache) : nil,
172
- newest_cache: newest_cache ? Time.at(newest_cache) : nil,
173
- expiry_days: @expiry_days
174
- }
175
- rescue SQLite3::Exception
176
- { lang: @lang, error: "Failed to read stats" }
177
- end
178
-
179
- # Clear all cached data
180
- def clear!
181
- close_db
182
- FileUtils.rm_f(@cache_path)
183
- ensure_schema
184
- end
185
-
186
- # Clear expired entries
187
- def cleanup_expired!
188
- open_db
189
- cutoff = Time.now.to_i - (@expiry_days * SECONDS_PER_DAY)
190
-
191
- @db.execute("BEGIN TRANSACTION")
192
-
193
- # Get expired categories
194
- expired = []
195
- @db.execute("SELECT name FROM categories WHERE cached_at < ?", [cutoff]) do |row|
196
- expired << row[0]
197
- end
198
-
199
- # Delete expired data
200
- expired.each do |name|
201
- @db.execute("DELETE FROM category_pages WHERE category_name = ?", [name])
202
- @db.execute("DELETE FROM category_hierarchy WHERE parent_name = ?", [name])
203
- @db.execute("DELETE FROM categories WHERE name = ?", [name])
204
- end
205
-
206
- @db.execute("COMMIT")
207
-
208
- expired.size
209
- rescue SQLite3::Exception
210
- @db&.execute("ROLLBACK") rescue nil
211
- 0
212
- end
213
-
214
- # Close database connection
215
- def close
216
- close_db
217
- end
218
-
219
- private
220
-
221
- def normalize_name(name)
222
- name.to_s.sub(/^[Cc]ategory:/, "").strip
223
- end
224
-
225
- def build_tree(category_name, max_depth, visited)
226
- name = normalize_name(category_name)
227
- return nil if visited.include?(name)
228
-
229
- visited << name
230
- data = get(name)
231
-
232
- result = {
233
- name: name,
234
- cached: !data.nil?,
235
- page_count: data ? data[:pages].size : 0,
236
- children: []
237
- }
238
-
239
- if data && max_depth > 0
240
- data[:subcats].each do |subcat|
241
- child = build_tree(subcat, max_depth - 1, visited)
242
- result[:children] << child if child
243
- end
244
- end
245
-
246
- result
247
- end
248
-
249
- def open_db
250
- return if @db
251
-
252
- FileUtils.mkdir_p(File.dirname(@cache_path))
253
- @db = SQLite3::Database.new(@cache_path)
254
- @db.execute("PRAGMA journal_mode = WAL")
255
- @db.execute("PRAGMA synchronous = NORMAL")
256
- @db.execute("PRAGMA cache_size = -16000") # 16MB cache
257
- end
258
-
259
- def close_db
260
- @db&.close
261
- @db = nil
262
- end
263
-
264
- def ensure_schema
265
- open_db
266
-
267
- @db.execute(<<~SQL)
268
- CREATE TABLE IF NOT EXISTS categories (
269
- name TEXT PRIMARY KEY,
270
- page_count INTEGER DEFAULT 0,
271
- subcat_count INTEGER DEFAULT 0,
272
- cached_at INTEGER
273
- )
274
- SQL
275
-
276
- @db.execute(<<~SQL)
277
- CREATE TABLE IF NOT EXISTS category_pages (
278
- category_name TEXT NOT NULL,
279
- page_title TEXT NOT NULL,
280
- PRIMARY KEY (category_name, page_title)
281
- )
282
- SQL
283
-
284
- @db.execute("CREATE INDEX IF NOT EXISTS idx_category_pages_category ON category_pages(category_name)")
285
-
286
- @db.execute(<<~SQL)
287
- CREATE TABLE IF NOT EXISTS category_hierarchy (
288
- parent_name TEXT NOT NULL,
289
- child_name TEXT NOT NULL,
290
- PRIMARY KEY (parent_name, child_name)
291
- )
292
- SQL
293
-
294
- @db.execute("CREATE INDEX IF NOT EXISTS idx_hierarchy_parent ON category_hierarchy(parent_name)")
295
- @db.execute("CREATE INDEX IF NOT EXISTS idx_hierarchy_child ON category_hierarchy(child_name)")
296
-
297
- @db.execute(<<~SQL)
298
- CREATE TABLE IF NOT EXISTS metadata (
299
- key TEXT PRIMARY KEY,
300
- value TEXT
301
- )
302
- SQL
303
-
304
- # Store cache version
305
- @db.execute(
306
- "INSERT OR REPLACE INTO metadata (key, value) VALUES ('cache_version', ?)",
307
- [CACHE_VERSION.to_s]
308
- )
309
- rescue SQLite3::Exception => e
310
- warn "CategoryCache: Failed to create schema: #{e.message}"
311
- end
312
- end
313
- end