AutoRABIT Knowledge Base
  • 👋Welcome to the Knowledge Base
  • Fundamentals
    • ⚡AutoRABIT Solutions
    • LearningHub
    • ℹ️FAQs
      • General User Definitions
        • ARM User Definitions
      • ARM-FAQs
        • Connection & Authentication
        • Common Errors and Resolutions
        • Deployment
        • Data Loader
        • CI Jobs
        • Retention Policy
        • nCino
      • CodeScan-FAQs
        • General
          • CodeScan Static IP Ranges
          • Difference b/w CodeScan Self-Hosted and CodeScan Cloud
          • Single Sign-On (SSO)
          • What is a Subscription Code?
          • What is a CodeScan License Key?
          • Can I use CodeScan with a proxy?
          • Not receiving email notifications
          • CodeScan Blocks, Lines, and Field Inquiries
          • How are Metric Definitions Defined?
          • What Is Cyclomatic Complexity?
          • Can I export my test results?
          • CodeScan requests read and update permissions while connecting to Bitbucket
          • SSL Certificates
          • Does SonarQube support test execution reports for pull requests?
        • CodeScan Self-Hosted Issues
          • Self-Hosted Errors and Solutions
          • Self-Hosted FAQs
          • License Errors
          • License Issues (IDE)
          • Setting the System Environment Variable
          • Setting Up CodeScan for Use with a Proxy
        • CodeScan Cloud Issues
          • Cloud Errors and Solutions
        • Common Issues and Solutions
      • Vault-FAQs
        • Vault-FAQs
        • Common Error Messages
        • Limitations
        • Unsupported Metadata Types
  • Release Notes
    • 🔁Release Notes
      • ARM Release Notes
        • Release Notes 25.2
        • Release Notes 25.1
          • Release Notes 25.1.4
          • Release Notes 25.1.3
          • Release Notes 25.1.2
          • Release Notes 25.1.0
        • Release Notes 24.4
          • Release Notes 24.4.5
          • Release Notes 24.4.4
          • Release Notes 24.4.3
          • Release Notes 24.4.2
          • Release Notes 24.4.1
        • Release Notes 24.3
          • Release Notes 24.3.5
          • Release Notes 24.3.4
          • Release Notes 24.3.3
          • Release Notes 24.3.2
          • Release Notes 24.3.1
        • Release Notes 24.2
        • Release Notes 24.1
        • Release Notes 23.1
        • Release Notes 22.3
        • Release Notes 22.2
        • Release Notes 22.1
        • Release Notes 21.6
        • Release Notes 21.5
      • CodeScan Release Notes
        • Cloud Releases
          • Release Notes 25.1
          • Release Notes 25.0
          • Release Notes 24.0
          • Prior Versions
            • Release Notes 23
              • Release Notes 23.2
              • Release Notes 23.1
            • Release Notes 22
              • Release Notes 22.8
              • Release Notes 22.7
              • Release Notes 22.4
              • Release Notes 22.3
              • Release Notes 22.2
              • Release Notes 22.1
            • Release Notes 21
              • Release Notes 21.5
              • Release Notes 21.4
            • Release Notes 4
              • Release Notes 4.5
              • Release Notes 4.4
              • Release Notes 4.3
              • Release Notes 4.2
        • Self Hosted Releases
          • Eagle Edition
            • Release Notes 25.1.0 Eagle 3.0
            • Release Notes 24.1.1 Eagle 2.0
            • Release Notes 24.1.0 Eagle
          • Tiger Edition
            • Release Notes 25.0.1 Tiger 3.0
            • Release Notes 24.0.13 Tiger 2.0
            • Release Notes 24.0.9 Tiger
          • Prior Editions
            • Release Notes 24
              • Release Notes 24.0.8
              • Release Notes 24.0.5
              • Release Notes 24.0.4
              • Release Notes 24.0.1
            • Release Notes 23.1
        • CodeScan for Government
      • nCino Release Notes
        • Release Notes 25.1
        • Release Notes 24.4
        • Release Notes 24.3
        • Release Notes 24.2
        • Release Notes 24.1
        • Release Notes 23.1
        • Release Notes 22.3
      • Vault Release Notes
        • Release Notes 24.0
        • Release Notes 23.0
        • Release Notes 22.0
        • Release Notes 21.0
      • Guard Release Notes
        • Release Notes 25.1
  • Product Guides
    • ARM
      • Getting Started
        • Signing Up with ARM
          • User Profile
        • Understanding ARM
          • What is ARM?
          • What can I do with ARM?
          • Who can use ARM?
          • ARM Supported Metadata Types
        • Navigating ARM
      • ARM Administration
        • User Management
          • User Types
          • Predefined Roles
          • Users, Roles & Permissions
          • Adding New Users
          • Assigning User Roles
          • Removing or Suspending Users
          • Exporting User Details
          • Managing User Account Settings
          • Resetting Account Passwords
          • Profiles
          • Permissions
          • Credential Manager
          • Delegating Approvals to Another User
          • Enforcing Single Sign-On (SSO)
          • Salesforce API Version
          • Changing Super Admin in ARM
        • Registration
          • Version Control Repository
            • GIT Integration
              • GIT Tag
            • SVN
            • TFS
            • Bitbucket
          • Version Control Branch
            • GIT Branch Creation
            • Creation of a TFS Branch
            • Creation of SVN Branch
          • Salesforce Org
            • Salesforce Authentication using OAuth
            • Salesforce Org Re-Authentication
          • Static Code Analysis in CI-CD
        • Subscription Management
        • Workspaces
        • Search and Substitute
        • ALM Management
      • Getting Set Up
        • Version Control Repository
          • GIT Integration
            • GIT Tag
          • SVN
          • TFS
          • Bitbucket
        • Version Control Branch
          • GIT Branch Creation
          • Creation of a TFS Branch
          • Creation of SVN Branch
        • Salesforce Org
          • Salesforce Org Management
          • Salesforce Authentication using OAuth
          • Salesforce Org Reauthentication
        • Branching Baseline
        • Static Code Analysis in CI/CD
        • Browser Support
      • ARM Features
        • Dashboard & Pipelines
          • Dashboards & Widgets
          • Pipelines
        • Webhooks
          • Configure a Webhook in Bitbucket
          • Configure a Webhook in Bitbucket Enterprise
          • Configure a Webhook in GitHub
          • Configure a Webhook in GitHub Enterprise
          • Configure a Webhook in GitLab
          • Configure a Webhook in Microsoft Azure
          • Configure a Webhook in Slack
          • Configure a Webhook in Teams
          • Configure a Webhook in Visual Studio GIT
          • Configure a webhook in Visual Studio GIT Enterprise
        • Version Control
          • Introduction to Version Control
            • Version Control Repositories Summary
            • Version Control Branch Workflow
          • Version Control Repository
          • EZ-Commits
            • How Do I Commit?
            • Commits Summary
            • Committing Individual Forms from Form Manager (RBC Metadata)
          • EZ-Merge
            • Merge Conflicts
            • Merge Requests
            • Squash and Merge
            • Git Commit History and Merge Operations Basics
          • Change Labels
            • Commit Labels
            • Release Labels
              • Selective Deployments Using Pre-Prepared Artifacts
              • Artifact Preparation and Deployment Process
            • ALM Labels
          • External Pull Request
            • Azure Cloud Authentication
            • Pull Request Support for Azure Cloud
            • External Pull Request Summary Page
          • Commit Templates
          • GIT Revert
          • Understanding Duplicate File Change Commits in Git
          • Merge Approvals
        • Data Loader
          • Single Data Loader
            • Extract Salesforce Data
            • Insert Salesforce Data
            • Update Salesforce Data
            • Upsert Salesforce Data
            • Delete Salesforce Data
            • Using Data Loader with Lookups
          • Data Loader Pro
          • Data Loader Configuration
          • Test Environment Setup
          • Validation / Workflow Rules
          • Preparing the CSV file for ARM Data Loader
        • Automation and CI
          • Create a New CI Job
            • Build a Package from Salesforce
            • Backup your project to Version Control
            • Build a package from Version Control
            • Deploy a package from a Salesforce Org
            • Deploy from Salesforce with VC backup
            • Deploy from Version Control to a Salesforce Org
            • Deploy from SFDX branch to a Salesforce Org
            • Run Test Automation Scripts
            • Install an Unlocked Package from Version Control Branch
          • Triggering Builds for your CI Job
          • CI Job History
          • CI Job List
          • Configure Callout URL
          • CI Job Rollback
          • Parallel Processor
          • Enabling GitHub Checks
          • Automate Merge When CI Builds Pass
        • Deployment
          • Monitor Deployments
          • Apex Unit Tests
          • Connecting and Syncing Salesforce Orgs
          • Creating and Deploying Changes
          • Deploying Profile and Permission Sets
          • Deployment Rollback
          • Destructive Changes
        • nCino
          • Feature Migration
            • Create a Feature Migration Template
            • Create a Feature Migration Template with Predefined nCino Objects
            • Feature Migration Summary Page
          • Feature Deployment
            • Deployment Using Feature Migration Template
            • Deployment via Template using Salesforce Org
            • Deployment Using Version Control
            • Deployment via Version Control using Salesforce Org
            • Feature Deployment Summary
          • Feature Commits
          • Feature CI Jobs
            • Running a CI Job
            • CI Job Results
            • CI Job List screen
            • nCino Webhooks
          • Post Deployment Activities
          • Specify Baseline Revision in Continuous Integration for Version Control
          • Selecting a Range of Revisions
          • nCino RBC Deployment Rollback
          • nCino Developer APIs
            • nCino API References
          • nCino Compare
          • Exclude the OwnerID from Automapping in nCino CI jobs
          • External Unique ID Validation
          • Select External Unique ID
        • Salesforce DX
          • Salesforce DX Metadata Format
          • Registering a DevHub
          • Create a Scratch Org
          • Create a Module
          • Create an Unlocked/Managed Package
          • Import an Unlocked/Managed Package
        • Reports
          • Reports Overview
          • Code Coverage Reports
          • Deployment Reports
          • Static Code Analysis
          • Audit Report
        • Environment Provisioning
          • Migration Template
            • Enable History Tracking on Objects
            • Disable History Tracking on Objects
            • Enable History Tracking on Custom Fields
            • Disable History Tracking on Custom Fields
            • Run Destructive Changes
            • Execute Anonymous Apex
            • Enable Validation Rules
            • Disable Validation Rules
            • Enable Workflow Rules
            • Disable Workflow Rules
            • Enable Flows
            • Disable Flows
            • Enable Apex Triggers
            • Disable Apex Triggers
            • Migrate Custom Settings Data
          • Unsupported Metadata Templates
            • Account Teams
              • EnableAccountTeams
              • DeleteAccount
              • DisableAccountTeams
              • NewRoleAccount
              • Reorder
              • Replace
              • SortAlphabetically
            • AddTabsinAppManager
            • ActivityButtonOverrides
            • ApexExceptionEmail
            • ComplianceBCCEmail
            • AutoNumberFields
            • Campaign Influences
              • CampaignInfluencesEnable
              • CampaignInfluencesDisable
            • Case Contact Roles
              • NewContactRoles
              • DeleteContactRoles
              • ReorderContactRoles
              • ReplaceContactRoles
            • Contact Role Templates
              • EditTeamRole
              • NewTeamRole
              • ReplaceTeamRole
            • Console Layout Assignment
              • ConsoleLayoutsAssignments
              • DeleteConsoleLayout
              • NewConsoleLayouts
            • Create Lead Mapping Rules
              • LeadMapping
            • Create Organization-Wide Email Footers
              • DeleteEmailFooters
              • EditEmailFooters
              • EmailFooters
            • Case Feed Layout
            • Create Public Groups
              • Assign Roles and Profiles to Public Groups
              • PublicGroups
            • Web to Case
            • Data Category Visibility Settings
            • Delegated Administration
              • DelegatedAdministrationNew
              • DelegatedAdministrationEdit
            • Delete Outbound Messages
            • Delete Scheduled Jobs
            • Delete Time Based Workflow
            • Disable Scheduled Reports
            • Edit Queue
            • Email to Case Settings
              • Email to Case
              • Update Email to Case
            • File Upload and Download Security
            • Fiscal Year
            • Edit Lead
            • Email Admin Settings
            • Email Relay Activation
            • Manage Email Services
              • DeleteEmailServices
              • EditEmailServices
              • NewEmailServices
            • Manage Libraries
            • Page Layout Assignment
            • Manage User Records
            • Mobile Administration
              • Mobile Dashboard Settings
              • Mobile Notifications
              • Mobile Salesforce Settings
              • Salesforce Navigation
              • Salesforce Offline
            • Multiline Layout Fields For Contract Line Items
            • Multi Line Layout Fields for Opportunity Teams
            • Territory Model Options
              • New Territory Model
              • Edit Territory Model
              • Delete Territory Model
            • Offline Briefcase Configuration
              • Offline Briefcase Configuration New
              • Offline Briefcase Configuration Edit
              • Offline Briefcase Configuration Delete
            • Opportunity Deal Alerts
              • Edit Deal Alert
              • New Deal Alert
            • Opportunity Update Reminders
              • EditReminder
            • Organization Wide Email Addresses
              • Delete
              • Edit All
              • Organization All Profile
            • Predefined Case Teams
              • DelPredefined
              • NewPredefined
              • EditAdd
              • EditRemove
              • EditName
            • Product Schedule Settings
            • Public Calendar
              • Public Calendar Delete
              • Public Calendar Edit
              • Public Calendar New
            • Public Calendars and Resources Sharing
              • Public Calendar and Resources Sharing Add
              • Public Calender and Resources Sharing Edit
              • Public Calendar and Resources Sharing Delete
            • Publish Communities
            • Quote Templates
              • Active Quote
              • Deactive Quote
              • Delete Quote
              • New Quote
            • Report Dashboards Create Manage Folders
              • Create New Dashboard Folder
              • Create New Report Folder
              • Delete Folder
              • Share Settings
            • Resource Calendar
              • Resources Calendar Delete
              • Resources Calendar Edit
              • Resources Calendar New
            • Sandbox Refresh
            • Enable Salesforce to Salesforce
            • Schedule Apex Classes Monthly
            • Schedule Apex Classes Weekly
            • Search Settings
            • Self Service Public Solutions Edit
            • Site
            • Social Accounts Contacts and Lead Settings
            • SoftPhone Layouts
              • Softphone Layout New
              • SoftPhone Layout Edit
              • SoftPhone Layout Delete
            • Solution Categories
              • Solution Category Add
              • Solution Category Edit
            • Solution Settings Edit
            • Tag Settings
            • Territory View Rules
              • Delete Territory View Rules
              • Edit Territory View Rules
              • New Territory View Rules
            • User Interface Settings
            • Update Custom Label
            • Update Url for Remote Site Settings
            • Web to Lead
              • Edit Web Lead
              • Web To Lead
      • Integration and Plugins
        • SSO
          • SSO With Microsoft Entra ID
          • SSO for OKTA
          • SSO For PingFederate
          • SSO For ADFS
          • SAML SSO (Generic IdP)
        • Active Directory
        • JIRA
        • Azure DevOps
        • OmniStudio
          • Deploying OmniStudio Components
          • OmniStudio Configuration Settings
          • Committing OmniStudio Components to a Branch
        • AccelQ
        • HashiCorp Vault
        • Provar
        • SCA for Checkmarx
          • Checkmarx One Integration
        • Apex PMD
        • CodeScan Overview
        • SonarQube
        • Jenkins
        • Visual Code Extension
          • Installing VS Code Extension
          • Configuring VS Code Extension
          • Working with VS Code Extension
        • Integrate ServiceNow with ARM
        • URL Callout Integration with Tricentis
        • ARM for Salesforce Data Cloud
      • Security Information and Event Management
        • Common Event Format (CEF) Data
        • ARM Event Type
        • Retrieval APIs
      • Developer APIs
        • Authentication
        • API Access
        • Errors
        • API References
      • On-Premises / Dedicated Instances
        • Upgrade Guides
      • Troubleshooting
        • Best Practices
          • Salesforce Deployment Best Practices
          • Version Control Best Practices
          • CI Job Configurations
          • Vlocity
          • IP Whitelist
          • How to Include Network Settings in Commit or Deployment
          • Branching Strategy & CI/CD Pipeline
          • Metadata comparison between two Salesforce Orgs
          • Working with Translations in ARM
          • Revision Range & Release Label Deployment
          • Salesforce API Version Mismatch for the CI Build and Custom Deployment
          • Prerequisite while performing a commit using AutoRABIT
          • Flows in Salesforce
        • Known Issues / Limitations
          • ARM Known Issues
          • ARM Known Limitations
          • Salesforce Known Limitations
        • How-To's
          • Configure Merge Approval
          • Check Time Stamp for Commit/Merge
          • Enable SCA Apex PMD validation criteria.
          • Create API Token
          • Create Users' Credentials
          • Configure Record Types Picklist Values
          • Configure Multi-Proxy
          • Configure Mail Server Settings
          • Notifications (Mail Server Settings)
          • Enable Delta on PermissionSets
          • Default Apex Class Configuration
          • Enable Enhanced Domains
          • Provide branch access to users
        • FAQs
    • CodeScan
      • CodeScan Overview
      • System Requirements and Installation Self-Hosted
        • Installing CodeScan Self-Hosted
      • Getting Started
        • Users, Roles and Permissions
          • User Account
          • Reset the Password
          • Adding Users to a CodeScan Cloud Organization
            • Accepting invitations to add a user to a CodeScan Organization
          • Deleting User from a CodeScan Organization
          • Member Permissions
          • IDP Group Mapping
        • Setting up a CodeScan Cloud Organization
          • About CodeScan Cloud Organizations
          • Deleting Projects and Organizations
          • Generate a Security Token
          • Finding your Organization Key
          • Finding your Project Key
          • Setting up Payment
          • Understanding branches in CodeScan Cloud
          • Understanding branches for Salesforce project
          • Understanding the New Code Tab
        • Adding Projects to CodeScan
          • Add a project to CodeScan from Salesforce
          • Add a project to CodeScan from GitHub
          • Add a Project to CodeScan from Bitbucket
          • Add a Project to CodeScan from Git
          • Add a project to CodeScan from GitLab
      • Quality Profiles
        • Setting a Default Quality Profile
        • Customizing Quality Profiles
        • Exporting CodeScan Quality Profiles
      • Quality Gates
        • Understanding Quality Gates
        • Assigning Specific Quality Gates to a Project
        • Customizing Quality Gates
      • CodeScan Rules
        • CodeScan Rule List
        • Security-Related Rules
        • Creating Custom Rules with XPath
        • Configuration for Polyfill.io Vulnerability Rules
        • Configuration for Salesforce Metadata Rules
        • Metadata Rules on CodeScan Self-Hosted
      • Issues
        • Filtering Issues in CodeScan
        • Export issues to CSV in CodeScan Cloud
        • Exporting Issues using CodeScan-Export Tool
        • About Issue Status
        • Security Hotspots
      • Report and Analysis
        • Scheduled Reports
        • Analysis Scope on CodeScan Cloud
        • Ignoring Violations
        • Importing Salesforce CLI Code Coverage
        • Housekeeping
      • CodeScan Support
        • Raise a Service Request
      • CodeScan Integration
        • Integration Requirements
        • Project Naming Conventions
        • Single Sign-On (SSO)
          • Single Sign-On with OKTA
          • Single Sign-On with Entra ID
          • Single Sign-On with ADFS
          • Single Sign-On with PingOne
        • ARM
          • CodeScan Integration with ARM
        • CodeScan SFDX Plugin
          • Run analysis locally using SFDX
          • Importing Code Coverage from SFDX projects
        • IDE Plugins
          • Installing CodeScan for VS Code
          • Installing CodeScan for IntelliJ
        • Copado
          • Copado SFDX Integration
          • Copado MDAPI Integration
        • Flosum
          • CodeScan and Flosum Integration
        • Azure DevOps
          • Scan CodeScan Cloud projects in Azure DevOps
        • GitLab
          • Integrating CodeScan in GitLab
        • Bitbucket Pipelines
          • Integrating CodeScan in Bitbucket Pipelines
          • Reattaching Bitbucket Projects
        • GitHub Actions
          • CodeScan in Github Actions using the SFDX Plugin
          • Integrating CodeScan with GitHub Actions
        • Jenkins
          • CodeScan with Windows Agents
          • CodeScan with Linux/Unix Agents
          • Use Jenkins with CodeScan Salesforce project
        • Webhooks
          • Slack integration with Zapier
    • Vault
      • Vault™ Overview
      • Getting Started
        • Registering for an Account
        • Signing In
        • Resetting your Password
        • Managing Users and Roles
        • Setting Up Multifactor Authentication in Vault
        • Managing User Sessions
        • User Profile and Permission Access for Salesforce Users
        • Transferring Admin Ownership
        • Controlling Access to the Salesforce Org
      • Configuring Vault
        • Configure Backup Environment
          • Amazon AWS S3 Storage Environment
            • Bring your own Key (BYOK) with Vault
            • IAM Role Support
          • Google Cloud Platform
          • Create an Azure Storage Account
          • Azure Blob Storage Environment
          • Microsoft Azure Blob Retention Policy
          • NFS
          • SAN (Storage Area Network) Environment
        • Licenses
        • SSO Configuration
          • SSO for OKTA
          • SSO with Microsoft Entra ID for Vault
        • Registering Salesforce Org
          • Setup backup configuration for Salesforce Org
          • Archival Configuration
          • Unique Identifier (UID)
        • Scheduled Backup List
        • Alerts & Notifications
        • Workflow/Validation Rules
        • TLS Supported
        • Creating and Configuring Proxy Servers
      • Vault Features
        • Archive
          • Archiving Your Salesforce Data
          • Parent-Child Record Archival
        • Backup
          • Start the Backup
          • Schedule a Vault Backup
          • Understanding Backup Behavior
        • Compare
          • Comparing Two Backups
        • Compliance
          • GDPR - Secure and Comply
            • Right to Be Forgotten Request
          • PCI DSS
        • Replicate
          • Job Configuration
          • Job History
          • Masking Rules
        • Reporting
          • Archive Reports
          • Stale Jobs
        • Restore
          • Restoring the Metadata/Data to the Salesforce Org
        • SIEM Logs
        • Vault Connect
      • Vault Best Practices
      • Vault-FAQs
      • Knowledge Articles
        • Backup Support for Knowledge Articles
        • Restoring Knowledge Articles with Vault
        • nCino
          • Registering nCino configured Salesforce Org
          • Backup Configuration for your Salesforce Org
          • Archival Configuration for your Salesforce Org
          • Restoring nCino Features
    • Guard
      • Risk Assessment
      • Permissions Explorer
      • Change Monitoring
      • Policies
      • Integration User License
  • Resources
    • 🖥️AutoRABIT Support
    • 💬Community Forum
    • 📙Glossary
Powered by GitBook
On this page
  • Copado Extensions Setup
  • CodeScan Object Modifications
  • Function Modifications
  • Quality Gate Rule
  • User Story Page
  • Using the "Run CodeScan" button on the User Story page

Was this helpful?

Edit on GitHub
Export as PDF
  1. Product Guides
  2. CodeScan
  3. CodeScan Integration
  4. Copado

Copado SFDX Integration

PreviousCopadoNextCopado MDAPI Integration

Last updated 16 days ago

Was this helpful?

Our Integration with Copado SFDX pipelines is currently a modification of their extension from their DevOps exchange. These modifications to the function script and Static Code Analysis Violation object add the following functionality:

  • User stories are scanned after Commit. This adds a quality gate result to the User Story and creates a branch on the CodeScan project.

  • The Production branch scans are updated on Promotion. When a change is made in your main branch, CodeScan will scan it to give you a view of the state of your production and accurate delta scans for your User Stories.

  • All User Story results are added to the Static Analysis Results object for review on the Copado platform.

  • The CodeScan project will be created automatically if it doesn't exist.

  • A single project will exist in CodeScan for each Copado Pipeline.

Note: Copado cannot be integrated with On-Premises/Self-Hosted CodeScan.

Copado Extensions Setup

As mentioned, this is an extension of Copado's SFDX integration with CodeScan.

If you haven't already, please follow the instructions on their SFDX Pipelines documentation or use the PDF attached here.

After installing the CodeScan Integration as Copado intended, you can make some improvements.

CodeScan Object Modifications

First, you will need to add two fields to the copado__Static_Code_Analysis_Violation__c object in setup.

  1. Field Name: CSExtKey API Name: CSExtKey__c Type: text Length: 255 ExternalId: true

  2. Field Name: CSProject API Name: CSProject__c Type: text Length: 255 ExternalId: false

Function Modifications

Then, navigate to the functions tab and find the Run CodeScan QIF function.

Under the script tab, click the lower edit button and replace the script with the following:

Expand to view script
echo $branchesAndFileIdJson
echo $git_json
originBranch=$(jq -r '.originBranch' <<< $branchesAndFileIdJson)
BRANCH="$originBranch"
echo "param branchesAndFileIdJson =  $branchesAndFileIdJson"
echo "param originBranch = $originBranch"
echo "param TOKEN = $TOKEN"
echo "param SERVER = $SERVER"
echo "param PROJECT_ID = $PROJECT_ID"
echo "param ORGANIZATION = $ORGANIZATION"
echo "param BRANCH = $BRANCH"
echo "DEST_BRANCH: $DEST_BRANCH"
echo "param USER_STORY = $USER_STORY"   
echo "param BASE_BRANCH = $BASE_BRANCH"
echo "param COPADO_PROJECT = $COPADO_PROJECT"
OUTPUT_JSON="output.json"
OUTPUT_CSV="violations.csv"
CSV_STRING=""
exitCode=0
NEW_PROJECT="true"

# Check if the project has been scanned before
curl -u $TOKEN: -s "$SERVER/api/ce/component?component=$PROJECT_ID" -o $OUTPUT_JSON || exitCode=$?
# Check if the curl command was successful
if [[ $? -ne 0 ]]
then
  echo "Failed to fetch data from the API"
  exit 1
fi


# Set New Project based on response
NEW_PROJECT=$(node <<EOF
  const fs = require('fs');
  try {
    // Read the JSON file and parse it
    const data = JSON.parse(fs.readFileSync('$OUTPUT_JSON', 'utf8'));
    // Check if there is an "errors" field indicating an error
    if (data.errors) {
      console.error("Project does not exist or there is an error in the response:" + JSON.stringify(data));
      console.log("true");
    } else if ('current' in data) {
      console.log("false");  // Project has been scanned before
    } else {
      console.log("true");   // New project, not scanned before
    }
  } catch (error) {
    console.error("ERROR: ", error);
    process.exit(1);
  }
EOF
)

# Need to determine changed files in User Story

# Check for branch type and scan
if [[ "$BRANCH" =~ .+/US-[0-9]+ ]]
then
  API_URL="$SERVER/api/issues/search?componentKeys=$PROJECT_ID&pullRequest=$BRANCH&statuses=OPEN"
  if [[ "$NEW_PROJECT" = true ]]
  then
    copado-git-get $BASE_BRANCH
    copado -p "Running codescan on Main Branch for first run..."
    sfdx codescan:run --token=$TOKEN --server=$SERVER --projectkey=$PROJECT_ID --organization=$ORGANIZATION --json 2>&1 | tee /tmp/result.json \
        || exitCode=$?
    echo "Codescan completed. exit code: $exitCode"
  fi
  copado -p "Cloning repo..."
  copado-git-get $BRANCH
  ls -a
  copado -p "Running codescan on User Story..."
  sfdx codescan:run --token=$TOKEN --server=$SERVER --projectkey=$PROJECT_ID --organization=$ORGANIZATION -Dsonar.pullrequest.base=master -Dsonar.pullrequest.branch="$COPADO_PROJECT" -Dsonar.pullrequest.key=$BRANCH --json 2>&1 | tee /tmp/result.json \
      || exitCode=$?
  echo "Codescan completed. exit code: $exitCode"
  copado -u /tmp/result.json
else
  API_URL="$SERVER/api/issues/search?componentKeys=$PROJECT_ID&statuses=OPEN"
  if [[ "$DEST_BRANCH" == "$BASE_BRANCH" ]]
  then
    copado-git-get $BASE_BRANCH
    copado -p "Running codescan on Main Branch..."
    sfdx codescan:run --token=$TOKEN --server=$SERVER --projectkey=$PROJECT_ID --organization=$ORGANIZATION  --json 2>&1 | tee /tmp/result.json \
        || exitCode=$?
    echo "Codescan completed. exit code: $exitCode"
    copado -u /tmp/result.json
  else
    echo "No scan needed."
    exit 0
  fi
fi

if [ -f /tmp/result.json ]
then
  # Fetch the issues from the API
  copado -p "Fetching issues..."

  # Fetch JSON data from the API
  echo $(curl -u $TOKEN: -s $API_URL -o $OUTPUT_JSON)

  # Check if the curl command was successful
  if [[ $? -ne 0 ]]
  then
    echo "Failed to fetch data from the API"
    exit 1
  fi

  # Create a CSV
  copado -p "Creating CSV..."
fi

rows=$(node <<EOF
const fs = require('fs');

// Read the JSON file
const data = JSON.parse(fs.readFileSync('$OUTPUT_JSON', 'utf8'));
if (data.current) {
  console.error("No scan has been performed.");
} else {

  // Extract the issues array
  const issues = data.issues;

  // Create CSV headers
  const headers = ['CSExtKey__c', 'copado__Rule__c', 'copado__Type__c', 'copado__Severity__c', 'copado__File__c', 'CSProject__c', 'copado__Line__c' ];

  // Create CSV rows
  const rows = issues.map(issue => {
      const { key, rule, type, severity, component, project, line} = issue;
      
      return [
          key, 
          rule,
          type,
          severity, 
          component, 
          project, 
          line,
      ].join(',');
  });
  // Combine headers and rows
  const csv = [headers.join(','), ...rows].join('\n');
  // Write the CSV file
  fs.writeFileSync('$OUTPUT_CSV', csv);
  // Output rows as JSON
  console.log(JSON.stringify(rows));
}
EOF
)

# Check if the Node.js script was successful
if [[ $? -ne 0 ]]
then
  echo "Failed to convert JSON to CSV"
  exit 1
fi

if [[ "$rows" != '' ]]
then
  # Convert JSON rows to CSV string
  CSV_STRING=$(jq -r 'join("#")' <<< "$rows")

  # Escape special characters in CSV_STRING for Apex
  CSV_STRING=$(echo "$CSV_STRING" | sed 's/\\/\\\\/g; s/"/\\"/g')
  echo "CSV_STRING: $CSV_STRING"

  # Check if the CSV file exists and upload it 
  if [ -f "$OUTPUT_CSV" ]; then
    copado -u $OUTPUT_CSV --name $OUTPUT_CSV 
    echo "Script completed successfully. CSV file is located at $OUTPUT_CSV"
  else
    copado -u $OUTPUT_JSON
    echo "CSV creation was unsuccessful. JSON file is located at $OUTPUT_JSON"
  fi

  # Import issues as Salesforce records
  copado -p "Importing issues..."
fi
# Create and run Apex script
echo "
if('$USER_STORY' != ''){
  string recID='$USER_STORY';
  List<copado__User_Story__c> userStories = [SELECT Id FROM copado__User_Story__c WHERE Id = :recID LIMIT 1];
  Id usid = userStories.isEmpty() ? null : userStories[0].Id;

  if (usid != null) {
    // Proceed with creating Static Code Analysis Result
    Id recTypeId = Schema.SObjectType.copado__Static_Code_Analysis_Result__c.getRecordTypeInfosByName().get('CodeScan').getRecordTypeId();
    copado__Static_Code_Analysis_Result__c scar = new copado__Static_Code_Analysis_Result__c(recordtypeId=recTypeId,copado__User_Story__c=usid);
    insert scar;
    id scarid = scar.id;   

    List<copado__Static_Code_Analysis_Violation__c> SCAV = new List<copado__Static_Code_Analysis_Violation__c>();
    
    String csvAsString = '$CSV_STRING';
    System.debug('CSV as string:'+csvAsString);

    if(csvAsString != ''){
        String[] csvFileLines = csvAsString.split('#');
        System.debug(csvFileLines.size());

        for(Integer i=0; i<csvFileLines.size(); i++){
            String[] csvRecordData = csvFileLines[i].split(',');
            String issueLink='$SERVER/project/issues?pullRequest=$BRANCH&issues='+csvRecordData[0]+'&open='+csvRecordData[0]+'&id=$PROJECT_ID';
            
            copado__Static_Code_Analysis_Violation__c viol= new copado__Static_Code_Analysis_Violation__c(
                CSExtKey__c = csvRecordData[0],             
                copado__Rule__c = csvRecordData[1],
                copado__Type__c = csvRecordData[2],
                copado__Severity__c = csvRecordData[3],   
                copado__File__c = csvRecordData[4],                                                                            
                CSProject__c = csvRecordData[5],
                copado__Line__c = Integer.valueOf(csvRecordData[6].removeEnd('\n')), 
                copado__Static_Code_Analysis_Result__c = scarid,
                copado__Info_URL__c = issueLink
            );
            SCAV.add(viol);   
        }
    insert SCAV;
    } else {
        System.debug('No Issues in CSV');
    }
  } else {
    System.debug('Could not find User Story with name: ' + recID);
  }

} else {
  System.debug('Not a User Story, check issues in CodeScan'); 
}
" > /tmp/run.apex

# Fix URLs
export CF_SF_ENDPOINT="https://$(echo $CF_SF_ENDPOINT | sed -e 's/[^/]*\/\/\([^@]*@\)\?\([^:/]*\).*/\2/')"

copado -p "Inserting parent..."
SFDX_ACCESS_TOKEN="$CF_SF_SESSIONID" sf org login access-token --alias copadoOrg --instance-url "$CF_SF_ENDPOINT" --no-prompt
sf apex run --file /tmp/run.apex --target-org copadoOrg --json
if [[ $? -ne 0 ]]
then
  echo "The Apex Script failed to add violations."
  exit 1
fi

exit $exitCode

Click save.

The configuration tab should show the callback type is ApexClass and the ApexClass is EvaluateCodeScanResult.

Navigate to the Parameters tab and click Edit.

Click Add New Parameter and add the following parameters:

Name: USER_STORY Value: {$Context.copado__JobExecution__r.copado__UserStoryCommit__r.copado__User_Story__c}

Name: BASE_BRANCH Value: {$Context.copado__JobExecution__r.copado__Pipeline__r.copado__Main_Branch__c}

Name: COPADO_PROJECT Value: {$Context.copado__JobExecution__r.copado__UserStoryCommit__r.copado__User_Story__r.copado__Project__r.Name}

Name: DEST_BRANCH Value: {$Destination.Branch}

Click Save.

Quality Gate Rule

In order to get the Quality Gate to run the appropriate events, the Quality Gate Rule needs one more trigger event.

Navigate to the Quality Gate Rules tab and open the CodeScan Quality Gate Rule.

Deactivate the rule and add Promote to the Copado Actions list under the Trigger heading.

Activate the rule again.

User Story Page

We recommend adding the Static Code Analysis results related list to the User Story page to make them easier to access.

Violations will be stored as Static Code Analysis Violations.

Using the "Run CodeScan" button on the User Story page

The Run CodeScan button allows you to run the scan directly from a User Story without committing and will reflect the results in a Static Code Analysis Results object attached to the User Story.

It will not update the Test record Pass/Fail for the User Story as it is not executing in Copado's Quality Integration Framework like the function above.

To add and use the Run CodeScan Action on the User Story page, some additions must be made to the Run CodeScan function. First, under the script tab, click the lower edit button and replace the script with the following:

Expand to view script
BRANCH="feature/$USER_STORY"
echo "param TOKEN = $TOKEN"
echo "param SERVER = $SERVER"
echo "param PROJECT_ID = $PROJECT_ID"
echo "param ORGANIZATION = $ORGANIZATION"
echo "param BRANCH = $BRANCH"
echo "param USER_STORY = $USER_STORY"   
echo "param BASE_BRANCH = $BASE_BRANCH"
echo "param COPADO_PROJECT = $COPADO_PROJECT"
OUTPUT_JSON="output.json"
OUTPUT_CSV="violations.csv"
CSV_STRING=""
exitCode=0
NEW_PROJECT="true"

# Check if the project has been scanned before
curl -u $TOKEN: -s "$SERVER/api/ce/component?component=$PROJECT_ID" -o $OUTPUT_JSON || exitCode=$?
# Check if the curl command was successful
if [[ $? -ne 0 ]]
then
  echo "Failed to fetch data from the API"
  exit 1
fi


# Set New Project based on response
NEW_PROJECT=$(node <<EOF
  const fs = require('fs');
  try {
    // Read the JSON file and parse it
    const data = JSON.parse(fs.readFileSync('$OUTPUT_JSON', 'utf8'));
    // Check if there is an "errors" field indicating an error
    if (data.errors) {
      console.error("Project does not exist or there is an error in the response:" + JSON.stringify(data));
      console.log("true");
    } else if ('current' in data) {
      console.log("false");  // Project has been scanned before
    } else {
      console.log("true");   // New project, not scanned before
    }
  } catch (error) {
    console.error("ERROR: ", error);
    process.exit(1);
  }
EOF
)

# Need to determine changed files in User Story

# Check for branch type and scan
if [[ "$BRANCH" =~ .+/US-[0-9]+ ]]
then
  API_URL="$SERVER/api/issues/search?componentKeys=$PROJECT_ID&pullRequest=$BRANCH&statuses=OPEN"
  if [[ "$NEW_PROJECT" = true ]]
  then
    copado-git-get $BASE_BRANCH
    copado -p "Running codescan on Main Branch for first run..."
    sfdx codescan:run --token=$TOKEN --server=$SERVER --projectkey=$PROJECT_ID --organization=$ORGANIZATION --json 2>&1 | tee /tmp/result.json \
        || exitCode=$?
    echo "Codescan completed. exit code: $exitCode"
  fi
  copado -p "Cloning repo..."
  copado-git-get $BRANCH
  ls -a
  copado -p "Running codescan on User Story..."
  sfdx codescan:run --token=$TOKEN --server=$SERVER --projectkey=$PROJECT_ID --organization=$ORGANIZATION -Dsonar.pullrequest.base=$BASE_BRANCH -Dsonar.pullrequest.branch="$COPADO_PROJECT" -Dsonar.pullrequest.key="$BRANCH" --json 2>&1 | tee /tmp/result.json \
      || exitCode=$?
  echo "Codescan completed. exit code: $exitCode"
  copado -u /tmp/result.json
else
  echo "No scan needed."
fi

if [ -f /tmp/result.json ]
then
  # Fetch the issues from the API
  copado -p "Fetching issues..."

  # Fetch JSON data from the API
  echo $(curl -u $TOKEN: -s $API_URL -o $OUTPUT_JSON)

  # Check if the curl command was successful
  if [[ $? -ne 0 ]]
  then
    echo "Failed to fetch data from the API"
    exit 1
  fi

  # Create a CSV
  copado -p "Creating CSV..."
fi

rows=$(node <<EOF
const fs = require('fs');

// Read the JSON file
const data = JSON.parse(fs.readFileSync('$OUTPUT_JSON', 'utf8'));
if (data.current) {
  console.error("No scan has been performed.");
} else {

  // Extract the issues array
  const issues = data.issues;

  // Create CSV headers
  const headers = ['CSExtKey__c', 'copado__Rule__c', 'copado__Type__c', 'copado__Severity__c', 'copado__File__c', 'CSProject__c', 'copado__Line__c' ];

  // Create CSV rows
  const rows = issues.map(issue => {
      const { key, rule, type, severity, component, project, line} = issue;
      
      return [
          key, 
          rule,
          type,
          severity, 
          component, 
          project, 
          line,
      ].join(',');
  });
  // Combine headers and rows
  const csv = [headers.join(','), ...rows].join('\n');
  // Write the CSV file
  fs.writeFileSync('$OUTPUT_CSV', csv);
  // Output rows as JSON
  console.log(JSON.stringify(rows));
}
EOF
)

# Check if the Node.js script was successful
if [[ $? -ne 0 ]]
then
  echo "Failed to convert JSON to CSV"
  exit 1
fi

if [[ "$rows" != '' ]]
then
  # Convert JSON rows to CSV string
  CSV_STRING=$(jq -r 'join("#")' <<< "$rows")

  # Escape special characters in CSV_STRING for Apex
  CSV_STRING=$(echo "$CSV_STRING" | sed 's/\\/\\\\/g; s/"/\\"/g')
  echo "CSV_STRING: $CSV_STRING"

  # Check if the CSV file exists and upload it 
  if [ -f "$OUTPUT_CSV" ]; then
    copado -u $OUTPUT_CSV --name $OUTPUT_CSV 
    echo "Script completed successfully. CSV file is located at $OUTPUT_CSV"
  else
    copado -u $OUTPUT_JSON
    echo "CSV creation was unsuccessful. JSON file is located at $OUTPUT_JSON"
  fi

  # Import issues as Salesforce records
  copado -p "Importing issues..."
fi
# Create and run Apex script
echo "
if('$USER_STORY' != ''){
  string recID='$USER_STORY';
  List<copado__User_Story__c> userStories = [SELECT Id FROM copado__User_Story__c WHERE Name = :recID LIMIT 1];
  Id usid = userStories.isEmpty() ? null : userStories[0].Id;

  if (usid != null) {
    // Proceed with creating Static Code Analysis Result
    Id recTypeId = Schema.SObjectType.copado__Static_Code_Analysis_Result__c.getRecordTypeInfosByName().get('CodeScan').getRecordTypeId();
    copado__Static_Code_Analysis_Result__c scar = new copado__Static_Code_Analysis_Result__c(recordtypeId=recTypeId,copado__User_Story__c=usid);
    insert scar;
    id scarid = scar.id;   

    List<copado__Static_Code_Analysis_Violation__c> SCAV = new List<copado__Static_Code_Analysis_Violation__c>();
    
    String csvAsString = '$CSV_STRING';
    System.debug('CSV as string:'+csvAsString);

    if(csvAsString != ''){
        String[] csvFileLines = csvAsString.split('#');
        System.debug(csvFileLines.size());

        for(Integer i=0; i<csvFileLines.size(); i++){
            String[] csvRecordData = csvFileLines[i].split(',');
            String issueLink='$SERVER/project/issues?pullRequest=$BRANCH&issues='+csvRecordData[0]+'&open='+csvRecordData[0]+'&id=$PROJECT_ID';
            
            copado__Static_Code_Analysis_Violation__c viol= new copado__Static_Code_Analysis_Violation__c(
                CSExtKey__c = csvRecordData[0],             
                copado__Rule__c = csvRecordData[1],
                copado__Type__c = csvRecordData[2],
                copado__Severity__c = csvRecordData[3],   
                copado__File__c = csvRecordData[4],                                                                            
                CSProject__c = csvRecordData[5],
                copado__Line__c = Integer.valueOf(csvRecordData[6].removeEnd('\n')), 
                copado__Static_Code_Analysis_Result__c = scarid,
                copado__Info_URL__c = issueLink
            );
            SCAV.add(viol);   
        }
    insert SCAV;
    } else {
        System.debug('No Issues in CSV');
    }
  } else {
    System.debug('Could not find User Story with name: ' + recID);
  }

} else {
  System.debug('Not a User Story, check issues in CodeScan'); 
}
" > /tmp/run.apex

# Fix URLs
export CF_SF_ENDPOINT="https://$(echo $CF_SF_ENDPOINT | sed -e 's/[^/]*\/\/\([^@]*@\)\?\([^:/]*\).*/\2/')"

copado -p "Inserting parent..."
SFDX_ACCESS_TOKEN="$CF_SF_SESSIONID" sf org login access-token --alias copadoOrg --instance-url "$CF_SF_ENDPOINT" --no-prompt
sf apex run --file /tmp/run.apex --target-org copadoOrg --json
if [[ $? -ne 0 ]]
then
  echo "The Apex Script failed to add violations."
  exit 1
fi
exit $exitCode

Navigate to the Parameters tab and click Edit.

Click Add New Parameter and add the following parameters:

Name: USER_STORY Value: {$Context}

Name: BASE_BRANCH Value: {$Pipeline.copado__Main_Branch__c}

Name: COPADO_PROJECT Value: {$Job.ExecutionParent.copado__Project__r.Name}

1MB
Copado Labs - CodeScan Integration.pdf
pdf