Skip to content

Instantly share code, notes, and snippets.

@kyle-west
Created August 6, 2020 15:20
Show Gist options
  • Save kyle-west/24b1a6d2b45e971cf4fc3e0b2f57e674 to your computer and use it in GitHub Desktop.
Save kyle-west/24b1a6d2b45e971cf4fc3e0b2f57e674 to your computer and use it in GitHub Desktop.
Copy string keys from a locale JSON file to another
#!/bin/bash
###########################################################################
# USAGE Example:
# lang-cp from_dir from_file_prefix to_dir key1 key2 key3@KEY_3_NEW_NAME key4
###########################################################################
from_list=$(find $1 | grep "$2_.*json")
echo "Copying from $2..."
for f in $from_list; do
lang=$(echo $f | cut -d '_' -f 2 | cut -d '.' -f 1)
to_lang=${lang//-/_}
to_file="$3/$to_lang/translation.json"
for key in ${@:4}; do
as=$(node -e "if ('$key'.includes('@')) {console.log('$key'.split('@')[1])} else {console.log('$key')}")
key=$(node -e "if ('$key'.includes('@')) {console.log('$key'.split('@')[0])} else {console.log('$key')}")
echo -e "$2_$lang.json --> $to_lang/translation.json"
echo -e " from: $key"
echo -e " to: $as"
value=$(node -e "
let from = $(cat $f);
console.log(from[\"$key\"])
");
node -e "
let to = $(cat $to_file 2>/dev/null || echo '{}');
if (\"$value\" !== 'undefined') {
if (!to[\"$as\"]) to[\"$as\"] = \"$value\";
}
console.log(JSON.stringify(to, null, 2));
" > $to_file;
done
done
@kyle-west
Copy link
Author

Compare to lang-mv

Install

Best installed via bashful CLI.

bashful gist install https://gist.github.com/kyle-west/24b1a6d2b45e971cf4fc3e0b2f57e674

Usage

Assumes your components use this type of i18n structure.

lang-cp <from-dir> <from-file-prefix> <to-dir> <key-name[@<rename-key>]> [...<key-name[@<rename-key>]>]

Example

Context:

~/dev
├── project1
│   ├── locales
│   │   ├── original-component_de.json
│   │   ├── original-component_en.json
│   │   └── ...
│   └── ...
├── project2
│   ├── locales
│   └── ...
└── ...

Inside original-component_en.json:

{
  "SIGN_IN_BTN": "Sign In",
  "LOGOUT_BTN": "Sign Out",
  "GENERAL_ERROR": "An unexpected problem has occurred. Please check back later."
}

Copy the locale keys from project1 to project2 (while also renaming GENERAL_ERROR key to UNEXPECTED_ERROR):

lang-cp ~/dev/project1/locales original-component ~/dev/project2/locales \
  SIGN_IN_BTN \
  LOGOUT_BTN \
  GENERAL_ERROR@UNEXPECTED_ERROR

@kyle-west
Copy link
Author

Special thanks to @jlubean for making improvements to lang-mv and thus creating this package!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment