Created
January 19, 2021 07:09
-
-
Save Thong-Tran/30f776e458cb2fd3a3f43cabd0dd49b5 to your computer and use it in GitHub Desktop.
Parser and generate i18n for typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import sys | |
if sys.version_info < (3, 6): | |
print("Must be using Python 3.6 or higher") | |
exit(1) | |
from typing import List | |
import os | |
import json | |
import re | |
from argparse import ArgumentParser, RawDescriptionHelpFormatter | |
REGEX = r'(?:\$|i18n\.)tc?\([\'"](.*?(?<!\\))[\'"]' | |
def parse_i18n(*, exten: List[str]=None, parser_path='.', out_file='i18n.ts'): | |
data = {} | |
data_old = {} | |
if os.path.exists(out_file): | |
with open(out_file, 'r', encoding='utf8') as f: | |
text = f.read() | |
text = text.replace('export default ', '').replace(';', '') | |
data_old = json.loads(text) | |
for root, _, files in os.walk(os.path.abspath(parser_path)): | |
if 'node_modules' in root: | |
continue | |
for file in files: | |
if any(file.endswith(target) for target in exten): | |
# print(os.path.join(root, file)) | |
with open(os.path.join(root, file), 'r', encoding='utf8') as f: | |
list_str = re.findall(REGEX, f.read()) | |
for key in list_str: | |
if key not in data_old: | |
data[key] = key | |
out_path = os.path.dirname(out_file) | |
out_name = os.path.basename(out_file) | |
if os.path.exists(out_file) and len(data) > 0: | |
output = json.dumps(data, indent=2, ensure_ascii=False).encode('utf8') | |
with open(os.path.join(out_path, f'new-{out_name}'), 'wb') as f: | |
f.write(b'export default ' + output + b';') | |
data.update(data_old) | |
output = json.dumps(data, indent=2, ensure_ascii=False).encode('utf8') | |
with open(out_file, 'wb') as f: | |
f.write(b'export default ' + output + b';') | |
def main(argv): | |
parser = ArgumentParser( | |
formatter_class=RawDescriptionHelpFormatter, | |
description=( | |
'Parser and genere i18n\n' | |
'Example: python3 ./parse-i18n.py .ts .vue' | |
), | |
) | |
parser.add_argument( | |
'exten', | |
type=str, | |
nargs='+', | |
help='extension file to parser' | |
) | |
parser.add_argument( | |
'-o', "--out-file", | |
type=str, metavar='file', | |
default= parse_i18n.__kwdefaults__['out_file'], | |
help=f"set output file (default: {parse_i18n.__kwdefaults__['out_file']})" | |
) | |
parser.add_argument( | |
'-p', "--parser-path", | |
type=str, metavar='path', | |
default= parse_i18n.__kwdefaults__['parser_path'], | |
help=f"set folder to parser (default: {parse_i18n.__kwdefaults__['parser_path']} )" | |
) | |
kwargs = vars(parser.parse_args(argv)) | |
# print(kwargs) | |
parse_i18n(**kwargs) | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment