> For the complete documentation index, see [llms.txt](https://docs.sonarsource.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sonarsource.com/sonarqube-cli/integrations/git-hooks.md).

# Git hooks

`sonar integrate git` installs Git code scanning hooks that scan your code at commit or push time. Installed hooks delegate to the CLI's Git hook handlers (`sonar hook git-pre-commit` or `sonar hook git-pre-push`), which run secrets scanning (and optionally dependency-risks scanning on pre-commit), with no extra tooling required. See [Add dependency-risks scanning to pre-commit](#add-dependency-risks-scanning-to-pre-commit) for the optional SCA scan.

In an interactive terminal, the command shows a **SonarQube Git Integration (source code scanning)** banner and notes that the integration covers secrets and dependency-risks detection. Some scan types may be unavailable for certain hook types (for example, dependency-risks scanning is pre-commit only). The command prompts for install scope (project or global) when you omit both `--global` and `--project`, then prompts you to install each code scanning hook (`pre-commit` and `pre-push`).

Pass `--hook` to install a specific hook without prompts, `--global` for a machine-wide install, or `--non-interactive` to install without confirmation (see [Non-interactive install](#non-interactive-install)).

## Prerequisites

* [The SonarQube CLI is installed and authenticated](/sonarqube-cli/quickstart-guide.md).
* A Git repository (for project-scoped installs).

## Project key

On a project-scoped install, the CLI resolves your SonarQube project key before it installs hooks. When you omit `-p, --project`, it auto-detects the key from `sonar-project.properties`, SonarQube for IDE connected mode (`.sonarlint/connectedMode.json`), or the git `origin` remote when the repository is bound on SonarQube. In an interactive terminal, a **Project** phase shows the detected key.

Pass `-p` to override auto-detection or to install when no project binding exists on disk. If the CLI can't detect a project key, it warns that some features (including optional dependency-risks scanning) won't be available, but you can still install secrets-scanning hooks.

Explicit `-p` implies project scope and skips the install-scope prompt. Auto-detection does not skip that prompt.

## Choose pre-commit or pre-push

The CLI supports two hook types. Both stop a secret from leaving your machine, but at different moments:

| Hook         | Fires when…          | What it scans                                                           | Trade-off                                                                                  |
| ------------ | -------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `pre-commit` | You run `git commit` | Staged files for secrets; optionally dependency manifests for SCA risks | Catches secrets the earliest. Runs on every commit, which is slower for big change sets.   |
| `pre-push`   | You run `git push`   | Files changed in unpushed commits for secrets                           | Catches secrets just before they leave your machine. Lets you `git commit` freely locally. |

For most teams, `pre-commit` is the right default. It catches secrets before they enter local history. Choose `pre-push` if your developers commit constantly and want a single batched check before sharing.

## Install

### Per repository (default)

```bash
# Interactive: prompts for pre-commit and pre-push separately
sonar integrate git

# Install a specific hook without prompts:
sonar integrate git --hook pre-commit
sonar integrate git --hook pre-push
```

In an interactive install, you can accept both hooks in one run. You can also install them one at a time by running the command again with a different `--hook` value.

### Globally for every repository

```bash
sonar integrate git --global
```

Globally-installed hooks live in `~/.sonar/sonarqube-cli/hooks/`. The CLI sets `git config --global core.hooksPath` to that directory so every Git repo on your machine uses them, unless a repo has its own hooks path.

### Non-interactive install

```bash
# Without --hook: installs both pre-commit and pre-push
sonar integrate git --global --non-interactive

# Or pick one hook explicitly:
sonar integrate git --hook pre-commit --global --non-interactive
```

In non-interactive mode the CLI does not prompt for scope or feature selection; scope defaults to project when you omit `--global`, and without `--hook` it installs both hook types. It fails fast on conflicts. Combine with `--force` to overwrite a pre-existing hook (see below).

## Add dependency-risks scanning to pre-commit

On a project-scoped install, you can extend the `pre-commit` hook to run a Software Composition Analysis (SCA) scan on dependency manifest files in addition to the mandatory secrets scan. The scan uses the same engine as [Software Composition Analysis (SCA)](/sonarqube-cli/analysis/sca.md) and requires Advanced Security with SCA enabled on your SonarQube project.

Dependency-risks scanning is available only for **pre-commit** hooks at **project** scope. It is not supported with `--global` or `pre-push` hooks.

### Install with dependency-risks

Dependency-risks scanning requires a SonarQube project key. The CLI resolves the key from `-p` or from auto-detection (see [Project key](#project-key)). When a key is available, pass `--dependency-risks` to enable the scan from the command line:

```bash
# Interactive: auto-detects project key, then asks whether to enable dependency-risks
sonar integrate git

# Interactive: explicit project key (skips the scope prompt)
sonar integrate git -p my-project

# Non-interactive: install pre-commit with secrets and dependency-risks scanning
sonar integrate git --hook pre-commit --dependency-risks -p my-project --non-interactive
```

In an interactive install with a resolved project key, the CLI asks whether to enable dependency-risks scanning on the pre-commit hook when Software Composition Analysis (SCA) is available on your SonarQube connection. If SCA is not enabled, the prompt is skipped and only secrets scanning is installed. If you pass `--dependency-risks` on the command line, the scan is enabled without that prompt when SCA is available; otherwise the CLI prints a message and continues with secrets scanning only.

The project key is baked into the generated hook at install time. Re-run `sonar integrate git` with updated flags to change it.

### Limitations

| Constraint                                       | Reason                                                                                                                                                                                                                      |
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Requires a project key with `--dependency-risks` | The hook needs a SonarQube project key to run SCA. Pass `-p` or configure auto-detection (see [Project key](#project-key)).                                                                                                 |
| Not valid with `--global`                        | Global hooks apply across repositories and cannot carry a project key.                                                                                                                                                      |
| `pre-commit` only                                | Dependency-risks scanning runs on staged manifest files at commit time.                                                                                                                                                     |
| SCA must be enabled on the connection            | The CLI checks SCA availability before offering or installing dependency-risks scanning. Same prerequisites as `sonar analyze dependency-risks`. See [Software Composition Analysis (SCA)](/sonarqube-cli/analysis/sca.md). |

### What the hook does

When dependency-risks scanning is enabled, the pre-commit handler:

1. Scans staged files for secrets (same as the default hook).
2. If any staged dependency manifest or lock file changed, runs a dependency-risks scan against your SonarQube project for **new** risks at `MEDIUM` severity or above (`BLOCKER`, `HIGH`, and `MEDIUM`).
3. Blocks the commit when matching risks are found.

The hook skips the dependency-risks stage when no manifests changed, when the SCA scanner binary is not installed, or when the scan cannot complete (for example, a network error). In those cases the commit is not blocked. When the scan completes with no new risks, the hook prints a brief success line (`No dependency risks found.`). When risks are found, the hook blocks the commit with a minimal summary (for example, `3 dependency risks found (1 BLOCKER, 2 HIGH)`) and points you to `sonar analyze dependency-risks -p <YourProjectKey>` for the full table, fix recommendations, and details. Use `git commit --no-verify` to bypass if the risks are already reviewed.

## How the CLI handles existing hooks

When you install per-repo, the CLI looks at your project's hook setup in this order:

1. **Husky** (`.husky/` directory): the CLI registers via Husky.
2. **pre-commit framework** (`.pre-commit-config.yaml`): the CLI adds a local hook entry that runs `sonar hook git-pre-commit` or `sonar hook git-pre-push` with the changed filenames (`pass_filenames: true`).
3. **Plain Git hooks** (`.git/hooks/`): the CLI writes a hook script directly.

If a hook already exists in the target location and was **not** installed by `sonar integrate git`, the command refuses to overwrite it. Pass `--force` to overwrite:

```bash
sonar integrate git --force
```

This is safe to do when you want SonarQube secrets scanning to chain with an existing hook script. A marker comment identifies the hook, so subsequent `sonar integrate git` runs recognize and update it without `--force`.

## Verify the hook

1. Create a file with a fake-looking but secret-shaped value:

   ```javascript
   // secrets.js
   const API_KEY = "sqp_1aa323ae0689cd4a1abd062a2ad0a224ae8a1d13";
   ```
2. Stage and try to commit:

   ```bash
   git add secrets.js
   git commit -m "Test"
   ```
3. The commit should be blocked and the secret reported.

Delete the test file once confirmed.

## Bypass the hook

If you need to skip the hook for a single commit (for example, while running a script that the hook would interfere with), use Git's built-in `--no-verify` flag:

```bash
git commit --no-verify
```

> **Warning:** Use `--no-verify` sparingly. The whole point of the hook is to catch secrets before they enter your history. Prefer fixing the offending file over bypassing the check.

## Uninstall

To remove the hook:

* **Per-repo (plain Git hooks):** delete the file in `.git/hooks/pre-commit` (or `pre-push`). The CLI marks its hooks with a comment so you can identify them.
* **Per-repo (Husky / pre-commit framework):** remove the SonarQube entry from your Husky scripts or `.pre-commit-config.yaml`.
* **Globally:** unset the global hooks path with `git config --global --unset core.hooksPath` and delete the directory at `~/.sonar/sonarqube-cli/hooks/`.

See [Uninstalling](/sonarqube-cli/administration/uninstall.md) for the full removal procedure.

## Related pages <a href="#related-pages" id="related-pages"></a>

* [Secrets scanning](/sonarqube-cli/analysis/secrets-scanning.md)
* [Software Composition Analysis (SCA)](/sonarqube-cli/analysis/sca.md)
* [Claude Code](/sonarqube-cli/integrations/claude-code.md)
* [GitHub Copilot](/sonarqube-cli/integrations/github-copilot.md)
* [Exit codes](/sonarqube-cli/using-sonarqube-cli/exit-codes.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.sonarsource.com/sonarqube-cli/integrations/git-hooks.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
