Skip to content

Instantly share code, notes, and snippets.

@hartbit
Created July 24, 2014 12:37
Show Gist options
  • Save hartbit/803a4856f6952408d3ae to your computer and use it in GitHub Desktop.
Save hartbit/803a4856f6952408d3ae to your computer and use it in GitHub Desktop.
Script to update Storyboard localisation strings in Base Internalization for Xcode
#!/usr/bin/ruby
#
# update_storyboard_strings.rb - automatically extract translatable strings from storyboards and update strings files
# Based on:
# - http://forums.macrumors.com/showpost.php?p=16060008&postcount=4 by mikezang
# - http://oleb.net/blog/2013/02/automating-strings-extraction-from-storyboards-for-localization/ by Ole Begemann
require 'Tempfile'
Dir.glob('**/Base.lproj/*.storyboard') do |storyboard_path|
strings_filename = File.basename(storyboard_path, '.*') + '.strings'
lproj_rootdir = File.dirname(File.dirname(storyboard_path))
strings_paths = Dir.glob("#{lproj_rootdir}/*.lproj/#{strings_filename}")
strings_maxtime = strings_paths.map{ |path| File.mtime(path) }.max
unless File.mtime(storyboard_path) > strings_maxtime then
puts "#{storyboard_path}: no changes, doing nothing"
next
end
new_strings_path = Dir::Tmpname.create('') {}
unless system("ibtool --export-strings-file #{new_strings_path} #{storyboard_path}") then
puts "Exiting due to ibtool error. Please run `killall -9 ibtoold` and try again."
exit(1)
end
new_strings_converted_path = Dir::Tmpname.create('') {}
system("iconv -f UTF-16 -t UTF-8 #{new_strings_path} > #{new_strings_converted_path}")
new_strings_lines = IO.readlines(new_strings_converted_path, encoding: "utf-8")
File.delete(new_strings_path)
File.delete(new_strings_converted_path)
strings_regexp = /\s*"([^\"]*)"\s*=\s*"([^\"]*)"\s*;\s*/
strings_paths.each do |strings_path|
puts "#{storyboard_path}: writing to #{strings_path}"
old_strings_hash = Hash.new
File.open(strings_path, 'r:UTF-8').each_line do |line|
if match = strings_regexp.match(line) then
old_strings_hash[match[1]] = match[2]
end
end
strings_tmppath = Dir::Tmpname.create('') {}
File.open(strings_tmppath, 'w:UTF-8') do |file|
new_strings_lines.each do |line|
if match = strings_regexp.match(line) then
if old_translation = old_strings_hash[match[1]] then
line.sub!(/(\s*"[^\"]*"\s*=\s*")[^\"]*("\s*;\s*)/, '\1' + old_translation + '\2')
end
end
file.puts line
end
end
FileUtils.mv(strings_tmppath, strings_path)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment