Cloud Native 9 min read

How to Build a Custom Sonar Redline Step with Flow-CLI V2

This guide walks you through installing Flow-CLI V2, creating a TypeScript‑based custom step that integrates Sonar scanning with redline checks, publishing the step, and using it in a cloud‑native pipeline to enforce code quality gates.

Alibaba Cloud Native
Alibaba Cloud Native
Alibaba Cloud Native
How to Build a Custom Sonar Redline Step with Flow-CLI V2

Overview

Flow-CLI V2 is a TypeScript‑based command‑line tool for Alibaba Cloud Efficient pipelines, enabling developers to create custom pipeline steps or components.

Prerequisites

A publicly reachable Sonar instance (e.g., https://sonarcloud.io/).

Node.js installed locally.

Flow‑CLI installed (see below).

Install Flow‑CLI

npm i -g @flow-step/flow-cli --registry=https://registry.npmmirror.com

Verify the installation with flow-cli -h.

Authenticate

flow-cli login

The command opens a browser for authentication; after login, select the target enterprise from the prompted list.

Clone the example step

git clone https://atomgit.com/flow-step-custom/RedlineSonar.git

Repository layout:

README.md          # step description
package.json       # TypeScript project definition
tsconfig.json
src/
  index.ts         # runtime logic
  params.ts        # parameter definitions
step.yaml          # front‑end step definition

Step definition (step.yaml)

Key fields in step.yaml:

id : globally unique identifier for the step.

name : human‑readable step name.

items : list of input parameters (Sonar host, token, project key, redline list).

redline : definition of redline checks; each entry specifies a metric key and a comparison type (LE ≤, GE ≥, EQ =).

Example snippet:

apiVersion: v2
kind: DefaultJob
id: RedlineSonar
name: RedlineSonar
items:
  - label: Sonar服务器地址
    name: STEP_SONAR_HOST
    type: input
  - label: Sonar Token
    name: STEP_SONAR_TOKEN
    type: password
  - label: Sonar Project Key
    name: STEP_SONAR_PROJECT_KEY
    type: input
  - label: 红线信息
    name: CHECK_REDLINES
    type: addable_group
    template:
      items:
        - name: redline
          type: custom_redline_dropdown
          datamap: '[{"key":"Bugs","type":"LE"},{"key":"Vulnerabilities","type":"LE"},{"key":"Smells","type":"LE"},{"key":"Coverage","type":"GE"}]'

Backend implementation (src/index.ts)

The step performs the following actions:

Read and validate input parameters.

Call Sonar /api/measures/search with the project key and a list of metric keys (bugs, vulnerabilities, code_smells, coverage, etc.).

Extract numeric values from the response.

Convert each metric into a RedlineResult using generateRedlineResult (error level for bugs, vulnerabilities, smells; warning level for coverage).

Assemble a RedlineInfo object containing a title, a link to the Sonar component measures page, and the array of redline results.

Invoke the SDK function

step.redline.redlineCheck(redlineInfo, process.env['CHECK_REDLINES'])

. If any check fails, the step aborts with a non‑zero exit code.

async function runStep(): Promise<void> {
  const params = getParams();
  logAndValidParams(params);
  const metrics = await requestSonarMetrics(
    `${params.sonarHost}/api/measures/search`,
    params.sonarToken,
    {
      projectKeys: params.sonarProjectKey,
      metricKeys: 'alert_status,bugs,reliability_rating,vulnerabilities,security_rating,code_smells,sqale_rating,duplicated_lines_density,coverage,ncloc,ncloc_language_distribution'
    }
  );

  const bugs = Number(metrics['bugs']);
  const vulnerabilities = Number(metrics['vulnerabilities']);
  const smells = Number(metrics['code_smells']);
  const coverage = Number(metrics['coverage']);

  const redlineResults = [];
  redlineResults.push(generateRedlineResult('Bugs', '缺陷', bugs, redline.Error));
  redlineResults.push(generateRedlineResult('Vulnerabilities', '漏洞', vulnerabilities, redline.Error));
  redlineResults.push(generateRedlineResult('Smells', '坏味道', smells, redline.Error));
  redlineResults.push(generateRedlineResult('Coverage', '覆盖率', coverage, redline.Warning));

  const redlineInfo = {
    title: 'Redline Sonar',
    reportUrl: `${params.sonarHost}/component_measures?id=${params.sonarProjectKey}`,
    readlineResults: redlineResults
  };

  const ok = step.redline.redlineCheck(redlineInfo, process.env['CHECK_REDLINES']);
  if (!ok) {
    step.error('Redline check failed');
    process.exit(-1);
  }
}

Publish the step

After customizing the code, publish the step to the enterprise repository:

flow-cli step publish

Use the step in a pipeline

In the pipeline editor, add an “Enterprise Step”, select the container environment, and choose the published RedlineSonar step. The step will invoke Sonar, evaluate the configured redline thresholds, and fail the pipeline if any threshold is violated.

References

Git repository: https://atomgit.com/flow-step-custom/RedlineSonar

step.yaml file: https://atomgit.com/flow-step-custom/RedlineSonar/blob/master/step.yaml

Backend source (src/index.ts): https://atomgit.com/flow-step-custom/RedlineSonar/blob/master/src/index.ts

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TypeScriptCI/CDFlow-CLICustom StepRedlineSonar
Alibaba Cloud Native
Written by

Alibaba Cloud Native

We publish cloud-native tech news, curate in-depth content, host regular events and live streams, and share Alibaba product and user case studies. Join us to explore and share the cloud-native insights you need.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.