Class: I18nContextGenerator::Writers::AndroidXmlWriter

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/i18n_context_generator/writers/android_xml_writer.rb

Overview

Writer that updates Android strings.xml files with context comments Uses line-by-line approach to preserve original formatting

Instance Method Summary collapse

Methods included from Helpers

#find_swift_files, #result_matches_source_path?, #skip_description?, #writable_result?

Constructor Details

#initialize(context_prefix: 'Context: ', context_mode: 'replace') ⇒ AndroidXmlWriter

Returns a new instance of AndroidXmlWriter.



13
14
15
16
# File 'lib/i18n_context_generator/writers/android_xml_writer.rb', line 13

def initialize(context_prefix: 'Context: ', context_mode: 'replace')
  @context_prefix = context_prefix
  @context_mode = context_mode
end

Instance Method Details

#write(results, source_path) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/i18n_context_generator/writers/android_xml_writer.rb', line 18

def write(results, source_path)
  return unless File.exist?(source_path)

  original_content = File.binread(source_path)
  lines = File.readlines(source_path, encoding: 'UTF-8')
  results_by_key = build_results_lookup(results, source_path)
  return false unless results_by_key.values.any? { |result| writable_result?(result) }

  output_lines = []
  i = 0

  while i < lines.length
    line = lines[i]

    # Only write comments on <string> elements, not <plurals> or <string-array>.
    # Plural/array parent comments would use a single child's description which
    # is misleading for the resource as a whole.
    # Match the complete opening tag so attribute order, quote style, and
    # multiline attributes do not affect write-back.
    if (element = string_element_at(lines, i))
      indent = element[:indent]
      key = element[:key]
      result = results_by_key[key]

      insert_context_comment(output_lines, indent, result.description) if writable_result?(result)
    end

    output_lines << line
    i += 1
  end

  rendered = output_lines.join
  return false if rendered == original_content

  AtomicFile.replace(source_path, rendered) do |candidate_path|
    REXML::Document.new(File.read(candidate_path, encoding: 'UTF-8'))
  end
  true
end