Skip to content

Instantly share code, notes, and snippets.

@paour
Forked from ben-efiz/gist:4494099
Last active September 23, 2024 00:24
Show Gist options
  • Save paour/11291062 to your computer and use it in GitHub Desktop.
Save paour/11291062 to your computer and use it in GitHub Desktop.
#! /usr/bin/python
import argparse
import os.path
import glob
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''\
Replacing values in arrays.xml with @string/ links. Generates three new files for each locale:
strings.xml (edited strings.xml containing the only the actual strings) and
string_arrays.xml (contains string-arrays pointing to the strings, don\'t localize)
strings.xml.bak (original strings.xml file)''',
epilog='''\
Run from the root of your project to automatically handle all languages (if the translations
are in an inconsistent state, no effort is made to fix them)'''
)
parser.add_argument('-i', '--input', help='Input file, e.g. strings.xml', metavar='FILE', default='strings.xml')
parser.add_argument('-p', '--prefix', help='Optional prefix added to each new string key, e.g. array_')
parser.add_argument('-o', '--output', help='Optional name to use instead of string-arrays.xml', default='string-arrays.xml')
args = vars(parser.parse_args())
xmlString = ' <string name=\"{0}\">{1}</string>'
xmlStringLink = '@string/'
xmlComment = ' <!-- {0} -->'
xmlHeader = '<?xml version=\'1.0\' encoding=\'UTF-8\'?>'
xmlResourcesBegin = '<resources>'
xmlResourcesEnd = '</resources>'
input_filename = args['input']
prefix = args['prefix']
if prefix is None:
prefix = ''
def convert(parent, input_file):
backup_file = parent + input_file + '.bak'
os.rename(parent + input_file, backup_file)
current = ''
num = 0
# input file
fi = open(backup_file)
# output file: transform string-arrays into lists of strings
fo = open(parent + input_file, 'w')
# string-array file: put string-arrays here, with references to the actual strings,
# but only for the main language
if parent == '' or parent.endswith('values/'):
# put string-arrays here
string_array_file = parent + args['output']
if os.path.isfile(string_array_file):
# append, except for closing tag
os.rename(string_array_file, string_array_file + '.bak')
fab = open(string_array_file + '.bak', 'r')
fa = open(string_array_file, 'w')
for l in iter(fab):
line = l.lstrip().rstrip()
if not line.startswith(xmlResourcesEnd):
fa.write(l)
else:
fa = open(string_array_file, 'w')
fa.write(xmlHeader)
fa.write('\n')
fa.write(xmlResourcesBegin)
fa.write('\n')
else:
fa = None
# process each line
for l in iter(fi):
line = l.lstrip().rstrip()
if line.startswith('<string-array name=\"') and line.endswith('\">'):
if fa:
fa.write(l)
# remember array name for new strings
current = line[20:-2]
num = 0
fo.write(xmlComment.format(current))
fo.write('\n')
elif line.startswith('<item>') and line.endswith('</item>') and current:
strKey = prefix + current + '_' + str(num)
strValue = line[6:-7] # replace with string link
if fa:
fa.write(l.replace(strValue, xmlStringLink + strKey)) # generate new strings
fo.write(xmlString.format(strKey, strValue))
fo.write('\n')
num += 1
elif line.startswith('</string-array>'):
del current
if fa:
fa.write(l)
else:
fo.write(l)
fi.close()
fo.close()
if fa:
fa.write(xmlResourcesEnd)
fa.close()
if os.path.isfile('res/values/' + input_filename):
print 'At root of project, will process all languages'
for parent_dir in glob.glob('res/values-*/') + ['res/values/']:
if os.path.isfile(parent_dir + input_filename):
convert(parent_dir, input_filename)
elif not os.path.isfile(input_filename):
print 'File not found'
exit(1)
else:
convert('', input_filename)
@paour
Copy link
Author

paour commented Apr 28, 2014

Updated to correctly append to string-arrays file when it's non-empty to start with

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment