wp2txt 2.3.4 → 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 (83) hide show
  1. checksums.yaml +4 -4
  2. data/.dockerignore +0 -4
  3. data/.github/workflows/ci.yml +16 -1
  4. data/.github/workflows/publish-image.yml +8 -4
  5. data/.gitignore +3 -6
  6. data/CHANGELOG.md +32 -0
  7. data/DEVELOPMENT.md +63 -93
  8. data/DEVELOPMENT_ja.md +61 -93
  9. data/Dockerfile +1 -1
  10. data/README.md +93 -8
  11. data/README_ja.md +84 -8
  12. data/Rakefile +10 -21
  13. data/bin/wp2txt +84 -15
  14. data/bin/wp2txt-mcp +1 -1
  15. data/docs/INDEXES.md +61 -1
  16. data/lib/wp2txt/article.rb +2 -3
  17. data/lib/wp2txt/bz2_stream.rb +63 -0
  18. data/lib/wp2txt/cli.rb +90 -26
  19. data/lib/wp2txt/config.rb +2 -11
  20. data/lib/wp2txt/constants.rb +13 -1
  21. data/lib/wp2txt/corpus.rb +10 -23
  22. data/lib/wp2txt/data/template_aliases.json +4 -1
  23. data/lib/wp2txt/data/template_patterns.json +61643 -0
  24. data/lib/wp2txt/dump_snapshot.rb +99 -0
  25. data/lib/wp2txt/extraction_run.rb +272 -0
  26. data/lib/wp2txt/extractor.rb +481 -327
  27. data/lib/wp2txt/formatter.rb +14 -12
  28. data/lib/wp2txt/fts_index.rb +1 -1
  29. data/lib/wp2txt/index_cache.rb +144 -55
  30. data/lib/wp2txt/index_commands.rb +109 -18
  31. data/lib/wp2txt/langlinks_importer.rb +19 -35
  32. data/lib/wp2txt/lead_terms.rb +228 -0
  33. data/lib/wp2txt/link_counter.rb +171 -0
  34. data/lib/wp2txt/magic_words.rb +44 -28
  35. data/lib/wp2txt/metadata_index.rb +82 -13
  36. data/lib/wp2txt/multistream.rb +911 -824
  37. data/lib/wp2txt/output_writer.rb +3 -1
  38. data/lib/wp2txt/page_props_importer.rb +170 -0
  39. data/lib/wp2txt/parser_functions.rb +23 -5
  40. data/lib/wp2txt/ractor_worker.rb +6 -4
  41. data/lib/wp2txt/regex.rb +24 -4
  42. data/lib/wp2txt/site_info.rb +123 -0
  43. data/lib/wp2txt/sql_dump_reader.rb +57 -0
  44. data/lib/wp2txt/stream_processor.rb +9 -2
  45. data/lib/wp2txt/stream_store.rb +91 -0
  46. data/lib/wp2txt/template_args.rb +111 -0
  47. data/lib/wp2txt/template_expander.rb +110 -124
  48. data/lib/wp2txt/template_patterns.rb +182 -0
  49. data/lib/wp2txt/utils.rb +164 -127
  50. data/lib/wp2txt/version.rb +1 -1
  51. data/lib/wp2txt/wikitext_regions.rb +66 -0
  52. data/spec/auto_download_spec.rb +9 -6
  53. data/spec/category_fetcher_spec.rb +135 -463
  54. data/spec/cli_targeted_spec.rb +60 -0
  55. data/spec/config_spec.rb +2 -15
  56. data/spec/constants_spec.rb +0 -4
  57. data/spec/docs_sync_spec.rb +3 -3
  58. data/spec/dump_fetch_spec.rb +293 -0
  59. data/spec/extraction_run_spec.rb +520 -0
  60. data/spec/index_build_spec.rb +113 -0
  61. data/spec/index_commands_version_spec.rb +17 -0
  62. data/spec/langlinks_importer_spec.rb +27 -0
  63. data/spec/lead_terms_edge_cases_spec.rb +194 -0
  64. data/spec/lead_terms_links_qids_spec.rb +204 -0
  65. data/spec/multistream_reader_spec.rb +140 -0
  66. data/spec/multistream_spec.rb +8 -214
  67. data/spec/output_integrity_spec.rb +45 -2
  68. data/spec/p1_correctness_spec.rb +12 -9
  69. data/spec/page_properties_spec.rb +161 -0
  70. data/spec/regex_spec.rb +30 -0
  71. data/spec/region_semantics_spec.rb +71 -0
  72. data/spec/spec_helper.rb +3 -3
  73. data/spec/support/dump_status.rb +34 -0
  74. data/spec/support/multistream_fixture.rb +26 -8
  75. data/spec/template_args_spec.rb +133 -0
  76. data/spec/template_expander_spec.rb +29 -111
  77. data/spec/template_passthrough_spec.rb +58 -0
  78. data/spec/template_patterns_spec.rb +253 -0
  79. data/spec/tracked_paths_spec.rb +168 -0
  80. data/spec/utils_spec.rb +7 -1
  81. metadata +45 -5
  82. data/lib/wp2txt/category_cache.rb +0 -313
  83. data/spec/category_cache_spec.rb +0 -226
data/lib/wp2txt/utils.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "strscan"
4
+ require_relative "wikitext_regions"
4
5
  require_relative "constants"
5
6
  require_relative "regex"
6
7
  require_relative "text_processing"
@@ -118,9 +119,23 @@ module Wp2txt
118
119
  }
119
120
  }.freeze
120
121
 
122
+ # {{!}} and {{=}} stand for a literal "|" and "=" inside template
123
+ # arguments; they become those characters only once templates are expanded,
124
+ # so they are held until then as noncharacters, which Unicode reserves for
125
+ # a program's internal use and text for interchange does not hold
126
+ LITERAL_PIPE = "\u{FDD0}"
127
+ LITERAL_EQUALS = "\u{FDD1}"
128
+ # Noncharacters this program uses internally (see also TemplatePatterns)
129
+ INTERNAL_CHARACTERS = "\u{FDD0}-\u{FDD5}"
130
+ INTERNAL_CHARACTER_REFERENCE = /&#(?:x0*fdd[0-5]|0*6497[6-9]|0*6498[01]);/i
131
+
121
132
  def format_wiki(text, config = {})
122
133
  # Work with a mutable copy to reduce intermediate string allocations
123
- result = +text.to_s
134
+ # The noncharacters used as placeholders are not text: any in the input
135
+ # are shown as U+FFFD rather than taken for "|" or "="
136
+ result = text.to_s.tr(INTERNAL_CHARACTERS, "\u{FFFD}")
137
+ result.gsub!(/\{\{\s*!\s*\}\}/, LITERAL_PIPE)
138
+ result.gsub!(/\{\{\s*=\s*\}\}/, LITERAL_EQUALS)
124
139
 
125
140
  # Early exit: Skip expensive processing if no templates present
126
141
  has_templates = result.include?("{{")
@@ -131,7 +146,8 @@ module Wp2txt
131
146
  magic_expander = MagicWordExpander.new(
132
147
  config[:title],
133
148
  namespace: config[:namespace] || "",
134
- dump_date: config[:dump_date]
149
+ dump_date: config[:dump_date],
150
+ literal_equals: LITERAL_EQUALS
135
151
  )
136
152
  result = magic_expander.expand(result)
137
153
  end
@@ -140,7 +156,8 @@ module Wp2txt
140
156
  # This evaluates {{#if:...}}, {{#switch:...}}, {{#expr:...}}, etc.
141
157
  if config[:expand_templates] && has_templates && result.include?("{{#")
142
158
  parser_functions = ParserFunctions.new(
143
- reference_date: config[:dump_date]
159
+ reference_date: config[:dump_date],
160
+ literal_equals: LITERAL_EQUALS
144
161
  )
145
162
  result = parser_functions.evaluate(result)
146
163
  end
@@ -148,8 +165,13 @@ module Wp2txt
148
165
  # Expand common templates if enabled and text still contains templates
149
166
  # This converts {{birth date|...}}, {{convert|...}}, etc. to readable text
150
167
  if config[:expand_templates] && result.include?("{{")
168
+ # Templates it does not know are left for the cleaner, which removes
169
+ # those removed by rule and keeps what the others were given to show
151
170
  template_expander = TemplateExpander.new(
152
- reference_date: config[:dump_date]
171
+ reference_date: config[:dump_date],
172
+ lang: config[:lang],
173
+ preserve_unknown: true,
174
+ literal_equals: LITERAL_EQUALS
153
175
  )
154
176
  result = template_expander.expand(result)
155
177
  end
@@ -157,12 +179,15 @@ module Wp2txt
157
179
  # CPU-intensive regex processing (can be parallelized with Ractor)
158
180
  result = format_wiki_regex_transform(result, config)
159
181
 
182
+ # A character reference to a placeholder is not one either
183
+ result.gsub!(INTERNAL_CHARACTER_REFERENCE, "\u{FFFD}")
160
184
  # Decode HTML entities (e.g., Ø → Ø)
161
185
  # This uses HTMLEntities gem - must be done outside Ractor
162
186
  result = special_chr(result)
163
187
 
164
188
  # Convert marker placeholders to final [MARKER] format
165
189
  result = finalize_markers(result)
190
+ result.tr!(LITERAL_PIPE + LITERAL_EQUALS, "|=")
166
191
  result
167
192
  end
168
193
 
@@ -425,6 +450,12 @@ module Wp2txt
425
450
  REF_OPEN_PLACEHOLDER = "«REFOPEN»"
426
451
  REF_CLOSE_PLACEHOLDER = "«REFCLOSE»"
427
452
 
453
+ # A single bracket is a link only when it opens with a URL; any other is
454
+ # shown as written ("[sic]", "[англ.]"), held as these until the scan ends
455
+ LITERAL_BRACKETS = "\u{FDD4}\u{FDD5}"
456
+ URL_START = %r{\A(?:(?:https?|ftps?|sftp|git|ircs?|nntp|svn|ssh|telnet|gopher|mms|redis|worldwind|wikipedia)://|//|
457
+ (?:mailto|news|tel|sips?|sms|urn|geo|magnet|xmpp|bitcoin|matrix):)}xi.freeze
458
+
428
459
  def process_external_links(str)
429
460
  # Early exit if no external links present
430
461
  return str unless str.include?("[")
@@ -433,7 +464,9 @@ module Wp2txt
433
464
  .gsub("[/ref]", REF_CLOSE_PLACEHOLDER)
434
465
 
435
466
  processed = process_nested_single_pass(protected_str, "[", "]") do |contents|
436
- if /\A\s.+\s\z/ =~ contents
467
+ if !contents.strip.match?(URL_START)
468
+ "#{LITERAL_BRACKETS[0]}#{contents}#{LITERAL_BRACKETS[1]}"
469
+ elsif /\A\s.+\s\z/ =~ contents
437
470
  " (#{contents.strip}) "
438
471
  else
439
472
  parts = contents.split(" ", 2)
@@ -448,6 +481,7 @@ module Wp2txt
448
481
 
449
482
  processed.gsub(REF_OPEN_PLACEHOLDER, "[ref]")
450
483
  .gsub(REF_CLOSE_PLACEHOLDER, "[/ref]")
484
+ .tr(LITERAL_BRACKETS, "[]")
451
485
  end
452
486
 
453
487
  #################### template processing ####################
@@ -574,150 +608,153 @@ module Wp2txt
574
608
  # Helper to check if template name matches any in a list (case-insensitive)
575
609
  def template_matches?(name, template_list)
576
610
  return false if template_list.nil? || template_list.empty?
577
- normalized_name = name.to_s.strip.downcase
578
- template_list.any? { |t| t.downcase == normalized_name }
611
+ # MediaWiki treats "_" and " " in template names as the same character
612
+ normalized_name = name.to_s.tr("_", " ").strip.downcase
613
+ template_list.any? { |t| t.tr("_", " ").downcase == normalized_name }
579
614
  end
580
615
 
581
616
  def correct_inline_template(str, enabled_markers = [], extract_citations = false)
582
617
  # Early exit if no templates present
583
618
  return str unless str.include?("{{")
584
619
 
620
+ # What a template shows is text: an "=" in it does not name an argument
621
+ # of a template around it
585
622
  process_nested_single_pass(str, "{{", "}}") do |contents|
586
- parts = contents.split("|")
587
- template_name = (parts[0] || "").strip
588
- template_name_lower = template_name.downcase
589
-
590
- # =========================================================================
591
- # Specific template handlers (order matters - check before generic patterns)
592
- # =========================================================================
593
-
594
- # {{IPA|...}} or {{IPA-xx|...}} or {{IPAc-xx|...}}
595
- # Must be checked BEFORE mixed_script_templates which also contains IPA
596
- if template_name_lower == "ipa" || template_name_lower.start_with?("ipa-") || template_name_lower.start_with?("ipac-")
597
- if enabled_markers.include?(:ipa)
598
- marker_placeholder(:ipa)
599
- else
600
- (parts[1] || "").to_s.strip
601
- end
602
- # Language templates: {{lang|code|text}} or {{lang-xx|text}}
603
- # Must be checked BEFORE mixed_script_templates which also contains lang
604
- elsif template_name_lower == "lang"
605
- parts.size >= 3 ? parts[2].to_s.strip : (parts[1] || "").to_s.strip
606
- elsif template_name_lower.start_with?("lang-")
623
+ TemplateArgs.literal_equals(inline_template_text(contents, enabled_markers, extract_citations), LITERAL_EQUALS)
624
+ end
625
+ end
626
+
627
+ def inline_template_text(contents, enabled_markers, extract_citations)
628
+ parts = WikitextRegions.split_pipes(contents)
629
+ template_name = (parts[0] || "").strip
630
+ template_name_lower = template_name.downcase
631
+
632
+ # =========================================================================
633
+ # Specific template handlers (order matters - check before generic patterns)
634
+ # =========================================================================
635
+
636
+ # {{IPA|...}} or {{IPA-xx|...}} or {{IPAc-xx|...}}
637
+ # Must be checked BEFORE mixed_script_templates which also contains IPA
638
+ if template_name_lower == "ipa" || template_name_lower.start_with?("ipa-") || template_name_lower.start_with?("ipac-")
639
+ if enabled_markers.include?(:ipa)
640
+ marker_placeholder(:ipa)
641
+ else
607
642
  (parts[1] || "").to_s.strip
608
- elsif template_name_lower == "fontsize"
609
- parts.size >= 3 ? parts[2].to_s.strip : (parts[1] || "").to_s.strip
610
- # {{langwithname|code|name|text}} - extract the text (3rd param)
611
- elsif template_name_lower == "langwithname"
612
- parts.size >= 4 ? parts[3].to_s.strip : (parts.last || "").to_s.strip
613
- # {{math|...}} or {{mvar|...}} - mathematical notation
614
- elsif template_name_lower == "math" || template_name_lower == "mvar"
615
- if enabled_markers.include?(:math)
616
- marker_placeholder(:math)
617
- else
618
- (parts[1] || "").to_s.strip
619
- end
620
- # {{chem|...}} or {{ce|...}} - chemical formulas
621
- elsif template_name_lower == "chem" || template_name_lower == "ce"
622
- if enabled_markers.include?(:chem)
623
- marker_placeholder(:chem)
624
- else
625
- (parts[1] || "").to_s.strip
626
- end
643
+ end
644
+ # Language templates: {{lang|code|text}} or {{lang-xx|text}}
645
+ # Must be checked BEFORE mixed_script_templates which also contains lang
646
+ elsif template_name_lower == "lang"
647
+ parts.size >= 3 ? parts[2].to_s.strip : (parts[1] || "").to_s.strip
648
+ elsif template_name_lower.start_with?("lang-")
649
+ (parts[1] || "").to_s.strip
650
+ elsif template_name_lower == "fontsize"
651
+ parts.size >= 3 ? parts[2].to_s.strip : (parts[1] || "").to_s.strip
652
+ # {{langwithname|code|name|text}} - extract the text (3rd param)
653
+ elsif template_name_lower == "langwithname"
654
+ parts.size >= 4 ? parts[3].to_s.strip : (parts.last || "").to_s.strip
655
+ # {{math|...}} or {{mvar|...}} - mathematical notation
656
+ elsif template_name_lower == "math" || template_name_lower == "mvar"
657
+ if enabled_markers.include?(:math)
658
+ marker_placeholder(:math)
659
+ else
660
+ (parts[1] || "").to_s.strip
661
+ end
662
+ # {{chem|...}} or {{ce|...}} - chemical formulas
663
+ elsif template_name_lower == "chem" || template_name_lower == "ce"
664
+ if enabled_markers.include?(:chem)
665
+ marker_placeholder(:chem)
666
+ else
667
+ (parts[1] || "").to_s.strip
668
+ end
627
669
 
628
- # =========================================================================
629
- # Data-driven template matching (generic patterns from template_aliases.json)
630
- # =========================================================================
670
+ # =========================================================================
671
+ # Data-driven template matching (generic patterns from template_aliases.json)
672
+ # =========================================================================
631
673
 
632
- # Handle citation templates
633
- elsif CITATION_TEMPLATE_REGEX.match?(contents)
634
- if extract_citations
635
- format_citation(contents)
636
- else
637
- ""
638
- end
639
- # Remove navigation/reference templates entirely
640
- elsif REMOVE_TEMPLATES_REGEX.match?(contents)
641
- ""
642
- # Remove flag templates (data-driven)
643
- elsif FLAG_TEMPLATE_REGEX.match?(contents) || COUNTRY_CODE_REGEX.match?(template_name)
674
+ # Handle citation templates
675
+ elsif CITATION_TEMPLATE_REGEX.match?(contents)
676
+ if extract_citations
677
+ format_citation(contents)
678
+ else
644
679
  ""
645
- # Ruby text templates: 読み仮名, ruby, etc. (data-driven)
646
- elsif template_matches?(template_name, RUBY_TEXT_TEMPLATES)
680
+ end
681
+ # Remove navigation/reference templates entirely
682
+ elsif REMOVE_TEMPLATES_REGEX.match?(contents)
683
+ ""
684
+ # Remove flag templates (data-driven)
685
+ elsif FLAG_TEMPLATE_REGEX.match?(contents) || COUNTRY_CODE_REGEX.match?(template_name)
686
+ ""
687
+ # Ruby text templates: 読み仮名, ruby, etc. (data-driven)
688
+ elsif template_matches?(template_name, RUBY_TEXT_TEMPLATES)
689
+ text = (parts[1] || "").strip
690
+ reading = (parts[2] || "").strip
691
+ reading.empty? ? text : "#{text}(#{reading})"
692
+ # Interwiki link templates: 仮リンク, ill, interlanguage link (data-driven)
693
+ elsif template_matches?(template_name, INTERWIKI_LINK_TEMPLATES)
694
+ # First parameter is display text
695
+ (parts[1] || "").to_s.strip
696
+ # Mixed script templates: nihongo, transl, etc. (data-driven)
697
+ elsif template_matches?(template_name, MIXED_SCRIPT_TEMPLATES)
698
+ # Format depends on template type
699
+ if template_name_lower == "nihongo" || template_name_lower.start_with?("nihongo")
647
700
  text = (parts[1] || "").strip
648
- reading = (parts[2] || "").strip
649
- reading.empty? ? text : "#{text}(#{reading})"
650
- # Interwiki link templates: 仮リンク, ill, interlanguage link (data-driven)
651
- elsif template_matches?(template_name, INTERWIKI_LINK_TEMPLATES)
652
- # First parameter is display text
653
- (parts[1] || "").to_s.strip
654
- # Mixed script templates: nihongo, transl, etc. (data-driven)
655
- elsif template_matches?(template_name, MIXED_SCRIPT_TEMPLATES)
656
- # Format depends on template type
657
- if template_name_lower == "nihongo" || template_name_lower.start_with?("nihongo")
658
- text = (parts[1] || "").strip
659
- kanji = (parts[2] || "").strip
660
- romaji = (parts[3] || "").strip
661
- if kanji.empty? && romaji.empty?
662
- text
663
- elsif romaji.empty?
664
- "#{text} (#{kanji})"
665
- elsif kanji.empty?
666
- "#{text} (#{romaji})"
667
- else
668
- "#{text} (#{kanji}, #{romaji})"
669
- end
670
- elsif template_name_lower == "transl" || template_name_lower == "transliteration"
671
- # {{transl|lang|text}} -> text
672
- (parts[2] || parts[1] || "").to_s.strip
701
+ kanji = (parts[2] || "").strip
702
+ romaji = (parts[3] || "").strip
703
+ if kanji.empty? && romaji.empty?
704
+ text
705
+ elsif romaji.empty?
706
+ "#{text} (#{kanji})"
707
+ elsif kanji.empty?
708
+ "#{text} (#{romaji})"
673
709
  else
674
- # Default: extract first content parameter
675
- (parts[1] || "").to_s.strip
710
+ "#{text} (#{kanji}, #{romaji})"
676
711
  end
677
- # Convert templates (data-driven)
678
- elsif template_matches?(template_name, CONVERT_TEMPLATES)
679
- num = (parts[1] || "").strip
680
- unit = (parts[2] || "").strip
681
- unit.empty? ? num : "#{num} #{unit}"
682
- # Formatting templates: small, nowrap, nbsp, etc. (data-driven)
683
- elsif FORMATTING_TEMPLATE_REGEX.match?(contents)
684
- if template_name_lower == "nbsp"
685
- " " # Non-breaking space
686
- else
687
- # Extract content from formatting template
688
- (parts[1] || "").to_s.strip
689
- end
690
- # Default handling for other templates
712
+ elsif template_name_lower == "transl" || template_name_lower == "transliteration"
713
+ # {{transl|lang|text}} -> text
714
+ (parts[2] || parts[1] || "").to_s.strip
715
+ else
716
+ # Default: extract first content parameter
717
+ (parts[1] || "").to_s.strip
718
+ end
719
+ # Convert templates (data-driven)
720
+ elsif template_matches?(template_name, CONVERT_TEMPLATES)
721
+ num = (parts[1] || "").strip
722
+ unit = (parts[2] || "").strip
723
+ unit.empty? ? num : "#{num} #{unit}"
724
+ # Formatting templates: small, nowrap, nbsp, etc. (data-driven)
725
+ elsif FORMATTING_TEMPLATE_REGEX.match?(contents)
726
+ if template_name_lower == "nbsp"
727
+ " " # Non-breaking space
691
728
  else
692
- extract_template_content(parts)
729
+ # Extract content from formatting template
730
+ (parts[1] || "").to_s.strip
693
731
  end
732
+ # Default handling for other templates
733
+ else
734
+ extract_template_content(parts)
694
735
  end
695
736
  end
696
737
 
697
- # Extract meaningful content from template parts
738
+ # The text an unknown template was given to show: its first unnamed
739
+ # argument, passing over a language code when another follows it. Named
740
+ # arguments are settings, and a template given nothing shows nothing of the
741
+ # article's
698
742
  def extract_template_content(parts)
699
- return "" if parts.empty?
700
- return parts[0].to_s.strip if parts.size == 1
701
-
702
- # Skip the template name, try to find non-parameter content
703
- parts[1..].each do |part|
704
- next if part.nil?
705
- # Skip if it looks like a parameter (contains =)
706
- next if part.include?("=")
707
- content = part.strip
708
- return content unless content.empty?
709
- end
743
+ candidates = TemplateArgs.parse(parts[1..].to_a).positional.map { |arg| arg.to_s.strip }.reject(&:empty?)
744
+ candidates.shift if candidates.size > 1 && language_code?(candidates.first)
745
+ candidates.first || ""
746
+ end
710
747
 
711
- # If all parts have =, try to extract value from first parameter
712
- parts[1..].each do |part|
713
- next if part.nil?
714
- if part.include?("=")
715
- key, value = part.split("=", 2)
716
- return value.to_s.strip unless value.nil? || value.strip.empty?
717
- end
718
- end
748
+ # A code of a Wikipedia edition's language, alone or with a subtag ("zh-hant")
749
+ def language_code?(arg)
750
+ LANGUAGE_CODES.key?(arg) || (arg.match?(LANGUAGE_CODE_ARG) && LANGUAGE_CODES.key?(arg.split("-").first))
751
+ end
719
752
 
720
- ""
753
+ LANGUAGE_CODE_ARG = /\A[a-z]{2,3}(?:-[a-z]{2,4})?\z/
754
+ LANGUAGE_CODES = begin
755
+ path = File.join(__dir__, "data", "language_metadata.json")
756
+ codes = File.exist?(path) ? JSON.parse(File.read(path))["languages"].keys : []
757
+ codes.to_h { |code| [code, true] }
721
758
  end
722
759
 
723
760
  # =========================================================================
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Wp2txt
4
- VERSION = "2.3.4"
4
+ VERSION = "2.5.0"
5
5
  end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Wp2txt
4
+ # Literal regions suppress wikitext parsing. Galleries and timelines can
5
+ # contain links, but their contents are not the article's lead prose.
6
+ module WikitextRegions
7
+ LITERAL_TAGS = %w[nowiki pre math chem ce score syntaxhighlight source graph mapframe templatedata].freeze
8
+ NON_PROSE_TAGS = %w[gallery timeline].freeze
9
+ COMMENT = /<!--.*?(?:-->|\z)/m
10
+
11
+ def self.region_pattern(tags)
12
+ /<!--.*?(?:-->|\z)|<(?<tag>#{tags.join('|')})(?=[\s\/>])(?:"[^"]*"|'[^']*'|[^'">])*?(?:\/>|>.*?(?:<\/\k<tag>\s*>|\z))/mi
13
+ end
14
+
15
+ LITERAL_REGION = region_pattern(LITERAL_TAGS)
16
+ LEAD_REGION = region_pattern(LITERAL_TAGS + NON_PROSE_TAGS)
17
+ LITERAL_REGION_AT = /\G(?:#{LITERAL_REGION})/
18
+ LEAD_REGION_AT = /\G(?:#{LEAD_REGION})/
19
+
20
+ module_function
21
+
22
+ def end_at(text, offset, lead: false)
23
+ match = (lead ? LEAD_REGION_AT : LITERAL_REGION_AT).match(text, offset)
24
+ match.end(0) if match
25
+ end
26
+
27
+ def remove_literal(text)
28
+ text.gsub(LITERAL_REGION, "")
29
+ end
30
+
31
+ # One space per codepoint, including internal newlines: an excluded
32
+ # region must not introduce a paragraph or heading boundary.
33
+ def mask_lead(text)
34
+ text.gsub(LEAD_REGION) { |region| " " * region.length }
35
+ end
36
+
37
+ def split_pipes(text)
38
+ parts = [+""]
39
+ stack = []
40
+ i = 0
41
+ while i < text.length
42
+ two = text[i, 2]
43
+ if text[i] == "<" && (stop = end_at(text, i))
44
+ parts.last << text[i...stop]
45
+ i = stop
46
+ elsif ["{{", "[["].include?(two)
47
+ stack << (two == "{{" ? "}}" : "]]")
48
+ parts.last << two
49
+ i += 2
50
+ elsif !stack.empty? && two == stack.last
51
+ stack.pop
52
+ parts.last << two
53
+ i += 2
54
+ else
55
+ if text[i] == "|" && stack.empty?
56
+ parts << +""
57
+ else
58
+ parts.last << text[i]
59
+ end
60
+ i += 1
61
+ end
62
+ end
63
+ parts
64
+ end
65
+ end
66
+ end
@@ -164,15 +164,18 @@ RSpec.describe "Wp2txt Auto Download" do
164
164
  end
165
165
 
166
166
  describe "#clear_cache!" do
167
- it "removes language-specific cache directory" do
167
+ it "removes everything cached for the language and nothing for others" do
168
168
  manager = Wp2txt::DumpManager.new(:ja, cache_dir: cache_dir)
169
- lang_dir = File.join(cache_dir, "jawiki")
170
- FileUtils.mkdir_p(lang_dir)
171
- File.write(File.join(lang_dir, "test.txt"), "test")
169
+ mine = %w[jawiki-20260101-multistream-index.txt.bz2 jawiki-20260101-multistream.xml.bz2
170
+ jawiki-20260101-multistream-18streams.xml.bz2 jawiki-checked.json]
171
+ mine.each { |name| File.write(File.join(cache_dir, name), "x") }
172
+ snapshot_dir = File.join(cache_dir, "jawiki-20260101-0123456789ab", "streams")
173
+ FileUtils.mkdir_p(snapshot_dir)
174
+ others = %w[enwiki-20260101-multistream-index.txt.bz2 jawiktionary-20260101-pages.xml.bz2]
175
+ others.each { |name| File.write(File.join(cache_dir, name), "x") }
172
176
 
173
- expect(File.exist?(lang_dir)).to be true
174
177
  manager.clear_cache!
175
- expect(File.exist?(lang_dir)).to be false
178
+ expect(Dir.children(cache_dir)).to match_array(others)
176
179
  end
177
180
  end
178
181