Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: Optimize git change detection with performance improvement and multi-repository support (#9870)

Tim O'Farrell06ad5e30c936
diff --git a/openhands/runtime/utils/git_handler.py b/openhands/runtime/utils/git_handler.py
index d587c66202..8a165a06d6 100644
--- a/openhands/runtime/utils/git_handler.py
+++ b/openhands/runtime/utils/git_handler.py
@@ -1,5 +1,6 @@
from dataclasses import dataclass
from typing import Callable
+from uuid import uuid4
@dataclass
@@ -75,36 +76,10 @@ class GitHandler:
output = self.execute(cmd, self.cwd)
return output.exit_code == 0
- def _get_valid_ref(self) -> str | None:
- """
- Determines a valid Git reference for comparison.
-
- Returns:
- str | None: A valid Git reference or None if no valid reference is found.
- """
- current_branch = self._get_current_branch()
- default_branch = self._get_default_branch()
-
- ref_current_branch = f'origin/{current_branch}'
- ref_non_default_branch = f'$(git --no-pager merge-base HEAD "$(git --no-pager rev-parse --abbrev-ref origin/{default_branch})")'
- ref_default_branch = 'origin/' + default_branch
- ref_new_repo = '$(git --no-pager rev-parse --verify 4b825dc642cb6eb9a060e54bf8d69288fbee4904)' # compares with empty tree
-
- refs = [
- ref_current_branch,
- ref_non_default_branch,
- ref_default_branch,
- ref_new_repo,
- ]
- for ref in refs:
- if self._verify_ref_exists(ref):
- return ref
-
- return None
-
def _get_ref_content(self, file_path: str) -> str:
"""
Retrieves the content of a file from a valid Git reference.
+ Finds the git repository closest to the file in the tree and executes the command in that context.
Args:
file_path (str): The file path in the repository.
@@ -112,87 +87,165 @@ class GitHandler:
Returns:
str: The content of the file from the reference, or an empty string if unavailable.
"""
- ref = self._get_valid_ref()
- if not ref:
+ if not self.cwd:
return ''
- cmd = f'git --no-pager show {ref}:{file_path}'
- output = self.execute(cmd, self.cwd)
- return output.content if output.exit_code == 0 else ''
-
- def _get_default_branch(self) -> str:
- """
- Retrieves the primary Git branch name of the repository.
-
- Returns:
- str: The name of the primary branch.
- """
- cmd = 'git --no-pager remote show origin | grep "HEAD branch"'
- output = self.execute(cmd, self.cwd)
- return output.content.split()[-1].strip()
-
- def _get_current_branch(self) -> str:
- """
- Retrieves the currently selected Git branch.
-
- Returns:
- str: The name of the current branch.
- """
- cmd = 'git --no-pager rev-parse --abbrev-ref HEAD'
- output = self.execute(cmd, self.cwd)
- return output.content.strip()
-
- def _get_changed_files(self) -> list[str]:
- """
- Retrieves a list of changed files compared to a valid Git reference.
+ unique_id = uuid4().hex
+
+ # Single bash command that finds the closest git repository to the file and gets the ref content
+ cmd = f"""bash -c '
+ # Convert to absolute path
+ file_path="$(realpath "{file_path}")"
+
+ # Find the closest git repository by walking up the directory tree
+ current_dir="$(dirname "$file_path")"
+ git_repo_dir=""
+
+ while [[ "$current_dir" != "/" ]]; do
+ if [[ -d "$current_dir/.git" ]] || git -C "$current_dir" rev-parse --git-dir >/dev/null 2>&1; then
+ git_repo_dir="$current_dir"
+ break
+ fi
+ current_dir="$(dirname "$current_dir")"
+ done
+
+ # If no git repository found, exit
+ if [[ -z "$git_repo_dir" ]]; then
+ exit 1
+ fi
+
+ # Get the file path relative to the git repository root
+ repo_root="$(cd "$git_repo_dir" && git rev-parse --show-toplevel)"
+ relative_file_path="${{file_path#${{repo_root}}/}}"
+
+ # Function to get current branch
+ get_current_branch() {{
+ git -C "$git_repo_dir" rev-parse --abbrev-ref HEAD 2>/dev/null
+ }}
+
+ # Function to get default branch
+ get_default_branch() {{
+ git -C "$git_repo_dir" remote show origin 2>/dev/null | grep "HEAD branch" | awk "{{print \\$NF}}" || echo "main"
+ }}
+
+ # Function to verify if a ref exists
+ verify_ref_exists() {{
+ git -C "$git_repo_dir" rev-parse --verify "$1" >/dev/null 2>&1
+ }}
+
+ # Get valid reference for comparison
+ current_branch="$(get_current_branch)"
+ default_branch="$(get_default_branch)"
+
+ # Check if origin remote exists
+ has_origin="$(git -C "$git_repo_dir" remote | grep -q "^origin$" && echo "true" || echo "false")"
+
+ if [[ "$has_origin" == "true" ]]; then
+ ref_current_branch="origin/$current_branch"
+ ref_non_default_branch="$(git -C "$git_repo_dir" merge-base HEAD "$(git -C "$git_repo_dir" rev-parse --abbrev-ref origin/$default_branch)" 2>/dev/null || echo "")"
+ ref_default_branch="origin/$default_branch"
+ else
+ # For repositories without origin, try HEAD~1 (previous commit) or empty tree
+ ref_current_branch="HEAD~1"
+ ref_non_default_branch=""
+ ref_default_branch=""
+ fi
+ ref_new_repo="$(git -C "$git_repo_dir" rev-parse --verify 4b825dc642cb6eb9a060e54bf8d69288fbee4904 2>/dev/null || echo "")" # empty tree
+
+ # Try refs in order of preference
+ valid_ref=""
+ for ref in "$ref_current_branch" "$ref_non_default_branch" "$ref_default_branch" "$ref_new_repo"; do
+ if [[ -n "$ref" ]] && verify_ref_exists "$ref"; then
+ valid_ref="$ref"
+ break
+ fi
+ done
+
+ # If no valid ref found, exit
+ if [[ -z "$valid_ref" ]]; then
+ exit 1
+ fi
+
+ # Get the file content from the reference
+ git -C "$git_repo_dir" show "$valid_ref:$relative_file_path" 2>/dev/null || exit 1
+
+ # {unique_id}'"""
+
+ result = self.execute(cmd, self.cwd)
+
+ if result.exit_code != 0:
+ return ''
- Returns:
- list[str]: A list of changed file paths.
- """
- ref = self._get_valid_ref()
- if not ref:
- return []
-
- diff_cmd = f'git --no-pager diff --name-status {ref}'
- output = self.execute(diff_cmd, self.cwd)
- if output.exit_code != 0:
- raise RuntimeError(
- f'Failed to get diff for ref {ref} in {self.cwd}. Command output: {output.content}'
- )
- return output.content.splitlines()
-
- def _get_untracked_files(self) -> list[dict[str, str]]:
- """
- Retrieves a list of untracked files in the repository. This is useful for detecting new files.
+ # TODO: The command echoes the bash script. Why?
+ content = result.content.split(f'{unique_id}')[-1]
- Returns:
- list[dict[str, str]]: A list of dictionaries containing file paths and statuses.
- """
- cmd = 'git --no-pager ls-files --others --exclude-standard'
- output = self.execute(cmd, self.cwd)
- obs_list = output.content.splitlines()
- return (
- [{'status': 'A', 'path': path} for path in obs_list]
- if output.exit_code == 0
- else []
- )
+ return content
def get_git_changes(self) -> list[dict[str, str]] | None:
"""
- Retrieves the list of changed files in the Git repository.
+ Retrieves the list of changed files in Git repositories.
+ Examines each direct subdirectory of the workspace directory looking for git repositories
+ and returns the changes for each of these directories.
+ Optimized to use a single git command per repository for maximum performance.
Returns:
- list[dict[str, str]] | None: A list of dictionaries containing file paths and statuses. None if not a git repository.
+ list[dict[str, str]] | None: A list of dictionaries containing file paths and statuses. None if no git repositories found.
"""
- if not self._is_git_repo():
+ # If cwd is not set, return None
+ if not self.cwd:
return None
- changes_list = self._get_changed_files()
- result = parse_git_changes(changes_list)
+ # Single bash command that:
+ # 1. Creates a list of directories to check (current dir + direct subdirectories)
+ # 2. For each directory, checks if it's a git repo and gets status
+ # 3. Outputs in format: REPO_PATH|STATUS|FILE_PATH
+ cmd = """bash -c '
+ {
+ # Check current directory first
+ echo "."
+ # List direct subdirectories (excluding hidden ones)
+ find . -maxdepth 1 -type d ! -name ".*" ! -name "." 2>/dev/null || true
+ } | while IFS= read -r dir; do
+ if [ -d "$dir/.git" ] || git -C "$dir" rev-parse --git-dir >/dev/null 2>&1; then
+ # Get absolute path of the directory
+ # Get git status for this repository
+ git -C "$dir" status --porcelain -uall 2>/dev/null | while IFS= read -r line; do
+ if [ -n "$line" ]; then
+ # Extract status (first 2 chars) and file path (from char 3 onwards)
+ status=$(echo "$line" | cut -c1-2)
+ file_path=$(echo "$line" | cut -c4-)
+ # Convert status codes to single character
+ case "$status" in
+ "M "*|" M") echo "$dir|M|$file_path" ;;
+ "A "*|" A") echo "$dir|A|$file_path" ;;
+ "D "*|" D") echo "$dir|D|$file_path" ;;
+ "R "*|" R") echo "$dir|R|$file_path" ;;
+ "C "*|" C") echo "$dir|C|$file_path" ;;
+ "U "*|" U") echo "$dir|U|$file_path" ;;
+ "??") echo "$dir|A|$file_path" ;;
+ *) echo "$dir|M|$file_path" ;;
+ esac
+ fi
+ done
+ fi
+ done
+ ' """
+
+ result = self.execute(cmd.strip(), self.cwd)
+ if result.exit_code != 0 or not result.content.strip():
+ return None
- # join with any untracked files
- result += self._get_untracked_files()
- return result
+ # Parse the output
+ changes = []
+ for line in result.content.strip().split('\n'):
+ if '|' in line:
+ parts = line.split('|', 2)
+ if len(parts) == 3:
+ repo_path, status, file_path = parts
+ file_path = f'{repo_path}/{file_path}'[2:]
+ changes.append({'status': status, 'path': file_path})
+
+ return changes if changes else None
def get_git_diff(self, file_path: str) -> dict[str, str]:
"""
diff --git a/openhands/server/routes/files.py b/openhands/server/routes/files.py
index 2384651f79..5a012e5be6 100644
--- a/openhands/server/routes/files.py
+++ b/openhands/server/routes/files.py
@@ -234,11 +234,7 @@ async def git_changes(
) -> list[dict[str, str]] | JSONResponse:
runtime: Runtime = conversation.runtime
- cwd = await get_cwd(
- conversation_store,
- conversation.sid,
- runtime.config.workspace_mount_path_in_sandbox,
- )
+ cwd = runtime.config.workspace_mount_path_in_sandbox
logger.info(f'Getting git changes in {cwd}')
try:
@@ -275,11 +271,7 @@ async def git_diff(
) -> dict[str, Any] | JSONResponse:
runtime: Runtime = conversation.runtime
- cwd = await get_cwd(
- conversation_store,
- conversation.sid,
- runtime.config.workspace_mount_path_in_sandbox,
- )
+ cwd = runtime.config.workspace_mount_path_in_sandbox
try:
diff = await call_sync_from_async(runtime.get_git_diff, path, cwd)
@@ -292,20 +284,6 @@ async def git_diff(
)
-async def get_cwd(
- conversation_store: ConversationStore,
- conversation_id: str,
- workspace_mount_path_in_sandbox: str,
-) -> str:
- metadata = await conversation_store.get_metadata(conversation_id)
- cwd = workspace_mount_path_in_sandbox
- if metadata and metadata.selected_repository:
- repo_dir = metadata.selected_repository.split('/')[-1]
- cwd = os.path.join(cwd, repo_dir)
-
- return cwd
-
-
@app.post('/upload-files', response_model=POSTUploadFilesModel)
async def upload_files(
files: list[UploadFile],
diff --git a/tests/unit/test_git_handler.py b/tests/unit/test_git_handler.py
index 93f33493c8..59434023cd 100644
--- a/tests/unit/test_git_handler.py
+++ b/tests/unit/test_git_handler.py
@@ -136,168 +136,6 @@ class TestGitHandler(unittest.TestCase):
)
)
- def test_get_default_branch(self):
- """Test that _get_default_branch returns the correct branch name."""
- branch = self.git_handler._get_default_branch()
- self.assertEqual(branch, 'main')
-
- # Verify the command was executed
- self.assertTrue(
- any(
- cmd == 'git --no-pager remote show origin | grep "HEAD branch"'
- for cmd, _ in self.executed_commands
- )
- )
-
- def test_get_current_branch(self):
- """Test that _get_current_branch returns the correct branch name."""
- branch = self.git_handler._get_current_branch()
- self.assertEqual(branch, 'feature-branch')
- print('executed commands:', self.executed_commands)
-
- # Verify the command was executed
- self.assertTrue(
- any(
- cmd == 'git --no-pager rev-parse --abbrev-ref HEAD'
- for cmd, _ in self.executed_commands
- )
- )
-
- def test_get_valid_ref_with_origin_current_branch(self):
- """Test that _get_valid_ref returns the current branch in origin when it exists."""
- # This test uses the setup from setUp where the current branch exists in origin
- ref = self.git_handler._get_valid_ref()
- self.assertIsNotNone(ref)
-
- # Check that the refs were checked in the correct order
- verify_commands = [
- cmd
- for cmd, _ in self.executed_commands
- if cmd.startswith('git --no-pager rev-parse --verify')
- ]
-
- # First should check origin/feature-branch (current branch)
- self.assertTrue(any('origin/feature-branch' in cmd for cmd in verify_commands))
-
- # Should have found a valid ref (origin/feature-branch)
- self.assertEqual(ref, 'origin/feature-branch')
-
- # Verify the ref exists
- result = self._execute_command(
- f'git --no-pager rev-parse --verify {ref}', self.local_dir
- )
- self.assertEqual(result.exit_code, 0)
-
- def test_get_valid_ref_without_origin_current_branch(self):
- """Test that _get_valid_ref falls back to default branch when current branch doesn't exist in origin."""
- # Create a new branch that doesn't exist in origin
- self._execute_command(
- 'git --no-pager checkout -b new-local-branch', self.local_dir
- )
-
- # Clear the executed commands to start fresh
- self.executed_commands = []
-
- ref = self.git_handler._get_valid_ref()
- self.assertIsNotNone(ref)
-
- # Check that the refs were checked in the correct order
- verify_commands = [
- cmd
- for cmd, _ in self.executed_commands
- if cmd.startswith('git --no-pager rev-parse --verify')
- ]
-
- # Should have tried origin/new-local-branch first (which doesn't exist)
- self.assertTrue(
- any('origin/new-local-branch' in cmd for cmd in verify_commands)
- )
-
- # Should have found a valid ref (origin/main or merge-base)
- self.assertNotEqual(ref, 'origin/new-local-branch')
- self.assertTrue(ref == 'origin/main' or 'merge-base' in ref)
-
- # Verify the ref exists
- result = self._execute_command(
- f'git --no-pager rev-parse --verify {ref}', self.local_dir
- )
- self.assertEqual(result.exit_code, 0)
-
- def test_get_valid_ref_without_origin(self):
- """Test that _get_valid_ref falls back to empty tree ref when there's no origin."""
- # Create a new directory with a git repo but no origin
- no_origin_dir = os.path.join(self.test_dir, 'no-origin')
- os.makedirs(no_origin_dir, exist_ok=True)
-
- # Initialize git repo without origin
- self._execute_command('git --no-pager init', no_origin_dir)
- self._execute_command(
- "git --no-pager config user.email '[email protected]'", no_origin_dir
- )
- self._execute_command(
- "git --no-pager config user.name 'Test User'", no_origin_dir
- )
-
- # Create a file and commit it
- with open(os.path.join(no_origin_dir, 'file1.txt'), 'w') as f:
- f.write('Content in repo without origin')
- self._execute_command('git --no-pager add file1.txt', no_origin_dir)
- self._execute_command(
- "git --no-pager commit -m 'Initial commit'", no_origin_dir
- )
-
- # Create a custom GitHandler with a modified _get_default_branch method for this test
- class TestGitHandler(GitHandler):
- def _get_default_branch(self) -> str:
- # Override to handle repos without origin
- try:
- return super()._get_default_branch()
- except IndexError:
- return 'main' # Default fallback
-
- # Create a new GitHandler for this repo
- no_origin_handler = TestGitHandler(self._execute_command)
- no_origin_handler.set_cwd(no_origin_dir)
-
- # Clear the executed commands to start fresh
- self.executed_commands = []
-
- ref = no_origin_handler._get_valid_ref()
-
- # Verify that git commands were executed
- self.assertTrue(
- any(
- cmd.startswith('git --no-pager rev-parse --verify')
- for cmd, _ in self.executed_commands
- )
- )
-
- # Should have fallen back to the empty tree ref
- self.assertEqual(
- ref,
- '$(git --no-pager rev-parse --verify 4b825dc642cb6eb9a060e54bf8d69288fbee4904)',
- )
-
- # Verify the ref exists (the empty tree ref always exists)
- result = self._execute_command(
- 'git --no-pager rev-parse --verify 4b825dc642cb6eb9a060e54bf8d69288fbee4904',
- no_origin_dir,
- )
- self.assertEqual(result.exit_code, 0)
-
- def test_get_ref_content(self):
- """Test that _get_ref_content returns the content from a valid ref."""
- content = self.git_handler._get_ref_content('file1.txt')
- self.assertEqual(content.strip(), 'Modified content')
-
- # Should have called _get_valid_ref and then git show
- show_commands = [
- cmd
- for cmd, _ in self.executed_commands
- if cmd.startswith('git --no-pager show')
- ]
- self.assertTrue(any('file1.txt' in cmd for cmd in show_commands))
-
def test_get_current_file_content(self):
"""Test that _get_current_file_content returns the current content of a file."""
content = self.git_handler._get_current_file_content('file1.txt')
@@ -308,50 +146,6 @@ class TestGitHandler(unittest.TestCase):
any(cmd == 'cat file1.txt' for cmd, _ in self.executed_commands)
)
- def test_get_changed_files(self):
- """Test that _get_changed_files returns the list of changed files."""
- # Let's create a new file to ensure it shows up in the diff
- with open(os.path.join(self.local_dir, 'new_file.txt'), 'w') as f:
- f.write('New file content')
- self._execute_command('git --no-pager add new_file.txt', self.local_dir)
-
- files = self.git_handler._get_changed_files()
- self.assertTrue(files)
-
- # Should include file1.txt (modified) and file3.txt (deleted)
- file_paths = [line.split('\t')[-1] for line in files if '\t' in line]
- self.assertIn('file1.txt', file_paths)
- self.assertIn('file3.txt', file_paths)
- # Also check for the new file
- self.assertIn('new_file.txt', file_paths)
-
- # Should have called _get_valid_ref and then git diff
- diff_commands = [
- cmd
- for cmd, _ in self.executed_commands
- if cmd.startswith('git --no-pager diff')
- ]
- self.assertTrue(diff_commands)
-
- def test_get_untracked_files(self):
- """Test that _get_untracked_files returns the list of untracked files."""
- # Create an untracked file
- with open(os.path.join(self.local_dir, 'untracked.txt'), 'w') as f:
- f.write('Untracked file content')
-
- files = self.git_handler._get_untracked_files()
- self.assertEqual(len(files), 1)
- self.assertEqual(files[0]['path'], 'untracked.txt')
- self.assertEqual(files[0]['status'], 'A')
-
- # Verify the command was executed
- self.assertTrue(
- any(
- cmd == 'git --no-pager ls-files --others --exclude-standard'
- for cmd, _ in self.executed_commands
- )
- )
-
def test_get_git_changes(self):
"""Test that get_git_changes returns the combined list of changed and untracked files."""
# Create an untracked file
@@ -379,23 +173,63 @@ class TestGitHandler(unittest.TestCase):
self.assertIn('A', statuses) # Added
self.assertIn('D', statuses) # Deleted
- def test_get_git_diff(self):
- """Test that get_git_diff returns the original and modified content of a file."""
- diff = self.git_handler.get_git_diff('file1.txt')
- self.assertEqual(diff['modified'].strip(), 'Modified content again')
- self.assertEqual(diff['original'].strip(), 'Modified content')
-
- # Should have called _get_current_file_content and _get_ref_content
- self.assertTrue(
- any('cat file1.txt' in cmd for cmd, _ in self.executed_commands)
- )
- self.assertTrue(
- any(
- 'git --no-pager show' in cmd and 'file1.txt' in cmd
- for cmd, _ in self.executed_commands
- )
- )
+ def test_get_git_changes_multiple_repositories(self):
+ """Test that get_git_changes can detect changes in multiple git repositories within a workspace."""
+ # Create a workspace directory with multiple git repositories
+ workspace_dir = os.path.join(self.test_dir, 'workspace')
+ repo1_dir = os.path.join(workspace_dir, 'repo1')
+ repo2_dir = os.path.join(workspace_dir, 'repo2')
+ non_git_dir = os.path.join(workspace_dir, 'non_git')
+
+ os.makedirs(workspace_dir, exist_ok=True)
+ os.makedirs(repo1_dir, exist_ok=True)
+ os.makedirs(repo2_dir, exist_ok=True)
+ os.makedirs(non_git_dir, exist_ok=True)
+
+ # Set up repo1
+ self._execute_command('git --no-pager init', repo1_dir)
+ self._execute_command(
+ "git --no-pager config user.email '[email protected]'", repo1_dir
+ )
+ self._execute_command("git --no-pager config user.name 'Test User'", repo1_dir)
+ with open(os.path.join(repo1_dir, 'repo1_file.txt'), 'w') as f:
+ f.write('repo1 content')
+ self._execute_command('git --no-pager add repo1_file.txt', repo1_dir)
+ self._execute_command("git --no-pager commit -m 'Initial commit'", repo1_dir)
+ # Modify the file to create changes
+ with open(os.path.join(repo1_dir, 'repo1_file.txt'), 'w') as f:
+ f.write('repo1 modified content')
+
+ # Set up repo2
+ self._execute_command('git --no-pager init', repo2_dir)
+ self._execute_command(
+ "git --no-pager config user.email '[email protected]'", repo2_dir
+ )
+ self._execute_command("git --no-pager config user.name 'Test User'", repo2_dir)
+ with open(os.path.join(repo2_dir, 'repo2_file.txt'), 'w') as f:
+ f.write('repo2 content')
+ self._execute_command('git --no-pager add repo2_file.txt', repo2_dir)
+ self._execute_command("git --no-pager commit -m 'Initial commit'", repo2_dir)
+ # Add an untracked file
+ with open(os.path.join(repo2_dir, 'untracked.txt'), 'w') as f:
+ f.write('untracked content')
+
+ # Add a file to the non-git directory (should be ignored)
+ with open(os.path.join(non_git_dir, 'ignored_file.txt'), 'w') as f:
+ f.write('ignored content')
+
+ # Create a GitHandler for the workspace directory
+ workspace_handler = GitHandler(self._execute_command)
+ workspace_handler.set_cwd(workspace_dir)
+
+ # Clear executed commands to start fresh
+ self.executed_commands = []
+ # Get changes from all repositories
+ changes = workspace_handler.get_git_changes()
+ self.assertIsNotNone(changes)
-if __name__ == '__main__':
- unittest.main()
+ # Should find changes from both repositories
+ assert len(changes) == 2
+ assert {'status': 'M', 'path': 'repo1/repo1_file.txt'} in changes
+ assert {'status': 'A', 'path': 'repo2/untracked.txt'} in changes
diff --git a/tests/unit/test_git_handler_real.py b/tests/unit/test_git_handler_real.py
index 58d446231b..7ae2058502 100644
--- a/tests/unit/test_git_handler_real.py
+++ b/tests/unit/test_git_handler_real.py
@@ -79,32 +79,6 @@ class TestGitHandlerWithRealRepo(unittest.TestCase):
"""Test that _is_git_repo returns True for a git repository."""
self.assertTrue(self.git_handler._is_git_repo())
- def test_get_default_branch(self):
- """Test that _get_default_branch returns the correct branch name."""
- branch = self.git_handler._get_default_branch()
- self.assertEqual(branch, 'main')
-
- def test_get_current_branch(self):
- """Test that _get_current_branch returns the correct branch name."""
- branch = self.git_handler._get_current_branch()
- self.assertEqual(branch, 'feature-branch')
-
- def test_get_valid_ref(self):
- """Test that _get_valid_ref returns a valid ref."""
- ref = self.git_handler._get_valid_ref()
- self.assertIsNotNone(ref)
-
- # Push the feature branch to origin to test the highest priority ref
- self._execute_command('git push -u origin feature-branch', self.local_dir)
-
- # Get the valid ref again, should be origin/feature-branch now
- ref = self.git_handler._get_valid_ref()
- self.assertIsNotNone(ref)
-
- # Verify the ref exists
- result = self._execute_command(f'git rev-parse --verify {ref}', self.local_dir)
- self.assertEqual(result.exit_code, 0)
-
def test_get_ref_content(self):
"""Test that _get_ref_content returns the content from a valid ref."""
# First commit the changes to make sure we have a valid ref
@@ -120,27 +94,6 @@ class TestGitHandlerWithRealRepo(unittest.TestCase):
content = self.git_handler._get_current_file_content('file1.txt')
self.assertEqual(content.strip(), 'Modified content')
- def test_get_changed_files(self):
- """Test that _get_changed_files returns the list of changed files."""
- files = self.git_handler._get_changed_files()
- self.assertTrue(files)
-
- # Should include file1.txt (modified) and file2.txt (added)
- file_paths = [line.split('\t')[-1] for line in files]
- self.assertIn('file1.txt', file_paths)
- self.assertIn('file2.txt', file_paths)
-
- def test_get_untracked_files(self):
- """Test that _get_untracked_files returns the list of untracked files."""
- # Create an untracked file
- with open(os.path.join(self.local_dir, 'untracked.txt'), 'w') as f:
- f.write('Untracked file content')
-
- files = self.git_handler._get_untracked_files()
- self.assertEqual(len(files), 1)
- self.assertEqual(files[0]['path'], 'untracked.txt')
- self.assertEqual(files[0]['status'], 'A')
-
def test_get_git_changes(self):
"""Test that get_git_changes returns the combined list of changed and untracked files."""
# Create an untracked file