# Sample PR integrations in CI

We have captured here typical use cases of Pull Request Integration.

{% hint style="warning" %}
The **Target branch must have builds already reported** to Sealights, otherwise the prConfig command will fail.\
If your development process includes pull requests merged to features branch, you may want to exclude them from the scope if Sealights analysis or enforce a build to be reported with the creation of the feature branch (via a webhook).
{% endhint %}

## Maven Build for a Java application <a href="#maven-build-for-a-java-application" id="maven-build-for-a-java-application"></a>

In the example below, we simply create the `buildSessionId` outside the JSON command using the relevant parameters.

{% tabs %}
{% tab title="Github Actions" %}
{% code overflow="wrap" lineNumbers="true" %}

```yaml
name: Build with Sealights
on:
  push:
    branches:
      - "**"
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      SL_TOKEN: ${{ secrets.SL_TOKEN }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Set up JDK
        uses: actions/setup-java@v4
        with:
          java-version: "17"
          distribution: "temurin"
      - name: Download Sealights Agents
        # NOTE: The steps below can be consolidated into a shell script (e.g. sealights-setup.sh) per best practice
        run: |
          echo "Downloading Sealights Agents..."
          wget -nv https://agents.sealights.co/sealights-java/sealights-java-latest.zip
          unzip -o sealights-java-latest.zip
      - name: Create Sealights' UUID (BSID) according to context
        # NOTE: This step can be moved to a shell script (e.g. sealights-config.sh) per best practice
        env:
          SL_APP_NAME: ${{ github.event.repository.name }}
          SL_PACKAGES_INCLUDED: "*com.mycompany.*" ## UPDATE ME ! ##
          PR_NUMBER: ${{ github.event.pull_request.number }}
          PR_BASE_BRANCH: ${{ github.base_ref }}
          COMMIT_SHA: ${{ github.sha }}
          REPO_NAME: ${{ github.repository }}
          BRANCH_NAME: ${{ github.ref_name }}
        run: |
         if [ -n "${PR_NUMBER}" ]; then
            # Pull Request context (GitHub Actions environment variables)
            java -jar sl-build-scanner.jar -prConfig \
              -token "${SL_TOKEN}" \
              -appname "${SL_APP_NAME}" \
              -targetBranch "${PR_BASE_BRANCH}" \
              -pullRequestNumber "${PR_NUMBER}" \
              -latestCommit "${COMMIT_SHA}" \
              -repoUrl "https://github.com/${REPO_NAME}" \
              -pi "${SL_PACKAGES_INCLUDED}"
          else
            # Regular Build
            BUILD_NUMBER="${{ github.run_number }} ($(date -u '+%Y-%m-%d %H:%M'))"
            java -jar sl-build-scanner.jar -config \
              -token "${SL_TOKEN}" \
              -appname "${SL_APP_NAME}" \
              -branchname "${BRANCH_NAME}" \
              -buildname "${BUILD_NUMBER}" \
              -pi "${SL_PACKAGES_INCLUDED}"
          fi
      - name: Generate Sealights Maven Config and Update POM
        # NOTE: This step can be moved to a shell script (e.g. sealights-maven-config.sh) per best practice
        run: |
          cat > slmaven.json << 'EOF'
          {
            "executionType": "full",
            "token": "${SL_TOKEN}",
            "createBuildSessionId": false,
            "buildSessionIdFile": "./buildSessionId.txt",
            "filesIncluded": "*.class",
            "filesExcluded": "*test-classes*",
            "recursive": true,
            "includeResources": true,
            "testStage": "Unit Tests",
            "labId": null,
            "logEnabled": false,
            "logDestination": "console",
            "logLevel": "off",
            "logFolder": "/tmp/sl-logs",
            "sealightsJvmParams": {},
            "enabled": true,
            "filesStorage": "/tmp"
          }
          EOF
          echo "Updating POM with Sealights..."
          java -jar sl-build-scanner.jar -pom -configfile slmaven.json -workspacepath .
      - name: Build with Maven
        run: mvn clean install
```

{% endcode %}
{% endtab %}

{% tab title="Bitbucket CI" %}
{% hint style="info" %}
In the sample script below, please update lines 7 and 8 before executing it.
{% endhint %}

{% code overflow="wrap" lineNumbers="true" %}

```bash
#!/bin/bash
echo "Downloading Sealights Agents..."
wget -nv https://agents.sealights.co/sealights-java/sealights-java-latest.zip
unzip -o sealights-java-latest.zip

# sample values
export SL_APP_NAME="myApp"
export SL_PACKAGES_INCLUDED="*com.mycompany.*"

# Pull request parameters per the Sealights documentation
if [ -n "${BITBUCKET_PR_ID}" ]; then
      #Pull Request context (Bitbucket environment variables)
      java -jar sl-build-scanner.jar -prConfig -token $SL_TOKEN -appname $SL_APP_NAME \
            -targetBranch "origin/$BITBUCKET_PR_DESTINATION_BRANCH" -pullRequestNumber $BITBUCKET_PR_ID \
            -latestCommit $BITBUCKET_COMMIT -repoUrl "https://bitbucket.mycompany.int/$BITBUCKET_REPO_SLUG" \
            -pi $SL_PACKAGES_INCLUDED
else
      #Regular Build
      java -jar sl-build-scanner.jar -config -token $SL_TOKEN -appname $SL_APP_NAME \
            -branchname "${GIT_BRANCH}" -buildname "${BUILD_NUMBER}" -pi $SL_PACKAGES_INCLUDED
fi

echo  '{
        "token": ${SL_TOKEN},
        "createBuildSessionId": false,
        "buildSessionIdFile": "./buildSessionId.txt",
        "filesIncluded": "*.class",
        "filesExcluded": "*test-classes*",
        "recursive": true,
        "includeResources": true,
        "testStage": "Unit Tests",
        "labId": null,
        "executionType": "full",
        "logEnabled": false,
        "logDestination": "console",
        "logLevel": "off",
        "logFolder": "/tmp/sl-logs",
        "sealightsJvmParams": {},
        "enabled": true,
        "filesStorage": "/tmp"
}' > slmaven.json
  
echo "Updating POM with Sealights..."
java -jar sl-build-scanner.jar -pom -configfile slmaven.json -workspacepath .
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Azure DevOps Pipeline for a DotNet application <a href="#azure-devops-pipeline-for-a-dotnet-application" id="azure-devops-pipeline-for-a-dotnet-application"></a>

{% hint style="info" %}
In the sample script below, if required, please update lines 1 to 4 and 25-26 before executing it.
{% endhint %}

{% hint style="info" %}
Lines 8-9, 22-23 and 26-27 contain the `` ` `` characters allowing multi-line commands in Powershell scripts, to increase readiness of this sample code.
{% endhint %}

{% code overflow="wrap" lineNumbers="true" %}

```powershell
$sldomain="mycompany.sealights.co" 
$slagenttoken="$(AgentToken.Sandbox)"
$APP_NAME="MyApplication"
$APP_NAMESPACE="CalculatorServer.Controllers"

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Write-Output "Download the Sealights DotNet agent version set in settings..." 
$agentversion = ((iwr -Uri https://$($sldomain)/api/v2/agents/dotnet/recommended -Headers @{'Accept' = 'application/json'; 'Authorization' = "Bearer $($slagenttoken)"}).Content `
                          | ConvertFrom-Json | Select-Object agent).agent.version
iwr -OutFile sealights-dotnet-agent.zip -Uri http://agents.sealights.co/SL.DotNet/SL.DotNet-$($agentversion).zip
Expand-Archive .\sealights-dotnet-agent.zip -DestinationPath SL.DotNet -Force
Write-Output "Sealights agent version used is: $(Get-Content .\SL.DotNet\version.txt)" 

#Retrieve the same name of target branch as reported in Sealights Dashboard by removing the uncecessary prefix
$PR_TARGET_BRANCH="$(System.PullRequest.TargetBranch)".Replace("refs/heads/","")
#Retrieve the last Commit Hash from the PR branch and not the one from the ADO local Merge (via git log history)
$PR_LAST_COMMIT=$(git log -2 --format=%H).Split(" ")[1]
$PR_NUMBER="$(System.PullRequest.PullRequestId)"
$REPO_URL="$(System.PullRequest.SourceRepositoryURI)"

Write-Output "`n*** Create PR BSID ***"
.\SL.DotNet\x64\SL.DotNet.exe prConfig --appName $APP_NAME --pullRequestNumber $PR_NUMBER --targetBranch $PR_TARGET_BRANCH --latestCommit $PR_LAST_COMMIT --repositoryUrl $REPO_URL `
        --includeNamespace $APP_NAMESPACE --buildSessionIdFile $(Build.ArtifactStagingDirectory)\SealightsBuildSessionId.txt --token $($slagenttoken) --logEnabled true --logAppendConsole true --ignoreCertificateErrors true

# Base path where all relative paths should start from. By default the agent searches for the solution file and uses its path for this value
$SOLUTION_DIR="$(Build.Repository.LocalPath)"
#Path to the source workspace
$SOURCE_DIR="$(Build.Repository.LocalPath)\src"

Write-Output "`n*** Prepare for MSBuild ***"
.\SL.DotNet\x64\SL.DotNet.exe prepareForMsBuild --buildSessionIdFile $(Build.ArtifactStagingDirectory)\SealightsBuildSessionId.txt --workspacePath $SOURCE_DIR `
        --baseDir $SOLUTION_DIR --ignoreGeneratedCode true --debugMode true --logEnabled true --logAppendConsole true --ignoreCertificateErrors true --token $($slagenttoken) --scm git --scmProvider vsts 
```

{% endcode %}
