Skip to content

Git Worktree Support#279

Merged
yamadashy merged 2 commits intoyamadashy:mainfrom
slavashvets:main
Jan 11, 2025
Merged

Git Worktree Support#279
yamadashy merged 2 commits intoyamadashy:mainfrom
slavashvets:main

Conversation

@slavashvets
Copy link
Contributor

Fixes an issue where Repomix fails when processing repositories created using git worktree. The error occurred because in worktree repositories, .git is a file containing a reference to the main repository, rather than a directory:

❯ repomix

📦 Repomix v0.2.17

Error filtering files: ENOTDIR: not a directory, stat '/Users/shvets/repos/testrepo_worktree/.git/**'
✖ Error during packing
Unexpected error: Failed to filter files in directory /Users/shvets/repos/testrepo_worktree. Reason: ENOTDIR: not a directory, stat '/Users/shvets/repos/testrepo_worktree/.git/**'
For more help, please visit: https://github.com/yamadashy/repomix/issues

Changes

  • Added detection of git worktree reference files
  • Modified ignore patterns to handle .git file instead of .git/** directory for worktrees
  • Added tests to verify worktree handling

Why

When using git worktree, developers can create multiple working trees from a single repository. This is a common workflow for working on multiple branches simultaneously. The current version of Repomix fails in these cases with an ENOTDIR error because it tries to process .git as a directory.

@bolt-new-by-stackblitz
Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

📝 Walkthrough

Walkthrough

The pull request introduces a new asynchronous function isGitWorktreeRef in the fileSearch.ts module to detect git worktree references. The searchFiles function is updated to handle git worktree scenarios by dynamically adjusting ignore patterns. When a .git path is identified as a worktree reference, the function modifies the ignore patterns to exclude the worktree reference file while maintaining appropriate file search behavior.

Changes

File Change Summary
src/core/file/fileSearch.ts - Added isGitWorktreeRef async function to check git worktree references
- Modified searchFiles to handle git worktree scenarios
- Dynamically adjust ignore patterns based on worktree detection
tests/core/file/fileSearch.test.ts - Added test cases for git worktree handling
- Verified searchFiles behavior with mocked file system interactions

Possibly related PRs


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6aff1c5 and c7061a4.

📒 Files selected for processing (2)
  • src/core/file/fileSearch.ts (3 hunks)
  • tests/core/file/fileSearch.test.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/core/file/fileSearch.test.ts
  • src/core/file/fileSearch.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
src/core/file/fileSearch.ts (3)

45-58: Consider enhancing the robustness of isGitWorktreeRef.

The function works correctly but could be more robust with these improvements:

  1. Add input validation for gitPath
  2. Extract "gitdir:" as a constant
  3. Trim the file content before checking
+const GIT_WORKTREE_PREFIX = "gitdir:";
+
 // Check if a path is a git worktree reference file
 const isGitWorktreeRef = async (gitPath: string): Promise<boolean> => {
+  if (!gitPath) {
+    return false;
+  }
+
   try {
     const stats = await fs.stat(gitPath);
     if (!stats.isFile()) {
       return false;
     }

     const content = await fs.readFile(gitPath, "utf8");
-    return content.startsWith("gitdir:");
+    return content.trim().startsWith(GIT_WORKTREE_PREFIX);
   } catch {
     return false;
   }
 };

84-97: Extract git-related patterns as constants and add documentation.

The git worktree handling logic could be more maintainable with these improvements:

  1. Extract git-related patterns as constants
  2. Add comments explaining the pattern adjustment logic
+const GIT_DIR_PATTERN = ".git/**";
+const GIT_FILE_PATTERN = ".git";
+
 // Check if .git is a worktree reference
 const gitPath = path.join(rootDir, ".git");
 const isWorktree = await isGitWorktreeRef(gitPath);

+// For git worktrees, we need to:
+// 1. Remove the '.git/**' pattern as it's not a directory
+// 2. Add '.git' to ignore the reference file itself
 const adjustedIgnorePatterns = [...ignorePatterns];
 if (isWorktree) {
-  // Remove '.git/**' pattern and add '.git' to ignore the reference file
-  const gitIndex = adjustedIgnorePatterns.indexOf(".git/**");
+  const gitIndex = adjustedIgnorePatterns.indexOf(GIT_DIR_PATTERN);
   if (gitIndex !== -1) {
     adjustedIgnorePatterns.splice(gitIndex, 1);
-    adjustedIgnorePatterns.push(".git");
+    adjustedIgnorePatterns.push(GIT_FILE_PATTERN);
   }
 }

101-101: Optimize array spreading in globby options.

The spread operator is used twice with adjustedIgnorePatterns. Consider passing the array directly to avoid unnecessary array copying.

 const filePaths = await globby(includePatterns, {
   cwd: rootDir,
-  ignore: [...adjustedIgnorePatterns],
+  ignore: adjustedIgnorePatterns,
   ignoreFiles: [...ignoreFilePatterns],
   onlyFiles: true,
   // ...
 });

 const directories = await globby(includePatterns, {
   cwd: rootDir,
-  ignore: [...adjustedIgnorePatterns],
+  ignore: adjustedIgnorePatterns,
   ignoreFiles: [...ignoreFilePatterns],
   onlyDirectories: true,
   // ...
 });

Also applies to: 122-122

tests/core/file/fileSearch.test.ts (2)

276-310: Enhance git worktree test coverage.

The test case is good but could be improved:

  1. Use the same constants as the implementation
  2. Add test cases for error scenarios (invalid file content, read errors)
+const GIT_DIR_PATTERN = ".git/**";
+const GIT_FILE_PATTERN = ".git";
+const GIT_WORKTREE_PREFIX = "gitdir:";

 test('should handle git worktree correctly', async () => {
   // Mock .git file content for worktree
-  const gitWorktreeContent = 'gitdir: /path/to/main/repo/.git/worktrees/feature-branch';
+  const gitWorktreeContent = `${GIT_WORKTREE_PREFIX} /path/to/main/repo/.git/worktrees/feature-branch`;

   // ... existing test code ...

   // Verify .git file (not directory) is in ignore patterns
-  expect(ignorePatterns).toContain('.git');
+  expect(ignorePatterns).toContain(GIT_FILE_PATTERN);
   // Verify .git/** is not in ignore patterns
-  expect(ignorePatterns).not.toContain('.git/**');
+  expect(ignorePatterns).not.toContain(GIT_DIR_PATTERN);
 });

+test('should handle invalid git worktree file content', async () => {
+  vi.mocked(fs.stat).mockResolvedValue({
+    isFile: () => true,
+  } as fs.Stats);
+  vi.mocked(fs.readFile).mockResolvedValue('invalid content');
+
+  const mockConfig = createMockConfig({
+    ignore: {
+      useGitignore: true,
+      useDefaultPatterns: true,
+      customPatterns: [],
+    },
+  });
+
+  const result = await searchFiles('/test/dir', mockConfig);
+  const globbyCall = vi.mocked(globby).mock.calls[0];
+  const ignorePatterns = globbyCall[1]?.ignore as string[];
+
+  // Should treat it as a regular git repository
+  expect(ignorePatterns).toContain(GIT_DIR_PATTERN);
+  expect(ignorePatterns).not.toContain(GIT_FILE_PATTERN);
+});

312-342: Use consistent constants in regular git repository test.

For consistency with the implementation and the worktree test, use the same constants for git patterns.

+const GIT_DIR_PATTERN = ".git/**";
+const GIT_FILE_PATTERN = ".git";

 test('should handle regular git repository correctly', async () => {
   // ... existing test code ...

   // Verify .git/** is in ignore patterns for regular git repos
-  expect(ignorePatterns).toContain('.git/**');
+  expect(ignorePatterns).toContain(GIT_DIR_PATTERN);
   // Verify just .git is not in ignore patterns
-  expect(ignorePatterns).not.toContain('.git');
+  expect(ignorePatterns).not.toContain(GIT_FILE_PATTERN);
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 001e3f7 and 70bbab2.

📒 Files selected for processing (2)
  • src/core/file/fileSearch.ts (3 hunks)
  • tests/core/file/fileSearch.test.ts (1 hunks)

Previously repomix failed when processing git worktree directories due to .git being a file rather than directory. Now it correctly adjusts ignore patterns for worktree references.
@codecov
Copy link

codecov bot commented Jan 11, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 92.20%. Comparing base (41314f6) to head (c7061a4).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #279      +/-   ##
==========================================
+ Coverage   92.12%   92.20%   +0.07%     
==========================================
  Files          44       44              
  Lines        2146     2168      +22     
  Branches      469      474       +5     
==========================================
+ Hits         1977     1999      +22     
  Misses        169      169              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@yamadashy
Copy link
Owner

Hi, @slavashvets !
Thank you for catching this issue and providing a fix! I hadn't noticed this issue.

I've reviewed the changes and tested the functionality - everything looks perfect. The implementation and test coverage are solid.

I'll merge this right away. Thanks for your contribution! 🙌

@yamadashy yamadashy merged commit 070e422 into yamadashy:main Jan 11, 2025
@yamadashy
Copy link
Owner

@slavashvets
I've released version 0.2.20 which includes your Git Worktree fix. 🎉
https://github.com/yamadashy/repomix/releases/tag/v0.2.20

Thank you again for your great contribution! The Git Worktree support makes Repomix more useful for developers using this Git feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants