Skip to content

fix(pr): handle --count gracefully in repositories with few commits - #197

Open
rudra-chothe wants to merge 10 commits into
gunjanghate:mainfrom
rudra-chothe:feature/my-protected-feature
Open

fix(pr): handle --count gracefully in repositories with few commits#197
rudra-chothe wants to merge 10 commits into
gunjanghate:mainfrom
rudra-chothe:feature/my-protected-feature

Conversation

@rudra-chothe

@rudra-chothe rudra-chothe commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

📝 Description

Fixes #165

The gg pr command used HEAD~${count}..HEAD to collect modified files. In repositories with fewer commits than the requested --count, this Git
range is invalid and causes the command to fail — common in new or beginner test repositories.
This PR:

  • Caps --count to the number of commits available in the repository
  • Shows a helpful message when fewer commits exist than requested
  • Builds a safe diff range for modified files (including single-commit/root repos via empty-tree fallback)
  • Adds regression tests in cli/tests/prCommitRange.test.js

🚀 Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📖 Documentation update (adding/improving docs or Mermaid diagrams)
  • 🎨 Style/Refactor (non-functional changes, formatting, or renaming)

🧪 How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce.

  • Test Environment:
    • Node Version: v18+ (project requirement)
    • OS: Windows 11
    • Shell: PowerShell
  • Command(s) Executed:
    • npm test (from cli/)
    • Manual reproduction:
      mkdir test-gitgenie-pr
      cd test-gitgenie-pr
      git init
      echo "hello" > README.md
      git add README.md
      git commit -m "docs: initial commit"
      node path/to/cli/index.js pr --count 5
  • Expected Result:
    • Command succeeds without fatal: ambiguous argument 'HEAD~5..HEAD'
    • User sees a notice that only 1 commit exists and PR description is generated
  • Actual Result:
    • Warning shown: Requested 5 commits, but only 1 exist. Using all available commits.
    • PR description generated successfully with commit summary and README.md in Files Modified
    • All CLI tests pass, including new prCommitRange.test.js

⚠️ Breaking Changes

  • No
  • Yes (If yes, please explain the impact and why it is necessary)

📸 Screenshots / Logs

image
Click to expand logs ```bash Requested 5 commits, but only 1 exist. Using all available commits. Analyzing last 1 commit... Generated PR Description: ## Summary This PR includes updates from recent commits. ## Changes Made ### Other Changes - docs: initial commit ## Files Modified - README.md ```
--- ## ✅ Checklist - [x] My code follows the style guidelines of this project. - [x] I have performed a self-review of my own code. - [ ] I have commented my code, particularly in hard-to-understand areas. - [ ] I have made corresponding changes to the documentation (README.md). - [x] My changes generate no new warnings. ---

Summary by CodeRabbit

Release Notes

  • Documentation

    • Expanded documentation with additional examples, usage scenarios, and comprehensive testing guidance.
  • New Features

    • Added validation to prevent accidental commits in detached HEAD state (use --no-branch to override).
  • Bug Fixes

    • Improved file staging to properly include dotfiles and deleted files.
    • Enhanced Git remote URL validation.
    • Improved consistency of AI provider behavior across commit workflows.
  • Tests

    • Added validation test coverage for remote URLs and API keys.

@vercel

vercel Bot commented Jun 7, 2026

Copy link
Copy Markdown

@rudra-chothe is attempting to deploy a commit to the Gunjan Ghate's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@rudra-chothe, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 58 minutes and 59 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 54e6f347-850e-48cb-823c-47f6fa9e72c3

📥 Commits

Reviewing files that changed from the base of the PR and between 7a323aa and be646d3.

📒 Files selected for processing (2)
  • cli/helpers/gitUtils.js
  • cli/tests/stageAllFiles.test.js
📝 Walkthrough

Walkthrough

This PR strengthens CLI validation and safety through remote URL verification, improves git staging to handle deletions and dotfiles, adds a detached-HEAD guard in the commit flow, refactors split-command AI flag handling for consistency, and includes test coverage for the new validators and staging behavior.

Changes

CLI Validation, Staging, and Safety Improvements

Layer / File(s) Summary
Git validation utilities
cli/helpers/gitUtils.js
Adds validateRemoteUrl(url) to validate HTTPS and SSH remote URL formats, and refactors stageAllFiles() to use git.add(['-A']) for inclusion of dotfiles and deletions.
Remote URL validation in interactive and --remote flows
cli/index.js
Imports and applies validateRemoteUrl to validate user-provided URLs in both interactive origin-setup and --remote flag flows, exiting immediately on validation failure.
Staging helper refactor and change detection update
cli/index.js
Updates "have unstaged changes?" check to use both git.diff() and git.status() arrays (not_added/deleted/modified) for more complete change detection before staging.
Detached HEAD safety check in commit flow
cli/index.js
Adds guard that blocks committing in detached-HEAD state (when commits exist) unless user explicitly disables branch handling via --no-branch; replaces prior warning-only behavior with exit and clear instructions.
Provider API key validation delegation
cli/providers/gemini.js
Delegates GeminiProvider.validateApiKey to shared validateProviderApiKey('gemini', apiKey) utility instead of inline key-format heuristics.
Split command AI flag consistency
cli/commands/split.js
Refactors split command to consistently use computed useAI flag instead of direct opts.genie checks; updates dry-run messages and provider argument passing in commit-all and review flows to use useAI ? provider : null.
Test coverage for validators and stageAllFiles
cli/tests/validation.test.js, cli/tests/stageAllFiles.test.js
Adds test suites validating validateRemoteUrl across HTTPS/SSH formats and rejections, GeminiProvider.validateApiKey for API key formats, and stageAllFiles() behavior with dotfiles, regular files, and tracked deletions.
README documentation updates
Readme.md
Normalizes section headings, adds "Auto-detect commit type" explanation with console-log examples, expands "Example Usage & Sample Commands" with PowerShell snippets for --osc and --genie flows, adds subsections for interactive/advanced/legacy examples, updates "Testing Commands" to reflect --no-branch default and AI example, and reformats PR contribution instructions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • gunjanghate/GitGenie#99: Both PRs modify cli/commands/split.js and cli/helpers/gitUtils.js/stageAllFiles implementation, with this PR's updates directly refactoring staging and AI flag behavior in those files.
  • gunjanghate/GitGenie#132: Both PRs touch the Gemini API key validation path by delegating to shared resolveApiKey utilities, consolidating provider-specific validation logic.
  • gunjanghate/GitGenie#72: Both PRs modify cli/index.js commit flow and change detection logic, including unstaged status checking and branch/no-branch messaging around detached-HEAD and staging changes.

Suggested labels

cli, Medium, quality:clean

Poem

🐰 Validates remotes with a careful hop,
Stages all files—dotfiles don't stop,
Detached heads now get their due care,
Split commands use flags clean and fair,
Tests ensure the path's crystal-clear!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR summary shows changes beyond the issue #165 scope: README updates, CLI command refactoring (split.js), new git utilities (validateRemoteUrl), API key validation changes, and unrelated test files. Focus changes on issue #165 (handle --count in pr command). Move unrelated changes (README, split.js refactor, validateRemoteUrl, Gemini validation) to separate PRs.
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main bug fix: handling the --count flag gracefully in repositories with few commits, addressing issue #165.
Description check ✅ Passed The PR description is well-structured, follows the template with all major sections completed, includes issue reference, test environment details, commands, expected/actual results, logs, and proper checklist items.
Linked Issues check ✅ Passed The code changes address issue #165 requirements: capping --count to available commits, showing helpful warnings, handling single-commit repos, and providing regression tests.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
Readme.md (1)

319-319: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update staging step in the architecture diagram to match current implementation.

The diagram still says git add ., but current behavior stages with -A (including deletions and dotfiles). This is now stale and can mislead contributors validating staging flow.

Suggested doc fix
-    DiffCheck -- No --> StageAll[Prompt & git add .]
+    DiffCheck -- No --> StageAll[Prompt & git add -A]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Readme.md` at line 319, The diagram label still shows "git add ." but the
implementation stages with "git add -A"; update the architecture diagram text
(e.g., the StageAll node that currently reads StageAll[Prompt & git add .]) to
use "git add -A" (or "git add --all") so the diagram matches actual behavior and
clearly indicates deletions and dotfiles are included.
cli/index.js (1)

793-804: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Trim the interactive remoteUrl before persisting it.

Line 798 validates a trimmed value, but Line 803 uses the raw prompt value. Inputs like ' https://github.com/org/repo.git ' pass validation yet can be stored/used with whitespace.

Suggested patch
-    const { remoteUrl } = await inquirer.prompt([
+    const { remoteUrl } = await inquirer.prompt([
       {
         type: 'input',
         name: 'remoteUrl',
         message: 'Enter remote origin URL (e.g. https://github.com/user/repo.git):',
         validate: validateRemoteUrl
       }
     ]);
+    const normalizedRemoteUrl = remoteUrl.trim();

     try {
-      await git.remote(['add', 'origin', remoteUrl]);
-      console.log(chalk.green(`✅ Remote origin set to ${remoteUrl}`));
+      await git.remote(['add', 'origin', normalizedRemoteUrl]);
+      console.log(chalk.green(`✅ Remote origin set to ${normalizedRemoteUrl}`));
       return true;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/index.js` around lines 793 - 804, Prompted remoteUrl is validated on a
trimmed value but the raw prompt result is used as-is; after receiving the
prompt result (variable remoteUrl) trim it before using or persisting it (i.e.,
pass remoteUrl.trim() to git.remote(['add','origin', ...]) and to the
console.log message) so stored/used remotes never contain leading/trailing
whitespace; reference variables/functions: remoteUrl, validateRemoteUrl,
git.remote(['add','origin', ...]).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cli/helpers/gitUtils.js`:
- Around line 27-33: The SSH validation is too restrictive: update sshScpPattern
and sshUrlPattern so they accept any user (not only "git") and match the
advertised formats "user@host:path" and "ssh://[user@]host[:port]/path";
specifically, modify sshScpPattern (currently named sshScpPattern) to allow a
generic username before the @ (e.g., alphanumeric plus common username chars)
and modify sshUrlPattern (currently named sshUrlPattern) to make the "user@"
portion optional (allowing ssh://host... and ssh://user@host...) while keeping
the existing host, optional port and path rules, then keep the same returned
error string.

In `@cli/index.js`:
- Around line 936-945: The code forces 'main' when opts.branch == false or
!hasCommits which can repoint main; instead use the repository's current branch
name from branchInfo (e.g., branchInfo.current or branchInfo.name) and check
that out rather than force-creating 'main'. Set branchName = branchInfo.current
|| 'main' and use a normal checkout of branchName (not git checkout -B main) so
you commit on the current branch; if branchInfo has no current name, fall back
to creating a new safe branch name (e.g., gg-work/${Date.now()}) or 'main' only
as last resort.

In `@cli/tests/stageAllFiles.test.js`:
- Around line 47-54: The test pre-stages the README deletion with execSync('git
rm --cached README.md'), so remove that pre-staging and let stageAllFiles() be
the only thing that stages deletions; specifically edit the test in
stageAllFiles.test.js to delete the execSync('git rm --cached README.md', {
stdio: 'ignore' }) line (or replace it with a command that only removes the
working file but does not stage, e.g., ensure the file is removed via
rm(join(process.cwd(), 'README.md'), { force: true }) before calling
stageAllFiles()), so that the call to stageAllFiles() is what's being tested for
staging deletions.

---

Outside diff comments:
In `@cli/index.js`:
- Around line 793-804: Prompted remoteUrl is validated on a trimmed value but
the raw prompt result is used as-is; after receiving the prompt result (variable
remoteUrl) trim it before using or persisting it (i.e., pass remoteUrl.trim() to
git.remote(['add','origin', ...]) and to the console.log message) so stored/used
remotes never contain leading/trailing whitespace; reference
variables/functions: remoteUrl, validateRemoteUrl, git.remote(['add','origin',
...]).

In `@Readme.md`:
- Line 319: The diagram label still shows "git add ." but the implementation
stages with "git add -A"; update the architecture diagram text (e.g., the
StageAll node that currently reads StageAll[Prompt & git add .]) to use "git add
-A" (or "git add --all") so the diagram matches actual behavior and clearly
indicates deletions and dotfiles are included.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fb7c9fa3-60bf-44b6-9fe3-d5281e010c23

📥 Commits

Reviewing files that changed from the base of the PR and between ef03020 and 7a323aa.

📒 Files selected for processing (7)
  • Readme.md
  • cli/commands/split.js
  • cli/helpers/gitUtils.js
  • cli/index.js
  • cli/providers/gemini.js
  • cli/tests/stageAllFiles.test.js
  • cli/tests/validation.test.js

Comment thread cli/helpers/gitUtils.js Outdated
Comment thread cli/index.js
Comment thread cli/tests/stageAllFiles.test.js Outdated
rudra-chothe and others added 2 commits June 9, 2026 10:13
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@gunjanghate

Copy link
Copy Markdown
Owner

@rudra-chothe looks good

@gunjanghate

Copy link
Copy Markdown
Owner

@rudra-chothe do tell where are the main code implementation exists apart from Docs and test files

@rudra-chothe

Copy link
Copy Markdown
Contributor Author

@rudra-chothe do tell where are the main code implementation exists apart from Docs and test files

the main code changes are in cli/index.js, cli/commands/split.js, cli/helpers/gitUtils.js, cli/providers/gemini.js and others are test files

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.

[Bug]: gg pr fails in repositories with fewer commits than --count

2 participants