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
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "template_args"
4
+ require_relative "template_patterns"
5
+
3
6
  module Wp2txt
4
7
  # Expands common MediaWiki templates to their text representation
5
8
  # Handles date templates, convert templates, and other common patterns
@@ -9,48 +12,10 @@ module Wp2txt
9
12
  July August September October November December
10
13
  ].freeze
11
14
 
12
- # Unit conversion factors
13
- CONVERSIONS = {
14
- # Length
15
- ["km", "mi"] => 0.621371,
16
- ["mi", "km"] => 1.60934,
17
- ["m", "ft"] => 3.28084,
18
- ["ft", "m"] => 0.3048,
19
- ["cm", "in"] => 0.393701,
20
- ["in", "cm"] => 2.54,
21
- ["mm", "in"] => 0.0393701,
22
- ["in", "mm"] => 25.4,
23
- ["yd", "m"] => 0.9144,
24
- ["m", "yd"] => 1.09361,
25
- # Weight
26
- ["kg", "lb"] => 2.20462,
27
- ["lb", "kg"] => 0.453592,
28
- ["g", "oz"] => 0.035274,
29
- ["oz", "g"] => 28.3495,
30
- ["t", "lb"] => 2204.62,
31
- ["lb", "t"] => 0.000453592,
32
- # Temperature (special handling)
33
- ["C", "F"] => :celsius_to_fahrenheit,
34
- ["°C", "°F"] => :celsius_to_fahrenheit,
35
- ["F", "C"] => :fahrenheit_to_celsius,
36
- ["°F", "°C"] => :fahrenheit_to_celsius,
37
- # Area
38
- ["km2", "sqmi"] => 0.386102,
39
- ["sqmi", "km2"] => 2.58999,
40
- ["ha", "acre"] => 2.47105,
41
- ["acre", "ha"] => 0.404686,
42
- ["m2", "sqft"] => 10.7639,
43
- ["sqft", "m2"] => 0.092903,
44
- # Speed
45
- ["km/h", "mph"] => 0.621371,
46
- ["mph", "km/h"] => 1.60934,
47
- ["m/s", "km/h"] => 3.6,
48
- ["km/h", "m/s"] => 0.277778,
49
- # Volume
50
- ["l", "gal"] => 0.264172,
51
- ["gal", "l"] => 3.78541,
52
- ["ml", "floz"] => 0.033814,
53
- ["floz", "ml"] => 29.5735
15
+ # Words {{convert}} takes between the values of a range (5|-|10, 16|to|17)
16
+ CONVERT_RANGE_WORDS = {
17
+ "-" => "–", "–" => "–", "to" => "to", "to(-)" => "to", "and" => "and", "and(-)" => "and",
18
+ "or" => "or", "x" => "×", "by" => "by", "+/-" => "±", "±" => "±", "+" => "+", "~" => "~"
54
19
  }.freeze
55
20
 
56
21
  # Unit display names
@@ -87,9 +52,17 @@ module Wp2txt
87
52
  "floz" => "fl oz"
88
53
  }.freeze
89
54
 
90
- def initialize(reference_date: nil, preserve_unknown: false)
55
+ # @param reference_date [Time, nil] "now" for templates that count from
56
+ # today (ages): the dump's date, so a dump always gives the same text
57
+ # @param lang [String, nil] the wiki's language code
58
+ # @param literal_equals [String, nil] put in place of "=" in what a
59
+ # template shows, so that a template around it does not take it for
60
+ # the start of an argument's value (changed back by the caller)
61
+ def initialize(reference_date: nil, preserve_unknown: false, lang: nil, literal_equals: nil)
91
62
  @reference_date = reference_date || Time.now
92
63
  @preserve_unknown = preserve_unknown
64
+ @lang = lang&.to_s
65
+ @literal_equals = literal_equals
93
66
  end
94
67
 
95
68
  # Main expansion method
@@ -143,6 +116,8 @@ module Wp2txt
143
116
 
144
117
  template_content = text[(start_idx + 2)...end_idx]
145
118
  expanded = expand_single_template(template_content)
119
+ # A template left for later stages keeps its own syntax
120
+ expanded = TemplateArgs.literal_equals(expanded, @literal_equals) unless expanded == "{{#{template_content}}}"
146
121
  result << expanded
147
122
 
148
123
  pos = end_idx + 2
@@ -180,13 +155,41 @@ module Wp2txt
180
155
  @rendered_by_cleaner.include?(template_name.tr("_", " "))
181
156
  end
182
157
 
158
+ def removed_by_rule?(content)
159
+ Wp2txt::CITATION_TEMPLATE_REGEX.match?(content) || Wp2txt::REMOVE_TEMPLATES_REGEX.match?(content)
160
+ end
161
+
162
+ # A template shown as a block marker ([INFOBOX], [REFERENCES]) that shows
163
+ # no text of its own is left to the markers
164
+ def left_to_marker?(name, definition)
165
+ return false unless definition["p"].to_s.empty?
166
+
167
+ @block_marker_templates ||= Wp2txt::BLOCK_MARKERS.flat_map { |type| Wp2txt::MARKER_PATTERNS.dig(type, :templates) || [] }
168
+ @block_marker_templates.any? { |regex| regex.match?("{{#{name.strip}") }
169
+ end
170
+
183
171
  def text_renderer
184
172
  @text_renderer ||= Object.new.extend(Wp2txt)
185
173
  end
186
174
 
187
175
  def expand_single_template(content)
188
176
  parts = split_template_parts(content)
189
- return "" if parts.empty?
177
+ return "" if parts[0].strip.empty?
178
+
179
+ # The edition's own way of showing the template, where it is known;
180
+ # citations and templates removed by rule stay removed. Templates in
181
+ # the arguments are expanded first, once the arguments are split, as
182
+ # the pattern may depend on their values (a language code)
183
+ if @lang && (definition = TemplatePatterns.lookup(@lang, parts[0])) && !removed_by_rule?(content) &&
184
+ !left_to_marker?(parts[0], definition)
185
+ args = parts[1..].map { |part| part.include?("{{") ? expand(part) : part }
186
+ text = TemplatePatterns.render(definition, TemplateArgs.parse(args))
187
+ return text if text
188
+
189
+ # The arguments as expanded, for the rules below and for the cleaner
190
+ parts = [parts[0], *args]
191
+ content = parts.join("|")
192
+ end
190
193
 
191
194
  template_name = parts[0].strip.downcase
192
195
  params = parse_template_params(parts[1..])
@@ -281,63 +284,48 @@ module Wp2txt
281
284
  # text). Deleting them dropped those words; leaving the raw template
282
285
  # for later confused links that contain it (an image caption with a
283
286
  # "|" inside). Render them now, with the cleaner's own rules.
284
- text_renderer.correct_inline_template("{{#{expand(content)}}}")
287
+ text_renderer.correct_inline_template("{{#{expand(content)}}}").tr(Wp2txt::LITERAL_EQUALS, @literal_equals || "=")
285
288
  else
286
289
  @preserve_unknown ? "{{#{content}}}" : ""
287
290
  end
288
291
  end
289
292
  end
290
293
 
294
+ # The name and the arguments, split at pipes outside {{...}} and [[...]];
295
+ # an empty last argument ({{x|a|}}) is an argument given
291
296
  def split_template_parts(content)
292
297
  parts = []
293
298
  current = +""
294
299
  depth = 0
300
+ i = 0
295
301
 
296
- content.each_char do |c|
297
- if c == "{" || c == "["
302
+ while i < content.length
303
+ pair = content[i, 2]
304
+ if pair == "{{" || pair == "[["
298
305
  depth += 1
299
- current << c
300
- elsif c == "}" || c == "]"
306
+ current << pair
307
+ i += 2
308
+ elsif pair == "}}" || pair == "]]"
301
309
  depth -= 1
302
- current << c
303
- elsif c == "|" && depth == 0
304
- parts << current
305
- current = +""
310
+ current << pair
311
+ i += 2
306
312
  else
307
- current << c
313
+ c = content[i]
314
+ if c == "|" && depth <= 0
315
+ parts << current
316
+ current = +""
317
+ else
318
+ current << c
319
+ end
320
+ i += 1
308
321
  end
309
322
  end
310
323
 
311
- parts << current unless current.empty?
312
- parts
324
+ parts << current
313
325
  end
314
326
 
315
327
  def parse_template_params(parts)
316
- params = { positional: [] }
317
-
318
- parts.each do |part|
319
- # Check for named parameter (key=value)
320
- # Only treat as named parameter if:
321
- # 1. Contains '='
322
- # 2. The key part looks like a valid parameter name (alphanumeric/underscore only)
323
- # 3. Key doesn't contain HTML tags or other special chars
324
- if part.include?("=")
325
- key, value = part.split("=", 2)
326
- key_stripped = key.strip
327
- # Valid param name: only letters, digits, underscore, space
328
- # Should NOT contain < > { } or other markup
329
- if key_stripped.match?(/\A[\w\s]+\z/) && !key_stripped.match?(/[<>{}\[\]]/)
330
- params[key_stripped.downcase] = value&.strip
331
- else
332
- # Treat as positional if key doesn't look valid
333
- params[:positional] << part.strip
334
- end
335
- else
336
- params[:positional] << part.strip
337
- end
338
- end
339
-
340
- params
328
+ TemplateArgs.parse(parts).to_params
341
329
  end
342
330
 
343
331
  # Date formatting methods
@@ -345,6 +333,7 @@ module Wp2txt
345
333
  def format_date(params, style: :mdy)
346
334
  pos = params[:positional]
347
335
  return "" if pos.empty?
336
+ return written_date(pos) if written_date(pos)
348
337
 
349
338
  year = pos[0].to_i
350
339
  month = pos[1]&.to_i
@@ -370,9 +359,18 @@ module Wp2txt
370
359
  end
371
360
  end
372
361
 
362
+ # A date written other than in numbers (a month name, the whole date in one
363
+ # argument) is kept as written, as its parts cannot be read as numbers
364
+ # @return [String, nil] nil when the date is in numbers
365
+ def written_date(pos)
366
+ parts = pos.first(3).map { |v| v.to_s.strip }.reject(&:empty?)
367
+ parts.join(" ") unless parts.all? { |v| v.match?(/\A\d+\z/) }
368
+ end
369
+
373
370
  def format_simple_date(params)
374
371
  pos = params[:positional]
375
372
  return "" if pos.empty?
373
+ return written_date(pos) if written_date(pos)
376
374
 
377
375
  year = pos[0].to_i
378
376
  month = pos[1]&.to_i
@@ -384,6 +382,7 @@ module Wp2txt
384
382
  def format_date_with_age(params, style: :mdy, age_label: "age")
385
383
  pos = params[:positional]
386
384
  return "" if pos.empty?
385
+ return written_date(pos) if written_date(pos)
387
386
 
388
387
  year = pos[0].to_i
389
388
  month = pos[1]&.to_i || 1
@@ -399,6 +398,7 @@ module Wp2txt
399
398
 
400
399
  def format_death_date_with_age(params)
401
400
  pos = params[:positional]
401
+ return written_date(pos) if written_date(pos)
402
402
  return "" if pos.length < 6
403
403
 
404
404
  death_year = pos[0].to_i
@@ -546,36 +546,21 @@ module Wp2txt
546
546
 
547
547
  # Convert template
548
548
 
549
+ # {{convert}}: the values and the unit as written. The converted figures
550
+ # are computed by the template, and not reproduced.
549
551
  def expand_convert(params)
550
- pos = params[:positional]
552
+ pos = params[:positional].map(&:strip)
551
553
  return "" if pos.empty?
552
554
 
553
- value = pos[0].to_f
554
- from_unit = pos[1]&.strip || ""
555
- to_unit = pos[2]&.strip || ""
556
-
557
- return "#{format_number(value)} #{from_unit}" if to_unit.empty?
558
-
559
- # Normalize units
560
- from_normalized = normalize_unit(from_unit)
561
- to_normalized = normalize_unit(to_unit)
562
-
563
- conversion = CONVERSIONS[[from_normalized, to_normalized]]
564
-
565
- if conversion.nil?
566
- "#{format_number(value)} #{UNIT_DISPLAY[from_normalized] || from_unit}"
567
- elsif conversion.is_a?(Symbol)
568
- # Special conversion (temperature)
569
- converted = send(conversion, value)
570
- from_display = UNIT_DISPLAY[from_normalized] || from_unit
571
- to_display = UNIT_DISPLAY[to_normalized] || to_unit
572
- "#{format_number(value)} #{from_display} (#{format_number(converted)} #{to_display})"
573
- else
574
- converted = value * conversion
575
- from_display = UNIT_DISPLAY[from_normalized] || from_unit
576
- to_display = UNIT_DISPLAY[to_normalized] || to_unit
577
- "#{format_number(value)} #{from_display} (#{format_number(converted)} #{to_display})"
555
+ parts = [pos[0]]
556
+ i = 1
557
+ while (word = CONVERT_RANGE_WORDS[pos[i]]) && !pos[i + 1].to_s.empty?
558
+ parts << word << pos[i + 1]
559
+ i += 2
578
560
  end
561
+ text = parts.join(" ").gsub(" – ", "–")
562
+ unit = pos[i].to_s
563
+ unit.empty? ? text : "#{text} #{UNIT_DISPLAY[normalize_unit(unit)] || unit}"
579
564
  end
580
565
 
581
566
  def normalize_unit(unit)
@@ -583,24 +568,6 @@ module Wp2txt
583
568
  unit.gsub(/\s+/, "")
584
569
  end
585
570
 
586
- def format_number(value)
587
- # Format number, removing unnecessary decimals
588
- rounded = value.round(1)
589
- if rounded == rounded.to_i
590
- rounded.to_i.to_s
591
- else
592
- format("%.1f", rounded)
593
- end
594
- end
595
-
596
- def celsius_to_fahrenheit(c)
597
- (c * 9.0 / 5.0 + 32).round
598
- end
599
-
600
- def fahrenheit_to_celsius(f)
601
- ((f - 32) * 5.0 / 9.0).round
602
- end
603
-
604
571
  # Common template expansions
605
572
 
606
573
  def expand_circa(params)
@@ -0,0 +1,182 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "template_args"
5
+
6
+ module Wp2txt
7
+ # How each Wikipedia edition displays its most used inline templates, as
8
+ # learned from the edition's own parser (scripts/fetch_template_patterns.rb):
9
+ # a pattern of the displayed text with slots for the arguments, such as
10
+ # "ドイツ語: {1}" for {{Lang-de|...}} on the Japanese edition.
11
+ module TemplatePatterns
12
+ DATA_PATH = File.join(__dir__, "data", "template_patterns.json")
13
+
14
+ # Loaded once and made shareable, so that Ractors read the same data
15
+ DATA = Ractor.make_shareable(File.exist?(DATA_PATH) ? JSON.parse(File.read(DATA_PATH)) : { "wikis" => {} })
16
+
17
+ module_function
18
+
19
+ def data
20
+ @data || DATA
21
+ end
22
+
23
+ # Identifies the patterns in use, for the record of an extraction
24
+ def digest
25
+ data.dig("meta", "digest")
26
+ end
27
+
28
+ # The definition of a template on an edition, under its own name or another
29
+ # name that redirects to it
30
+ # @return [Hash, nil]
31
+ def lookup(lang, name)
32
+ wiki = data["wikis"][lang.to_s]
33
+ return nil unless wiki
34
+
35
+ key = normalize(name)
36
+ wiki["templates"][key] || wiki["templates"][wiki["aliases"][key]]
37
+ end
38
+
39
+ # The displayed text of a call, or nil when the pattern does not tell how
40
+ # the call shows: one learned from a number (n arguments, the first a
41
+ # number) for a call with more arguments or other text first, and one
42
+ # learned for a language code from n arguments for a call of another shape
43
+ # (an argument missing or empty) or with a code not among those it was
44
+ # learned from. A call with a named argument the template is known to show
45
+ # or to be shown otherwise with is shown by the pattern learned with that
46
+ # argument, where the call gives no other and the pattern fits it, or else
47
+ # by its pattern followed by the values of those the template shows, each once
48
+ # @param definition [Hash] from lookup
49
+ # @param args [TemplateArgs]
50
+ # @return [String, nil]
51
+ def render(definition, args)
52
+ count = args.positional_count
53
+ # No language code is a number: a year in its place is a date's
54
+ return nil if (code_arg = definition["code_arg"]) && args[code_arg].to_s.strip.match?(/\A\p{Nd}+\z/)
55
+
56
+ if (limit = definition["n"])
57
+ if code_arg
58
+ return nil if count != limit || args.positional.any? { |v| v.to_s.strip.empty? }
59
+ return nil if definition["codes"] && !definition["codes"].include?(args[code_arg].to_s.strip.downcase)
60
+ # Learned with no named argument: one not known to change nothing is not told
61
+ return nil unless (given_named(definition, args) - known_named(definition)).empty?
62
+ elsif count > limit || !args[1].to_s.strip.match?(NUMBER)
63
+ return nil
64
+ end
65
+ end
66
+
67
+ # A template given one or two arguments may show other text than with three
68
+ pattern = (count < 3 && definition["p#{count}"]) || definition["p"]
69
+ if code_arg
70
+ pattern = definition.dig("by_code", args[code_arg].to_s.strip.downcase) || pattern
71
+ end
72
+ return fill(definition, args, pattern) if pattern.empty?
73
+
74
+ replaces = definition.fetch("replaces", {})
75
+ # Those not known to change the text are not told, as with no named argument
76
+ given = given_named(definition, args) & (known_named(definition) + replaces.keys)
77
+ # Those standing in for an argument are shown by the pattern, one for each
78
+ changing = (given - standing_in(definition, args)) & known_named(definition)
79
+ return fill(definition, args, pattern) if changing.empty?
80
+
81
+ # Learned with the arguments the pattern shows, those not given left empty
82
+ with = definition.dig("with", given[0]) if given.size == 1
83
+ return fill(definition, args, with) if with && with_fits?(definition, args, pattern, with, given[0])
84
+
85
+ # Otherwise the pattern, followed by the values of those it shows that
86
+ # hold a word or a number (a separator such as "、" holds neither)
87
+ text = fill(definition, args, pattern)
88
+ shown = definition.fetch("shows", [])
89
+ values = args.named.select { |name, _| changing.include?(name) && shown.include?(name) }.values
90
+ values.map { |value| value.to_s.strip }.select { |value| value.match?(/[\p{L}\p{N}]/) }.each do |value|
91
+ text = "#{text} #{value}".strip unless link_text(text).include?(link_text(value))
92
+ end
93
+ text
94
+ end
95
+
96
+ # Text with each link as the text it shows, to tell a value already shown
97
+ def link_text(text)
98
+ text.gsub(/\[\[(?:[^\[\]|]*\|)?([^\[\]|]*)\]\]/, '\1')
99
+ end
100
+
101
+ # Whether the pattern learned with a named argument shows the call: it
102
+ # keeps the arguments of the call's pattern unless it shows the named one
103
+ # in their place (for a call of fewer arguments, it keeps them whatever it
104
+ # shows), and an argument the call leaves empty is not joined to its text
105
+ def with_fits?(definition, args, pattern, with, name)
106
+ slots = with.scan(/\{(\d+)\}/).flatten
107
+ keeps = (pattern.scan(/\{(\d+)\}/).flatten - slots).empty?
108
+ return false unless keeps || (pattern == definition["p"] && with.include?("{#{name}}"))
109
+
110
+ slots.none? do |slot|
111
+ next false unless slot_value(definition, args, slot).strip.empty?
112
+
113
+ with.scan(/(.)?\{#{slot}\}(.)?/).flatten.compact.any? { |c| !c.match?(/[\s{}()\[\]()「」【】]/) }
114
+ end
115
+ end
116
+
117
+ # The named arguments a call gives in place of its arguments: for each
118
+ # argument, the first of those standing in for it that has a value
119
+ def standing_in(definition, args)
120
+ definition.fetch("replaces", {}).reject { |param, _| args[param].to_s.empty? }
121
+ .group_by { |_, slot| slot }.map { |_, params| params[0][0] }
122
+ end
123
+
124
+ # Named arguments of a call, given a value, other than those that change
125
+ # nothing and those given a value the template reads as off
126
+ def given_named(definition, args)
127
+ ignores = definition.fetch("ignores", [])
128
+ off = definition.fetch("off", {})
129
+ args.named.reject do |name, value|
130
+ value = value.to_s.strip
131
+ value.empty? || ignores.include?(name) || off.fetch(name, []).include?(value)
132
+ end.keys
133
+ end
134
+
135
+ # Named arguments known to be shown or to change the text
136
+ def known_named(definition)
137
+ definition.fetch("shows", []) + definition.fetch("with", {}).keys
138
+ end
139
+
140
+ def fill(definition, args, pattern)
141
+ # Each slot's value is put in as a token first, so that cleaning the
142
+ # pattern's own brackets and spaces never touches what an argument holds
143
+ values = []
144
+ text = pattern.gsub(/\{([^{}]+)\}/) do
145
+ value = slot_value(definition, args, ::Regexp.last_match(1))
146
+ next "" if value.strip.empty?
147
+
148
+ values << value
149
+ "#{TOKEN_OPEN}#{values.size - 1}#{TOKEN_CLOSE}"
150
+ end
151
+ # Brackets left with nothing in them, where an argument was not given
152
+ text = text.gsub(EMPTY_BRACKETS, "").gsub(/ {2,}/, " ").strip
153
+ text.gsub(TOKEN) { values[::Regexp.last_match(1).to_i] }
154
+ end
155
+
156
+ # The value shown in a slot: a named argument given in its place, else the
157
+ # argument itself, else, when that is empty, the one the template shows instead
158
+ def slot_value(definition, args, slot, seen = [])
159
+ return "" if seen.include?(slot)
160
+
161
+ named = definition.fetch("replaces", {}).find { |param, target| target == slot && !args[param].to_s.empty? }
162
+ return args[named[0]].to_s if named
163
+
164
+ value = args[slot].to_s
165
+ other = definition.fetch("fallback", {})[slot]
166
+ value.strip.empty? && other ? slot_value(definition, args, other, seen + [slot]) : value
167
+ end
168
+
169
+ NUMBER = /\A[+\-−]?\d[\d.,\s ']*\z/.freeze
170
+ EMPTY_BRACKETS = /\s*(?:(\s*)|\(\s*\)|\[\s*\]|「\s*」|【\s*】)/
171
+ TOKEN_OPEN = "\u{FDD2}"
172
+ TOKEN_CLOSE = "\u{FDD3}"
173
+ TOKEN = /#{TOKEN_OPEN}(\d+)#{TOKEN_CLOSE}/.freeze
174
+
175
+ # A template name as MediaWiki matches it: spaces for underscores, single
176
+ # spaces, and a capital first letter
177
+ def normalize(name)
178
+ text = name.to_s.tr("_", " ").gsub(/\s+/, " ").strip
179
+ text.empty? ? text : text[0].upcase + text[1..]
180
+ end
181
+ end
182
+ end