Skip to content

Commit a52857d

Browse files
authored
Merge pull request #1 from MariaHilmar/fix/wsl-git-coleta
fix: coleta Git via WSL (repos /root/MGI)
2 parents a6ccf01 + f9dd1a1 commit a52857d

3 files changed

Lines changed: 80 additions & 52 deletions

File tree

coleta_git_contratos.py

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,68 +6,83 @@
66
Consolidação de múltiplos repositórios na mesma saída
77
"""
88

9+
import os
910
import subprocess
1011
import json
1112
from datetime import datetime
1213
from pathlib import Path
1314
from typing import Dict, List, Optional, Tuple
1415
import re
1516

17+
try:
18+
from issue_keys import wsl_path_for_repo
19+
except ImportError:
20+
def wsl_path_for_repo(repo: str) -> str:
21+
paths = {
22+
"contratos_v2": "/root/MGI/contratos_v2",
23+
"contratos": "/root/MGI/contratos",
24+
}
25+
return paths.get(repo, "/root/MGI/contratos_v2")
26+
27+
WSL_DISTRO = os.environ.get("MGI_WSL_DISTRO", "Ubuntu")
28+
29+
1630
class GitColeta:
1731
def __init__(self, repo_path: str, repo_name: Optional[str] = None):
1832
self.repo_path = Path(repo_path)
1933
self.repo_name = repo_name or Path(repo_path).name
34+
self.wsl_repo_path = wsl_path_for_repo(self.repo_name)
2035
self.data: Dict = {
2136
'timestamp': datetime.now().isoformat(),
2237
'repositorio': self.repo_name,
2338
'caminho': str(repo_path),
39+
'wsl_caminho': self.wsl_repo_path,
2440
'commits': [],
2541
'branches': [],
2642
'releases': [],
2743
'stats': {}
2844
}
2945

30-
def run_git(self, cmd: str, timeout: int = 30) -> str:
31-
"""Executa comando git no repositório.
32-
33-
Verifica o returncode e loga stderr para evitar falhas silenciosas.
34-
"""
46+
def _run_git(self, git_args: str, timeout: int = 30) -> str:
47+
"""Executa git dentro do WSL Ubuntu (repos em /root/MGI/...)."""
48+
cmd = [
49+
"wsl",
50+
"-d",
51+
WSL_DISTRO,
52+
"bash",
53+
"-lc",
54+
f"cd {self.wsl_repo_path} && git {git_args}",
55+
]
3556
try:
3657
result = subprocess.run(
3758
cmd,
38-
cwd=self.repo_path,
3959
capture_output=True,
4060
text=True,
41-
shell=True,
4261
timeout=timeout,
4362
)
4463
if result.returncode != 0:
45-
stderr = (result.stderr or '').strip()
46-
print(f"❌ Git retornou codigo {result.returncode} em {self.repo_name}: {stderr}")
64+
stderr = (result.stderr or "").strip()
65+
if stderr:
66+
print(f"ERRO Git ({self.repo_name}): {stderr}")
4767
return ""
4868
return result.stdout.strip()
4969
except subprocess.TimeoutExpired:
50-
print(f" Timeout ({timeout}s) executando git em {self.repo_name}: {cmd}")
70+
print(f"ERRO Timeout ({timeout}s) git em {self.repo_name}: {git_args[:80]}")
5171
return ""
5272
except Exception as e:
53-
print(f"❌ Erro executando git em {self.repo_name}: {e}")
73+
print(f"ERRO executando git em {self.repo_name}: {e}")
5474
return ""
5575

76+
def run_git(self, cmd: str, timeout: int = 30) -> str:
77+
"""Executa comando git no repositório (aceita 'git ...' ou args diretos)."""
78+
git_args = cmd.strip()
79+
if git_args.startswith("git "):
80+
git_args = git_args[4:]
81+
return self._run_git(git_args, timeout=timeout)
82+
5683
def validar_repo(self) -> bool:
57-
"""Verifica se o repositório é acessível e é um repositório Git válido."""
58-
try:
59-
result = subprocess.run(
60-
'git rev-parse --git-dir',
61-
cwd=self.repo_path,
62-
capture_output=True,
63-
text=True,
64-
shell=True,
65-
timeout=10,
66-
)
67-
return result.returncode == 0
68-
except Exception as e:
69-
print(f"❌ Repositorio inacessivel {self.repo_name}: {e}")
70-
return False
84+
"""Verifica se o repositório WSL é acessível e é um repositório Git válido."""
85+
return bool(self._run_git("rev-parse --git-dir", timeout=10))
7186

7287
def coleta_commits(self, since_days: int = 30) -> List[Dict[str, str]]:
7388
"""Extrai commits dos últimos N dias"""

processar_issues_memoria.py

Lines changed: 2 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -55,37 +55,12 @@ def probe_local_git_repos() -> bool:
5555

5656
def probe_wsl_git_available(timeout_seconds: int = 8) -> bool:
5757
"""Verifica se WSL Ubuntu + repo Git respondem (cache em memoria)."""
58+
del timeout_seconds # GitColeta valida via WSL com timeout proprio
5859
global _WSL_GIT_AVAILABLE
5960
if _WSL_GIT_AVAILABLE is not None:
6061
return _WSL_GIT_AVAILABLE
6162

62-
if not probe_local_git_repos():
63-
_WSL_GIT_AVAILABLE = False
64-
return False
65-
66-
import subprocess
67-
68-
from issue_keys import wsl_path_for_repo
69-
70-
repo_path = wsl_path_for_repo("contratos_v2")
71-
cmd = [
72-
"wsl",
73-
"-d",
74-
"Ubuntu",
75-
"bash",
76-
"-lc",
77-
f"cd {repo_path} && git rev-parse --git-dir",
78-
]
79-
try:
80-
result = subprocess.run(
81-
cmd,
82-
capture_output=True,
83-
text=True,
84-
timeout=timeout_seconds,
85-
)
86-
_WSL_GIT_AVAILABLE = result.returncode == 0
87-
except (OSError, subprocess.TimeoutExpired):
88-
_WSL_GIT_AVAILABLE = False
63+
_WSL_GIT_AVAILABLE = probe_local_git_repos()
8964
return _WSL_GIT_AVAILABLE
9065

9166

tests/test_coleta_git_contratos.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""Testes da coleta Git via WSL."""
2+
3+
from __future__ import annotations
4+
5+
from unittest.mock import MagicMock, patch
6+
7+
import coleta_git_contratos as cgc
8+
9+
10+
def test_validar_repo_usa_wsl():
11+
coleta = cgc.GitColeta("<path-contratos_v2>", "contratos_v2")
12+
assert coleta.wsl_repo_path == "/root/MGI/contratos_v2"
13+
14+
with patch.object(coleta, "_run_git", return_value=".git") as mock_run:
15+
assert coleta.validar_repo() is True
16+
mock_run.assert_called_once_with("rev-parse --git-dir", timeout=10)
17+
18+
19+
def test_run_git_remove_prefixo_git():
20+
coleta = cgc.GitColeta("<path-contratos>", "contratos")
21+
22+
with patch.object(coleta, "_run_git", return_value="ok") as mock_run:
23+
assert coleta.run_git('git status -sb') == "ok"
24+
mock_run.assert_called_once_with("status -sb", timeout=30)
25+
26+
27+
def test_run_git_via_wsl_comando():
28+
coleta = cgc.GitColeta("<path-contratos_v2>", "contratos_v2")
29+
mock_result = MagicMock(returncode=0, stdout="main\n", stderr="")
30+
31+
with patch("coleta_git_contratos.subprocess.run", return_value=mock_result) as mock_sub:
32+
output = coleta._run_git("branch --show-current")
33+
34+
assert output == "main"
35+
mock_sub.assert_called_once()
36+
cmd = mock_sub.call_args.args[0]
37+
assert cmd[:5] == ["wsl", "-d", "Ubuntu", "bash", "-lc"]
38+
assert "cd /root/MGI/contratos_v2 && git branch --show-current" == cmd[5]

0 commit comments

Comments
 (0)