Skip to content

feat: add git hook integration with install and uninstall commands#38

Merged
nirvik34 merged 3 commits into
nirvik34:mainfrom
Harikishanth:feat/git-hook-integration
Jun 4, 2026
Merged

feat: add git hook integration with install and uninstall commands#38
nirvik34 merged 3 commits into
nirvik34:mainfrom
Harikishanth:feat/git-hook-integration

Conversation

@Harikishanth
Copy link
Copy Markdown

@Harikishanth Harikishanth commented May 19, 2026

Description

Add gitbun hooks install and gitbun hooks uninstall commands to manage a prepare-commit-msg git hook that automatically pre-fills the commit editor with a gitbun-generated message.

Fixes #4

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Documentation update
  • Frontend styling/component update

GSSoC '26 Contribution Details

  • level:beginner

  • level:intermediate

  • level:advanced

  • level:critical

  • I have been assigned to this issue by a maintainer.

How Has This Been Tested?

  • npm test passes locally
  • npm run lint passes without errors
  • I ran the CLI locally using npm run dev and verified the output

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas

Additional Notes

What was added:

  • src/hooks/install.ts — writes a prepare-commit-msg hook to .git/hooks/ using bare Node.js fs, marks it with a gitbun identifier for safe removal
  • src/hooks/uninstall.ts — removes the hook only if it was installed by gitbun, refuses to delete hooks it didn't create
  • src/index.ts — added --generate-only flag that outputs the generated message to stdout without committing (used internally by the hook)
  • bin/smartcommit.ts — added hooks install [--force] and hooks uninstall subcommands

Usage:
gitbun hooks install # installs prepare-commit-msg hook
gitbun hooks install --force # overwrites an existing hook
gitbun hooks uninstall # removes the hook (only if installed by gitbun)

How it works:
Once installed, running git commit automatically triggers gitbun to generate a commit message and pre-fill the editor. The user can review and edit before confirming. Running git commit -m "..." or amending skips the hook entirely.

Existing flow is completely unaffected — users who never run gitbun hooks install experience zero change in behaviour.

Summary by CodeRabbit

  • New Features
    • CLI renamed to gitbun.
    • Added --generate-only to print the generated commit message to stdout and skip committing.
    • Added hooks subcommand with install (supports --force) to add a prepare-commit-msg hook.
    • Added hooks uninstall to remove the installed prepare-commit-msg hook.

Review Change Stack

@vercel
Copy link
Copy Markdown

vercel Bot commented May 19, 2026

Someone is attempting to deploy a commit to the nirvik34's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 19, 2026

Caution

Review failed

Failed to post review comments

Warning

.coderabbit.yaml has a parsing error

The CodeRabbit configuration file in this repository has a parsing error and default settings were used instead. Please fix the error(s) in the configuration file. You can initialize chat with CodeRabbit to get help with the configuration file.

💥 Parsing errors (1)
Validation error: Invalid option: expected one of "chill"|"assertive" at "reviews.profile"
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • 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
📝 Walkthrough

Walkthrough

Adds a --generate-only CLI mode that prints the computed commit message and exits, plus hooks install/hooks uninstall commands that manage a marked prepare-commit-msg Git hook which calls gitbun --generate-only.

Changes

Git Hook Integration and Generate-Only Mode

Layer / File(s) Summary
CLI generate-only flag and wiring
bin/smartcommit.ts, src/index.ts
Added --generate-only to the CLI and generateOnly?: boolean to CliOptions. When set, run() prints the generated commit message to stdout and returns before confirmation/dry-run/commit.
Hook installation implementation
src/hooks/install.ts
Added installHook(force = false) which resolves the Git hooks dir, writes a prepare-commit-msg script containing a gitbun marker that runs gitbun --generate-only, prevents overwriting unmarked hooks unless --force, attempts to chmod the hook, and logs or exits on fatal errors.
Hook uninstallation implementation
src/hooks/uninstall.ts
Added uninstallHook() which locates the prepare-commit-msg hook, verifies it contains the gitbun marker, aborts if the marker is missing, and deletes the hook when validated.
CLI hook commands
bin/smartcommit.ts
Added hooks install (with --force) and hooks uninstall subcommands that call the new hook management functions; renamed program from smartcommit to gitbun.

Sequence Diagram

sequenceDiagram
  participant User
  participant CLI as gitbun CLI
  participant Installer as installHook()
  participant Hooks as .git/hooks/prepare-commit-msg
  participant Generator as "gitbun --generate-only"
  User->>CLI: gitbun hooks install
  CLI->>Installer: installHook(force)
  Installer->>Hooks: write hook script with gitbun marker
  Hooks-->>User: hook installed message
  User->>User: git commit (later)
  Hooks->>Generator: execute with COMMIT_EDITMSG path
  Generator-->>Hooks: stdout generated commit message
  Hooks->>Hooks: prepend/replace commit message file when non-empty
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • nirvik34/gitbun#42: Modifies run(options) control flow; may interact with generateOnly early-return behavior.
  • nirvik34/gitbun#14: Changes templating/formatting in commit generation which affects output used by --generate-only.
  • nirvik34/gitbun#25: Alters commit message generation pipeline that --generate-only prints before performing commit.

Suggested labels

type: feature, level:intermediate, quality:clean, gssoc:approved

Suggested reviewers

  • nirvik34

Poem

🐰 A hook I baked with nimble paws,
It whispers messages without a pause,
--generate-only hums so bright,
Install, uninstall—done just right,
Gitbun hops in at commit-time's cause.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: adding git hook integration with install and uninstall commands, which matches the primary focus of the changeset.
Linked Issues check ✅ Passed The PR implements the core requirements from #4: optional git hook support with install/uninstall commands, prepare-commit-msg hook integration, staged changes analysis, and lightweight optional implementation that doesn't disrupt manual workflows.
Out of Scope Changes check ✅ Passed All changes are within scope and directly support the linked issue #4 objectives: CLI commands and options for hook management, hook installation/uninstallation logic, and generate-only output for hook usage.

✏️ 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.

Copy link
Copy Markdown
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: 3

🧹 Nitpick comments (2)
src/hooks/install.ts (2)

46-61: ⚡ Quick win

Use octal notation for file permissions.

Line 49 passes "755" as a string to chmodSync. Node.js fs.chmodSync expects a numeric mode, and while strings are auto-converted, the idiomatic form is octal: 0o755.

♻️ Proposed fix
   try {
-    chmodSync(hookPath, "755");
+    chmodSync(hookPath, 0o755);
   } catch {
🤖 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 `@src/hooks/install.ts` around lines 46 - 61, The chmodSync call is using a
string mode ("755"); change it to the numeric octal form so permissions are set
idiomatically and correctly — replace the chmodSync(hookPath, "755") invocation
with chmodSync(hookPath, 0o755) (keep the surrounding try/catch and references
to hookPath and HOOK_SCRIPT intact).

5-5: ⚡ Quick win

Consider extracting the marker to a shared constant.

HOOK_MARKER is duplicated in both install.ts and uninstall.ts. Extracting it to a shared constants file (e.g., src/hooks/constants.ts) would prevent the definitions from drifting over time.

🤖 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 `@src/hooks/install.ts` at line 5, HOOK_MARKER is duplicated between install.ts
and uninstall.ts; extract it into a single exported constant in a new shared
module (e.g., create an exported const HOOK_MARKER in a new constants.ts) and
update both files to import that constant instead of declaring it locally,
ensuring both modules reference the same identifier to avoid drift.
🤖 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 `@src/hooks/install.ts`:
- Around line 7-19: HOOK_SCRIPT contains a Unicode em dash in the marker string
and blindly redirects gitbun output into the commit message file; replace the em
dash with an ASCII hyphen/minus in the HOOK_SCRIPT marker and change the
generation step to run gitbun --generate-only, check its exit status, and only
write its stdout to COMMIT_MSG_FILE on success (otherwise preserve
COMMIT_MSG_FILE and log or print the error); reference HOOK_SCRIPT,
COMMIT_MSG_FILE and the gitbun --generate-only invocation when making the
change.
- Around line 21-29: The installHook implementation currently builds hooksDir
using process.cwd() which breaks when run from a subdirectory; replace that
logic in installHook to determine the repo git directory by calling git
rev-parse --git-dir (via execFileSync with encoding 'utf8' and .trim()) and then
set hooksDir = join(gitDir, "hooks"); apply the identical change to the
uninstall logic (e.g., the uninstallHook in src/hooks/uninstall.ts) so both
installHook and uninstallHook compute hooksDir from git rev-parse --git-dir
instead of process.cwd().

In `@src/hooks/uninstall.ts`:
- Around line 7-14: uninstallHook currently resolves the .git/hooks path using
process.cwd() (hookPath in uninstallHook), which can mislocate the repository
root; instead run git rev-parse --git-dir (e.g., via child_process.execSync or
spawnSync) to get the repository git directory, normalize that path and build
the hooks path from it, falling back to the existing join(process.cwd(), ".git",
"hooks", "prepare-commit-msg") only if the git command fails; update
uninstallHook to mirror the same git-dir resolution approach used in install.ts
so the hookPath calculation is consistent and robust.

---

Nitpick comments:
In `@src/hooks/install.ts`:
- Around line 46-61: The chmodSync call is using a string mode ("755"); change
it to the numeric octal form so permissions are set idiomatically and correctly
— replace the chmodSync(hookPath, "755") invocation with chmodSync(hookPath,
0o755) (keep the surrounding try/catch and references to hookPath and
HOOK_SCRIPT intact).
- Line 5: HOOK_MARKER is duplicated between install.ts and uninstall.ts; extract
it into a single exported constant in a new shared module (e.g., create an
exported const HOOK_MARKER in a new constants.ts) and update both files to
import that constant instead of declaring it locally, ensuring both modules
reference the same identifier to avoid drift.
🪄 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: 120eb231-648c-4622-8dd0-fde09f193047

📥 Commits

Reviewing files that changed from the base of the PR and between 721dfc2 and 1469fdb.

📒 Files selected for processing (4)
  • bin/smartcommit.ts
  • src/hooks/install.ts
  • src/hooks/uninstall.ts
  • src/index.ts

Comment thread src/hooks/install.ts
Comment thread src/hooks/install.ts
Comment thread src/hooks/uninstall.ts
@nirvik34
Copy link
Copy Markdown
Owner

@Harikishanth Please resolve the merge conflict

…ration

# Conflicts:
#	bin/smartcommit.ts
#	src/index.ts
@nirvik34 nirvik34 merged commit 3def702 into nirvik34:main Jun 4, 2026
1 of 3 checks passed
@nirvik34 nirvik34 added type: feature Adds a new feature level:intermediate Decent knowledge required to work on quality:clean Bonus points under GSSOC for clean PR gssoc:approved Approved PR's under GSSOC mentor:nirvik34 labels Jun 4, 2026
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Jun 4, 2026

🎉 This PR is included in version 1.14.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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

Labels

gssoc:approved Approved PR's under GSSOC level:intermediate Decent knowledge required to work on mentor:nirvik34 quality:clean Bonus points under GSSOC for clean PR released type: feature Adds a new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Git Hook Integration

2 participants