如何 运行 仅在对 master 分支的拉取请求时使用管道

How to run pipeline only on pull request to master branch

Bitbucket 管道允许定义对拉取请求的检查,并具有允许检查源分支的 glob 过滤器。

pipelines:
  pull-requests:
    '**': #this runs as default for any branch not elsewhere defined
      - step:
          script
            - ...
    feature/*: #any branch with a feature prefix
      - step:
          script:
            - ...

如何根据目标分支过滤?有一些测试只有在合并到master时才需要做。

遗憾的是,拉取请求管道机制是基于源分支而不是目标分支工作的。

这是在他们的跟踪器添加 pull-request 功能的问题上由其中一名团队成员解释的:

The branch pattern under pull requests defines the source branch. This is so that you can run a different pipeline depending on the fix. For example you may have a different set of tests for feature branches vs hotfix branches. Note that this is only talking about the tests that run against the PR during development.

来源: Geoff Crain's comment

实际上 this exact feature 还存在另一个问题。

但是团队的回答是:

I can definitely see why this would be useful, especially when merging to the master/main branch.

Given our current priorities, however, this is unlikely something that we'll support in the short term. In the meantime though, I'll open this ticket to gauge the interest of other users in seeing the same thing.

来源: Aneita Yang's comment

也就是说,您可以通过这种 hack 以某种方式获得所需的行为:

pipelines:
  pull-requests:
    '**': #this runs as default for any branch not elsewhere defined
      - step:
          script
            - if [ "${BITBUCKET_PR_DESTINATION_BRANCH}" != "master" ]; then printf 'not a target branch we want to check'; exit; fi
            - printf 'running useful tests'

或者,如果您已经在对所有拉取请求进行一些测试,就像我理解的那样:

pipelines:
  pull-requests:
    '**': #this runs as default for any branch not elsewhere defined
      - step:
          script
            - printf 'these are the all PR tests'
            - if [ "${BITBUCKET_PR_DESTINATION_BRANCH}" = "master" ]; then printf 'those are the extra checks on master'; fi

或者,它可以自己外化到脚本中:

bitbucket-pipelines.yaml

pipelines:
  pull-requests:
    '**': #this runs as default for any branch not elsewhere defined
      - step:
          script
            - ./bin/tests "${BITBUCKET_PR_DESTINATION_BRANCH}"

bin/tests

#!/usr/bin/env bash

printf 'these are the all PR tests'

if [ "" = "master" ]
then 
    printf 'those are the extra checks on master'
fi

另请参阅:管道文档页面中的变量:https://confluence.atlassian.com/bitbucket/variables-in-pipelines-794502608.html