Skip to content

Instantly share code, notes, and snippets.

@cmlenz
Created May 29, 2013 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cmlenz/5673821 to your computer and use it in GitHub Desktop.
Save cmlenz/5673821 to your computer and use it in GitHub Desktop.
Update the strings files for an Interface Builder file such as a XIB or a storyboard that uses base localization (a feature added in iOS 6 and OS X 10.8).
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This script can update the localizable strings files for an Interface Builder
file such as a XIB or a storyboard that uses base localization (a feature added
in iOS 6 and OS X 10.8).
You invoke it by passing the path to the IB file, which should sit in a
Base.lproj directory:
updatestrings.py MyProject/Base.lproj/MainStoryboard.storyboard
For every language directory (.lproj) it finds next to the base directory, this
script will first read and store the current translations (keyed by the
original string in the IB file). Then it regenerates the strings files by
invoking `ibtool` with the `--export-strings-file` option. Finally, it attempts
to merge all the translations it found out about in the first step back into the
new strings files.
I'm pretty sure there's room for improvement here. This was a rather quick and
simple hack, but it works a lot better for me than anything else I found. Feel
free to fork and improve.
The MIT License
Copyright Christopher Lenz 2013
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import argparse, io, os, re, sys, subprocess
def escape_quotes(string):
return string.replace('"', '\\"')
def format_comment(info):
return ' '.join('%s = "%s";' % (k, v) for (k, v) in info.items())
comment_re = re.compile(r'^/\*\s*(.+)\s*\*/$')
string_re = re.compile(r'^"(.+?)"\s*=\s*"(.+?)";?$')
def parse_comment(comment):
d = {}
parts = comment.split(';')
for part in parts:
part = part.strip().rstrip(';')
if not part:
continue
name, value = part.split('=')
name = name.strip()
value = value.strip().strip('"')
d[name] = value
return d
def read_strings(filename):
try:
infile = io.open(filename, 'r', encoding='UTF-16')
infile.read(1) # check BOM
except UnicodeError:
infile = io.open(filename, 'r', encoding='UTF-8')
info = None
for line in infile:
if not line:
continue
m = comment_re.match(line)
if m:
info = parse_comment(m.group(1))
continue
m = string_re.match(line)
if m:
ident = m.group(1)
string = m.group(2)
yield ident, string, info
info = None
def process(filepath):
abspath = os.path.abspath(filepath)
basename = os.path.basename(abspath)
dirname = os.path.dirname(abspath)
if os.path.basename(dirname).lower() != 'base.lproj':
raise Exception, '%s must be set up for base localization' % basename
basepath = os.path.dirname(dirname)
for lprojdir in [n for n in os.listdir(basepath) if n.endswith('.lproj')]:
if lprojdir.lower() == 'base.lproj':
continue
lang = os.path.splitext(lprojdir)[0]
strings_path = os.path.join(basepath, lprojdir,
os.path.splitext(basename)[0] + '.strings')
translations = {}
print 'Processing %s' % strings_path
if os.path.exists(strings_path):
for ident, string, info in read_strings(strings_path):
obj_id, propname = ident.split('.')
if propname in info:
origstr = info[propname]
translations[origstr] = string
os.rename(strings_path, strings_path + '.old')
subprocess.check_call(['ibtool', '--export-strings-file', strings_path,
abspath])
results = []
for ident, string, info in read_strings(strings_path):
obj_id, propname = ident.split('.')
if propname in info:
origstr = info[propname]
string = translations.get(origstr, string)
results.append((ident, string, info))
with io.open(strings_path, 'w', encoding='UTF-8') as outfile:
for ident, string, info in results:
outfile.write(u'/* %s */\n' % format_comment(info))
outfile.write(u'"%s" = "%s";\n' % (escape_quotes(ident),
escape_quotes(string)))
outfile.write(u'\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Update .strings files from '
'XIB or storyboard using base '
'localization')
parser.add_argument('path', metavar='FILE',
help='path to the XIB or storyboard file')
args = parser.parse_args()
process(args.path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment