Skip to content

Commit eab01bc

Browse files
Merge pull request #1 from lucasferreiralimax/i18n
i18n and refactory folders
2 parents 81b0570 + eea0520 commit eab01bc

24 files changed

+300
-123
lines changed
File renamed without changes.

gitman/commands/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from .projects_update import projects_update
2+
from .ncu_update import ncu_update
3+
from .get_cli_version import get_cli_version
4+
from .check_outdated import check_outdated
5+
from .check_status import check_status
6+
7+
# Exportando funções/módulos
8+
__all__ = ["projects_update", "ncu_update", "get_cli_version", "check_outdated", "check_status"]
Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
11
import os
22
import subprocess
3+
import i18n
34

45
# Função para verificar dependências desatualizadas em todos os projetos
56
def check_outdated(base_dir):
67
for dir in os.listdir(base_dir):
78
full_path = os.path.join(base_dir, dir)
89
if os.path.isdir(full_path):
9-
print("Entrando no diretório:", full_path)
10+
print(i18n.t('check_outdated.entering_directory', fullpath=full_path))
1011
os.chdir(full_path)
1112

1213
try:
13-
print("Rodando 'outdated' em", full_path)
14+
print(i18n.t('check_outdated.running_outdated', fullpath=full_path))
1415
subprocess.run(['npm', 'outdated'], check=True)
1516

1617
except subprocess.CalledProcessError as e:
17-
print(f"Erro ao verificar dependências desatualizadas em {full_path}:")
18+
print(i18n.t('check_outdated.error', fullpath=full_path))
1819
print(e.stderr)
1920

2021
os.chdir('..')
2122

22-
print("Verificação concluída.")
23+
print(i18n.t('check_status.complete_status'))
Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
11
import os
22
import subprocess
3+
import i18n
34

45
# Função para verificar o status do Git em todos os projetos
56
def check_status(base_dir):
67
for dir in os.listdir(base_dir):
78
full_path = os.path.join(base_dir, dir)
89
if os.path.isdir(full_path):
9-
print("Entrando no diretório:", full_path)
10+
print(i18n.t('check_status.entering_directory', fullpath=full_path))
1011
os.chdir(full_path)
1112

1213
try:
13-
print("Verificando o status do Git em", full_path)
14+
print(i18n.t('check_status.checking_git_status', fullpath=full_path))
1415
subprocess.run(['git', 'status'], check=True)
1516

1617
except subprocess.CalledProcessError as e:
17-
print(f"Erro ao verificar o status do Git em {full_path}:")
18+
print(i18n.t('check_status.git_error', fullpath=full_path))
1819
print(e.stderr)
1920

2021
os.chdir('..')
21-
22-
print("Verificação de status do Git concluída.")
22+
23+
print(i18n.t('check_status.complete_status'))
Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
from importlib.metadata import version
2+
import i18n
23

34
# Função para exibir a versão do programa
45
def get_cli_version():
56
try:
6-
return version('gitman')
7+
print(i18n.t('comman.version', version=version('gitman')))
78
except Exception:
8-
return "Versão desconhecida"
9+
print(i18n.t('comman.version_not_found'))
Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,28 @@
11
import os
22
import subprocess
3+
import i18n
34

4-
# Função para rodar npx npm-check-updates e atualizar dependências
5-
def ncu_update_projects(projects, commit_message, base_dir):
5+
# Função para rodar npx npm-check-updates e atualizar
6+
def ncu_update(projects, commit_message, base_dir):
67
project_list = projects.split(',')
78

89
for project_dir in project_list:
910
full_path = os.path.join(base_dir, project_dir)
1011
if not os.path.isdir(full_path):
11-
print(f"O diretório {full_path} não existe.")
12+
print(i18n.t('ncu_update.ncu_directory_not_exist').format(fullpath=full_path))
1213
continue
1314

15+
print(i18n.t('ncu_update.ncu_entering_directory').format(fullpath=full_path))
1416
os.chdir(full_path)
1517

16-
print(f"Atualizando todas as dependências em {full_path} com npm-check-updates")
17-
1818
try:
19+
print(i18n.t('ncu_update.ncu_running').format(fullpath=full_path))
1920
# Executa npx npm-check-updates
2021
ncu_result = subprocess.run(['npx', 'npm-check-updates', '-u'], capture_output=True, text=True)
2122

2223
# Exibir a saída completa para depuração
23-
print(f"Saída do npx npm-check-updates:\n{ncu_result.stdout}")
24-
print(f"Erros do npx npm-check-updates:\n{ncu_result.stderr}")
24+
print(i18n.t('ncu_update.ncu_output').format(output=ncu_result.stdout))
25+
print(i18n.t('ncu_update.ncu_errors').format(errors=ncu_result.stderr))
2526

2627
# Se houver atualizações, ncu_result.returncode será 1
2728
if ncu_result.returncode not in [0, 1]:
@@ -31,8 +32,8 @@ def ncu_update_projects(projects, commit_message, base_dir):
3132
install_result = subprocess.run(['npm', 'install'], capture_output=True, text=True)
3233

3334
# Exibir a saída completa para depuração
34-
print(f"Saída do npm install:\n{install_result.stdout}")
35-
print(f"Erros do npm install:\n{install_result.stderr}")
35+
print(i18n.t('ncu_update.ncu_npm_install_output').format(output=install_result.stdout))
36+
print(i18n.t('ncu_update.ncu_npm_install_errors').format(errors=install_result.stderr))
3637

3738
if install_result.returncode != 0:
3839
raise subprocess.CalledProcessError(install_result.returncode, install_result.args, output=install_result.stdout, stderr=install_result.stderr)
@@ -41,12 +42,17 @@ def ncu_update_projects(projects, commit_message, base_dir):
4142
subprocess.run(['git', 'add', 'package.json', 'package-lock.json'], check=True)
4243
subprocess.run(['git', 'commit', '-m', commit_message], check=True)
4344
subprocess.run(['git', 'push'], check=True)
45+
46+
print(i18n.t('ncu_update.ncu_git_commit_message').format(message=commit_message))
47+
print(i18n.t('ncu_update.ncu_git_push'))
4448

4549
except subprocess.CalledProcessError as e:
46-
print(f"Erro ao executar npm-check-updates ou npm install em {full_path}:")
47-
print(f"Comando: {e.cmd}")
48-
print(f"Retorno do comando: {e.returncode}")
49-
print(f"Saída: {e.output}")
50-
print(f"Erro: {e.stderr}")
50+
print(i18n.t('ncu_update.ncu_error').format(fullpath=full_path))
51+
print(i18n.t('ncu_update.ncu_command').format(command=e.cmd))
52+
print(i18n.t('ncu_update.ncu_return_code').format(returncode=e.returncode))
53+
print(i18n.t('ncu_update.ncu_output').format(output=e.output.decode()))
54+
print(i18n.t('ncu_update.ncu_error_details').format(errors=e.stderr.decode()))
5155

5256
os.chdir('..')
57+
58+
print(i18n.t('ncu_update.ncu_complete'))
Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
import os
22
import subprocess
3+
import i18n
34

45
# Função para atualizar dependências de um projeto
5-
def update_projects(projects, ignored_deps, commit_message, base_dir):
6+
def projects_update(projects, ignored_deps, commit_message, base_dir):
67
project_list = projects.split(',')
78

89
for project_dir in project_list:
910
full_path = os.path.join(base_dir, project_dir)
1011
if not os.path.isdir(full_path):
11-
print(f"O diretório {full_path} não existe.")
12+
print(i18n.t('update.up_directory_not_exist').format(fullpath=full_path))
1213
continue
1314

1415
os.chdir(full_path)
1516

16-
print(f"Verificando dependências desatualizadas em {full_path}")
17+
print(i18n.t('update.up_checking_outdated').format(fullpath=full_path))
1718

1819
try:
1920
# Gera uma lista de dependências desatualizadas com nome e versão
@@ -23,8 +24,8 @@ def update_projects(projects, ignored_deps, commit_message, base_dir):
2324
)
2425

2526
# Exibir a saída completa para depuração
26-
print(f"Saída do npm outdated:\n{outdated_result.stdout}")
27-
print(f"Erros do npm outdated:\n{outdated_result.stderr}")
27+
print(i18n.t('update.up_outdated_output').format(output=outdated_result.stdout))
28+
print(i18n.t('update.up_outdated_errors').format(errors=outdated_result.stderr))
2829

2930
# Se houver dependências desatualizadas, outdated_result.returncode será 1
3031
if outdated_result.returncode not in [0, 1]:
@@ -41,29 +42,32 @@ def update_projects(projects, ignored_deps, commit_message, base_dir):
4142
)
4243

4344
if outdated_packages:
44-
print("Dependências desatualizadas encontradas. Atualizando dependências:")
45+
print(i18n.t('update.up_outdated_found'))
4546
for package in outdated_packages.split('\n'):
4647
package_name = package.split(':')[1]
4748
print(f" - {package_name}")
4849

4950
# Atualiza cada pacote individualmente
5051
for package in outdated_packages.split('\n'):
5152
package_name = package.split(':')[1]
52-
print(f"Atualizando {package_name}")
53+
print(i18n.t('update.up_updating_package').format(package_name=package_name))
5354
subprocess.run(['npm', 'install', package_name, '--legacy-peer-deps'], check=True)
5455

5556
# Adiciona mudanças ao Git, cria um commit e faz push
5657
subprocess.run(['git', 'add', 'package.json', 'package-lock.json'], check=True)
5758
subprocess.run(['git', 'commit', '-m', commit_message], check=True)
5859
subprocess.run(['git', 'push'], check=True)
60+
61+
print(i18n.t('update.up_git_commit_message').format(message=commit_message))
62+
print(i18n.t('update.up_git_push'))
5963
else:
60-
print(f"Todas as dependências estão atualizadas em {full_path}")
64+
print(i18n.t('update.up_all_to_date').format(fullpath=full_path))
6165

6266
except subprocess.CalledProcessError as e:
63-
print(f"Erro ao verificar/atualizar dependências em {full_path}:")
64-
print(f"Comando: {e.cmd}")
65-
print(f"Retorno do comando: {e.returncode}")
66-
print(f"Saída: {e.output}")
67-
print(f"Erro: {e.stderr}")
67+
print(i18n.t('update.up_error').format(fullpath=full_path))
68+
print(i18n.t('update.up_command').format(command=e.cmd))
69+
print(i18n.t('update.up_return_code').format(returncode=e.returncode))
70+
print(i18n.t('update.up_output').format(output=e.output.decode()))
71+
print(i18n.t('update.up_error_details').format(errors=e.stderr.decode()))
6872

6973
os.chdir('..')

gitman/config.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import i18n
2+
import platform
3+
import subprocess
4+
5+
def i18nConfig():
6+
# Obter informações do sistema
7+
system_info = platform.system()
8+
9+
if system_info == 'Windows':
10+
# Para Windows, usando o módulo winreg para obter o idioma
11+
import winreg
12+
13+
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Control Panel\\International", 0, winreg.KEY_READ)
14+
system_lang, _ = winreg.QueryValueEx(key, "LocaleName")
15+
winreg.CloseKey(key)
16+
17+
elif system_info == 'Darwin':
18+
# Para macOS, usando o comando 'defaults' para obter o idioma
19+
proc = subprocess.Popen(['defaults', 'read', '-g', 'AppleLocale'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
20+
out, _ = proc.communicate()
21+
system_lang = out.strip().decode('utf-8')
22+
23+
else:
24+
# Para Linux e outros sistemas baseados em Unix, usando 'locale' para obter o idioma
25+
proc = subprocess.Popen(['locale'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
26+
out, _ = proc.communicate()
27+
system_lang = out.split()[0].decode('utf-8').split('=')[1]
28+
29+
if system_lang:
30+
system_lang = system_lang[:2]
31+
32+
i18n.load_path.append('gitman/translations')
33+
i18n.set('fallback', 'en')
34+
i18n.set('locale', system_lang)

gitman/main.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import sys
4+
import i18n
5+
from .config import i18nConfig
6+
from .commands import projects_update
7+
from .commands import ncu_update
8+
from .commands import get_cli_version
9+
from .commands import check_outdated
10+
from .commands import check_status
11+
12+
gitman = """
13+
_______ __ .___________..___ ___. ___ .__ __.
14+
/ _____|| | | || \/ | / \ | \ | |
15+
| | __ | | `---| |----`| \ / | / ^ \ | \| |
16+
| | |_ | | | | | | |\/| | / /_\ \ | . ` |
17+
| |__| | | | | | | | | | / _____ \ | |\ |
18+
\______| |__| |__| |__| |__| /__/ \__\ |__| \__|
19+
20+
"""
21+
22+
# Função para exibir o uso correto do script
23+
def usage():
24+
print(gitman)
25+
print(i18n.t('main.usage.description'))
26+
for i in range(1, 9):
27+
new_line = 'line' + str(i)
28+
print(i18n.t('main.usage.'+ new_line))
29+
sys.exit(1)
30+
31+
# Função principal do programa
32+
def app():
33+
try:
34+
i18nConfig()
35+
36+
# Verifica os parâmetros do script
37+
if len(sys.argv) == 1:
38+
usage()
39+
40+
project_directory = ""
41+
ignored_dependencies = ""
42+
ncu_flag = False
43+
commit_message = "update: deps of project"
44+
base_directory = os.path.expanduser("~/Documents")
45+
46+
# Processa os argumentos de linha de comando
47+
args = sys.argv[1:]
48+
while args:
49+
opt = args.pop(0)
50+
if opt == '-b':
51+
base_directory = os.path.expanduser(args.pop(0))
52+
elif opt == '-u':
53+
project_directory = args.pop(0)
54+
elif opt == '-i':
55+
ignored_dependencies = args.pop(0)
56+
elif opt == '-a':
57+
check_outdated(base_directory)
58+
elif opt == '-g':
59+
check_status(base_directory)
60+
elif opt == '-n':
61+
project_directory = args.pop(0)
62+
ncu_flag = True
63+
elif opt == '-m':
64+
commit_message = args.pop(0)
65+
elif opt in ('-v', '--version'):
66+
get_cli_version()
67+
sys.exit(0)
68+
else:
69+
usage()
70+
71+
# Executa o comando apropriado baseado nos parâmetros fornecidos
72+
if ncu_flag:
73+
ncu_update(project_directory, commit_message, base_directory)
74+
elif project_directory:
75+
projects_update(project_directory, ignored_dependencies, commit_message, base_directory)
76+
77+
except KeyboardInterrupt:
78+
print(gitman)
79+
print('\nGitman execution interrupted; exiting.')
80+
sys.exit(0)
81+
82+
except Exception as e:
83+
print(f"Erro: {e}")
84+
sys.exit(1)
85+
86+
if __name__ == "__main__":
87+
app()
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
en:
2+
entering_directory: "Entering directory: %{fullpath}"
3+
running_outdated: "Running 'outdated' in %{fullpath}"
4+
error: "Error checking outdated dependencies in %{fullpath}:"
5+
complete_check: "Check completed."

0 commit comments

Comments
 (0)