Built-in Plugin
About 7411 wordsAbout 25 min
In each stage operation, in addition to using custom tasks, CNB also extends some commonly used built-in tasks for developers to use.
Overview
- docker:
- cache: Build Docker image cache to speed up dependency installation
- cnb:
- await-resolve: Wait/notify mechanism for collaboration across multiple pipelines
- apply: Trigger sub-pipelines within the same repository
- trigger: Trigger sub-pipelines in a specified repository
- read-file: Export file content as environment variables
- vscode:
- go: Control the availability of remote development environments
- git:
- reviewer: Automatically add reviewers to pull requests
- auto-merge: Automatically merge pull requests
- issue-update: Update issue status
- release: Release repository
- testing:
- coverage: Report unit test coverage
- artifact:
- remove-tag: Remove CNB artifact tags
Docker
cache
docker:cache
Docker Cache, builds a Docker image as a cache to be reused in future builds.
It helps avoid redundant downloads of network resources such as dependencies
.
Applicable Events
Parameters
dockerfile
- type:
String
- required:
true
The path to the Dockerfile used to build the cache image.
To avoid excessively long build times, the Docker image build timeout is controlled by the job.timeout parameter.
by
- type:
Array<String>
|String
- required:
false
Specifies the list of files that the cache image build process depends on.
Note: Files not listed in by
, except for the Dockerfile, are treated as non-existent during the image build process.
- Supports array format
- Supports string format, with multiple files separated by commas.
versionBy
- type:
Array<String>
|String
- required:
false
Used for version control. If versionBy
is not provided, it defaults to the value of by
.
When the content of the file pointed to by versionBy
changes, a new version is considered. The calculation logic is based on the expression:
sha1(Dockerfile + versionBy + buildArgs + target + arch)
- Supports array format
- Supports string format, with multiple files separated by commas.
buildArgs
- type:
Object
- required:
false
Inserts additional build arguments during build (--build-arg $key=$value
). If the value is null, only the key is added (--build-arg $key
).
target
- type:
String
- required:
false
Corresponds to the --target parameter in docker build, allowing selective building of specific stages in the Dockerfile instead of the entire Dockerfile.
sync
- type:
Boolean
- required:
false
- default:
false
Specifies whether to operate in synchronous mode. If true
, it waits for the cache image to be successfully pushed before proceeding with subsequent tasks.
ignoreBuildArgsInVersion
- type:
Boolean
- required:
false
- default:
false
Specifies whether to ignore buildArgs
in version calculation.
See Version Control
Output Results
{
// The docker image name corresponding to the cache
name;
}
Configuration Examples
main:
push:
- docker:
image: node:14
stages:
- name: build cache image
type: docker:cache
options:
dockerfile: cache.dockerfile
# by supports two formats: array, string
by:
- package.json
- package-lock.json
versionBy:
- package-lock.json
exports:
name: DOCKER_CACHE_IMAGE_NAME
- name: use cache
image: $DOCKER_CACHE_IMAGE_NAME
commands:
- cp -r "$NODE_PATH" ./node_modules
- name: build with cache
script:
- npm run build
Where cache.dockerfile
is a Dockerfile used to build the cache image, for example:
# Choose a Base image
FROM node:14
# Set working directory
WORKDIR /space
# Copy the file list from 'by'
COPY . .
# Install dependencies based on the copied files
RUN npm ci
# Set the required environment variables
ENV NODE_PATH=/space/node_modules
cnb
await
See await-resolve
resolve
See await-resolve
await-resolve
cnb:await
cnb:resolve
await
waits for the execution of resolve
, which can pass variables to await
.
Through await-resolve
, multiple concurrent pipelines can cooperate with each other, enabling more flexible sequence control.
Tips
Difference between await-resolve
and apply
, trigger
:
The former refers to a pipeline in a build that waits at an await task until it receives a resolve notification from another pipeline corresponding to the key
before continuing.
The latter triggers a new pipeline from an existing one. It can be asynchronous, synchronous, and can even span repositories.
- Usage Limitations
- Deadlock Detection
- Applicable Events
- Await Parameters
- Resolve Parameters
- Output Results
Usage Limitations
- Can only await and resolve pipelines triggered by the
same event
. - A
key
can only be resolved once but can be awaited multiple times. - Group await and resolve operations using a
key
.
Deadlock Detection
While await and resolve can provide flexible flow control, they can introduce complex edge cases such as:
- Deadlocks
- Pipeline-1 and Pipeline-2 await each other
- Multiple pipelines form an await loop
- Infinite waiting
- Awaiting a non-existent key or a key without a corresponding resolve
- Failure in the pipeline where resolve is executed
- Duplicate resolves
- Multiple resolve tasks associated with the same key
The deadlock detection
mechanism automatically detects these anomalies, terminates the await's waiting state, and throws a dead lock found.
exception.
The order of await and resolve in the configuration file does not affect the execution result. The final await task will always wait for the corresponding resolve to complete, and this scenario will not be terminated by the deadlock detection
mechanism.
Applicable Events
Await Parameters
key
- type: String
- required: true
Pairing ID
Resolve Parameters
key
- type: String
- required: true
Pairing ID
data
- type: object
- required: false
Object to be passed
In key: value
format, supports multiple levels. Example:
- name: resolve a json
type: cnb:resolve
options:
key: demo
data:
a: 1
b:
c: 2
The result of the await task is the data
object declared by resolve. This object can be accessed through exports
. Example:
- name: await a json
type: cnb:await
options:
key: demo
exports:
a: VAR_A
b.c: VAR_B
- name: show var
script:
- echo ${VAR_A} # 1
- echo ${VAR_B} # 2
Alternatively, you can simply indicate a waiting action without passing any content:
- name: ready
type: cnb:resolve
options:
key: i-am-ready
- name: ready
type: cnb:await
options:
key: i-am-ready
Output Results
{
// Content returned by resolve
data
}
apply
cnb:apply
Triggers a custom event pipeline in the current repository.
Applicable Events
push
commit.add
branch.create
pull_request.target
pull_request.mergeable
tag_push
pull_request.merged
api_trigger
web_trigger
crontab
tag_deploy
Parameters
config
- type:
String
- required:
false
Complete CI configuration file content.
configFrom
- type:
String
- required:
false
Specifies a local file as the configuration file.
event
- type:
String
- required:
false
- default:
api_trigger
Name of the custom event to execute, must be api_trigger
or start with api_trigger_
.
sync
- type:
Boolean
- required:
false
- default:
false
Whether to execute synchronously.
In synchronous mode, it waits for the current apply pipeline to succeed before executing the next task.
continueOnBuildError
- type:
Boolean
- required:
false
- default:
false
In synchronous mode, whether to continue executing the next task when the triggered pipeline build fails.
title
- type:
String
- required:
false
Custom pipeline title.
Environment Variables Related
Pass business-defined environment variables visible to the current job in the new pipeline.
Default values include the following environment variables that cannot be overridden by users:
APPLY_TRIGGER_BUILD_ID
(similar toCNB_BUILD_ID
in default CI environment variables)APPLY_TRIGGER_PIPELINE_ID
(similar toCNB_PIPELINE_ID
in default CI environment variables)APPLY_TRIGGER_REPO_SLUG
(similar toCNB_REPO_SLUG
in default CI environment variables)APPLY_TRIGGER_REPO_ID
(similar toCNB_REPO_ID
in default CI environment variables)APPLY_TRIGGER_USER
(similar toCNB_BUILD_USER
in default CI environment variables)APPLY_TRIGGER_BRANCH
(similar toCNB_BRANCH
in default CI environment variables)APPLY_TRIGGER_COMMIT
(similar toCNB_COMMIT
in default CI environment variables)APPLY_TRIGGER_COMMIT_SHORT
(similar toCNB_COMMIT_SHORT
in default CI environment variables)APPLY_TRIGGER_ORIGIN_EVENT
(similar toCNB_EVENT
in default CI environment variables)CNB_PULL_REQUEST_ID
(similar toCNB_PULL_REQUEST_ID
in default CI environment variables)CNB_PULL_REQUEST_IID
(similar toCNB_PULL_REQUEST_IID
in default CI environment variables)CNB_PULL_REQUEST_MERGE_SHA
(similar toCNB_PULL_REQUEST_MERGE_SHA
in default CI environment variables)
Config Value Priority
Values are retrieved in the following order until a value is found:
config
configFrom
.cnb.yml
in the current repository- If apply is called in the
pull_request.merged
event, the merged configuration file is used - If apply is called in the
pull_request.target
orpull_request.mergeable
events, the configuration file of the target branch is used - Otherwise, the configuration file of the current branch is used
The configFrom
parameter only supports local files like ./test/.cnb.yml
. If you need to use a remote file, you should download it locally first.
Output Results
{
"sn": "cnb-i5o-1ht8e12hi", // Build number
"buildLogUrl": "http://xxx/my-group/my-repo/-/build/logs/cnb-i5o-1ht8e12hi", // Build log link
"message": "success",
"buildSuccess": true, // Whether the triggered build was successful, this key only exists in synchronous mode
"lastJobExports": {} // Environment variables exported by the last job in the triggered pipeline
}
Configuration Examples
main:
push:
- stages:
- name: trigger
type: cnb:apply
options:
configFrom: ./test/.cnb.yml
event: api_trigger_test
main:
push:
- stages:
- name: trigger
type: cnb:apply
options:
config: |
main:
api_trigger_test:
- stages:
- name: test
script: echo test
event: api_trigger_test
main:
push:
- stages:
- name: trigger
type: cnb:apply
options:
# Execute other events in the current configuration file
event: api_trigger_test
api_trigger_test:
- stages:
- name: test
script: echo test
main:
push:
- stages:
- name: trigger
type: cnb:apply
options:
configFrom: .xxx.yml
event: api_trigger_test
sync: true
Trigger
cnb:trigger
Triggers a custom event pipeline in a specified repository within the current repository (requires permission to trigger the corresponding repository pipeline).
Applicable Events
Parameters
token
- type:
String
- default: Environment variable CNB_TOKEN
Personal access token.
The new pipeline triggerer is the user corresponding to the token, and it will check for permissions to trigger the target repository pipeline.
slug
- type:
String
- required:
true
Full path of the target repository, e.g., group/repo.
event
- type:
String
- required:
true
Name of the custom event to trigger, must be api_trigger
or start with api_trigger_
.
The target repository must have a pipeline configured for the corresponding branch and event to be triggered.
You can also specify pipeline configuration using the config
parameter.
branch
- type:
String
- required:
false
Branch to trigger, defaults to the main branch of the target repository.
sha
- type:
String
- required:
false
CommitId in the triggering branch, defaults to the latest commit record of the branch.
env
- type: TriggerEnv
- required:
false
Environment variables to pass when triggering the target repository pipeline.
Default values include the following environment variables that cannot be overridden by users:
API_TRIGGER_BUILD_ID
(similar toCNB_BUILD_ID
in default CI environment variables)API_TRIGGER_PIPELINE_ID
(similar toCNB_PIPELINE_ID
in default CI environment variables)API_TRIGGER_REPO_SLUG
(similar toCNB_REPO_SLUG
in default CI environment variables)API_TRIGGER_REPO_ID
(similar toCNB_REPO_ID
in default CI environment variables)API_TRIGGER_USER
(similar toCNB_BUILD_USER
in default CI environment variables)API_TRIGGER_BRANCH
(similar toCNB_BRANCH
in default CI environment variables)API_TRIGGER_COMMIT
(similar toCNB_COMMIT
in default CI environment variables)API_TRIGGER_COMMIT_SHORT
(similar toCNB_COMMIT_SHORT
in default CI environment variables)
sync
- type:
Boolean
- required:
false
- default:
false
Whether to execute synchronously. In synchronous mode, it waits for the current trigger pipeline to succeed before executing the next task.
continueOnBuildError
- type:
Boolean
- required:
false
- default:
false
In synchronous mode, whether to continue executing the next task if the triggered pipeline build fails.
title
- type:
String
- required:
false
Custom pipeline title.
Type Definitions
TriggerEnv
{
[key: String]: String | Number | Boolean
}
Output Results
{
"sn": "cnb-i5o-1ht8e12hi", // Build number
"buildLogUrl": "http://xxx/my-group/my-repo/-/build/logs/cnb-i5o-1ht8e12hi", // Build log link
"message": "success",
"buildSuccess": true, // Whether the triggered build was successful, this key only exists in synchronous mode
"lastJobExports": {} // Environment variables exported by the last job in the triggered pipeline
}
Configuration Examples
Basic Usage
Trigger a pipeline in the main branch of a specified repository in the current repository.
The pipeline configuration file uses the .cnb.yml
file from the main branch of the repository.
Use the access token $TOKEN
to check if the user has permission to trigger the target repository pipeline.
main:
push:
- stages:
- name: trigger
type: cnb:trigger
imports: https://cnb.cool/<your-repo-slug>/-/blob/main/xxx/envs.yml
options:
token: $TOKEN
slug: a/b
branch: main
event: api_trigger_test
read-file
cnb:read-file
Reads the content of a specified file, which can be exported as an environment variable for use in subsequent tasks.
Using the ##[set-output key=value]
command to output variables is more convenient but will display the content in the logs, making it unsuitable for sensitive information.
For sensitive information that is predetermined, you can use imports
for importing, and for sensitive information generated during the build process, you can write it to a file and use this built-in task to read it.
imports
only supports files existing in remote repositories, while this built-in task only supports reading files that exist locally.
The file type is determined by the suffix, currently supporting .json
, .yml
, .yaml
, and plain text (key=value
structure).
Applicable Events
Parameters
filePath
- type: String
- required: true
Local file path.
Output Results
{
// Object read from the file
}
Configuration Examples
Write some variables needed for subsequent tasks to a file, then use this built-in task to read the file and export it as environment variables for use in subsequent tasks.
{
"myVar": "myVar",
"deep": {
"myVar": "myVar in deep"
},
"deepWithEnvKey": {
"myVar": "myVar in deepWithEnvKey"
}
}
main:
push:
- env:
myKey: deepWithEnvKey
stages:
- name: write env file
script: echo "write env to myJson.json"
- name: export env
type: cnb:read-file
options:
filePath: myJson.json
exports:
myVar: ENV_MY_VAR
deep.myVar: ENV_DEEP_MY_VAR # Specify a multi-level key
$myKey.myVar: ENV_ENV_KEY_MY_VAR # Get the key specified through an environment variable
- name: echo env
script:
- echo $ENV_MY_VAR
- echo $ENV_DEEP_MY_VAR
- echo $ENV_ENV_KEY_MY_VAR
vscode
go
vscode:go
Difference in configuring this built-in task for remote development:
- Using this task: When starting cloud-native development, you need to wait for this task to complete before the WebIDE and VSCode/Cursor client entry points appear.
- Not using this task: After the pipeline's prepare stage completes (code-server code service starts), the WebIDE and VSCode/Cursor client entry points will appear before the stages tasks are executed.
The difference in the timing of the appearance of the entry points mentioned above refers to the transition from the loading
waiting page to the entry point selection page. In reality, whether or not this task is used, remote development is already available once the code-server
code service has started.
Note: Using this task will increase the waiting time. If you need to delay developers' entry into the environment until certain tasks are completed, you can use this task.
Applicable Events
vscode
branch.create
api_trigger
web_trigger
Output Results
{
// WebIDE URL
"url": ""
}
Configuration Examples
$:
# vscode event: specifically for starting remote development in the page
vscode:
- docker:
# Use a custom image as the development environment; if not provided, the default image cnbcool/default-dev-env:latest will be used
image: cnbcool/default-dev-env:latest
services:
- vscode
- docker
stages:
# Want to wait for this task to complete before entering the development environment
- name: ls
script: ls -al
- name: vscode go
type: vscode:go
# Tasks that can be executed after entering the development environment
- name: ls
script: ls -al
git
auto-merge
git:auto-merge
Automatically merges a Pull Request, typically used after the pull_request
pipeline checks and code review, in the pull_request.mergeable
pipeline to automatically merge the PR without manual intervention.
The triggering conditions and timing of the pull_request.mergeable
event can be found in the events.
Applicable Events
pull_request.mergeable
Parameters
mergeType
- type:
String
- required:
false
- default:
auto
Merge strategy, defaulting to auto
: merges by merge
if multiple people contribute, otherwise uses squash
.
mergeCommitMessage
- type:
String
- required:
false
Commit message for the merge.
When the merge strategy is rebase
, this information is not required.
When the merge strategy is merge
, the default message is chore: merge node(merged by CNB)
, automatically appending PR references, reviewers' names, and contributors' names. For example:
chore: merge node(merged by CNB)
PR-URL: !916
Reviewed-By: tom
Reviewed-By: jerry
Co-authored-by: jack
When the merge strategy is squash
, the default value is the first commit message of the PR. It also appends PR references, reviewers' names, and contributors' names. For example:
main:
pull_request.mergeable:
- stages:
- name: automerge
type: git:auto-merge
options:
mergeType: squash
This configuration will result in the following effect:
Suppose a PR (feat/model-a -> main) has two commit records:
- Commit 1: Submitted on October 1, 2023
feat(model-a): Add a new feature to module A
Due to some reason, add a certain feature
close #10
- Commit 2: Fixed some issues pointed out during code review, submitted on October 2, 2023
fix(model-a): Fix issues pointed out during review
After automatic merging, a commit node like this will appear on the main branch, where the subsequent commit record (Commit 2) will be erased:
feat(model-a): Add a new feature to module A
Due to some reason, add a certain feature
close #10
PR-URL: !3976
Reviewed-By: tom
Reviewed-By: jerry
Co-authored-by: jack
mergeCommitFooter
- type:
String
- required:
false
Footer information to be set for the merge, with multiple footers separated by \n
, effective only for merge
and squash
.
When the merge strategy is rebase
, this information is not required.
When the merge strategy is merge
or squash
, the provided information will be added as footers line by line, followed by PR references, reviewers' names, and contributors' names. For example:
main:
pull_request.mergeable:
- stages:
- name: automerge
type: git:auto-merge
options:
mergeType: squash
mergeCommitMessage: "add feature for some jobs"
mergeCommitFooter: "--story=123\n--story=456"
add feature for some jobs
--story=123
--story=456
PR-URL: !916
Reviewed-By: tom
Reviewed-By: jerry
Co-authored-by: jack
removeSourceBranch
- type:
Boolean
- required:
false
- default:
false
Whether to delete the source branch after merging.
This value is irrelevant when the source branch and target branch are in different repositories.
ignoreAssignee
- type:
Boolean
- required:
false
- default:
false
Whether to ignore the assignee
.
When a PR has a specified assignee
, this task will not automatically merge the PR because the assignee
is meant to assign someone to handle it manually.
Setting this to true
allows for forcibly merging the PR even if there is an assignee
.
Output Results
{
reviewedBy, // String, information of the contributor appended to the commit message
reviewers, // Array<String>, list of reviewers
}
Configuration Examples
Stand-alone Usage
main:
pull_request.mergeable:
- stages:
- name: automerge
type: git:auto-merge
options:
mergeType: merge
When a PR on the main branch triggers the pull_request.mergeable
event, the PR will be automatically merged using the merge
strategy.
Used with Target Branch push
Event
main:
push:
- stages:
- name: build
script: npm run build
- name: publish
script: npm run publish
pull_request.mergeable:
- stages:
- name: automerge
type: git:auto-merge
options:
mergeType: merge
When a PR on the main branch triggers the pull_request.mergeable
event, the PR will be automatically merged using the merge
strategy. After the automatic merge, a push
event will be triggered on the target branch (main) to continue with the declared build
and publish
processes.
Regarding the responsibility for the resulting push event flow:
- If the PR submitter is a member of the target repository, then the submitter is responsible for the subsequent
push
event flow. - If the PR submitter is not a member of the target repository (e.g., submitting a PR from a Forked Repo in an open-source project), then the last
Reviewer
in theCode Review
process will be responsible for the subsequentpush
event flow.
Best Practices
Using squash
Auto-Merge
Utilize squash
merging to create only one commit node on the target branch for each PR and optionally delete the source branch if permissions allow.
main:
review:
- stages:
- name: automerge
type: git:auto-merge
options:
mergeType: squash
removeSourceBranch: true
Automatically Selecting Merge Type with auto
Automatically determine the merge type based on whether multiple people are contributing (use merge
) or if it's a single contributor (use squash
).
main:
review:
- stages:
- name: automerge
type: git:auto-merge
options:
mergeType: auto
Establishing a Dedicated CR Group for Cross-Review Auto-Merge
- Automatically merge after code review approval.
- Include reviewer information in the commit message.
main:
pull_request.mergeable:
- stages:
- name: Auto-Merge after CR Approval
type: git:auto-merge
options:
mergeType: squash
mergeCommitMessage: $CNB_LATEST_COMMIT_MESSAGE
exports:
reviewedBy: REVIEWED_BY
- name: notify
image: tencentcom/wecom-message
settings:
robot: "155af237-6041-4125-9340-000000000000"
msgType: markdown
content: |
> Auto-Merge after CR Approval <@${CNB_BUILD_USER}>
>
> ${CNB_PULL_REQUEST_TITLE}
> [${CNB_EVENT_URL}](${CNB_EVENT_URL})
>
> ${REVIEWED_BY}
pull_request:
- stages:
# ...other tasks omitted
- name: notify
image: tencentcom/wecom-message
options:
robot: "155af237-6041-4125-9340-000000000000"
msgType: markdown
content: |
> ${CURR_REVIEWER_FOR_AT}
>
> ${CNB_PULL_REQUEST_TITLE}
> [${CNB_EVENT_URL}](${CNB_EVENT_URL})
>
> from ${CNB_BUILD_USER}
git-issue-update
git:issue-update
Update Issue Status, close or open an issue, and modify issue labels.
- Applicable Events
- Work Mechanism
- How to Get Issue ID
- Including Issue ID in Commit Logs
- Parameters
- Output Results
- Configuration Examples
Applicable Events
Work Mechanism
Check if the issue exists -> Check if it meets the when
condition (optional) -> Check if it meets the lint
condition (optional) -> Update issue status or labels
How to Get Issue ID
- If the
fromText
parameter is provided, retrieve it fromfromText
.fromText
is mandatory forbranch.delete
(as the branch is deleted, context cannot be retrieved). - If
fromText
parameter is not provided, retrieve it from the context.push
event: Retrieve from the commit logs of all commits in the current push.- Pull Request events: Retrieve from the commit logs of all commits in the PR.
- Other events: Retrieve from the commit log of the latest commit.
Extraction formats include:
#IssueID
: Represents an issue in the current repository. For example, #123 represents issue ID 123 in the current repository.groupName/repoName#IssueID
: Represents an issue across repositories. For example, test/test#123 represents issue ID 123 in the test/test repository.
Ensure there is a space before #123 or test/test#123.
Including Issue ID in Commit Logs
When committing code, you can include the associated IssueID
in the commit log, which can be automatically extracted when using the current built-in task to update the associated issue for updating labels and status.
It is recommended to include the IssueID
in the body of the commit log. Here are two command-line methods:
- Method 1: Use
shift + enter
for a new line, and it's recommended to add a blank line between the title and body.
git commit -m "fix(Cloud-Native Build): Fix an error
cnb/feedback#123"
- Method 2: Using this method will create two new lines between the title and body.
git commit -m "fix(Cloud-Native Build): Fix an error" -m "cnb/feedback#123"
Parameters
fromText
- type:
String
- required:
false
Parse the IssueId
from the given text.
If not declared, automatically parse from the commit records in the context.
You can specify a text containing a reference to
IssueId
to declare the target operation, for example:${LATEST_CHANGE_LOG}
.
state
- type: IssueStateMap
- required:
false
Corresponds to the state
attribute. When set to close
, it can close the Issue
.
label
- type: IssueUpdateLabel
- required:
false
Description of the operation on labels.
when
- type: IssueUpdateStatus
- required:
false
Filter conditions, where multiple conditions are connected by or
. When empty, it indicates operations on all Issues
.
lint
- type: IssueUpdateStatus
- required:
false
Check if the Issue
meets the conditions. If not met, an exception is thrown. Multiple conditions are connected by or
, and when empty, no checks are performed.
defaultColor
- type:
String
- required:
false
Default color for added labels, effective only when the label.add
parameter is provided.
Type Definitions
IssueStateMap
Enum<String>
: open | close
IssueUpdateLabel
- add
- type:
Array<String>
|String
- required:
false
- type:
List of labels to add. If the label does not exist, it will be automatically created.
- remove
- type:
Array<String>
|String
- required:
false
- type:
List of labels to remove.
IssueUpdateStatus
- label
- type:
Array<String>
|String
- required:
false
- type:
Labels, where multiple values are connected by or
.
Output Results
{
issues // List of issues
}
Configuration Examples
- After merging into main, update labels
main:
push:
- stages:
- name: update issue
type: git:issue-update
options:
# Remove the "In Progress" label and add the "Pre-release" label
label:
add: Pre-release
remove: In Progress
# Perform the above label operations only when there are "feature" or "bug" labels
when:
label:
- feature
- bug
- When a tag is pushed, close the issue and update labels
$:
tag_push:
- stages:
- name: release operation
script: echo "Use release tasks instead of the current task"
# Perform issue update operation after release operation
- name: update issue
type: git:issue-update
options:
# Close the issue
state: close
# Remove the "Pre-release" label and add the "Released" label
label:
add: Released
remove: Pre-release
# Perform the above operations only when there are "feature" or "bug" labels
when:
label:
- feature
- bug
- Add labels based on changelog
$:
tag_push:
- stages:
- name: changelog
image: cnbcool/changelog
exports:
latestChangeLog: LATEST_CHANGE_LOG
- name: update issue
type: git:issue-update
options:
fromText: ${LATEST_CHANGE_LOG}
label:
add: Requirement Accepted
when:
label: feature
Reviewer
git:reviewer
Configure reviewers or assignees to add or remove reviewers/assignees to a PR, with the option to specify a range of alternative reviewers/assignees.
Applicable Events
pull_request
pull_request.target
pull_request.update
Under pull_request
and pull_request.update
events, the trigger will check if the initiator has permission to operate on reviewers/assignees. This check is not performed under the pull_request
event. For PRs submitted across repositories, there may be cases where the initiator lacks permission. In such cases, it is recommended to use the pull_request.target
event.
Parameters
type
- type: REVIEW_OPERATION_TYPE
- required:
false
- default:
add-reviewer
Operation type:
add-reviewer
: Add reviewers, selecting a specified number of reviewers from thereviewers
parameteradd-reviewer-from-repo-members
: Select one reviewer directly from repository members and add them as a revieweradd-reviewer-from-group-members
: Select one reviewer from the repository's parent organization (direct superior organization) and add them as a revieweradd-reviewer-from-outside-collaborator-members
: Select one reviewer from the repository's external collaborators and add them as a reviewerremove-reviewer
: Remove specified members from existing reviewersadd-assignee
: Add assignees, adding members specified in thereviewers
parameterremove-assignee
: Remove specified members from existing assignees
reviewers
- type:
Array<String>
|String
- required:
false
Usernames of reviewers to add or remove. Multiple usernames can be separated by ,
or ;
.
Effective when type
is add-reviewer
, remove-reviewer
, add-assignee
, or remove-assignee
.
If both reviewers
and reviewersConfig
are configured, a specified number of reviewers or assignees will be randomly selected from both.
count
- type:
Number
- required:
false
Specify the number of reviewers or assignees to add, randomly selecting the specified number of reviewers or assignees.
- When
type=add-reviewer
, the default value forcount
is the number ofreviewers
, adding all by default - When
type=add-reviewer-from-repo-members
, the default value forcount
is 1 - When
type=add-reviewer-from-group-members
, the default value forcount
is 1 - When
type=add-reviewer-from-outside-collaborator-members
, the default value forcount
is 1 - When
type=add-assignee
, the default value forcount
is the number ofreviewers
, adding all by default
If the number of existing reviewers or assignees is < count
, then fill up to the specified count.
If the number of existing reviewers or assignees is >= count
, then no action is taken.
exclude
- type:
Array<String>
|String
- required:
false
Exclude specified users.
reviewersConfig
- type: IReviewersConfig |
String
- required:
false
File reviewers or assignees configuration. If the configuration includes reviewers or assignees for the current changed file, they will be added as reviewers or assignees.
Effective when type
is add-reviewer
or add-assignee
.
Supports two formats:
- String format, passing the relative path to the configuration file (supports
json
files):
{
"reviewersConfig": "config.json"
}
{
"./src": "name1,name2",
".cnb.yml": "name3"
}
- Object format, passing the file reviewers configuration:
{
"reviewersConfig": {
"./src": "name1,name2",
".cnb.yml": "name3"
}
}
In the file reviewers or assignees configuration, the key
is the relative file path, and the value
is the usernames of reviewers or assignees separated by commas.
If both reviewers
and reviewersConfig
are configured, a specified number of reviewers or assignees will be randomly selected from both.
role
- type: ROLE_TYPE
- required:
false
Roles that reviewers or assignees can have include: Developer
, Master
, Owner
. If Developer
is selected, members with Developer
and higher permissions can be added, including Developer
, Master
, Owner
.
Type Definitions
REVIEW_OPERATION_TYPE
Enum<String>
: add-reviewer | add-reviewer-from-repo-members | add-reviewer-from-group-members | add-reviewer-from-outside-collaborator-members | remove-reviewer | add-assignee | remove-assignee
IReviewersConfig
{
[key: String]: String
}
ROLE_TYPE
Enum<String>
: Developer | Master | Owner
Output Results
Output result for adding reviewers:
{
"reviewers": [],
"reviewersForAt": []
}
Output result for adding assignees:
{
"assignees": [],
"assigneesForAt": []
}
Configuration Examples
- Adding reviewers and assignees:
main:
pull_request:
- stages:
- name: Add Reviewers
type: git:reviewer
options:
type: add-reviewer
reviewers: aaa;bbb
- name: Add Assignees
type: git:reviewer
options:
type: add-assignee
reviewers: ccc;ddd
- Delete reviewers or assignees:
main:
pull_request:
- stages:
- name: Remove Reviewers
type: git:reviewer
options:
type: remove-reviewer
reviewers: aaa
- name: Remove Assignees
type: git:reviewer
options:
type: remove-assignee
reviewers: aaa
- Combining with
ifModify
, adding reviewers and assignees when specific files are modified:
main:
pull_request:
- stages:
- name: Review for Configuration Changes
ifModify:
- ".cnb.yml"
- "configs/**"
type: git:reviewer
options:
type: add-reviewer
reviewers: bbb
- name: Assign for Configuration Changes
ifModify:
- ".cnb.yml"
- "configs/**"
type: git:reviewer
options:
type: add-assignee
reviewers: ccc
- Combining with
if
, adding specific reviewers or assignees under certain conditions:
main:
pull_request:
- stages:
- name: Release after Hours? Requires Reviewers.
if: |
[ $(date +%H) -ge 18 ]
type: git:reviewer
options:
type: add-reviewer
reviewers: bbb
- name: Release after Hours? Requires Assignees.
if: |
[ $(date +%H) -ge 18 ]
type: git:reviewer
options:
type: add-assignee
reviewers: ccc
- Randomly selecting one person to review the code:
main:
pull_request:
- stages:
- name: Random Selection
image: tencentcom/random
settings:
from:
- aaa
- bbb
exports:
result: CURR_REVIEWER
- name: Show Current Reviewer
script: echo ${CURR_REVIEWER}
- name: Add Reviewer
type: git:reviewer
options:
type: add-reviewer
reviewers: ${CURR_REVIEWER}
- Selecting one reviewer from current repository members for review:
main:
pull_request:
- stages:
- name: Add Reviewer
type: git:reviewer
options:
type: add-reviewer-from-repo-members
Best Practices
Establish a dedicated code review (CR) group for cross-review and automatic merging.
- Randomly select N reviewers for a PR and notify the group.
- Automatically merge after the review is approved.
- Record reviewer information in the commit message.
- Configure Git to automatically merge based on multi-reviewer approval policies for cross-review.
main:
review:
- stages:
- name: Auto-Merge after CR Approval
type: git:auto-merge
options:
mergeType: squash
removeSourceBranch: true
mergeCommitMessage: $CNB_LATEST_COMMIT_MESSAGE
exports:
reviewedBy: REVIEWED_BY
# Send review message to WeChat Enterprise Bot
- name: Notify
image: tencentcom/wecom-message
settings:
msgType: markdown
robot: "155af237-6041-4125-9340-000000000000"
content: |
> Auto-Merge after CR Approval <@${CNB_BUILD_USER}>
>
> ${CNB_PULL_REQUEST_TITLE}
> [${CNB_EVENT_URL}](${CNB_EVENT_URL})
>
> ${REVIEWED_BY}
pull_request:
- stages:
# ...Other tasks omitted
# Send to dedicated CR group
- name: Add Reviewers
type: git:reviewer
options:
reviewers: aaa,bbb,ccc,ddd
count: 2
exports:
reviewersForAt: CURR_REVIEWER_FOR_AT
- name: Notify
image: tencentcom/wecom-message
settings:
msgType: markdown
robot: "155af237-6041-4125-9340-000000000000"
message: |
> ${CURR_REVIEWER_FOR_AT}
>
> ${CNB_PULL_REQUEST_TITLE}
> [${CNB_EVENT_URL}](${CNB_EVENT_URL})
>
> from ${CNB_BUILD_USER}
Release
git:release
Publish a Release for the repository
Applicable Events
push
commit.add
branch.create
tag_push
pull_request.merged
api_trigger
web_trigger
tag_deploy
Parameters
Tips
This built-in task does not support uploading attachments. You can use the cnbcool/attachments task to upload attachments.
overlying
- type:
Boolean
- required:
false
- default:
false
Overlay mode:
true
: Overlay mode, meaning this is only for editing or updating the Release.false
: Non-overlay mode, meaning delete first, then recreate the Release.
Warning
Default is false
, meaning that when a Release version already exists, it will be deleted first and then recreated.
tag
- type:
String
- required:
false
Tag name corresponding to the release
, not required.
For tag_push
events, this is not needed as it directly takes the Tag name triggering the tag_push
event.
For non-tag_push
events, this is required as the Tag name corresponding to the Release.
title
- type:
String
- required:
false
- default: Tag name
Title of the Release.
description
- type:
String
- required:
false
Description of the Release.
preRelease
- type:
Boolean
- required:
false
- default:
false
Whether to set the release
as a pre-release.
latest
- type: "true" | "false" | true | false
- required:
false
- default:
false
Whether to set the Release as the latest version.
Output Results
None
Configuration Examples
- Generate changelog and automatically update Release description:
$:
tag_push:
- stages:
- name: Changelog
image: cnbcool/changelog
exports:
latestChangeLog: LATEST_CHANGE_LOG
- name: Upload Release
type: git:release
options:
title: release
description: ${LATEST_CHANGE_LOG}
- Publish a Release when pushing to the main branch:
main:
push:
- stages:
- name: Git Release
type: git:release
options:
tag: Nightly
description: description
Testing
Coverage
testing:coverage
Unit Test Coverage, calculates the coverage based on unit test result reports and reports badge data.
You can view the coverage badge data of the latest 100 commits by branch in the repository's Insights
page in the form of charts.
Tips
For coverage data uploaded by pipelines triggered by events related to Pull Requests (except pull_request.merged
), switch to the pull request view to see the unit test insights curve.
Applicable Events
Full Coverage
Parsed from local coverage report files, currently recognizing the following report formats:
json(js)
(recommended)json-summary
lcov
(recommended)jacoco
golang
Incremental Coverage
Parameters
pattern
- type:
String
- required:
false
In Glob format, specifies the location of the coverage report file relative to the current working directory. If not provided, it will try to find the following files in the current directory (including subdirectories): coverage.json, jacoco*.xml, lcov.info,*.lcov.
lines
- type:
Number
- required:
false
Specifies the full coverage red line. If the full coverage percentage is less than this value, the workflow will be blocked from exiting the pipeline.
diffLines
- type:
Number
- required:
false
Specifies the incremental coverage red line. If the full coverage percentage is less than this value, the workflow will be blocked from exiting the pipeline. Events like pull_request
, pull_request.update
, pull_request.target
support calculating incremental coverage results, while other events only calculate full coverage.
allowExts
- type:
String
- required:
false
Whitelist of code file types to be included in coverage calculation, separated by commas, e.g., .json
, .ts
, .js
. If not provided, all files in the report will be included in the calculation.
lang
- type:
String
- required:
false
When the coverage report target format is golang
, specify this parameter as go
to avoid calculation errors. This parameter can be ignored in other cases.
breakIfNoCoverage
- type:
Boolean
- required:
false
Whether to throw an error and terminate the process if no coverage report file is found.
Output Results
{
// Code line coverage, e.g., 100. Value is NA if calculation fails.
"lines": 100,
// Incremental code line coverage, e.g., 100. Value is NA if calculation fails.
"diff_pct": 100
}
Configuration Examples
main:
push:
- stages:
- name: coverage
type: testing:coverage
options:
breakIfNoCoverage: false
exports:
lines: LINES
- name: result
script: echo $LINES
Artifact
remove-tag
artifact:remove-tag
Delete CNB Artifact Tags, currently only supports deleting CNB Docker and Helm tags. Write permissions for the repository are required.
Applicable Events
push
commit.add
tag_push
tag_deploy
pull_request.merged
api_trigger
web_trigger
crontab
branch.create
Parameters
name
- type:
String
- required:
true
Artifact package name
tags
- type:
Array<string>
- required:
true
type
- type:
String
- required:
false
- default:
docker
Artifact type, currently only supports Docker and Helm
Configuration Examples
main:
push:
- stages:
- name: remove tag
type: artifact:remove-tag
options:
# Package name
# Package name example 1, repository with the same name artifact: reponame
# Package name example 2, repository with a different name artifact: reponame/name
name: reponame/name
tags:
- tag1
- tag2
type: docker