Skip to content

Commit 1321dc1

Browse files
authored
Merge pull request #6 from rogermolas/json-support
JSON support
2 parents d96bd22 + bee93a3 commit 1321dc1

File tree

3 files changed

+94
-33
lines changed

3 files changed

+94
-33
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ csv-localizer use three required commands
2727

2828
| Commands| Descriptions|
2929
| :------: |:-------------
30-
| `-p` | Platforms (e.g ios or android) |
30+
| `-p` | Platforms (ios, android, json) |
3131
| `-i` | Input directory, CSV files directory path|
3232
| `-0` | Output directory, Generated localizable files path|
3333

csv-localizer

Lines changed: 93 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
#!/usr/bin/env python
22
import sys, argparse, logging, os, csv
33

4+
PLATFORM = None
5+
IN_PATH = None
6+
OUT_PATH = None
7+
LANG_KEYS = None # static will change later
8+
49
# Gather our code in a main() function
510
def main(args, loglevel):
611
logging.basicConfig(format="%(message)s", level=loglevel)
712
PLATFORM = args.platform
813
IN_PATH = args.input
914
OUT_PATH = args.output
10-
LANG_KEYS = None #static will change later
1115
print '\n'
1216
logging.info("Start Localizing .... ")
1317
print '\n'
1418
logging.info("------------------------------------")
15-
19+
1620
# check source path
1721
logging.debug("\n")
1822
logging.debug("Validating source path ...")
@@ -32,7 +36,7 @@ def main(args, loglevel):
3236
return
3337
logging.debug("Valid target path, generating output directory ...")
3438
logging.debug("\n")
35-
39+
3640
# generate output directory
3741
OUTPUT_DIR = os.path.join(OUT_PATH, "output")
3842
if not os.path.exists(OUTPUT_DIR):
@@ -42,23 +46,24 @@ def main(args, loglevel):
4246
else:
4347
logging.debug("Using output directory: %s" % OUTPUT_DIR)
4448
logging.debug("\n")
45-
49+
4650
logging.debug("\n")
4751
if PLATFORM == "ios":
4852
logging.debug("Platform : %s" % PLATFORM)
4953
elif PLATFORM == "android":
5054
logging.debug("Platform : %s" % PLATFORM)
55+
elif PLATFORM == "json":
56+
logging.debug("Platform : %s" % PLATFORM)
5157
else:
52-
logging.warn("Invalid platform, platform should be ios or android only")
58+
logging.warn("Invalid platform, platform should be ios, android, json only")
5359
logging.debug("\n")
54-
logging.error('ERROR LOCALIZING.')
60+
logging.error('ERROR LOCALIZING.\n')
5561
return
5662

57-
logging.info("Generation output : %s" % OUTPUT_DIR)
63+
logging.info("Generated output directory: %s" % OUTPUT_DIR)
5864
generate_keys(IN_PATH, OUTPUT_DIR, PLATFORM)
5965
print '\n'
60-
logging.info("DONE LOCALIZING.")
61-
print '\n'
66+
logging.info("DONE LOCALIZING.\n")
6267

6368
def generate_keys(source_path, output, platform):
6469
base_out_dir = output
@@ -70,7 +75,7 @@ def generate_keys(source_path, output, platform):
7075
filename, ext = os.path.splitext(f)
7176
if ext != '.csv':
7277
continue
73-
78+
7479
fullpath = os.path.join(dirname, f)
7580

7681
with open(fullpath, 'rb') as csvfile:
@@ -80,16 +85,19 @@ def generate_keys(source_path, output, platform):
8085
if i == 0:
8186
line.remove(line[0])
8287
LANG_KEYS = line # assign new value to key
83-
88+
8489
# iterate each language
8590
lang_path = ""
8691
for lang in LANG_KEYS:
8792
if platform == "ios":
8893
lang_path = os.path.join(base_out_dir, "{0}.lproj/".format(lang))
89-
94+
9095
if platform == "android":
9196
lang_path = os.path.join(base_out_dir, "values-{0}/".format(lang))
92-
97+
98+
if platform == "json":
99+
lang_path = os.path.join(base_out_dir, "{0}/".format(lang))
100+
93101
# Generate directory per language key
94102
if not os.path.exists(lang_path):
95103
os.makedirs(lang_path)
@@ -98,14 +106,17 @@ def generate_keys(source_path, output, platform):
98106
full_out_paths = [os.path.join(base_out_dir, "{0}.lproj/".format(langKey) + "Localizable.strings") for langKey in LANG_KEYS]
99107
if platform == "android":
100108
full_out_paths = [os.path.join(base_out_dir, "values-{0}/".format(langKey) + "strings.xml") for langKey in LANG_KEYS]
101-
109+
if platform == "json":
110+
full_out_paths = [os.path.join(base_out_dir, "{0}/".format(langKey) + "{0}_message.json".format(langKey)) for langKey in LANG_KEYS]
111+
102112
allwrites = [open(out_path, 'w') for out_path in full_out_paths]
103-
113+
104114
if platform == "ios":
105115
start_localize_ios(source_path, allwrites, LANG_KEYS)
106116
if platform == "android":
107117
start_localize_android(source_path, allwrites, LANG_KEYS)
108-
118+
if platform == "json":
119+
start_localize_json(source_path, allwrites, LANG_KEYS)
109120

110121

111122
# =========================================================================
@@ -121,15 +132,15 @@ def start_localize_ios(source_path, all_writes, lang_keys):
121132
continue
122133

123134
fullpath = os.path.join(dirname, f)
124-
logging.info("Localizing: %s", filename)
135+
logging.info("Localizing: %s to iOS", filename)
125136

126137
with open(fullpath, 'rb') as csvfile:
127138
[fwrite.write('\n/* {0} */\n'.format(filename)) for fwrite in allwrites]
128-
139+
129140
reader = csv.reader(csvfile, delimiter=',')
130141
iterrows = iter(reader)
131142
next(iterrows) # skip first line (it is header).
132-
143+
133144
for row in iterrows:
134145
row_key = row[0].replace(" ", "")
135146
# comment
@@ -141,7 +152,8 @@ def start_localize_ios(source_path, all_writes, lang_keys):
141152
if any([value == "" for value in row_values]):
142153
[fwrite.write('\n') for idx, fwrite in enumerate(allwrites)]
143154
else:
144-
[fwrite.write('"{key}" = "{lang}";\n'.format(key=row_key, lang=row_values[idx])) for idx, fwrite in enumerate(allwrites)]
155+
[fwrite.write('"{key}" = "{lang}";\n'.format(key=row_key, lang=row_values[idx]))
156+
for idx, fwrite in enumerate(allwrites)]
145157
[fwrite.close() for fwrite in allwrites]
146158

147159

@@ -153,23 +165,23 @@ def start_localize_android(source_path, all_writes, lang_keys):
153165

154166
[fwrite.write('<?xml version="1.0" encoding="utf-8"?>\n') for fwrite in allwrites]
155167
[fwrite.write('<resources>') for fwrite in allwrites]
156-
168+
157169
for dirname, dirnames, filenames in os.walk(source_path):
158170
for f in filenames:
159171
filename, ext = os.path.splitext(f)
160172
if ext != '.csv':
161173
continue
162-
174+
163175
fullpath = os.path.join(dirname, f)
164-
logging.info("Localizing: %s", filename)
176+
logging.info("Localizing: %s to Android", filename)
165177

166178
with open(fullpath, 'rb') as csvfile:
167179
[fwrite.write('\n<!-- {0} -->\n'.format(filename)) for fwrite in allwrites]
168-
180+
169181
reader = csv.reader(csvfile, delimiter=',')
170182
iterrows = iter(reader)
171183
next(iterrows) # skip first line (it is header).
172-
184+
173185
for row in iterrows:
174186
row_key = row[0].replace(" ", "")
175187
# comment
@@ -181,26 +193,75 @@ def start_localize_android(source_path, all_writes, lang_keys):
181193
if any([value == "" for value in row_values]):
182194
[fwrite.write('\n') for idx, fwrite in enumerate(allwrites)]
183195
else:
184-
[fwrite.write('\t<string name="{key}">{lang}</string>\n'.format(key=row_key, lang=row_values[idx])) for idx, fwrite in enumerate(allwrites)]
196+
[fwrite.write('\t<string name="{key}">{lang}</string>\n'.format(key=row_key, lang=row_values[idx]))
197+
for idx, fwrite in enumerate(allwrites)]
185198
[fwrite.write('</resources>') for fwrite in allwrites]
186199
[fwrite.close() for fwrite in allwrites]
187200

188201

189202
# =========================================================================
190-
# +++++++ Standard boilerplate to call the main() function to begin +++++++
203+
# ++++++++++++++++++++++++++++++ iOS ++++++++++++++++++++++++++++++++++++++
191204
# =========================================================================
205+
def start_localize_json(source_path, all_writes, lang_keys):
206+
allwrites = all_writes
207+
[fwrite.write('{') for fwrite in allwrites]
208+
209+
for dirname, dirnames, filenames in os.walk(source_path):
210+
for f in filenames:
211+
filename, ext = os.path.splitext(f)
212+
if ext != '.csv':
213+
continue
214+
215+
fullpath = os.path.join(dirname, f)
216+
logging.info("Localizing: %s to JSON", filename)
217+
218+
current_row = 0
219+
220+
with open(fullpath, 'rb') as csvfile:
221+
[fwrite.write('\n/* {0} */\n'.format(filename)) for fwrite in allwrites]
222+
223+
reader = csv.reader(csvfile, delimiter=',')
224+
iterrows = iter(reader)
225+
next(iterrows) # skip first line (it is header).
226+
list_data = list(iterrows)
227+
228+
for row in list_data:
229+
row_key = row[0].replace(" ", "")
230+
# comment
231+
if row_key[:2] == '//':
232+
continue
233+
row_values = [row[i+1] for i in range(len(lang_keys))]
234+
separator = ", \n"
192235

193-
parser = argparse.ArgumentParser(description = "Locatization commands")
194-
parser.add_argument("-p",help="Specify Platform (iOS, Android)" ,dest="platform", type=str, required=True)
195-
parser.add_argument("-i",help="Input source, CSV file path" ,dest="input", type=str, required=True)
196-
parser.add_argument("-o",help="Generated output path for localizable files" ,dest="output", type=str, required=True)
236+
# check if last row then remove ';'
237+
if current_row == len(list_data) - 1:
238+
separator = "\n"
239+
current_row += 1 # iterate row count
240+
241+
# if any row is empty, skip it!
242+
if any([value == "" for value in row_values]):
243+
[fwrite.write('\n') for idx, fwrite in enumerate(allwrites)]
244+
else:
245+
[fwrite.write('"{key}": "{lang}"{separator}'.format(key=row_key, lang=row_values[idx], separator=separator))
246+
for idx, fwrite in enumerate(allwrites)]
247+
[fwrite.write('}') for fwrite in allwrites]
248+
[fwrite.close() for fwrite in allwrites]
249+
250+
251+
# =========================================================================
252+
# +++++++ Standard boilerplate to call the main() function to begin +++++++
253+
# =========================================================================
254+
parser = argparse.ArgumentParser(description="Locatization commands")
255+
parser.add_argument("-p", help="Specify Platform (iOS, Android)", dest="platform", type=str, required=True)
256+
parser.add_argument("-i", help="Input source, CSV file path", dest="input", type=str, required=True)
257+
parser.add_argument("-o", help="Generated output path for localizable files", dest="output", type=str, required=True)
197258

198259
parser.add_argument("-v",
199260
"--verbose",
200261
help="increase output verbosity",
201262
action="store_true")
202263
args = parser.parse_args()
203-
264+
204265
# Setup logging
205266
if args.verbose:
206267
loglevel = logging.DEBUG

flow.png

-5.44 KB
Loading

0 commit comments

Comments
 (0)