Skip to content

fix(cli): Skip file copy when absolute path is specified for remote repository output#885

Merged
yamadashy merged 1 commit intomainfrom
fix/remote-action-absolute-path
Oct 10, 2025
Merged

fix(cli): Skip file copy when absolute path is specified for remote repository output#885
yamadashy merged 1 commit intomainfrom
fix/remote-action-absolute-path

Conversation

@yamadashy
Copy link
Owner

@yamadashy yamadashy commented Oct 10, 2025

Summary

Fixes #873

When using the remote repository feature with an absolute path specified for the output file, the previous implementation attempted to copy the file even though source and target resolved to the same path. This resulted in an error:

RepomixError: Failed to copy output file: EINVAL: invalid argument, 
copyfile '/tmp/my_private_dir/output.xml' -> '/tmp/my_private_dir/output.xml'.

This PR fixes the issue by implementing a fundamental solution: checking if source and target paths are identical before attempting to copy.

Changes

  • Modified copyOutputToCurrentDirectory to check if source and target paths are the same before copying
  • When they are identical, the copy operation is skipped with a trace log
  • This handles absolute paths and any other edge cases where paths resolve to the same location
  • The fix is self-contained within the function, making it more robust

Why This Approach?

This is more fundamental than checking for absolute paths at the call site because:

  • More generic: Handles any case where source equals target, not just absolute paths
  • Self-contained: The function itself is responsible for its safe operation
  • Simpler: No changes needed to calling code
  • Safer: Prevents file copy errors in all edge cases

Test Plan

  • Run npm run test - All 785 tests passing
  • Run npm run lint - No errors
  • Added test case: source and target are the same directory
  • Added test case: absolute path resolves to same location
  • Existing tests continue to pass

Checklist

  • Run npm run test
  • Run npm run lint

Copilot AI review requested due to automatic review settings October 10, 2025 14:57
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes a bug where the CLI would fail when using an absolute path for output files in remote repository operations. The error occurred because the code attempted to copy a file to itself when an absolute path was specified.

Key changes:

  • Modified the file copy logic to skip copying when an absolute output path is specified
  • Added comprehensive test coverage for both absolute and relative path scenarios

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/cli/actions/remoteAction.ts Updated condition to skip file copying when absolute output path is provided
tests/cli/actions/remoteAction.test.ts Added test cases to verify correct behavior for both absolute and relative output paths

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @yamadashy, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a specific issue within the remote repository feature where an error would occur if an absolute path was provided for the output file. The system was redundantly attempting to copy the file to itself, leading to an 'invalid argument' error. The change introduces a check to determine if the output path is absolute, and if so, bypasses the unnecessary copy operation, thereby resolving the error and streamlining the output process for absolute paths.

Highlights

  • Bug Fix: Resolved an EINVAL error that occurred when using the remote repository feature with an absolute output path, caused by an attempt to copy a file to its already specified absolute location.
  • Conditional File Copy: The file copy operation is now skipped if the output path is absolute, as the file is already written to the correct destination by writeOutputToDisk.
  • Test Coverage: Added new test cases to explicitly verify that copyFile is not called for absolute paths and is correctly called for relative paths, ensuring the fix works as intended and existing functionality is preserved.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 10, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

The copy condition in runRemoteAction is narrowed: after generating output in the clone directory, the file is copied only when stdout is disabled and the provided output path is relative. Tests are added to verify skipping copy for absolute output paths and performing copy for relative paths.

Changes

Cohort / File(s) Summary
Remote action logic
src/cli/actions/remoteAction.ts
Tightens copy condition to execute only when stdout is off and output path is not absolute; updates comments accordingly.
CLI tests for remote action
tests/cli/actions/remoteAction.test.ts
Adds tests covering absolute-path (no copy) and relative-path (copy) behaviors; mocks filesystem and execGitShallowClone; asserts copy invocation counts.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant User
  participant CLI
  participant Git as Git Shallow Clone
  participant FS as Filesystem

  User->>CLI: runRemoteAction(options)
  CLI->>Git: execGitShallowClone(remote, tempDir)
  Git-->>CLI: path to generated output (in clone dir)

  alt stdout enabled
    note over CLI,FS: No file copy
    CLI-->>User: write to stdout
  else output path is absolute
    note right of CLI: Skip copy when absolute
    CLI->>FS: Move/ensure file at absolute path via initial write
    CLI-->>User: done
  else output path is relative
    CLI->>FS: copyFile(tempOutput, cwd/relativeOutput)
    CLI-->>User: done
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly describes the primary fix by indicating that the CLI will skip copying the output file when an absolute path is provided, accurately reflecting the core change in this pull request.
Linked Issues Check ✅ Passed The implementation meets all coding requirements from issue #873 by preventing self-copy for absolute paths, ensuring direct write behavior for those paths, and maintaining correct copy behavior for relative paths through updated logic and tests.
Out of Scope Changes Check ✅ Passed All changes are focused on the conditional file copy logic in runRemoteAction and related tests, with no additions or modifications outside the scope of fixing the absolute path copy behavior.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
Description Check ✅ Passed The pull request description clearly includes a concise summary of the issue and the implemented changes, and it provides a completed checklist with both npm run test and npm run lint items, satisfying the repository’s template requirements.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/remote-action-absolute-path

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Oct 10, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.82%. Comparing base (eb51476) to head (3233fc4).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #885   +/-   ##
=======================================
  Coverage   88.81%   88.82%           
=======================================
  Files         109      109           
  Lines        7608     7612    +4     
  Branches     1436     1438    +2     
=======================================
+ Hits         6757     6761    +4     
  Misses        851      851           

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request correctly fixes a bug where the CLI would fail when an absolute path was provided for the output file from a remote repository. The change skips the unnecessary file copy operation in this scenario. The logic is sound and is accompanied by new tests that verify the fix for absolute paths and ensure the existing behavior for relative paths remains unchanged. I've provided a couple of suggestions to improve code readability in the implementation and reduce duplication in the tests for better long-term maintainability.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Oct 10, 2025

Deploying repomix with  Cloudflare Pages  Cloudflare Pages

Latest commit: 3233fc4
Status: ✅  Deploy successful!
Preview URL: https://ff03ddb2.repomix.pages.dev
Branch Preview URL: https://fix-remote-action-absolute-p.repomix.pages.dev

View logs

@claude
Copy link
Contributor

claude bot commented Oct 10, 2025

Code Review

Overall Assessment

This is a well-implemented fix for issue #873 that correctly handles absolute paths in remote repository output. APPROVED.

What This PR Does Well

  1. Correct Root Cause Analysis: The fix properly identifies that when an absolute path is provided, writeOutputToDisk already writes the file to the correct location using path.resolve. Since the cwd is the temp directory and the filePath is already absolute, the resolve operation correctly uses the absolute path.

  2. Minimal Focused Change: The fix is surgical - only adding the necessary condition to skip the copy operation when an absolute path is specified.

  3. Clear Comments: The inline comments clearly explain the three scenarios: stdout mode, absolute path, and relative path.

  4. Comprehensive Test Coverage: Added two test cases that validate both branches - absolute path means copyFile NOT called, relative path means copyFile IS called.

  5. Follows Project Conventions: Uses dependency injection, follows existing code style, and commit message follows Conventional Commits format.

Code Quality

Logic Correctness: The condition is correct. path.isAbsolute works cross-platform (handles both Unix and Windows paths) and short-circuits properly.

No Edge Cases Missed: The fix handles undefined output, relative paths, absolute paths, and stdout mode correctly.

Performance: No concerns - just adds a simple boolean check.

Security: No concerns. No new file system operations or unsafe path handling.

Test Coverage: Well-structured tests following existing patterns.

Potential Improvements (Optional)

  1. Consider extracting the condition on line 98 into a shouldCopyOutput variable for better readability.

  2. Tests could verify file existence at expected location, but current approach is acceptable.

Recommendation

Ready to merge! This is a solid fix with appropriate test coverage.

When using the remote repository feature with an absolute path specified
for the output file, the previous implementation attempted to copy the file
even though source and target resolved to the same path. This resulted in
an error when trying to copy a file to itself.

This commit fixes the issue by:
- Checking if source and target paths are identical before copying
- Skipping the copy operation when they are the same
- This handles absolute paths and any other edge cases where paths resolve to the same location

The fix is implemented in copyOutputToCurrentDirectory function itself,
making it more robust and self-contained.

Fixes #873
@yamadashy yamadashy force-pushed the fix/remote-action-absolute-path branch from 676a069 to 3233fc4 Compare October 10, 2025 15:13
@claude
Copy link
Contributor

claude bot commented Oct 10, 2025

Code Review

✅ Summary

This PR provides an elegant and robust fix for issue #873. The solution correctly identifies that when an absolute path is specified for the output file, both source and target resolve to the same path, causing a file copy error. The fix is simple, effective, and well-tested.


🎯 Strengths

  1. Excellent Root Cause Analysis: The fix addresses the fundamental issue rather than patching symptoms. Checking for path identity is more generic than checking for absolute paths at the call site.

  2. Self-Contained Solution: The function now handles edge cases internally, making it more robust and easier to maintain.

  3. Comprehensive Test Coverage: Three test cases cover:

    • Same directory (straightforward case)
    • Absolute path resolution (the original bug)
    • Different directories (existing behavior)
  4. Clear Comments: The inline comment explains both what and why, which is helpful for future maintainers.

  5. Follows Project Guidelines:

    • Commit message follows Conventional Commits format
    • Tests and linting passed
    • PR template correctly filled out

💡 Suggestions for Improvement

Minor: Consider Using Canonical Path Comparison

The current implementation compares resolved paths as strings, which works correctly on most systems. However, on systems with symlinks or case-insensitive filesystems, there's a theoretical edge case where two different path strings could point to the same file.

Consider using fs.realpath() for more robust comparison:

const sourceRealPath = await fs.realpath(sourcePath);
const targetRealPath = await fs.realpath(targetPath);

if (sourceRealPath === targetRealPath) {
  logger.trace(`Source and target are the same (${sourcePath}), skipping copy`);
  return;
}

However, this would require:

  • Making the paths exist before comparison (which may not always be the case)
  • Handling errors when paths don't exist
  • Adding async operations which might impact performance

Given the current use case (remote action with temporary directories), the string comparison is sufficient and appropriate. I'd recommend keeping it as-is unless symlink scenarios become relevant.


Test Enhancement: Verify Logger Trace Call

The tests verify that fs.copyFile is not called, but they don't verify that the logger.trace message is emitted. Consider adding:

test('should skip copy when source and target are the same', async () => {
  const sourceDir = '/tmp/dir';
  const targetDir = '/tmp/dir';
  const fileName = 'output.txt';

  vi.mocked(fs.copyFile).mockResolvedValue();

  await copyOutputToCurrentDirectory(sourceDir, targetDir, fileName);

  expect(fs.copyFile).not.toHaveBeenCalled();
  // Optionally: verify trace logging
  // expect(logger.trace).toHaveBeenCalledWith(expect.stringContaining('Source and target are the same'));
});

This is optional and depends on whether logger assertions are used elsewhere in the test suite.


🔒 Security & Performance

  • No security concerns: The fix prevents an error condition and doesn't introduce new attack vectors
  • Performance: Minimal overhead (one string comparison)
  • No breaking changes: Existing behavior is preserved for all valid use cases

📊 Code Quality Assessment

Aspect Rating Notes
Correctness ⭐⭐⭐⭐⭐ Solves the reported issue completely
Design ⭐⭐⭐⭐⭐ Elegant, self-contained solution
Tests ⭐⭐⭐⭐⭐ Comprehensive coverage of edge cases
Maintainability ⭐⭐⭐⭐⭐ Clear code with good comments
Documentation ⭐⭐⭐⭐⭐ Excellent PR description with context

✨ Conclusion

Recommendation: APPROVE AND MERGE

This is a high-quality fix that:

  • Solves the reported issue elegantly
  • Includes comprehensive tests
  • Follows all project conventions
  • Has no apparent issues or risks

The suggestions above are minor enhancements that could be considered for future iterations but are not blockers for merging.

Great work @yamadashy! 🎉

@yamadashy yamadashy merged commit 0fd4bb5 into main Oct 10, 2025
48 checks passed
@yamadashy yamadashy deleted the fix/remote-action-absolute-path branch October 10, 2025 15:22
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.

Specifying an absolute file path for a remote repo output in library mode crashes

2 participants