Skip to content

Commit 4c9fb24

Browse files
committed
fix: giving the opportunity to choose on wich language you want to see informations
1 parent 260e4cc commit 4c9fb24

File tree

7 files changed

+356
-11
lines changed

7 files changed

+356
-11
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ repos:
4747
args: [ "--write-changes" ]
4848
additional_dependencies:
4949
- tomli
50+
exclude: "commitizen/cz/conventional_commits/\\.cache_multilanguage\\.txt"
5051

5152
- repo: https://github.com/commitizen-tools/commitizen
5253
rev: v4.1.0 # automatically updated by Commitizen

commitizen/commands/commit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def read_backup_message(self) -> str | None:
5151
def prompt_commit_questions(self) -> str:
5252
# Prompt user for the commit message
5353
cz = self.cz
54-
questions = cz.questions()
54+
questions = cz.questions(self.arguments["language"])
5555
for question in filter(lambda q: q["type"] == "list", questions):
5656
question["use_shortcuts"] = self.config.settings["use_shortcuts"]
5757
try:

commitizen/cz/conventional_commits/.cache_multilanguage.txt

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,138 @@ build_en=Changes that affect the build system or external dependencies (example
1010
ci_en=Changes to CI configuration files and scripts (example scopes: GitLabCI)
1111
scope_en=What is the scope of this change? (class or file name): (press [enter] to skip)
1212
subject_en=Write a short and imperative summary of the code changes: (lower case and no period)
13+
prefix_fr=Sélectionnez le type de changement que vous engagez
14+
fix_fr=Une correction de bogue. Corrèle avec LE CORRECTIF dans SemVer
15+
feat_fr=Une nouvelle fonctionnalité. Corréle avec MINEUR dans SemVer
16+
docs_fr=Modifications de la documentation uniquement
17+
style_fr=Modifications qui n'affectent pas la signification du code (escape blanc, mise en forme, points-virgules manquants, etc.)
18+
refactor_fr=Un changement de code qui ne corrige pas un bogue ni n'ajoute une fonctionnalité
19+
perf_fr=Un changement de code qui améliore les performances
20+
test_fr=Ajout de tests manquants ou correction de tests existants
21+
build_fr=Modifications affectant le système de génération ou les dépendances externes (par example, étendues : pip, docker, npm)
22+
ci_fr=Modifications apportées aux fichiers et scripts de configuration CI (example de portée : GitLabCI)
23+
scope_fr=Quelle est la portée de ce changement ? (nom de classe ou de fichier) : (appuyez sur [ENTER] pour ignorer)
24+
subject_fr=Rédigez un résumé court et impératif des changements de code : (minuscules et sans point)
25+
body_fr=Fournir des information contextuelles supplémentaires sur les changements de code : (appuyez sur [ENTER] pour ignorer)
26+
is_breaking_change_fr=S'agit-il d'un CHANGEMENT RADICAL ? Corrèle avec la MAJEURE en SemVer
27+
footer_fr=Pied de page. Information sur les modifications de rupture et les problèmes de référence que cette validation ferme : (appuyez sur [ENTER] pour ignorer)
28+
prefix_es=Selecciona el tipo de cambio que estás realizando
29+
fix_es=Una corrección de errores. Se correlaciona con EL PARCHE en SemVer
30+
feat_es=Una nueva función. Se correlaciona con MENOR en SemVer
31+
docs_es=Solo cambios en la documentación
32+
style_es=Cambios que no afectan el significado del código (espacios en blanco, formato, puntos y comas faltantes, etc.)
33+
refactor_es=Un cambio de código que no corrige un error ni añade una característica
34+
perf_es=Un cambio de código que mejora el rendimiento
35+
test_es=Añadiendo pruebas faltantes o corrección de pruebas existentes
36+
build_es=Cambios que afectan al sistema de compilación o dependencias externas (por ejemplo, ámbitos: pip, docker, npm)
37+
ci_es=Cambios en los archivos de configuración y scripts de CI (ámbitos de ejemplo: GitLabCI)
38+
scope_es=¿Cuál es el alcance de este cambio? (nombre de clase o archivo): (pulse [enter] para omitir)
39+
subject_es=Escriba un resumen breve e imperativo de los cambios en el código: (minúsculas y sin punto)
40+
body_es=Proporcione información contextual adicional sobre los cambios en el código: (pulse [enter] para omitir)
41+
is_breaking_change_es=¿Es este un CAMBIO RADICAL? Se correlaciona con la ESPECIALIZACIÓN en SemVer
42+
footer_es=Pie de página. Información sobre los cambios de última hora y los problemas de referencia que este compromiso cierra: (presione [enter] para omitir)
43+
prefix_de=Wählen Sie die Art der Änderung aus, die Sie vornehmen
44+
fix_de=Ein Bugfix. Korreliert mit PATCH in SemVer
45+
feat_de=Ein neues Feature. Korreliert mit MINOR in SemVer
46+
docs_de=Dokumentation nur Änderungen
47+
style_de=Änderungen, die die Bedeutung des Codes nicht beeinflussen (Leerzeichen, Formatierung, fehlende Semikolons usw.)
48+
refactor_de=Eine Codeänderung, die weder einen Fehler behebt noch eine Function hinzufügt
49+
perf_de=Eine Codeänderung, die die Leistung verbessert
50+
test_de=Hinzufügen fehlender oder Korrigieren vorhandener Tests
51+
build_de=Änderungen, die sich auf das Buildsystem oder externe Abhängigkeiten auswirken (Beispielumfänge: Pip, Docker, npm)
52+
ci_de=Änderungen an CI-Konfigurationsdateien und Skripten (Beispielumfänge: GitLabCI)
53+
scope_de=Was ist der Umfang dieser Änderung? (Klassen- oder Dateiname): (Drücken Sie [ENTER], um zu überspringen)
54+
subject_de=Schreiben Sie eine kurze und zwingende Zusammenfassung der Codeänderungen: (Kleinbuchstaben und kein Punkt)
55+
body_de=Geben Sie zusätzliche kontextbezogene Informationen zu den Codeänderungen an: (drücken Sie [ENTER], um zu überspringen)
56+
is_breaking_change_de=Ist das eine BAHNBRECHENDE VERÄNDERUNG? Korreliert mit HAUPTFACH in SemVer
57+
footer_de=Fußzeile. Informationen über Breaking Changes und Referenzprobleme, die mit diesem Commit geschlossen werden: (drücken Sie [ENTER], um zu überspringen)
58+
prefix_zh=选择您要提交的变更类型
59+
fix_zh=错误修复。与SemVer中的补丁相关
60+
feat_zh=新功能。与SemVer中的次要功能相关
61+
docs_zh=仅文档更改
62+
style_zh=不影响代码含义的更改(空格、格式、缺少分号等)
63+
refactor_zh=既不修复错误也不添加功能的代码更改
64+
perf_zh=改进性能的代码更改
65+
test_zh=添加缺失的测试或更正现有测试
66+
build_zh=影响构建系统或外部依赖项的更改(示例作用域: pip、docker、npm )
67+
ci_zh=对CI配置文件和脚本的更改(示例范围: GitLabCI )
68+
scope_zh=此更改的范围是什么? (类或文件名) : (按[ENTER]跳过)
69+
subject_zh=撰写简短而必要的代码更改摘要: (小写且无句点)
70+
body_zh=提供有关代码更改的其他上下文信息: (按[ENTER]跳过)
71+
is_breaking_change_zh=这是一个突破性的变化吗?与SemVer中的专业相关
72+
footer_zh=页脚。有关此提交关闭的重大更改和引用问题的信息: (按[ENTER]跳过)
73+
prefix_it=Seleziona il tipo di modifica che stai apportando
74+
fix_it=Una correzione di bug. Correla con la PATCH in SemVer
75+
feat_it=Una nuova funzionalità. Correla con MINORE in SemVer
76+
docs_it=Modifiche solo della documentazione
77+
style_it=Modifiche che non influiscono sul significato del codice (spazi bianchi, formattazione, punti e virgola mancanti, ecc.)
78+
refactor_it=Una modifica del codice che non corregge un bug né aggiunge una funzionalità
79+
perf_it=Una modifica del codice che migliora le prestazioni
80+
test_it=Aggiunta di test mancanti o correzione di test esistenti
81+
build_it=Modifiche che interessano il sistema di compilazione o dipendenze esterne (ambiti di esempio: pip, docker, npm)
82+
ci_it=Modifiche ai file e agli script di configurazione CI (ambiti di esempio: GitLabCI)
83+
scope_it=Qual è l'ambito di questa modifica? (classe o gnome file): (premere [enter] per saltare)
84+
subject_it=Scrivi un breve e imperativo riepilogo delle modifiche al codice: (minuscolo e senza punto)
85+
body_it=Fornisci ulteriori informazioni contestuali sulle modifiche al codice: (premi [Invio] per saltare)
86+
is_breaking_change_it=È un CAMBIAMENTO RADICALE? Correla con MAGGIORE in SemVer
87+
footer_it=Piè di pagina. Informazioni sulle Breaking Change e sui problemi di riferimento che questo commit chiude: (premi [invio] per saltare)
88+
prefix_pt=Seleccione o tipo de alteração que está a cometer
89+
fix_pt=Uma correção de bugs. Correlaciona com o PATCH no SemVer
90+
feat_pt=Um novo recurso. Correlaciona com MENOR no SemVer
91+
docs_pt=Apenas alterações na documentação
92+
style_pt=Alterações que não afetam o significado do código (espaço em branco, formatação, ponto e vírgula ausente, etc.)
93+
refactor_pt=Uma alteração de código que não corrige um bug nem adiciona um recurso
94+
perf_pt=Uma mudança de código que melhora o desempenho
95+
test_pt=Adição de testes ausentes ou correção de testes existentes
96+
build_pt=Mudanças que afetam o sistema de compilação ou dependências externas (escopos de exemplo: pip, docker, npm)
97+
ci_pt=Alterações em arquivos e scripts de configuração de CI (escopos de exemplo: GitLabCI)
98+
scope_pt=Qual é o escopo desta alteração? (gnome da classe ou do arquivo): (pressione [ENTER] para pular)
99+
subject_pt=Escreva um resumo curto e imperativo das alterações de código: (minúsculas e sem ponto final)
100+
body_pt=Forneça informações contextuais adicionais sobre as alterações de código: (pressione [ENTER] para pular)
101+
is_breaking_change_pt=Esta é uma MUDANÇA RADICAL? Correlaciona com ESPECIALIZAÇÃO em SemVer
102+
footer_pt=Rodapé. Informações sobre Breaking Changes e problemas de referência que este commit fecha: (pressione [ENTER] para pular)
103+
prefix_ru=Выберите тип изменения, которое вы вносите
104+
fix_ru=Исправление ошибки. Корреляция с ПАТЧЕМ в SemVer
105+
feat_ru=Новая функция. Соотносится с МИНОРОМ в SemVer
106+
docs_ru=Изменения только в документации
107+
style_ru=Изменения, которые не влияют на значение кода (пробелы, форматирование, отсутствующие точки с запятой и т. д.)
108+
refactor_ru=Изменение кода, которое не исправляет ошибку и не добавляет функцию
109+
perf_ru=Изменение кода, повышающее производительность
110+
test_ru=Добавление отсутствующих или исправление существующих тестов
111+
build_ru=Изменения, которые влияют на систему сборки или внешние зависимости (примеры областей: pip, docker, npm)
112+
ci_ru=Изменения в файлах конфигурации и сценариях CI (примеры областей: GitLabCI)
113+
scope_ru=Какова область применения этого изменения? (имя класса или файла): (нажмите [Enter], чтобы пропустить)
114+
subject_ru=Напишите краткое и обязательное резюме изменений кода: (строчные буквы и без точки)
115+
body_ru=Предоставьте дополнительную контекстную информацию об изменениях кода: (нажмите [Enter], чтобы пропустить)
116+
is_breaking_change_ru=Это кардинальное ИЗМЕНЕНИЕ? Коррелирует с МАЙОРОМ в SemVer
117+
footer_ru=Нижний колонтитул. Информация о нарушении изменений и проблемах со ссылками, которые закрывает эта фиксация: (нажмите [Enter], чтобы пропустить)
118+
prefix_ja=コミットする変更の種類を選択してください
119+
fix_ja=バグ修正。SemVerのパッチと関連しています
120+
feat_ja=新機能。SemVerのマイナーと関連します
121+
docs_ja=文書のみの変更
122+
style_ja=コードの意味に影響を与えない変更(空白、書式設定、セミコロンの欠落など)
123+
refactor_ja=バグを修正したり、機能を追加したりしないコードの変更
124+
perf_ja=パフォーマンスを向上させるコードの変更
125+
test_ja=不足しているテストの追加または既存のテストの修正
126+
build_ja=ビルドシステムまたは外部依存関係に影響する変更(スコープの例: pip、docker、npm)
127+
ci_ja=CI構成ファイルとスクリプトの変更(スコープの例: GitLabCI)
128+
scope_ja=この変更の範囲は何ですか? (クラス名またはファイル名) : ( [ENTER]を押してスキップ)
129+
subject_ja=コード変更の簡潔かつ必須の要約を記入してください: (小文字、ピリオドなし)
130+
body_ja=コードの変更に関する追加のコンテキスト情報を提供します: ( [ENTER]を押してスキップ)
131+
is_breaking_change_ja=これは画期的な変更ですか? SemVerのメジャーと相関する
132+
footer_ja=フッター。このコミットが閉じる重大な変更と参照の問題に関する情報: ( [ENTER]を押してスキップ)
133+
prefix_ko=커밋할 변경 유형 선택
134+
fix_ko=버그 수정. SemVer의 패치와 상관 관계
135+
feat_ko=새로운 기능입니다. SemVer에서 미성년자와 상관 관계가 있습니다.
136+
docs_ko=증빙 자료만 변경됨
137+
style_ko=코드의 의미에 영향을 미치지 않는 변경 사항 (공백, 서식, 누락된 세미콜론 등)
138+
refactor_ko=버그를 수정하거나 기능을 추가하지 않은 코드 변경
139+
perf_ko=성능을 향상시키는 코드 변경
140+
test_ko=누락되거나 수정된 기존 테스트 추가
141+
build_ko=빌드 시스템 또는 외부 종속성에 영향을 미치는 변경 사항 (예: 범위: pip, docker, npm)
142+
ci_ko=CI 구성 파일 및 스크립트 변경 (예: 범위: GitLabCI)
143+
scope_ko=변경 범위는 어떻게 됩니까? (클래스 또는 파일 이름): (건너뛰려면 [ENTER] 키를 누르세요)
144+
subject_ko=코드 변경 사항에 대한 짧고 필수적인 요약을 작성하십시오: (소문자 및 마침표 없음)
145+
body_ko=코드 변경에 대한 추가 문맥 정보 제공: (건너뛰려면 [ENTER] 키를 누르세요)
146+
is_breaking_change_ko=획기적인 변화인가요? SemVer의 전공과 상관 관계 있음
147+
footer_ko=Footer. Breaking Changes 및 이 커밋이 종료되는 참조 문제에 대한 정보: (건너뛰려면 [ENTER] 키를 누르세요)

commitizen/cz/conventional_commits/conventional_commits.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -156,28 +156,38 @@ def questions(self, language: str) -> Questions:
156156
"filter": parse_subject,
157157
"message": translate_text_from_eng(
158158
"Write a short and imperative summary of the code changes: (lower case and no period)\n",
159-
language, "subject"),
159+
language,
160+
"subject",
161+
),
160162
},
161163
{
162164
"type": "input",
163165
"name": "body",
164-
"message": (
165-
"Provide additional contextual information about the code changes: (press [enter] to skip)\n"
166+
"message": translate_text_from_eng(
167+
"Provide additional contextual information about the code changes: (press [enter] to skip)\n",
168+
language,
169+
"body",
166170
),
167171
"filter": multiple_line_breaker,
168172
},
169173
{
170174
"type": "confirm",
171-
"message": "Is this a BREAKING CHANGE? Correlates with MAJOR in SemVer",
175+
"message": translate_text_from_eng(
176+
"Is this a BREAKING CHANGE? Correlates with MAJOR in SemVer",
177+
language,
178+
"is_breaking_change",
179+
),
172180
"name": "is_breaking_change",
173181
"default": False,
174182
},
175183
{
176184
"type": "input",
177185
"name": "footer",
178-
"message": (
186+
"message": translate_text_from_eng(
179187
"Footer. Information about Breaking Changes and "
180-
"reference issues that this commit closes: (press [enter] to skip)\n"
188+
"reference issues that this commit closes: (press [enter] to skip)\n",
189+
language,
190+
"footer",
181191
),
182192
},
183193
]

commitizen/cz/conventional_commits/translation_multilanguage.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from translate import Translator
22

33
FILENAME = "commitizen/cz/conventional_commits/.cache_multilanguage.txt"
4+
IS_TRANSLATING = True
45
MULTILANGUAGE = {}
56

67

@@ -14,22 +15,34 @@ def load_multilanguage():
1415
key, value = line.strip().split("=", 1)
1516
MULTILANGUAGE[key] = value
1617

18+
1719
def generate_key(original_key, to_lang):
1820
return f"{original_key}_{to_lang}"
1921

22+
2023
def save_multilanguage(key, value):
2124
if "\n" in value:
2225
value = value.replace("\n", "")
2326
with open(FILENAME, "a") as file:
2427
file.write(f"{key}={value}\n")
2528

29+
2630
def translate_text(text, from_lang, to_lang):
31+
global IS_TRANSLATING
32+
if not IS_TRANSLATING:
33+
return text
2734
translator = Translator(from_lang=from_lang, to_lang=to_lang)
2835
translation = translator.translate(text)
36+
if "IS AN INVALID TARGET LANGUAGE" in translation:
37+
IS_TRANSLATING = False
38+
print("Error translating text")
39+
return text
2940
return translation
3041

42+
3143
def translate_text_from_eng(text, to_lang, key):
3244
global MULTILANGUAGE
45+
global IS_TRANSLATING
3346
key_generated = generate_key(key, to_lang)
3447
if not MULTILANGUAGE:
3548
load_multilanguage()
@@ -40,6 +53,9 @@ def translate_text_from_eng(text, to_lang, key):
4053
MULTILANGUAGE[key_generated] = text
4154
save_multilanguage(key_generated, MULTILANGUAGE[key_generated])
4255
return text
43-
MULTILANGUAGE[key_generated] = translate_text(text, "en", to_lang)
44-
save_multilanguage(key_generated, MULTILANGUAGE[key_generated])
45-
return MULTILANGUAGE[key_generated]
56+
output = translate_text(text, "en", to_lang)
57+
if IS_TRANSLATING:
58+
MULTILANGUAGE[key_generated] = output
59+
save_multilanguage(key_generated, MULTILANGUAGE[key_generated])
60+
return MULTILANGUAGE[key_generated]
61+
return text

0 commit comments

Comments
 (0)