Class: I18nContextGenerator::Parsers::XcstringsParser

Inherits:
Base
  • Object
show all
Defined in:
lib/i18n_context_generator/parsers/xcstrings_parser.rb

Overview

Parser for Apple string catalogs. Context generation is keyed by the catalog entry rather than by individual target-language localizations.

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

for

Class Method Details

.validate_catalog!(catalog, path:) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/i18n_context_generator/parsers/xcstrings_parser.rb', line 33

def self.validate_catalog!(catalog, path:)
  raise TypeError, 'root must be a mapping' unless catalog.is_a?(Hash)
  raise TypeError, 'sourceLanguage must be a non-empty string' unless nonempty_string?(catalog['sourceLanguage'])
  raise TypeError, 'strings must be a mapping' unless catalog['strings'].is_a?(Hash)

  valid_entries = catalog['strings'].all? { |key, entry| key.is_a?(String) && entry.is_a?(Hash) }
  raise TypeError, 'strings must map string keys to entries' unless valid_entries

  catalog
rescue TypeError => e
  raise Error, "Failed to parse Apple string catalog #{path}: #{e.message}"
end

Instance Method Details

#parse(path) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/i18n_context_generator/parsers/xcstrings_parser.rb', line 8

def parse(path)
  catalog = load_catalog(path)
  source_language = catalog['sourceLanguage']

  catalog.fetch('strings').filter_map do |key, entry|
    next if key.empty?
    next if entry['shouldTranslate'] == false

    TranslationEntry.new(
      key: key,
      text: source_text(key, entry, source_language),
      source_file: path,
      metadata: {
        comment: entry['comment'],
        source_language: source_language,
        resource_type: :string
      }.compact
    )
  end
rescue KeyError => e
  raise Error, "Failed to parse Apple string catalog #{path}: missing #{e.key.inspect}"
rescue Oj::ParseError, TypeError => e
  raise Error, "Failed to parse Apple string catalog #{path}: #{e.message}"
end