Class: Fastlane::Actions::GoogleSheetLocalizeAction

Inherits:
Action
  • Object
show all
Defined in:
lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb

Class Method Summary collapse

Class Method Details

.authorsObject



545
546
547
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 545

def self.authors
  ["Mario Hahn", "Thomas Koller"]
end

.available_optionsObject



558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 558

def self.available_options
  [
    FastlaneCore::ConfigItem.new(key: :service_account_path,
                            env_name: "SERVICE_ACCOUNT_PATH",
                         description: "Credentials path",
                            optional: false,
                                type: String),
     FastlaneCore::ConfigItem.new(key: :sheet_id,
                             env_name: "SHEET_ID",
                          description: "Your Google-spreadsheet id",
                             optional: false,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :platform,
                            env_name: "PLATFORM",
                         description: "Platform, ios or android",
                            optional: true,
                       default_value: Actions.lane_context[Actions::SharedValues::PLATFORM_NAME].to_s,
               default_value_dynamic: true,
                                type: String),
    FastlaneCore::ConfigItem.new(key: :tabs,
                            env_name: "TABS",
                         description: "Array of all Google Sheet Tabs",
                         default_value: [],
                            optional: true,
                                type: Array),
    FastlaneCore::ConfigItem.new(key: :language_titles,
                            env_name: "LANGUAGE_TITLES",
                         description: "Alle language titles",
                            optional: false,
                                type: Array),
    FastlaneCore::ConfigItem.new(key: :default_language,
                            env_name: "DEFAULT_LANGUAGE",
                         description: "Default Language",
                            optional: true,
                                type: String),
    FastlaneCore::ConfigItem.new(key: :comment_example_language,
                            env_name: "COMMENT_EXAMPLE_LANGUAGE",
                         description: "Comment Example Language",
                            optional: true,
                                type: String),
    FastlaneCore::ConfigItem.new(key: :base_language,
                            env_name: "BASE_LANGUAGE",
                         description: "Base language for Xcode projects",
                            optional: true,
                                type: String),
    FastlaneCore::ConfigItem.new(key: :localization_path,
                            env_name: "LOCALIZATION_PATH",
                         description: "Output path",
                            optional: false,
                                type: String),
    FastlaneCore::ConfigItem.new(key: :identifier_name,
                            env_name: "IDENTIFIER_NAME",
                         description: "Identifier for Platform",
                            optional: true,
                                type: String),
    FastlaneCore::ConfigItem.new(key: :code_generation_path,
                            env_name: "CODEGENERATIONPATH",
                         description: "Code generation path for the Swift file",
                            optional: true,
                                type: String)
  ]
end

.createComment(comment, example) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 236

def self.createComment(comment, example) 

  if comment.to_s.empty?
    return %Q(
    /**
    - Example:
    ````
    #{example}
    ````
    */
    )
  end

return %Q(
    /**
    - Sheet comment:
    ````
    #{comment}
    ````
    - Example:
    ````
    #{example}
    ````
    */
    )
end

.createFiles(languages, platform, destinationPath, defaultLanguage, base_language, codeGenerationPath, comment_example_language) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 134

def self.createFiles(languages, platform, destinationPath, defaultLanguage, base_language, codeGenerationPath, comment_example_language)
    self.createFilesForLanguages(languages, platform, destinationPath, defaultLanguage, base_language)

    if platform == "web"
      jsonFileName = "Localization.json"

      jsonFilepath = "#{destinationPath}/#{jsonFileName}"

      File.open(jsonFilepath, "w") do |f|

        jsonItem = {}

        languages.each { |language|
          filteredItems = self.filterUnusedRows(language["items"],'identifier', "true")

          allKeys = {}

          filteredItems.each { |item|
            identifier = item['identifier']

            text = item['text']

            matches = text.scan(/%[0-9][sdf]/)
            matches.each { |match|
              text = text.gsub(match, "{#{match[1]}}")
            }

            if !identifier.include?('//')
              allKeys[identifier] = text
            end
          }
          jsonItem[language["language"]] = allKeys
        }

        jsonString = JSON.pretty_generate(jsonItem)
        f.write(jsonString)
      end
    end

    if platform == "ios"

      swiftFilename = "Localization.swift"

      swiftPath = codeGenerationPath

      if codeGenerationPath.to_s.empty?
        swiftPath = destinationPath
      end

      languageItems = languages.select { |item| item["language"] == comment_example_language }.first

      filteredItems = self.filterUnusedRows(languageItems["items"],'identifier', "true")

      swiftFilepath = "#{swiftPath}/#{swiftFilename}"

      File.open(swiftFilepath, "w") do |f|
        f.write("import Foundation\n\n// swiftlint:disable all\npublic struct Localization {\n")
        filteredItems.each { |item|

          identifier = item['identifier']

          values = identifier.dup.split(".")

          constantName = ""

          values.each_with_index do |item, index|
            if index == 0
              item[0] = item[0].downcase
              constantName += item
            else
              item[0] = item[0].upcase
              constantName += item
            end
          end

          if constantName == "continue"
            constantName = "`continue`"
          end

          if constantName == "switch"
            constantName = "`switch`"
          end

          text = self.mapInvalidPlaceholder(item['text'])

          arguments = self.findArgumentsInText(text)

          if arguments.count == 0
            f.write(self.createComment(item['comment'], item['text']))
            f.write("public static let #{constantName} = localized(identifier: \"#{identifier}\")\n")
          else
            f.write(self.createComment(item['comment'], item['text']))
            f.write(self.createiOSFunction(constantName, identifier, arguments))
          end
        }
        f.write("\n}")
        f.write(self.createiOSFileEndString(destinationPath))
      end

    end
end

.createFilesForLanguages(languages, platform, destinationPath, defaultLanguage, base_language) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 263

def self.createFilesForLanguages(languages, platform, destinationPath, defaultLanguage, base_language)

  languages.each { |language|

  if platform == "ios"

    filteredItems = self.filterUnusedRows(language["items"],'identifier', "false")

    stringFileName = "Localizable.strings"
    pluralsFileName = "Localizable.stringsdict"

    languageName = language['language']

    if languageName == base_language
      languageName = "Base"
    end

    stringFilepath = "#{destinationPath}/#{languageName}.lproj/#{stringFileName}"
    pluralsFilepath = "#{destinationPath}/#{languageName}.lproj/#{pluralsFileName}"
    FileUtils.mkdir_p "#{destinationPath}/#{languageName}.lproj"

    File.open(stringFilepath, "w") do |f|
      filteredItems.each_with_index { |item, index|

        text = self.mapInvalidPlaceholder(item['text'])
        comment = item['comment']
        identifier = item['identifier']

        line = ""
        if identifier.include?('//')
          line = "\n\n#{identifier}\n"
        else

          if !text.include?("one|")

            if (text == "" || text == "TBD") && !defaultLanguage.to_s.empty?
              default_language_object = languages.select { |languageItem| languageItem['language'] == defaultLanguage }.first["items"]
              default_language_object = self.filterUnusedRows(default_language_object,'identifier', "false")

              defaultLanguageText = default_language_object[index]['text']
              puts "found empty text for:\n\tidentifier: #{identifier}\n\tlanguage:#{language['language']}\n\treplacing it with: #{defaultLanguageText}"
              text = self.mapInvalidPlaceholder(defaultLanguageText)
            end

            matches = text.scan(/%[0-9][sdf]/)

            matches.each { |match|
              text = text.gsub(match, "%#{match[1]}$#{match[2].gsub("s","@")}")
            }

            line = "\"#{identifier}\" = \"#{text}\";"
            if !comment.to_s.empty?
              line = line + " //#{comment}\n"
            else
              line = line + "\n"
            end
          end
        end
        f.write(line)
      }
    end

    File.open(pluralsFilepath, "w") do |f|

      f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
      f.write("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n")
      f.write("<plist version=\"1.0\">\n")
      f.write("<dict>\n")

      filteredItems.each_with_index { |item, index|

        text = self.mapInvalidPlaceholder(item['text'])
        identifier = item['identifier']

        if !identifier.include?('//') && text.include?("one|")
          if (text == "" || text == "TBD") && !defaultLanguage.to_s.empty?
            default_language_object = languages.select { |languageItem| languageItem['language'] == defaultLanguage }.first["items"]
            default_language_object = self.filterUnusedRows(default_language_object,'identifier', "false")

            defaultLanguageText = default_language_object[index]['text']
            puts "found empty text for:\n\tidentifier: #{identifier}\n\tlanguage:#{language['language']}\n\treplacing it with: #{defaultLanguageText}"
            text = self.mapInvalidPlaceholder(defaultLanguageText)
          end

          text = text.gsub("\n", "|")

          formatIdentifier = identifier.gsub(".", "")

          f.write("\t\t<key>#{identifier}</key>\n")
          f.write("\t\t<dict>\n")
          f.write("\t\t\t<key>NSStringLocalizedFormatKey</key>\n")
          f.write("\t\t\t<string>%#@#{formatIdentifier}@</string>\n")
          f.write("\t\t\t<key>#{formatIdentifier}</key>\n")
          f.write("\t\t\t<dict>\n")
          f.write("\t\t\t\t<key>NSStringFormatSpecTypeKey</key>\n")
          f.write("\t\t\t\t<string>NSStringPluralRuleType</string>\n")
          f.write("\t\t\t\t<key>NSStringFormatValueTypeKey</key>\n")
          f.write("\t\t\t\t<string>d</string>\n")

          text.split("|").each_with_index { |word, wordIndex|
            if wordIndex % 2 == 0
              f.write("\t\t\t\t<key>#{word}</key>\n")
            else
              f.write("\t\t\t\t<string>#{word}</string>\n")
            end
          }
          f.write("\t\t\t</dict>\n")
          f.write("\t\t</dict>\n")
        end
      }
      f.write("</dict>\n")
      f.write("</plist>\n")
    end
  end

  if platform == "android"
    languageDir = language['language']

    if languageDir == base_language
      languageDir = "values"
    else
      languageDir = "values-#{languageDir}"
    end

    FileUtils.mkdir_p "#{destinationPath}/#{languageDir}"
    File.open("#{destinationPath}/#{languageDir}/strings.xml", "w") do |f|
      f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
      f.write("<resources>\n")

      filteredItems = self.filterUnusedRows(language["items"],'identifier', "false")

      filteredItems.each_with_index { |item, index|

        comment = item['comment']
        identifier = item['identifier']
        text = item['text']

        line = ""

        if !comment.to_s.empty?
          line = line + "\t<!--#{comment}-->\n"
        end

        if (text == "" || text == "TBD") && !defaultLanguage.to_s.empty?
          default_language_object = languages.select { |languageItem| languageItem['language'] == defaultLanguage }.first["items"]
          default_language_object = self.filterUnusedRows(default_language_object,'identifier', "false")

          defaultLanguageText = default_language_object[index]['text']
          puts "found empty text for:\n\tidentifier: #{identifier}\n\tlanguage:#{language['language']}\n\treplacing it with: #{defaultLanguageText}"
          text = defaultLanguageText
        end

        text = text.gsub(/\\?'/, "\\\\'")

        if text.include?("one|")

          text = text.gsub("\n", "|")

          line = line + "    <plurals name=\"#{identifier}\">\n"

          plural = ""

          text.split("|").each_with_index { |word, wordIndex|
            if wordIndex % 2 == 0
              plural = "        <item quantity=\"#{word}\">"
            else
              plural = plural + "<![CDATA[#{word}]]></item>\n"
              line = line + plural
            end
          }
          line = line + "    </plurals>\n"
        elsif text.start_with?("[\"") && text.end_with?("\"]")

          line = line + "    <string-array name=\"#{identifier}\">\n"

          JSON.parse(text).each { |arrayItem|
            line = line + "        <item><![CDATA[#{arrayItem}]]></item>\n"
          }

          line = line + "    </string-array>\n"
        else
          line = line + "    <string name=\"#{identifier}\"><![CDATA[#{text}]]></string>\n"
        end

        f.write(line)
      }
      f.write("</resources>\n")
    end
  end
  }
end

.createiOSFileEndString(destinationPath) ⇒ Object



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 455

def self.createiOSFileEndString(destinationPath)

  bundle = "let bundle = Bundle(for: LocalizationHelper.self)"

  puts destinationPath

  if destinationPath.include?(".bundle")

    bundle = %Q(let bundleUrl = Bundle(for: LocalizationHelper.self).url(forResource: "#{destinationPath.split('/').last.gsub(".bundle", "")}", withExtension: "bundle")
  \n\t\tlet bundle = Bundle(url: bundleUrl!))
  end

  return %Q(
  \n\nprivate class LocalizationHelper { }
  \n\nextension Localization {
  \n\tprivate static func localized(identifier key: String, _ args: CVarArg...) -> String {
  \n\t\t#{bundle}
  \n\t\tlet format = NSLocalizedString(key, tableName: nil, bundle: bundle, comment: \"\")
  \n\t\tguard !args.isEmpty else { return format }
  \n\t\treturn String(format: format, locale: .current, arguments: args)
  \n\t}
  \n})
end

.createiOSFunction(constantName, identifier, arguments) ⇒ Object



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 479

def self.createiOSFunction(constantName, identifier, arguments)
    functionTitle = "public static func #{constantName}("

    arguments.each_with_index do |item, index|
      functionTitle = functionTitle + "_ arg#{index}: #{item[:type]}"
      if index < arguments.count - 1
        functionTitle = functionTitle + ", "
      else
        functionTitle = functionTitle + ") -> String {\n"
      end
    end
    functionTitle = functionTitle + "\t\treturn localized(identifier: \"#{identifier}\", "
    arguments.each_with_index do |item, index|
      functionTitle = functionTitle + "arg#{index}"
      if index < arguments.count - 1
        functionTitle = functionTitle + ", "
      else
        functionTitle = functionTitle + ")\n\t}"
      end
    end

    return functionTitle
end

.descriptionObject



541
542
543
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 541

def self.description
  "Creates .strings files for iOS and strings.xml files for Android"
end

.detailsObject



553
554
555
556
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 553

def self.details
  # Optional:
  "Creates .strings files for iOS and strings.xml files for Android. The localization is mananged on a google sheet."
end

.filterUnusedRows(items, identifier, filterComment) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 119

def self.filterUnusedRows(items, identifier, filterComment)
  filtered = items.select { |item|
      currentIdentifier = item[identifier]
      currentIdentifier != "NR" && currentIdentifier != "" && currentIdentifier != "TBD"
  }
  
  if filterComment == "false" 
     return filtered
  end

  return filtered.select { |item|
      !item[identifier].include?('//')
  }
end

.findArgumentsInText(text) ⇒ Object



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 503

def self.findArgumentsInText(text)

  if text.include?("one|")
    text = text.dup.split("|")[1]
  end

  result = Array.new
  filtered = self.mapInvalidPlaceholder(text)

  stringIndexes = filtered.scan(/%[0-9]?[s@]/)
  intIndexes = filtered.scan(/%[0-9]?[d]/)
  floatIndexes = filtered.scan(/%[0-9]?[f]/)
  doubleIndexes = filtered.scan(/%[0-9]?ld/)

  if stringIndexes.count > 0
    result = result.concat(stringIndexes.map { |e| { "index": e, "type": "String" }})
  end

  if intIndexes.count > 0
    result = result.concat(intIndexes.map { |e| { "index": e, "type": "Int" }})
  end

  if floatIndexes.count > 0
    result = result.concat(floatIndexes.map { |e| { "index": e, "type": "Float" }})
  end

  if doubleIndexes.count > 0
    result = result.concat(doubleIndexes.map { |e| { "index": e, "type": "Double" }})
  end

  return result
end

.generateJSONObject(contentRows, index, identifierIndex) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 91

def self.generateJSONObject(contentRows, index, identifierIndex)
    result = Array.new
    for i in 0..contentRows.count - 1
        item = self.generateSingleObject(contentRows[i], index, identifierIndex)

        if item[:identifier] != ""
          result.push(item)
        end
    end

    return result

end

.generateSingleObject(row, column, identifierIndex) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 105

def self.generateSingleObject(row, column, identifierIndex)
  identifier = row[identifierIndex]

  text = row[column]
  comment = row.last

  object = { 'identifier' => identifier,
             'text' => text,
             'comment' => comment
  }
  return object

end

.is_supported?(platform) ⇒ Boolean

Returns:

  • (Boolean)


621
622
623
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 621

def self.is_supported?(platform)
   [:ios, :mac, :android].include?(platform)
end

.mapInvalidPlaceholder(text) ⇒ Object



536
537
538
539
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 536

def self.mapInvalidPlaceholder(text)
  filtered = text.gsub('%s', '%@').gsub('"', '\"')
  return filtered
end

.return_valueObject



549
550
551
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 549

def self.return_value
  # If your method provides a return value, you can describe here what it does
end

.run(params) ⇒ Object



10
11
12
13
14
15
16
17
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/fastlane/plugin/google_sheet_localize/actions/google_sheet_localize_action.rb', line 10

def self.run(params)

  session = ::GoogleDrive::Session.(params[:service_account_path])
  spreadsheet_id = "https://docs.google.com/spreadsheets/d/#{params[:sheet_id]}"
  tabs = params[:tabs]
  platform = params[:platform]
  path = params[:localization_path]
  language_titles = params[:language_titles]
  default_language = params[:default_language]
  base_language = params[:base_language]
  code_generation_path = params[:code_generation_path]
  identifier_name = params[:identifier_name]
  comment_example_language = params[:comment_example_language]

  if identifier_name.to_s.empty?
    if platform == "ios"
      identifier_name = "Identifier iOS"
    end
    if platform == "android"
      identifier_name = "Identifier Android"
    end
    if platform == "web"
      identifier_name = "Identifier Web"
    end
  end

  if comment_example_language.to_s.empty?
    comment_example_language = default_language
  end

  spreadsheet = session.spreadsheet_by_url(spreadsheet_id)

  filterdWorksheets = []

  if tabs.count == 0
    filterdWorksheets = spreadsheet.worksheets
  else
    filterdWorksheets = spreadsheet.worksheets.select { |item| tabs.include?(item.title) }
  end

  result = []
  
  filterdWorksheets.each { |worksheet|

    identifierIndex = 0

    for i in 0..worksheet.max_cols
      if worksheet.rows[0][i] == identifier_name
        identifierIndex = i
      end
    end

    for i in 0..worksheet.max_cols

      title = worksheet.rows[0][i]

      if language_titles.include?(title)

        language = result.select { |item| item['language'] == title }.first

        if language.nil?
          language = {
            'language' => title,
            'items' => []
          }
        end

        contentRows = worksheet.rows.drop(1)

        items = language['items']
        items = items + self.generateJSONObject(contentRows, i, identifierIndex)

        language['items'] = items

        result.push(language)
      end
    end
}
self.createFiles(result, platform, path, default_language, base_language, code_generation_path, comment_example_language)
end