Skip to content

Instantly share code, notes, and snippets.

@andresmrm
Last active March 31, 2019 21:29
Show Gist options
  • Save andresmrm/2c2f959a8a5b5d4fd7ab05063f437cc1 to your computer and use it in GitHub Desktop.
Save andresmrm/2c2f959a8a5b5d4fd7ab05063f437cc1 to your computer and use it in GitHub Desktop.
[vue-18n] Extracts i18n keys from vue files and add them to the locale files. Supports only "v-t" method keys (not "$t") and json locale files (not yaml).
#!/usr/bin/env python3
'''
BEWARE: Poorly tested. Use at your own risk.
It replaces json files content. Backup first!
For use with https://github.com/kazupon/vue-i18n
Extracts i18n keys from vue files and add them to the locale files.
Supports only "v-t" method keys (not "$t") and json locale files (not yaml).
Doesn't support dynamic keys (v-t="var"), only static (v-t="'word'").
Usage:
Place this file in the project's root folder, which contains the "src" folder.
Run.
'''
import re
import json
from pathlib import Path
base_path = Path('src')
# extract i18n keys from vue files
i18n_keys = []
vue_files = base_path.glob('**/*.vue')
for filepath in vue_files:
with open(filepath, 'r') as fp:
text = fp.read()
i18n_keys += re.findall(r'v-t="\'(.+?)\'"', text)
locale_files = (base_path / 'locales').glob('**/*.json')
for filepath in locale_files:
print('\nprocessing', filepath)
with open(filepath, 'r') as fp:
locale_data = json.load(fp)
# add new keys
changed = False
for key in i18n_keys:
if key not in locale_data:
print('adding', key)
locale_data[key] = ''
changed = True
# check if extraneous keys exist
extraneous = set(locale_data) - set(i18n_keys)
if extraneous:
print('\npossible extraneous keys in', filepath)
print('\n'.join(extraneous))
# write modified file
if changed:
with open(filepath, 'w') as fp:
json.dump(locale_data, fp, ensure_ascii=False, indent=True)
else:
print('nothing to do')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment