-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalizeit.py
executable file
·219 lines (177 loc) · 5.94 KB
/
localizeit.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/python
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
from oauth2client import tools
from oauth2client import clientsecrets
import httplib2
import gspread
import argparse
import localizable
import os
import io
import json
import re
REDIRECT_URI = 'http://localhost/'
SCOPE = 'https://spreadsheets.google.com/feeds'
APP_NAME = 'localizeit'
IOS_KEY_COL = 0
AND_KEY_COL = 1
IOS_COM_COL = 2
AND_COM_COL = 3
FR_COL = 4
EN_COL = 5
ES_COL = 6
def log(string):
print(string)
def clean_value(value):
return value.replace('\n', '\\n')
def parse_row(args, row):
return {
'comment': row[IOS_COM_COL],
'keys': {
'ios': row[IOS_KEY_COL],
'android': row[AND_KEY_COL]
},
'values': {
'fr': clean_value(row[FR_COL]),
'en': clean_value(row[EN_COL]),
'es': clean_value(row[ES_COL])
}
}
def build_languages_dict(args):
return {
'fr': '',
'en': '',
'es': ''
}
def get_format_string(platform):
if 'ios' == platform:
return u'/* {comment} */\n"{key}" = "{value}";\n\n'
if 'android' == platform:
return u'\t<string name="{key}">{value}</string>\n'
return ''
def build_entry_from_row(args, lang, row_dict):
format_str = get_format_string(args.platform)
value = row_dict['values'][lang]
if args.platform == 'android':
value = value.replace("'", r"\'")
value = value.replace("&", "&")
value = value.replace("$@", "$s")
if '%' in value:
value = re.sub('%(?!\d)', '\%%', value)
if value == '':
value = '__MISSING__'
key = row_dict['keys'][args.platform]
if key == '':
return None
entry = format_str.format(
comment=row_dict['comment'],
key=key,
value=value)
return entry
def parse_worksheet(args, worksheet):
rows = worksheet.get_all_values()
result_dict = build_languages_dict(args)
row_count = 1
for row in rows:
# Skip header row
if row_count == 1:
row_count += 1
continue
row_dict = parse_row(args, row)
for lang_key in result_dict:
entry = build_entry_from_row(args, lang_key, row_dict)
if entry is None:
continue
result_dict[lang_key] += entry
row_count += 1
return result_dict
def create_if_not_exists(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def build_filepath(args, lang):
if 'ios' == args.platform:
output_dir = args.output + '/' + lang + '.lproj'
create_if_not_exists(output_dir)
return output_dir + '/Localizable.strings'
if 'android' == args.platform:
output_dir = ''
if 'en' == lang:
output_dir = args.output + '/values'
else:
output_dir = args.output + '/values-' + lang
create_if_not_exists(output_dir)
return output_dir + '/strings.xml'
raise Exception('Unsupported platform')
def generate(args):
log('GENERATE')
platform = args.platform
output_base_dir = args.output
spreadsheet_name = args.spreadsheet
client = authorize(args)
spreadsheet = client.open(spreadsheet_name)
worksheet = spreadsheet.sheet1
result = parse_worksheet(args, worksheet)
for lang in ['fr', 'en', 'es']:
filepath = build_filepath(args, lang)
output_file = io.open(filepath, 'w', encoding='utf8')
if 'ios' == platform:
output_file.write(result[lang])
elif 'android' == platform:
output_file.write(u'<?xml version="1.0" encoding="utf-8"?>\n<resources>\n')
output_file.write(result[lang])
output_file.write(u'</resources>')
output_file.close()
log('DONE')
def parse_config(args):
f = io.open(args.config, 'r', encoding='utf8')
config_str = f.read()
config_json = json.loads(config_str)
return config_json
def get_credentials(args):
# First check existing credentials
storage = Storage('.localizeit.storage')
credentials = storage.get()
if not credentials == None:
return credentials
config = parse_config(args)
# Run the oauth authorization flow
flow = OAuth2WebServerFlow(
client_id=config['client_id'],
client_secret=config['client_secret'],
scope=SCOPE,
redirect_uri=REDIRECT_URI)
flags = args
http = httplib2.Http()
return tools.run_flow(flow=flow, storage=storage, flags=flags, http=http)
def authorize(args):
credentials = get_credentials(args)
if credentials.access_token_expired:
credentials.refresh(httplib2.Http())
client = gspread.authorize(credentials)
return client
def main():
parser = argparse.ArgumentParser(parents=[tools.argparser])
parser.add_argument('-v', '--verbose',
help='Display more information about the files generation',
action='store_true')
subparsers = parser.add_subparsers(help='Available actions')
generate_parser = subparsers.add_parser('generate',
help='Generate files from Google Spreadsheet')
generate_parser.set_defaults(func=generate)
generate_parser.add_argument('platform',
help='The platform determines the format of the output files and the location of the output files',
choices=['ios', 'android'])
generate_parser.add_argument('-s', '--spreadsheet',
help='Google Spreadsheet to read/write from',
required=True)
generate_parser.add_argument('-c', '--config',
help='Path to the JSON config file used to store the client ID and SECRET',
default='localizeit.json')
generate_parser.add_argument('-o', '--output',
help='The destination path of the generated files',
required=True,
default='.')
args = parser.parse_args()
args.func(args)
if __name__ == '__main__': main()