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
@@ -419,7 +419,7 @@ module Wp2txt
419
419
  offset_pairs.each do |offset, next_offset|
420
420
  f.seek(offset)
421
421
  data = next_offset ? f.read(next_offset - offset) : f.read
422
- xml = MetadataIndexBuilder.decompress_bz2(data)
422
+ xml = Wp2txt.decompress_bz2(data)
423
423
  xml.scan(MetadataIndexBuilder::PAGE_BLOCK_REGEX) do
424
424
  scan_page(::Regexp.last_match(1), renderer, rows)
425
425
  end
@@ -3,19 +3,30 @@
3
3
  require "sqlite3"
4
4
  require "fileutils"
5
5
  require "digest"
6
+ require "securerandom"
7
+ require_relative "bz2_stream"
6
8
 
7
9
  module Wp2txt
8
10
  # SQLite-based cache for multistream index
9
11
  # Dramatically speeds up repeated index access by storing parsed entries in SQLite
12
+ #
13
+ # A cache file is built under a temporary name, line by line from the index
14
+ # (never holding the whole index in memory), and put in place by rename only
15
+ # once complete. A published cache is never written to again; readers open
16
+ # it read-only.
10
17
  class IndexCache
11
- CACHE_VERSION = 1
18
+ CACHE_VERSION = 2
12
19
  CACHE_SUFFIX = ".sqlite3"
20
+ BATCH_SIZE = 50_000
13
21
 
14
22
  attr_reader :cache_path, :source_path
15
23
 
16
- def initialize(source_path, cache_dir: nil)
24
+ # @param identity [String, nil] SHA-1 of the index file, when known: the
25
+ # cache is then bound to that very file, not just to its path and size
26
+ def initialize(source_path, cache_dir: nil, identity: nil)
17
27
  @source_path = source_path
18
28
  @cache_dir = cache_dir || default_cache_dir
29
+ @identity = identity
19
30
  @cache_path = build_cache_path
20
31
  @db = nil
21
32
  end
@@ -33,6 +44,7 @@ module Wp2txt
33
44
 
34
45
  # Check cache version
35
46
  return false if meta[:cache_version].to_i != CACHE_VERSION
47
+ return false if @identity && meta[:source_sha1] != @identity
36
48
 
37
49
  # Check source file hasn't changed
38
50
  source_stat = File.stat(@source_path)
@@ -77,56 +89,54 @@ module Wp2txt
77
89
  end
78
90
  end
79
91
 
92
+ # Build the cache from the index file it belongs to, reading it line by
93
+ # line. A failing decompressor leaves no cache behind.
94
+ # @yield [Integer] lines read so far, every BATCH_SIZE lines
95
+ # @raise [StreamError] when the index cannot be read in full
96
+ def build!(&progress)
97
+ publish do |db|
98
+ insert = db.prepare("INSERT OR REPLACE INTO index_entries (title, page_id, byte_offset) VALUES (?, ?, ?)")
99
+ offsets = db.prepare("INSERT OR IGNORE INTO stream_offsets (byte_offset) VALUES (?)")
100
+ count = 0
101
+ last_offset = nil
102
+ db.transaction
103
+ Wp2txt.each_index_line(@source_path) do |offset, page_id, title|
104
+ insert.execute([title, page_id, offset])
105
+ offsets.execute([offset]) unless offset == last_offset
106
+ last_offset = offset
107
+ count += 1
108
+ next unless (count % BATCH_SIZE).zero?
109
+
110
+ db.commit
111
+ db.transaction
112
+ progress&.call(count)
113
+ end
114
+ db.commit
115
+ insert.close
116
+ offsets.close
117
+ count
118
+ end
119
+ end
120
+
80
121
  # Save index entries to cache
81
122
  # @param entries_by_title [Hash] title => entry hash
82
123
  # @param stream_offsets [Array<Integer>] sorted stream offsets
83
124
  def save(entries_by_title, stream_offsets)
84
- FileUtils.mkdir_p(File.dirname(@cache_path))
85
-
86
- # Remove old cache if exists
87
- FileUtils.rm_f(@cache_path)
88
-
89
- open_db
90
- begin
91
- create_schema
92
-
93
- # Use transaction for better performance
94
- @db.execute("BEGIN TRANSACTION")
95
-
96
- # Save metadata
97
- source_stat = File.stat(@source_path)
98
- save_metadata(
99
- source_path: @source_path,
100
- source_mtime: source_stat.mtime.to_i,
101
- source_size: source_stat.size,
102
- cache_version: CACHE_VERSION,
103
- entry_count: entries_by_title.size
104
- )
105
-
106
- # Save entries in batches for performance
107
- stmt = @db.prepare("INSERT INTO index_entries (title, page_id, byte_offset) VALUES (?, ?, ?)")
125
+ publish do |db|
126
+ db.transaction
127
+ stmt = db.prepare("INSERT INTO index_entries (title, page_id, byte_offset) VALUES (?, ?, ?)")
108
128
  entries_by_title.each do |title, entry|
109
129
  stmt.execute([title, entry[:page_id], entry[:offset]])
110
130
  end
111
131
  stmt.close
112
132
 
113
- # Save stream offsets
114
- stmt = @db.prepare("INSERT INTO stream_offsets (byte_offset) VALUES (?)")
115
- stream_offsets.each do |offset|
116
- stmt.execute([offset])
117
- end
133
+ stmt = db.prepare("INSERT INTO stream_offsets (byte_offset) VALUES (?)")
134
+ stream_offsets.each { |offset| stmt.execute([offset]) }
118
135
  stmt.close
119
-
120
- @db.execute("COMMIT")
121
-
122
- true
123
- rescue SQLite3::Exception => e
124
- @db.execute("ROLLBACK") rescue nil
125
- FileUtils.rm_f(@cache_path)
126
- raise e
127
- ensure
128
- close_db
136
+ db.commit
137
+ entries_by_title.size
129
138
  end
139
+ true
130
140
  end
131
141
 
132
142
  # Find entries by titles (efficient batch lookup)
@@ -155,6 +165,26 @@ module Wp2txt
155
165
  end
156
166
  end
157
167
 
168
+ # Find entries by page IDs
169
+ # @param page_ids [Array<Integer>] page IDs to look up
170
+ # @return [Hash] page_id => entry, for the IDs found
171
+ def find_by_ids(page_ids)
172
+ return {} if page_ids.empty?
173
+ return {} unless valid?
174
+
175
+ results = {}
176
+ open_db
177
+ begin
178
+ sql = "SELECT title, page_id, byte_offset FROM index_entries WHERE page_id IN (#{page_ids.map { '?' }.join(',')})"
179
+ @db.execute(sql, page_ids) do |title, page_id, offset|
180
+ results[page_id] = { offset: offset, page_id: page_id, title: title }
181
+ end
182
+ results
183
+ ensure
184
+ close_db
185
+ end
186
+ end
187
+
158
188
  # All stream offsets in ascending order (for lazy title lookup without
159
189
  # loading the full index into memory)
160
190
  # @return [Array<Integer>] sorted byte offsets
@@ -205,20 +235,48 @@ module Wp2txt
205
235
  end
206
236
 
207
237
  def build_cache_path
208
- # Use source file basename + hash of full path for uniqueness
238
+ # Use source file basename + hash of full path for uniqueness; the
239
+ # version is part of the name, so a cache of another layout is never
240
+ # opened, let alone overwritten
209
241
  basename = File.basename(@source_path, ".*").sub(/-index$/, "")
210
242
  path_hash = Digest::MD5.hexdigest(@source_path)[0, 8]
211
- File.join(@cache_dir, "#{basename}_#{path_hash}#{CACHE_SUFFIX}")
243
+ bound = @identity ? "_#{@identity[0, 12]}" : ""
244
+ File.join(@cache_dir, "#{basename}_#{path_hash}#{bound}_v#{CACHE_VERSION}#{CACHE_SUFFIX}")
245
+ end
246
+
247
+ # Fill a new database under a temporary name, then put it in place.
248
+ # The journal is a plain rollback journal, so the finished file stands on
249
+ # its own (no -wal or -shm file to move with it).
250
+ def publish
251
+ FileUtils.mkdir_p(File.dirname(@cache_path))
252
+ tmp = "#{@cache_path}.#{Process.pid}.#{SecureRandom.hex(4)}.building"
253
+ db = SQLite3::Database.new(tmp)
254
+ db.execute("PRAGMA journal_mode = DELETE")
255
+ db.execute("PRAGMA synchronous = OFF")
256
+ create_schema(db)
257
+ source_stat = File.stat(@source_path)
258
+ count = yield db
259
+ save_metadata(db,
260
+ source_path: @source_path,
261
+ source_mtime: source_stat.mtime.to_i,
262
+ source_size: source_stat.size,
263
+ cache_version: CACHE_VERSION,
264
+ source_sha1: @identity,
265
+ entry_count: count)
266
+ db.close
267
+ db = nil
268
+ File.rename(tmp, @cache_path)
269
+ count
270
+ ensure
271
+ db&.close
272
+ FileUtils.rm_f(Dir.glob("#{tmp}*")) if tmp
212
273
  end
213
274
 
214
275
  def open_db
215
- @db ||= SQLite3::Database.new(@cache_path)
276
+ @db ||= SQLite3::Database.new(@cache_path, readonly: true)
216
277
  # Wait out transient SQLITE_BUSY from concurrent readers (e.g., parallel
217
278
  # extraction workers opening the cache simultaneously) instead of failing
218
279
  @db.busy_timeout = 5000
219
- # Performance optimizations
220
- @db.execute("PRAGMA journal_mode = WAL")
221
- @db.execute("PRAGMA synchronous = NORMAL")
222
280
  @db.execute("PRAGMA cache_size = -64000") # 64MB cache
223
281
  end
224
282
 
@@ -227,15 +285,15 @@ module Wp2txt
227
285
  @db = nil
228
286
  end
229
287
 
230
- def create_schema
231
- @db.execute(<<~SQL)
288
+ def create_schema(db)
289
+ db.execute(<<~SQL)
232
290
  CREATE TABLE IF NOT EXISTS metadata (
233
291
  key TEXT PRIMARY KEY,
234
292
  value TEXT
235
293
  )
236
294
  SQL
237
295
 
238
- @db.execute(<<~SQL)
296
+ db.execute(<<~SQL)
239
297
  CREATE TABLE IF NOT EXISTS index_entries (
240
298
  title TEXT PRIMARY KEY,
241
299
  page_id INTEGER,
@@ -243,18 +301,18 @@ module Wp2txt
243
301
  )
244
302
  SQL
245
303
 
246
- @db.execute("CREATE INDEX IF NOT EXISTS idx_page_id ON index_entries(page_id)")
247
- @db.execute("CREATE INDEX IF NOT EXISTS idx_byte_offset ON index_entries(byte_offset)")
304
+ db.execute("CREATE INDEX IF NOT EXISTS idx_page_id ON index_entries(page_id)")
305
+ db.execute("CREATE INDEX IF NOT EXISTS idx_byte_offset ON index_entries(byte_offset)")
248
306
 
249
- @db.execute(<<~SQL)
307
+ db.execute(<<~SQL)
250
308
  CREATE TABLE IF NOT EXISTS stream_offsets (
251
309
  byte_offset INTEGER PRIMARY KEY
252
310
  )
253
311
  SQL
254
312
  end
255
313
 
256
- def save_metadata(hash)
257
- stmt = @db.prepare("INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)")
314
+ def save_metadata(db, hash)
315
+ stmt = db.prepare("INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)")
258
316
  hash.each do |key, value|
259
317
  stmt.execute([key.to_s, value.to_s])
260
318
  end
@@ -272,4 +330,35 @@ module Wp2txt
272
330
  nil
273
331
  end
274
332
  end
333
+
334
+ # Title lookups served from a built IndexCache, without loading the index
335
+ # into memory (millions of entries for a large wiki). Offers the lookup
336
+ # interface of MultistreamIndex that the reader and the extractor use.
337
+ class LazyTitleIndex
338
+ def initialize(index_cache)
339
+ @cache = index_cache
340
+ end
341
+
342
+ def find_by_title(title)
343
+ find_by_titles([title])[title]
344
+ end
345
+
346
+ # @return [Hash] title => entry, for the titles found
347
+ def find_by_titles(titles)
348
+ titles.each_slice(500).each_with_object({}) { |slice, found| found.merge!(@cache.find_by_titles(slice)) }
349
+ end
350
+
351
+ # @return [Hash] page_id => entry, for the IDs found
352
+ def find_by_ids(page_ids)
353
+ page_ids.each_slice(500).each_with_object({}) { |slice, found| found.merge!(@cache.find_by_ids(slice)) }
354
+ end
355
+
356
+ def stream_offset_for(title)
357
+ find_by_title(title)&.fetch(:offset, nil)
358
+ end
359
+
360
+ def stream_offsets
361
+ @stream_offsets ||= @cache.stream_offsets
362
+ end
363
+ end
275
364
  end
@@ -251,11 +251,7 @@ module Wp2txt
251
251
  # metadata index. Version pinning: the langlinks file must carry the same
252
252
  # dump date as the built index (enforced by LanglinksImporter, no override)
253
253
  def run_import_langlinks(opts)
254
- manager = DumpManager.new(
255
- opts[:lang],
256
- cache_dir: opts[:cache_dir],
257
- dump_expiry_days: CLI.config.dump_expiry_days
258
- )
254
+ manager = dump_manager(opts)
259
255
  multistream = manager.cached_multistream_path
260
256
  unless File.exist?(multistream)
261
257
  print_error("No cached dump found for '#{opts[:lang]}'.")
@@ -393,8 +389,7 @@ module Wp2txt
393
389
  # The metadata index of the cached dump for --lang, or nil with an error printed
394
390
  # @return [Array(String, String, DumpManager)] [db_path, dump_date, manager]
395
391
  def built_index_for(opts)
396
- manager = DumpManager.new(opts[:lang], cache_dir: opts[:cache_dir],
397
- dump_expiry_days: CLI.config.dump_expiry_days)
392
+ manager = dump_manager(opts)
398
393
  multistream = manager.cached_multistream_path
399
394
  unless File.exist?(multistream)
400
395
  print_error("No cached dump found for '#{opts[:lang]}'.")
@@ -469,26 +464,34 @@ module Wp2txt
469
464
  print_info("Size", format_size(stats[:db_size]))
470
465
  end
471
466
 
467
+ # The dump manager for --lang, honoring --dump-date and --update-cache
468
+ def dump_manager(opts)
469
+ DumpManager.new(opts[:lang], cache_dir: opts[:cache_dir], dump_expiry_days: CLI.config.dump_expiry_days,
470
+ dump_date: opts[:dump_date], update: opts[:update_cache])
471
+ end
472
+
472
473
  # Resolve [multistream_path, index_path] from --lang (cached dump) or --input.
473
474
  # Returns [nil, nil] after printing an error when files cannot be located.
474
475
  def resolve_dump_paths(opts, download: false)
475
476
  if opts[:lang]
476
- manager = DumpManager.new(
477
- opts[:lang],
478
- cache_dir: opts[:cache_dir],
479
- dump_expiry_days: CLI.config.dump_expiry_days
480
- )
477
+ manager = dump_manager(opts)
481
478
  multistream = manager.cached_multistream_path
482
479
  index = manager.cached_index_path
483
- unless File.exist?(multistream) && File.exist?(index)
484
- unless download
485
- print_error("No cached dump found for '#{opts[:lang]}'.")
486
- print_info_message("Download and index it with: wp2txt --build-index -L #{opts[:lang]}")
487
- return [nil, nil]
488
- end
489
- print_header("Downloading dump files for '#{opts[:lang]}'")
480
+ if download
481
+ # Fetches what is missing, and checks (or replaces) what is cached
482
+ print_header("Dump files for '#{opts[:lang]}' (#{manager.latest_dump_date})")
490
483
  manager.download_index
491
484
  manager.download_multistream
485
+ # The shared names the indexes are built from must name this version's files
486
+ manager.align_cached_names!
487
+ elsif !(File.exist?(multistream) && File.exist?(index))
488
+ print_error("No cached dump found for '#{opts[:lang]}'.")
489
+ print_info_message("Download and index it with: wp2txt --build-index -L #{opts[:lang]}")
490
+ return [nil, nil]
491
+ elsif (mismatched = manager.mismatched_cached_files).any?
492
+ print_error("Cached files do not match dump version #{manager.latest_dump_date}: #{mismatched.join(', ')}")
493
+ print_info_message("Fetch them again with: wp2txt --build-index -L #{opts[:lang]}")
494
+ return [nil, nil]
492
495
  end
493
496
  [multistream, index]
494
497
  else
@@ -93,7 +93,7 @@ module Wp2txt
93
93
  offset_pairs.each do |offset, next_offset|
94
94
  f.seek(offset)
95
95
  data = next_offset ? f.read(next_offset - offset) : f.read
96
- xml = MetadataIndexBuilder.decompress_bz2(data)
96
+ xml = Wp2txt.decompress_bz2(data)
97
97
  xml.scan(MetadataIndexBuilder::PAGE_BLOCK_REGEX) do
98
98
  count_page(::Regexp.last_match(1), direct, via)
99
99
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "regex"
4
+ require_relative "template_args"
4
5
 
5
6
  module Wp2txt
6
7
  # Expands MediaWiki magic words to their actual values
@@ -91,7 +92,10 @@ module Wp2txt
91
92
  Sunday Monday Tuesday Wednesday Thursday Friday Saturday
92
93
  ].freeze
93
94
 
94
- def initialize(title, namespace: "", dump_date: nil)
95
+ # @param literal_equals [String, nil] put in place of "=" in a page name
96
+ # (see TemplateArgs.literal_equals)
97
+ def initialize(title, namespace: "", dump_date: nil, literal_equals: nil)
98
+ @literal_equals = literal_equals
95
99
  @title = title || ""
96
100
  @namespace = namespace || ""
97
101
  @dump_date = dump_date || Time.now
@@ -126,7 +130,7 @@ module Wp2txt
126
130
  text.gsub(/\{\{\s*([A-Z][A-Z0-9]*)\s*\}\}/i) do |match|
127
131
  word = $1.upcase
128
132
  if PAGE_CONTEXT_WORDS.key?(word)
129
- expand_page_context(PAGE_CONTEXT_WORDS[word])
133
+ TemplateArgs.literal_equals(expand_page_context(PAGE_CONTEXT_WORDS[word]), @literal_equals)
130
134
  elsif DATETIME_WORDS.key?(word)
131
135
  expand_datetime(DATETIME_WORDS[word])
132
136
  else
@@ -233,35 +237,37 @@ module Wp2txt
233
237
  result = text.dup
234
238
 
235
239
  # Simple string case functions (no nesting issues)
236
- result.gsub!(/\{\{\s*lc\s*:\s*([^}]*)\}\}/i) { $1.downcase }
237
- result.gsub!(/\{\{\s*uc\s*:\s*([^}]*)\}\}/i) { $1.upcase }
240
+ # Each function reads its argument with "=" as written, and what it
241
+ # shows has its "=" held again (see TemplateArgs.literal_equals)
242
+ result.gsub!(/\{\{\s*lc\s*:\s*([^}]*)\}\}/i) { shown(plain($1).downcase) }
243
+ result.gsub!(/\{\{\s*uc\s*:\s*([^}]*)\}\}/i) { shown(plain($1).upcase) }
238
244
  result.gsub!(/\{\{\s*lcfirst\s*:\s*([^}]*)\}\}/i) do
239
- s = $1
240
- s.empty? ? s : s[0].downcase + s[1..]
245
+ s = plain($1)
246
+ shown(s.empty? ? s : s[0].downcase + s[1..])
241
247
  end
242
248
  result.gsub!(/\{\{\s*ucfirst\s*:\s*([^}]*)\}\}/i) do
243
- s = $1
244
- s.empty? ? s : s[0].upcase + s[1..]
249
+ s = plain($1)
250
+ shown(s.empty? ? s : s[0].upcase + s[1..])
245
251
  end
246
252
 
247
253
  # URL encoding
248
254
  result.gsub!(/\{\{\s*urlencode\s*:\s*([^}|]*?)(?:\s*\|\s*[^}]*)?\}\}/i) do
249
- url_encode($1.strip)
255
+ url_encode(plain($1).strip)
250
256
  end
251
257
  result.gsub!(/\{\{\s*anchorencode\s*:\s*([^}]*)\}\}/i) do
252
- anchor_encode($1.strip)
258
+ shown(anchor_encode(plain($1).strip))
253
259
  end
254
260
 
255
261
  # Padding functions: {{padleft:string|length|pad}}
256
262
  result.gsub!(/\{\{\s*padleft\s*:\s*([^}|]*)\s*\|\s*(\d+)(?:\s*\|\s*([^}]*))?\}\}/i) do
257
- str, len, pad = $1, $2.to_i, ($3 || "0")
263
+ str, len, pad = plain($1), $2.to_i, ($3 || "0")
258
264
  pad = "0" if pad.empty?
259
- str.rjust(len, pad)
265
+ shown(str.rjust(len, pad))
260
266
  end
261
267
  result.gsub!(/\{\{\s*padright\s*:\s*([^}|]*)\s*\|\s*(\d+)(?:\s*\|\s*([^}]*))?\}\}/i) do
262
- str, len, pad = $1, $2.to_i, ($3 || "0")
268
+ str, len, pad = plain($1), $2.to_i, ($3 || "0")
263
269
  pad = "0" if pad.empty?
264
- str.ljust(len, pad)
270
+ shown(str.ljust(len, pad))
265
271
  end
266
272
 
267
273
  # formatnum - format number with thousand separators
@@ -279,21 +285,30 @@ module Wp2txt
279
285
  end
280
286
 
281
287
  # plural, grammar, gender - just return first argument (proper handling would need language rules)
282
- result.gsub!(/\{\{\s*plural\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { $1 }
283
- result.gsub!(/\{\{\s*grammar\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { $1 }
284
- result.gsub!(/\{\{\s*gender\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { $1 }
288
+ result.gsub!(/\{\{\s*plural\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { shown(plain($1)) }
289
+ result.gsub!(/\{\{\s*grammar\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { shown(plain($1)) }
290
+ result.gsub!(/\{\{\s*gender\s*:\s*[^}|]*\s*\|\s*([^}|]*)[^}]*\}\}/i) { shown(plain($1)) }
285
291
 
286
292
  # int - internationalization, just return the message name
287
- result.gsub!(/\{\{\s*int\s*:\s*([^}|]*)[^}]*\}\}/i) { $1.strip }
293
+ result.gsub!(/\{\{\s*int\s*:\s*([^}|]*)[^}]*\}\}/i) { shown(plain($1).strip) }
288
294
 
289
295
  result
290
296
  end
291
297
 
292
298
  # Expand #titleparts parser function
293
299
  # {{#titleparts:pagename|number of segments|first segment}}
300
+ # Text with each "=" held as a placeholder given back as written
301
+ def plain(text)
302
+ @literal_equals ? text.tr(@literal_equals, "=") : text
303
+ end
304
+
305
+ def shown(text)
306
+ TemplateArgs.literal_equals(text, @literal_equals)
307
+ end
308
+
294
309
  def expand_titleparts(text)
295
310
  text.gsub(/\{\{\s*#titleparts\s*:\s*([^}|]+)(?:\s*\|\s*([^}|]*))?(?:\s*\|\s*([^}]*))?\}\}/i) do
296
- pagename = $1.strip
311
+ pagename = plain($1.strip)
297
312
  num_segments = $2&.strip&.to_i
298
313
  first_segment = ($3&.strip&.to_i || 1)
299
314
 
@@ -301,15 +316,16 @@ module Wp2txt
301
316
  first_segment = 1 if first_segment < 1
302
317
  first_idx = first_segment - 1
303
318
 
304
- if num_segments && num_segments > 0
305
- parts[first_idx, num_segments]&.join("/") || ""
306
- elsif num_segments && num_segments < 0
307
- # Negative means "all but last N"
308
- end_idx = parts.length + num_segments
309
- end_idx > first_idx ? parts[first_idx...end_idx].join("/") : ""
310
- else
311
- parts[first_idx..]&.join("/") || ""
312
- end
319
+ shown_parts = if num_segments && num_segments > 0
320
+ parts[first_idx, num_segments]&.join("/") || ""
321
+ elsif num_segments && num_segments < 0
322
+ # Negative means "all but last N"
323
+ end_idx = parts.length + num_segments
324
+ end_idx > first_idx ? parts[first_idx...end_idx].join("/") : ""
325
+ else
326
+ parts[first_idx..]&.join("/") || ""
327
+ end
328
+ shown(shown_parts)
313
329
  end
314
330
  end
315
331
 
@@ -8,6 +8,8 @@ require "parallel"
8
8
  require "time"
9
9
  require "json"
10
10
  require_relative "regex"
11
+ require_relative "bz2_stream"
12
+ require_relative "site_info"
11
13
  require_relative "section_extractor"
12
14
  require_relative "version"
13
15
 
@@ -727,9 +729,7 @@ module Wp2txt
727
729
  return "first-letter" if @stream_offsets.empty?
728
730
 
729
731
  header_end = @stream_offsets.first.positive? ? @stream_offsets.first : @stream_offsets[1]
730
- xml = self.class.decompress_bz2(File.binread(@multistream_path, header_end))
731
- siteinfo = xml[%r{<siteinfo\b[^>]*>(.*?)</siteinfo>}m, 1].to_s
732
- siteinfo[%r{<case>\s*(first-letter|case-sensitive)\s*</case>}, 1] || "first-letter"
732
+ SiteInfo.parse(Wp2txt.decompress_bz2(File.binread(@multistream_path, header_end))).case_rule
733
733
  end
734
734
 
735
735
  # Scan a batch of [offset, next_offset] stream pairs.
@@ -740,20 +740,13 @@ module Wp2txt
740
740
  offset_pairs.each do |offset, next_offset|
741
741
  f.seek(offset)
742
742
  data = next_offset ? f.read(next_offset - offset) : f.read
743
- xml = decompress_bz2(data)
743
+ xml = Wp2txt.decompress_bz2(data, offset: offset)
744
744
  xml.scan(PAGE_BLOCK_REGEX) { scan_page(::Regexp.last_match(1), out) }
745
745
  end
746
746
  end
747
747
  out
748
748
  end
749
749
 
750
- def self.decompress_bz2(data)
751
- stdout, status = Open3.capture2("bzcat", stdin_data: data)
752
- raise "bzcat failed (exit #{status.exitstatus})" unless status.success?
753
-
754
- stdout.force_encoding(Encoding::UTF_8)
755
- end
756
-
757
750
  def self.scan_page(block, out)
758
751
  title = block[TITLE_REGEX, 1]
759
752
  return unless title && !title.empty?
@@ -779,8 +772,8 @@ module Wp2txt
779
772
 
780
773
  out[:pages] << [page_id, title, ns, redirect_to, text.length]
781
774
 
782
- categories = text.scan(CATEGORY_REGEX)
783
- .map { |c| MetadataIndex.normalize_category(c[0]) }
775
+ categories = Wp2txt.category_names(text)
776
+ .map { |c| MetadataIndex.normalize_category(c) }
784
777
  .reject(&:empty?).uniq
785
778
  if ns == MetadataIndex::NS_CATEGORY
786
779
  child = MetadataIndex.normalize_category(title.sub(/\A[^:]+:/, ""))