Skip to content

Commit

Permalink
Added github-workflow for comparing translation file (#1325)
Browse files Browse the repository at this point in the history
* ci: testing translational files

* ci: testing compare translational files

* ci: testing

* ci: workflow for translation files

* refactor: removed unwanted changes

* refactor: removed unnecessary lines

* fix: fixed all the failing translation file testcases

* fix: fixed file names
  • Loading branch information
1010varun authored Jan 2, 2024
1 parent 1183c72 commit 432f117
Show file tree
Hide file tree
Showing 6 changed files with 211 additions and 15 deletions.
170 changes: 170 additions & 0 deletions .github/workflows/compare_translations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"""Script to encourage more efficient coding practices.
Methodology:
Utility for comparing translations between default and other languages.
This module defines a function to compare two translations
and print any missing keys in the other language's translation.
Attributes:
FileTranslation : Named tuple to represent a combination
of file and missing translations.
Fields:
- file (str): The file name.
- missing_translations (list): List of missing translations.
Functions:
compare_translations(default_translation, other_translation):
Compare two translations and print missing keys.
load_translation(filepath):
Load translation from a file.
check_translations():
Load the default translation and compare it with other translations.
main():
The main function to run the script.
Parses command-line arguments, checks for the
existence of the specified directory, and then
calls check_translations with the provided or default directory.
Usage:
This script can be executed to check and print missing
translations in other languages based on the default English translation.
Example:
python compare_translations.py
NOTE:
This script complies with our python3 coding and documentation standards
and should be used as a reference guide. It complies with:
1) Pylint
2) Pydocstyle
3) Pycodestyle
4) Flake8
"""
# standard imports
import argparse
import json
import os
import sys
from collections import namedtuple

# Named tuple for file and missing
# translations combination
FileTranslation = namedtuple("FileTranslation",
["file", "missing_translations"])


def compare_translations(default_translation,
other_translation, default_file, other_file):
"""Compare two translations and return detailed info about missing/mismatched keys.
Args:
default_translation (dict): The default translation (en.json).
other_translation (dict): The other language translation.
default_file (str): The name of the default translation file.
other_file (str): The name of the other
translation file.
Returns:
list: A list of detailed error messages for each missing/mismatched key.
"""
errors = []

# Check for missing keys in other_translation
for key in default_translation:
if key not in other_translation:
error_msg = f"Missing Key: '{key}' - This key from '{default_file}' is missing in '{other_file}'."
errors.append(error_msg)
# Check for keys in other_translation that don't match any in default_translation
for key in other_translation:
if key not in default_translation:
error_msg = f"Error Key: '{key}' - This key in '{other_file}' does not match any key in '{default_file}'."
errors.append(error_msg)
return errors


def load_translation(filepath):
"""Load translation from a file.
Args:
filepath: Path to the translation file
Returns:
translation: Loaded translation
"""
with open(filepath, "r", encoding="utf-8") as file:
translation = json.load(file)
return translation


def check_translations(directory):
"""Load default translation and compare with other translations.
Args:
directory (str): The directory containing translation files.
Returns:
None
"""
default_file = "en.json"
default_translation = load_translation(os.path.join(directory, default_file))
translations = os.listdir(directory)
translations.remove(default_file) # Exclude default translation

error_found = False

for translation_file in translations:
other_file = os.path.join(directory, translation_file)
other_translation = load_translation(other_file)

# Compare translations and get detailed error messages
errors = compare_translations(
default_translation, other_translation, default_file, translation_file
)
if errors:
error_found = True
print(f"File {translation_file} has missing translations for:")
for error in errors:
print(f" - {error}")

if error_found:
sys.exit(1) # Exit with an error status code
else:
print("All translations are present")
sys.exit(0)


def main():
"""
Parse command-line arguments, check for the existence of the specified directory
and call check_translations with the provided or default directory.
"""
parser = argparse.ArgumentParser(
description="Check and print missing translations for all non-default languages."
)
parser.add_argument(
"--directory",
type=str,
nargs="?",
default=os.path.join(os.getcwd(), "public/locales"),
help="Directory containing translation files(relative to the root directory).",
)
args = parser.parse_args()

if not os.path.exists(args.directory):
print(f"Error: The specified directory '{args.directory}' does not exist.")
sys.exit(1)

check_translations(args.directory)


if __name__ == "__main__":
main()
5 changes: 5 additions & 0 deletions .github/workflows/pull-requests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ jobs:
if: steps.changed-files.outputs.only_changed != 'true'
run: npm run lint:check

- name: Compare translation files
run: |
chmod +x .github/workflows/compare_translations.py
python .github/workflows/compare_translations.py --directory public/locales
Test-Application:
name: Test Application
Expand Down
5 changes: 5 additions & 0 deletions public/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@
"eventCardSeeAll": "Voir Tout",
"noEvents": "Aucun événement à venir"
},
"latestPosts": {
"latestPostsTitle": "Dernières Publications",
"seeAllLink": "Voir Tout",
"noPostsCreated": "Aucune Publication Créée"
},
"listNavbar": {
"talawa_portal": "Portail D'Administrateur Talawa",
"roles": "Les rôles",
Expand Down
19 changes: 12 additions & 7 deletions public/locales/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@
"eventCardSeeAll": "सभी देखें",
"noEvents": "कोई आगामी घटनाएँ नहीं"
},
"latestPosts": {
"latestPostsTitle": "नवीनतम पोस्ट",
"seeAllLink": "सभी देखें",
"noPostsCreated": "कोई पोस्ट नहीं बनाई गई"
},
"listNavbar": {
"talawa_portal": "तलावा प्रशासन पोर्टल",
"roles": "भूमिकाएँ",
Expand Down Expand Up @@ -684,14 +689,14 @@
"selectContact": "बातचीत शुरू करने के लिए एक संपर्क चुनें",
"sendMessage": "मेसेज भेजें"
},
"ऑर्गप्रोफ़ाइलफ़ील्ड": {
"लोड हो रहा है": "लोड हो रहा है...",
"noCustomField": "कोई कस्टम फ़ील्ड उपलब्ध नहीं",
"customFieldName": "फ़ील्ड नाम",
"enterCustomFieldName": "फ़ील्ड नाम दर्ज करें",
"customFieldType": "फ़ील्ड प्रकार",
"orgProfileField": {
"loading": "लोड हो रहा है...",
"noCustomField": "कोई कस्टम फ़ील्ड उपलब्ध नहीं है",
"customFieldName": "फ़ील्ड का नाम",
"enterCustomFieldName": "फ़ील्ड का नाम दर्ज करें",
"customFieldType": "फ़ील्ड का प्रकार",
"saveChanges": "परिवर्तन सहेजें",
"कस्टम फ़ील्ड हटाएँ": "कस्टम फ़ील्ड हटाएँ",
"Remove Custom Field": "कस्टम फ़ील्ड हटाएँ",
"fieldSuccessMessage": "फ़ील्ड सफलतापूर्वक जोड़ा गया",
"fieldRemovalSuccess": "फ़ील्ड सफलतापूर्वक हटा दिया गया"
}
Expand Down
22 changes: 14 additions & 8 deletions public/locales/sp.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@
"eventCardSeeAll": "Ver Todos",
"noEvents": "No Hay Eventos Próximos"
},
"latestPosts": {
"latestPostsTitle": "Últimas Publicaciones",
"seeAllLink": "Ver Todo",
"noPostsCreated": "No se han creado publicaciones"
},
"listNavbar": {
"talawa_portal": "Portal De Administración Talawa",
"roles": "Roles",
Expand Down Expand Up @@ -684,15 +689,16 @@
"selectContact": "Seleccione un contacto para iniciar una conversación",
"sendMessage": "Enviar mensaje"
},
"campoPerfildeOrganización": {
"cargando": "Cargando...",

"orgProfileField": {
"loading": "Cargando..",
"noCustomField": "No hay campos personalizados disponibles",
"customFieldName": "Nombre de campo",
"enterCustomFieldName": "Ingrese el nombre del campo",
"customFieldType": "Tipo de campo",
"saveChanges": "Guardar cambios",
"Eliminar campo personalizado": "Eliminar campo personalizado",
"fieldSuccessMessage": "Campo agregado exitosamente",
"customFieldName": "Nombre del Campo",
"enterCustomFieldName": "Ingrese el Nombre del Campo",
"customFieldType": "Tipo de Campo",
"saveChanges": "Guardar Cambios",
"Remove Custom Field": "Eliminar Campo Personalizado",
"fieldSuccessMessage": "Campo añadido exitosamente",
"fieldRemovalSuccess": "Campo eliminado exitosamente"
}
}
5 changes: 5 additions & 0 deletions public/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@
"eventCardSeeAll": "查看全部",
"noEvents": "暂无即将举行的活动"
},
"latestPosts": {
"latestPostsTitle": "最新文章",
"seeAllLink": "查看全部",
"noPostsCreated": "暂无文章"
},
"listNavbar": {
"talawa_portal": "塔拉瓦管理門戶",
"roles": "角色",
Expand Down

0 comments on commit 432f117

Please sign in to comment.