I need to print the keys of Localizable.strings in my App, instead of their values (for a debugging purpose). Is there a fast way to override the NSLocalizedString() method or redefine the macro, something like:
#define NSLocalizedString(key, comment) NSLocalizedString(key, key)
CodePudding user response:
One option would be to export your app for localizations via Product Menu > Export Localizations within Xcode, then save the xcloc file to your Desktop.
After which you could use a python script to parse the inner xliff (xml) to find the file elements with original
attributes which contain Localizable.strings
and print the trans-unit
's source
element text within the body of them. Here's an example of a python script which should do it localizationKeys.py:
import sys
import os.path
from xml.etree import ElementTree as et
import argparse as ap
import re
if __name__ == '__main__':
parser = ap.ArgumentParser()
# filename argument ex: de.xliff
parser.add_argument('filename', help="filename of the xliff to find keys ex:de.xliff")
# verbose flag
parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Show all the output')
args = parser.parse_args()
if (os.path.isfile(args.filename)):
tree = et.parse(args.filename)
root = tree.getroot()
match = re.match(r'\{.*\}', root.tag)
ns = match.group(0) if match else ''
files = root.findall(ns 'file')
for file in files:
originalAttr = file.attrib['original']
# find all files which contain Localizable.strings
if originalAttr != None and 'Localizable.strings' in originalAttr:
if args.verbose == True:
print("----- Localizations for file: " originalAttr " -----")
# grab the body element
bodyElement = file.find(ns 'body')
# get all the trans-units
transUnits = bodyElement.findall(ns 'trans-unit')
for transUnit in transUnits:
# print all the source values (keys)
print(transUnit.find(ns 'source').text)
else:
print("No file found with the specified name: " args.filename)
Which you could then use as follows:
python3 localizationKeys.py en.xcloc/Localized\ Contents/en.xliff
Or if you'd prefer to print to to a file instead
python3 localizationKeys.py en.xcloc/Localized\ Contents/en.xliff > output.txt
This could almost definitely be more concise using xpath
instead, but this is just what I came up with quickly.
CodePudding user response:
Ok, this is how I obtained what I needed
// Overriding NSLocalizedString to print keys instead of values
#ifdef NSLocalizedString
#undef NSLocalizedString
#endif
#define NSLocalizedString(key, comment) key
In this way the App use the keys instead of the values