♻️ refactor(devtools/shared/git.py): update GitService to return exit code from _run\_git\_command and improve get\_commit\_history method signature and docstring.
This commit is contained in:
1 file changed
+37
-33
+37
-33
@@ -1,19 +1,21 @@
|
|||||||
"""
|
"""
|
||||||
Shared Git service for devtools.
|
Shared Git service for devtools.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import subprocess
|
import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Dict, Optional, Tuple
|
from typing import List, Dict, Optional, Tuple
|
||||||
import os
|
import os
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
|
||||||
class GitService:
|
class GitService:
|
||||||
"""Base Git service that can be extended by specific tools."""
|
"""Base Git service that can be extended by specific tools."""
|
||||||
|
|
||||||
def __init__(self, repo_path: str):
|
def __init__(self, repo_path: str):
|
||||||
"""Initialize GitService with repository path."""
|
"""Initialize GitService with repository path."""
|
||||||
self.repo_path = repo_path
|
self.repo_path = repo_path
|
||||||
if not os.path.exists(os.path.join(repo_path, '.git')):
|
if not os.path.exists(os.path.join(repo_path, ".git")):
|
||||||
raise ValueError(f"Not a git repository: {repo_path}")
|
raise ValueError(f"Not a git repository: {repo_path}")
|
||||||
|
|
||||||
def _is_git_repo(self) -> bool:
|
def _is_git_repo(self) -> bool:
|
||||||
@@ -23,25 +25,25 @@ class GitService:
|
|||||||
["git", "rev-parse", "--is-inside-work-tree"],
|
["git", "rev-parse", "--is-inside-work-tree"],
|
||||||
cwd=self.repo_path,
|
cwd=self.repo_path,
|
||||||
check=True,
|
check=True,
|
||||||
capture_output=True
|
capture_output=True,
|
||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
except subprocess.CalledProcessError:
|
except subprocess.CalledProcessError:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _run_git_command(self, args: List[str]) -> Tuple[str, str]:
|
def _run_git_command(self, args: List[str]) -> Tuple[str, str, int]:
|
||||||
"""Run a git command and return its output."""
|
"""Run a git command and return its output and return code."""
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
["git"] + args,
|
["git"] + args,
|
||||||
cwd=self.repo_path,
|
cwd=self.repo_path,
|
||||||
check=True,
|
check=True,
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True
|
text=True,
|
||||||
)
|
)
|
||||||
return result.stdout.strip(), result.stderr.strip()
|
return result.stdout.strip(), result.stderr.strip(), result.returncode
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
return e.stdout.strip(), e.stderr.strip()
|
return e.stdout.strip(), e.stderr.strip(), e.returncode
|
||||||
|
|
||||||
def get_staged_files(self) -> List[str]:
|
def get_staged_files(self) -> List[str]:
|
||||||
"""Get list of staged files."""
|
"""Get list of staged files."""
|
||||||
@@ -50,7 +52,9 @@ class GitService:
|
|||||||
|
|
||||||
def get_unstaged_files(self) -> List[str]:
|
def get_unstaged_files(self) -> List[str]:
|
||||||
"""Get list of unstaged files."""
|
"""Get list of unstaged files."""
|
||||||
stdout, _ = self._run_git_command(["ls-files", "--modified", "--others", "--exclude-standard"])
|
stdout, _ = self._run_git_command(
|
||||||
|
["ls-files", "--modified", "--others", "--exclude-standard"]
|
||||||
|
)
|
||||||
return stdout.splitlines() if stdout else []
|
return stdout.splitlines() if stdout else []
|
||||||
|
|
||||||
def get_diff(self, file_path: str, staged: bool = True) -> str:
|
def get_diff(self, file_path: str, staged: bool = True) -> str:
|
||||||
@@ -89,8 +93,8 @@ class GitService:
|
|||||||
"""Push changes to remote."""
|
"""Push changes to remote."""
|
||||||
if not branch:
|
if not branch:
|
||||||
branch = self.get_current_branch()
|
branch = self.get_current_branch()
|
||||||
stdout, stderr = self._run_git_command(["push", "origin", branch])
|
stdout, stderr, returncode = self._run_git_command(["push", "origin", branch])
|
||||||
return not stderr
|
return returncode == 0
|
||||||
|
|
||||||
def get_staged_changes(self, files: Optional[List[str]] = None) -> Dict[str, str]:
|
def get_staged_changes(self, files: Optional[List[str]] = None) -> Dict[str, str]:
|
||||||
"""Get staged changes for specified files or all staged changes."""
|
"""Get staged changes for specified files or all staged changes."""
|
||||||
@@ -100,36 +104,36 @@ class GitService:
|
|||||||
if files:
|
if files:
|
||||||
for file in files:
|
for file in files:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
['git', 'diff', '--staged', '--', file],
|
["git", "diff", "--staged", "--", file],
|
||||||
cwd=self.repo_path,
|
cwd=self.repo_path,
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True
|
text=True,
|
||||||
)
|
)
|
||||||
if result.stdout:
|
if result.stdout:
|
||||||
diffs[file] = result.stdout
|
diffs[file] = result.stdout
|
||||||
else:
|
else:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
['git', 'diff', '--staged'],
|
["git", "diff", "--staged"],
|
||||||
cwd=self.repo_path,
|
cwd=self.repo_path,
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True
|
text=True,
|
||||||
)
|
)
|
||||||
if result.stdout:
|
if result.stdout:
|
||||||
# Parse the diff to get individual file changes
|
# Parse the diff to get individual file changes
|
||||||
current_file = None
|
current_file = None
|
||||||
current_diff = []
|
current_diff = []
|
||||||
|
|
||||||
for line in result.stdout.split('\n'):
|
for line in result.stdout.split("\n"):
|
||||||
if line.startswith('diff --git'):
|
if line.startswith("diff --git"):
|
||||||
if current_file and current_diff:
|
if current_file and current_diff:
|
||||||
diffs[current_file] = '\n'.join(current_diff)
|
diffs[current_file] = "\n".join(current_diff)
|
||||||
current_file = line.split('b/')[-1].strip()
|
current_file = line.split("b/")[-1].strip()
|
||||||
current_diff = [line]
|
current_diff = [line]
|
||||||
elif current_file:
|
elif current_file:
|
||||||
current_diff.append(line)
|
current_diff.append(line)
|
||||||
|
|
||||||
if current_file and current_diff:
|
if current_file and current_diff:
|
||||||
diffs[current_file] = '\n'.join(current_diff)
|
diffs[current_file] = "\n".join(current_diff)
|
||||||
|
|
||||||
return diffs
|
return diffs
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
@@ -138,15 +142,13 @@ class GitService:
|
|||||||
def stage_all_changes(self) -> None:
|
def stage_all_changes(self) -> None:
|
||||||
"""Stage all changes in the repository."""
|
"""Stage all changes in the repository."""
|
||||||
try:
|
try:
|
||||||
subprocess.run(
|
subprocess.run(["git", "add", "."], cwd=self.repo_path, check=True)
|
||||||
['git', 'add', '.'],
|
|
||||||
cwd=self.repo_path,
|
|
||||||
check=True
|
|
||||||
)
|
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
raise Exception(f"Failed to stage changes: {str(e)}")
|
raise Exception(f"Failed to stage changes: {str(e)}")
|
||||||
|
|
||||||
def get_commit_history(self, since: Optional[str] = None, limit: Optional[int] = None) -> List[Dict[str, str]]:
|
def get_commit_history(
|
||||||
|
self, since: Optional[str] = None, limit: Optional[int] = None
|
||||||
|
) -> List[Dict[str, str]]:
|
||||||
"""Get commit history.
|
"""Get commit history.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -156,7 +158,7 @@ class GitService:
|
|||||||
args = [
|
args = [
|
||||||
"log",
|
"log",
|
||||||
"--pretty=format:%H%n%an%n%ad%n%B%n==END==",
|
"--pretty=format:%H%n%an%n%ad%n%B%n==END==",
|
||||||
"--date=format:%Y-%m-%d %H:%M:%S %z"
|
"--date=format:%Y-%m-%d %H:%M:%S %z",
|
||||||
]
|
]
|
||||||
|
|
||||||
if since:
|
if since:
|
||||||
@@ -169,16 +171,18 @@ class GitService:
|
|||||||
commits = []
|
commits = []
|
||||||
current_commit = []
|
current_commit = []
|
||||||
|
|
||||||
for line in stdout.split('\n'):
|
for line in stdout.split("\n"):
|
||||||
if line == "==END==":
|
if line == "==END==":
|
||||||
if current_commit:
|
if current_commit:
|
||||||
commit_hash, author, date, *message_lines = current_commit
|
commit_hash, author, date, *message_lines = current_commit
|
||||||
commits.append({
|
commits.append(
|
||||||
'hash': commit_hash,
|
{
|
||||||
'author': author,
|
"hash": commit_hash,
|
||||||
'date': date,
|
"author": author,
|
||||||
'message': '\n'.join(message_lines)
|
"date": date,
|
||||||
})
|
"message": "\n".join(message_lines),
|
||||||
|
}
|
||||||
|
)
|
||||||
current_commit = []
|
current_commit = []
|
||||||
else:
|
else:
|
||||||
current_commit.append(line)
|
current_commit.append(line)
|
||||||
|
|||||||
Reference in new issue
Block a user