purge_unused_strings.sh 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/bin/bash
  2. # Set the path to the JSON file and folder
  3. json_file_path="./public/locales/en/translation.json"
  4. folder_path="./src"
  5. tab_width=4
  6. # Check if jq and grep are installed
  7. if ! command -v jq &> /dev/null || ! command -v grep &> /dev/null
  8. then
  9. echo "jq or grep command not found. Please install jq and grep."
  10. exit
  11. fi
  12. # Recursive function to check for keys in nested JSON objects
  13. check_keys() {
  14. local keys="$1"
  15. local parent_key="$2"
  16. for key in $keys
  17. do
  18. local full_key=""
  19. if [[ -z $parent_key ]]; then
  20. full_key="$key"
  21. else
  22. full_key="$parent_key.$key"
  23. fi
  24. local children_keys=$(jq -r --arg key "$key" 'select(.[$key] | type == "object") | .[$key] | keys[]' "$json_file_path")
  25. if [ -n "$children_keys" ]; then
  26. # check first if the key is not in the ignore list
  27. check_keys "$children_keys" "$full_key"
  28. else
  29. if ! grep -rqE "'$full_key'|\"$full_key\"" "$folder_path"; then
  30. # Remove the key from the JSON file
  31. # echo the command to remove the key from the JSON file
  32. jq "del(.$(echo $full_key | sed 's/\./"."/g' | sed 's/^/"/' | sed 's/$/"/'))" "$json_file_path" > "$json_file_path.tmp" && mv "$json_file_path.tmp" "$json_file_path"
  33. echo "Removing key \"$full_key\" from the JSON file"
  34. else
  35. echo "Key \"$full_key\" is being used."
  36. fi
  37. fi
  38. done
  39. }
  40. # Get the top-level keys from the JSON file
  41. keys=$(jq -r 'keys[]' "$json_file_path")
  42. # Loop through the keys and recursively check for nested keys
  43. check_keys "$keys" ""
  44. # Format the updated JSON using the specified tab width
  45. jq --indent "$tab_width" '.' "$json_file_path" > "$json_file_path.tmp" && mv "$json_file_path.tmp" "$json_file_path"
  46. echo "Done checking for missing keys."