forked from KeepSafe/genstrings_swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
genstrings_swift.py
executable file
·92 lines (71 loc) · 2.62 KB
/
genstrings_swift.py
1
2
3
4
5
6
7
8
9
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
90
91
92
import re
import os
import io
import argparse
from collections import namedtuple
OUTPUT_FILE = 'Localizable_swift.strings'
OUTPUT_ENCODING = 'utf-16'
OUTPUT_LINE_PATTERN = u'/* {comment} */\n"{key}" = "{value}";\n\n'
EMPTY_COMMENT = u'No comment provided by engineer.'
string_pattern = re.compile('NSLocalizedString\(\s*(.+)\)', re.MULTILINE)
empty_pattern = re.compile('"([^"]*)"')
key_pattern = re.compile('key:\s*"([^"]*)"')
value_pattern = re.compile('value:\s*"([^"]*)"')
comment_pattern = re.compile('comment:\s*"([^"]*)"')
var_pattern = re.compile('%(.)')
String = namedtuple('String', ['key', 'value', 'comment'])
def read_cmd():
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', help='Command output directory', default='.')
parser.add_argument('filepaths', help='file(s) to generate strings from', type=argparse.FileType('r'), nargs='+')
args = parser.parse_args()
return args
def replace_vars(value):
var_result = list(var_pattern.finditer(value))
if len(var_result) > 1:
for idx, result in enumerate(var_result):
value = value.replace(result.group(0), '%{}${}'.format(idx + 1, result.group(1)), 1)
return value
def generate_string(params):
key_result = key_pattern.search(params)
if key_result:
key = key_result.group(1)
else:
key_result = empty_pattern.match(params)
if key_result:
key = key_result.group(1)
else:
print("can't resolve parameters for %s" % match.group(0))
value_result = value_pattern.search(params)
if value_result:
value = value_result.group(1)
else:
value = key
value = replace_vars(value)
comment_result = comment_pattern.search(params)
if comment_result:
comment = comment_result.group(1) or EMPTY_COMMENT
else:
comment = EMPTY_COMMENT
return String(key, value, comment)
def grep_file(filepaths):
strings = []
for filepath in filepaths:
with io.open(filepath.name, encoding='utf-8') as fp:
content = fp.read()
for match in string_pattern.finditer(content):
params = match.group(1)
string = generate_string(params)
strings.append(string)
return strings
def save_strings(output_dir, strings):
filepath = os.path.join(output_dir, OUTPUT_FILE)
with io.open(filepath, 'w', encoding=OUTPUT_ENCODING) as fp:
output_lines = map(lambda s: OUTPUT_LINE_PATTERN.format(**s._asdict()), strings)
fp.writelines(output_lines)
def main():
args = read_cmd()
strings = grep_file(args.filepaths)
save_strings(args.output, strings)
if __name__ == '__main__':
main()