# GitHub integration

SonarQube’s integration with GitHub Enterprise and GitHub.com allows you to maintain code quality and security in your GitHub repositories.

With this integration, you’ll be able to:

* **Import your GitHub repositories**: Import your GitHub repositories into SonarQube to easily set up SonarQube projects.
* **Analyze projects with GitHub Actions**: Integrate analysis into your build pipeline. Starting in [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/), SonarScanners running in GitHub Actions jobs can automatically detect branches or pull requests being built so you don’t need to specifically pass them as parameters to the scanner.
* **Add pull request decoration**: (starting in [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/)) See your quality gate and code metric results right in GitHub so you know if it’s safe to merge your changes.
* **Authenticate with GitHub**: Sign in to SonarQube with your GitHub credentials.

## Prerequisites <a href="#prerequisites" id="prerequisites"></a>

* To add pull request decoration to Checks in GitHub Enterprise, you must be running GitHub Enterprise version 2.21+.
* To analyze projects with GitHub Actions in GitHub Enterprise, you must be running [GitHub Enterprise version 3.0+](https://docs.github.com/en/enterprise-server@2.22/admin/github-actions/getting-started-with-github-actions-for-github-enterprise-server).

### Branch analysis <a href="#branch-analysis" id="branch-analysis"></a>

Community Edition doesn’t support the analysis of multiple branches, so you can only analyze your main branch. With [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/), you can analyze multiple branches and pull requests.

## Importing your GitHub repositories to SonarQube <a href="#importing-your-github-repository-to-sonarqube" id="importing-your-github-repository-to-sonarqube"></a>

You need to use a GitHub App to connect SonarQube with GitHub and import your GitHub repositories into SonarQube. This is also the first step in adding authentication, and, starting in [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/), the first step when adding pull request decorations.

If you want to set up authentication without importing your GitHub repositories, see the **Creating a dedicated app for authentication** section below for instructions on setting up authentication.

In this section, you’ll complete the following steps to connect SonarQube and GitHub with a GitHub App:

1. Create your GitHub App.
2. Install your GitHub App in your organization.
3. Update your SonarQube global settings with your GitHub App information.

### Step 1: Creating your GitHub app <a href="#step-1-creating-your-github-app" id="step-1-creating-your-github-app"></a>

See GitHub’s documentation on [creating a GitHub App](https://docs.github.com/apps/building-github-apps/creating-a-github-app/) for general information on creating your app.

Specify the following settings in your app:

* **GitHub App Name**: Your app’s name.
* **Homepage URL**: You can use any URL, such as `https://www.sonarsource.com/`.
* **User authorization callback URL**: Your instance’s base URL. For example, `https://yourinstance.sonarqube.com`.
* **Webhook URL**: Your instance’s base URL. For example, [`https://yourinstance.sonarqube.com`.](https://yourinstance.sonarqube.com)
* Grant access for the following **Repository permissions**:

|                                                                                                                                                          |              |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ |
| **Permission**                                                                                                                                           | **Access**   |
| Checks                                                                                                                                                   | Read & write |
| <p><strong>GitHub Enterprise:</strong> Repository metadata<br><strong>GitHub.com:</strong> Metadata<br>(this setting is automatically set by GitHub)</p> | Read-only    |
| Pull Requests                                                                                                                                            | Read & write |
| Commit statuses                                                                                                                                          | Read-only    |

* If setting up **GitHub Authentication**, in addition to the aforementioned Repository permissions, grant access for the following **Account permissions**:

|                 |            |
| --------------- | ---------- |
| **Permission**  | **Access** |
| Email addresses | Read-only  |

* And grant access for the following **Organization permissions**:

|                |            |
| -------------- | ---------- |
| **Permission** | **Access** |
| Members        | Read-only  |
| Projects       | Read-only  |

* Under "Where can this GitHub App be installed?," select **Any account**.

{% hint style="warning" %}
For security reasons, make sure you’re using `HTTPS` protocol for your URLs in your app.
{% endhint %}

### Step 2: Installing your GitHub app in your organization <a href="#step-2-installing-your-github-app-in-your-organization" id="step-2-installing-your-github-app-in-your-organization"></a>

Next, you need to install your GitHub App in your organization. See GitHub’s documentation on [installing GitHub Apps](https://docs.github.com/en/free-pro-team@latest/developers/apps/installing-github-apps) for more information.

### Step 3: Updating your SonarQube global settings with your GitHub app information <a href="#step-3-updating-your-sonarqube-global-settings-with-your-github-app-information" id="step-3-updating-your-sonarqube-global-settings-with-your-github-app-information"></a>

After you’ve created and installed your GitHub App, update your global SonarQube settings to finish integration and allow for the import of GitHub projects.

Navigate to **Administration** > **Configuration** > **General Settings** > **DevOps Platform Integrations** > **GitHub** and specify the following settings:

* **Configuration Name** (Enterprise and Data Center Edition only): The name used to identify your GitHub configuration at the project level. Use something succinct and easily recognizable.
* **GitHub URL**: For example, `https://github.company.com/api/v3` for GitHub Enterprise or `https://api.github.com/` for GitHub.com.
* **GitHub App ID**: The App ID is found on your GitHub App’s page on GitHub at **Settings** > **Developer Settings** > **GitHub Apps**.
* **Client ID**: The Client ID is found on your GitHub App’s page.
* **Client secret**: The Client secret is found on your GitHub App’s page.
* **Private Key**: Your GitHub App’s private key. You can generate a `.pem` file from your GitHub App’s page under **Private keys**. Copy and paste the contents of the file here.

## Analyzing projects with GitHub Actions <a href="#analyzing-projects-with-github-actions" id="analyzing-projects-with-github-actions"></a>

SonarScanners running in GitHub Actions can automatically detect branches and pull requests being built so you don’t need to specifically pass them as parameters to the scanner.

To analyze your projects with GitHub Actions, you need to:

* Create your GitHub Secrets.
* Configure your workflow YAML file.
* Commit and push your code to start the analysis.

### Creating your GitHub secrets <a href="#creating-your-github-secrets" id="creating-your-github-secrets"></a>

You can create repository secrets from your GitHub repository. See GitHub’s documentation on [Encrypted secrets](https://docs.github.com/en/actions/reference/encrypted-secrets) for more information.

You need to set the following GitHub repository secrets to analyze your projects with GitHub Actions:

* **Sonar Token**: Generate a SonarQube [generating-and-using-tokens](https://docs.sonarsource.com/sonarqube-server/8.9/user-guide/user-account/generating-and-using-tokens "mention") and, in GitHub, create a new repository secret in GitHub with `SONAR_TOKEN` as the **Name** and the token you generated as the **Value**.
* **Sonar Host URL**: In GitHub, create a new repository secret with `SONAR_HOST_URL` as the **Name** and your SonarQube server URL as the **Value**.

### Configuring your .github/workflows/build.yml file <a href="#configuring-your-githubworkflowsbuildyml-file" id="configuring-your-githubworkflowsbuildyml-file"></a>

This section shows you how to configure your `.github/workflows/build.yml` file.

You’ll set up your build according to your SonarQube edition:

* **Community Edition**: Community Edition doesn’t support multiple branches, so you should only analyze your main branch. You can restrict analysis to your main branch by setting it as the only branch in your `on.push.branches` configuration in your workflow YAML file, and not using `on.pull_request`.
* **Developer Edition and above**: GitHub Actions can build specific branches and pull requests if you use `on.push.branches` and `on.pull-requests` configurations as shown in the examples below.

Click the scanner you’re using below to expand the example configuration:

<details>

<summary>SonarScanner for Gradle</summary>

**Note:** A project key might have to be provided through a `build.gradle` file, or through the command line parameter. For more information, see the [sonarscanner-for-gradle](https://docs.sonarsource.com/sonarqube-server/8.9/analyzing-source-code/scanners/sonarscanner-for-gradle "mention") documentation.

Add the following to your `build.gradle` file:

```css-79elbk
plugins {
  id "org.sonarqube" version "3.1"
}
```

Write the following in your workflow YAML file:

```css-79elbk
name: Build
on:
  push:
    branches:
      - master # or the name of your main branch
  pull_request:
    types: [opened, synchronize, reopened]
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0  # Shallow clones should be disabled for a better relevancy of analysis
      - name: Set up JDK 11
        uses: actions/setup-java@v1
        with:
          java-version: 11
      - name: Cache SonarQube packages
        uses: actions/cache@v1
        with:
          path: ~/.sonar/cache
          key: ${{ runner.os }}-sonar
          restore-keys: ${{ runner.os }}-sonar
      - name: Cache Gradle packages
        uses: actions/cache@v1
        with:
          path: ~/.gradle/caches
          key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
          restore-keys: ${{ runner.os }}-gradle
      - name: Build and analyze
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}  # Needed to get PR information, if any
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
        run: ./gradlew build sonarqube --info
```

</details>

<details>

<summary>SonarScanner for Maven</summary>

**Note:** A project key might have to be provided through a `pom.xml` file or through the command line parameter. For more information, see the [sonarscanner-for-maven](https://docs.sonarsource.com/sonarqube-server/8.9/analyzing-source-code/scanners/sonarscanner-for-maven "mention") documentation.

Write the following in your workflow YAML file:

```css-79elbk
name: Build
on:
  push:
    branches:
      - master # or the name of your main branch
  pull_request:
    types: [opened, synchronize, reopened]
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0  # Shallow clones should be disabled for a better relevancy of analysis
      - name: Set up JDK 11
        uses: actions/setup-java@v1
        with:
          java-version: 11
      - name: Cache SonarQube packages
        uses: actions/cache@v1
        with:
          path: ~/.sonar/cache
          key: ${{ runner.os }}-sonar
          restore-keys: ${{ runner.os }}-sonar
      - name: Cache Maven packages
        uses: actions/cache@v1
        with:
          path: ~/.m2
          key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
          restore-keys: ${{ runner.os }}-m2
      - name: Build and analyze
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}  # Needed to get PR information, if any
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
        run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
```

</details>

<details>

<summary>SonarScanner for .NET</summary>

Write the following in your workflow YAML file:

```css-79elbk
name: Build
on:
  push:
    branches:
      - master # or the name of your main branch
  pull_request:
    types: [opened, synchronize, reopened]
jobs:
  build:
    name: Build
    runs-on: windows-latest
    steps:
      - name: Set up JDK 11
        uses: actions/setup-java@v1
        with:
          java-version: 1.11
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0  # Shallow clones should be disabled for a better relevancy of analysis
      - name: Cache SonarQube packages
        uses: actions/cache@v1
        with:
          path: ~\sonar\cache
          key: ${{ runner.os }}-sonar
          restore-keys: ${{ runner.os }}-sonar
      - name: Cache SonarQube scanner
        id: cache-sonar-scanner
        uses: actions/cache@v1
        with:
          path: .\.sonar\scanner
          key: ${{ runner.os }}-sonar-scanner
          restore-keys: ${{ runner.os }}-sonar-scanner
      - name: Install SonarQube scanner
        if: steps.cache-sonar-scanner.outputs.cache-hit != 'true'
        shell: powershell
        run: |
          New-Item -Path .\.sonar\scanner -ItemType Directory
          dotnet tool update dotnet-sonarscanner --tool-path .\.sonar\scanner
      - name: Build and analyze
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}  # Needed to get PR information, if any
        shell: powershell
        run: |
          .\.sonar\scanner\dotnet-sonarscanner begin /k:"example" /d:sonar.login="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="${{ secrets.SONAR_HOST_URL }}"
          dotnet build
          .\.sonar\scanner\dotnet-sonarscanner end /d:sonar.login="${{ secrets.SONAR_TOKEN }}"
```

</details>

<details>

<summary>SonarScanner CLI</summary>

A project key has to be provided through a `sonar-project.properties` file or through the command line as a parameter. For more information, see the [sonarscanner](https://docs.sonarsource.com/sonarqube-server/8.9/analyzing-source-code/scanners/sonarscanner "mention") documentation.

Write the following in your workflow YAML file:

```css-79elbk
name: Build
on:
  push:
    branches:
      - master # or the name of your main branch
  pull_request:
    types: [opened, synchronize, reopened]
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - uses: docker://sonarsource/sonar-scanner-cli:latest
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
```

</details>

### Failing the pipeline job when the quality gate fails. <a href="#failing-the-pipeline-job-when-the-quality-gate-fails" id="failing-the-pipeline-job-when-the-quality-gate-fails"></a>

In order for the Quality Gate to fail on the GitLab side when it fails on the SonarQube side, the scanner needs to wait for the SonarQube Quality Gate status. To enable this, set the `sonar.qualitygate.wait` property to `true` (check the above scanners’ documentation to know where to set this property).

You can set the `sonar.qualitygate.timeout` property to an amount of time (in seconds) that the scanner should wait for a report to be processed. The default is 300 seconds.

### Commit and push your code <a href="#commit-and-push-your-code" id="commit-and-push-your-code"></a>

Commit and push your code to start the analysis. Each new push you make on your branches or pull requests will trigger a new analysis in SonarQube.

## Adding pull request decoration to GitHub <a href="#adding-pull-request-decoration-to-github" id="adding-pull-request-decoration-to-github"></a>

After creating and installing your GitHub App above, you can add pull request decoration to show your Quality Gate and analysis metrics directly in GitHub.

The simplest way to add pull request decoration is by adding a project from GitHub by selecting **Add project** in the upper-right corner of the **Projects** homepage and selecting **GitHub**.

Then, follow the steps in SonarQube to analyze your project. The project settings for pull request decoration are set automatically.

{% hint style="info" %}
To decorate Pull Requests, a SonarQube analysis needs to be run on your code. You can find the additional parameters required for Pull Request analysis on the [pull-request-analysis](https://docs.sonarsource.com/sonarqube-server/8.9/analyzing-source-code/pull-request-analysis "mention") page.
{% endhint %}

If you’re creating your projects manually or adding quality gate reporting to an existing project, see the following section.

### Adding pull request decoration to a manually created or existing project <a href="#adding-pull-request-decoration-to-a-manually-created-or-existing-project" id="adding-pull-request-decoration-to-a-manually-created-or-existing-project"></a>

To add pull request decoration to a manually created or existing project, after you’ve created and installed your GitHub App and updated your global ALM Integration settings as shown in the **Importing your GitHub repositories into SonarQube** section above, set the following project settings at **Project Settings** > **General Settings** > **Pull Request Decoration**:

* **Configuration name**: The configuration name that corresponds to your GitHub instance.
* **Repository identifier**: The path of your repository URL.

### Advanced pull request configuration <a href="#advanced-pull-request-configuration" id="advanced-pull-request-configuration"></a>

<details>

<summary>Adding pull request decoration to projects that are part of a mono repository</summary>

*Pull request decoration for a mono repository setup is supported starting in* [*Enterprise Edition*](https://www.sonarsource.com/plans-and-pricing/enterprise/)*.*

In a mono repository setup, multiple SonarQube projects, each corresponding to a separate project within the mono repository, are all bound to the same GitHub repository. You’ll need to set up pull request decoration for each SonarQube project that is part of a mono repository.

To add pull request decoration to a project that’s part of a mono repository, set your project up manually as shown in the **Adding pull request decoration to a manually created or existing project** section above. You also need to set the **Enable mono repository support** setting to true at **Project Settings > General Settings > Pull Request Decoration**.

After setting your project settings, you need to ensure the correct project is being analyzed by adjusting the analysis scope and pass your project names to the scanner. See the following sections for more information.

#### Ensuring the correct project is analyzed <a href="#ensuring-the-correct-project-is-analyzed" id="ensuring-the-correct-project-is-analyzed"></a>

You need to adjust the analysis scope to make sure SonarQube doesn’t analyze code from other projects in your mono repository. To do this set up a **Source File Inclusion** for your project at **Project Settings > Analysis Scope** with a pattern that will only include files from the appropriate folder. For example, adding `./MyFolderName/**/*` to your inclusions would only include an analysis of code in the `MyFolderName` folder. See [narrowing-the-focus](https://docs.sonarsource.com/sonarqube-server/8.9/project-administration/narrowing-the-focus "mention") for more information on setting your analysis scope.

#### Passing project names to the scanner <a href="#passing-project-names-to-the-scanner" id="passing-project-names-to-the-scanner"></a>

Because of the nature of a mono repository, SonarQube scanners might read all project names of your mono repository as identical. To avoid having multiple projects with the same name, you need to pass the `sonar.projectName` parameter to the scanner. For example, if you’re using the Maven scanner, you would pass `mvn sonar:sonar -Dsonar.projectName=YourProjectName`.

</details>

<details>

<summary>Showing the analysis summary under the GitHub Conversation tab</summary>

By default, **Enable analysis summary under the GitHub Conversation tab** is on and your pull request analysis will be shown under both the **Conversation** and **Checks** tabs in GitHub. When off, your pull request analysis summary is only shown under the **Checks** tab.

</details>

<details>

<summary>Configuring multiple ALM instances</summary>

You can decorate pull requests from multiple ALM instances by creating a configuration for each ALM instance and then assigning that instance configuration to the appropriate projects.

* As part of [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/), you can create one configuration for each ALM.
* Starting in [Enterprise Edition](https://www.sonarsource.com/plans-and-pricing/enterprise/), you can create multiple configurations for each ALM. If you have multiple configurations of the same ALM connected to SonarQube, you have to create projects manually.

</details>

<details>

<summary>Linking issues</summary>

During pull request decoration, individual issues will be linked to their SonarQube counterparts automatically. For this to work correctly, you need to set the instance’s **Server base URL** (**Administration** > **Configuration** > **General Settings** > **General** > **General**) correctly. Otherwise, the links will default to `localhost`.

</details>

## Setting up GitHub authentication <a href="#setting-up-github-authentication" id="setting-up-github-authentication"></a>

To allow users to log in with GitHub credentials, use the GitHub App that you created above (see the **Importing your GitHub repositories using a GitHub app** section for more information) and update your global SonarQube settings.

{% hint style="info" %}
If you’re using Community Edition or you want to use a dedicated app for GitHub authentication, see the **Creating a dedicated app for authentication** section below.
{% endhint %}

To update your global SonarQube settings:

Navigate to **Administration** > **Configuration** > **General Settings** > **ALM Integrations** > **GitHub** and specify the following settings:

1. **Enabled**: set the switch to `true`.
2. **Client ID**: the Client ID is found below the GitHub App ID on your GitHub App’s page.
3. **Client secret**: the Client secret is found on your GitHub App’s page.

Now, from the login page, your users can connect their GitHub accounts with the new "Log in with GitHub" button.

### Creating a dedicated app for authentication <a href="#creating-a-dedicated-app-for-authentication" id="creating-a-dedicated-app-for-authentication"></a>

If you want to use a dedicated app for GitHub authentication, you can create a GitHub OAuth app. You’ll find general instructions for creating a GitHub OAuth App [here](https://docs.github.com/en/free-pro-team@latest/developers/apps/creating-an-oauth-app). Specify the following settings in your OAuth App:

* **Homepage URL**: the public URL of your SonarQube server. For example, `https://sonarqube.mycompany.com`. For security reasons, HTTP is not supported, and you must use HTTPS. The public URL is configured in SonarQube at **Administration** > **General** > **Server base URL**.
* **Authorization callback URL**: your instance’s base URL. For example, `https://yourinstance.sonarqube.com`.

After creating your app, follow the steps immediately above to update your global SonarQube settings.
