避免CI中的冗余构建和测试是一个很常见的问题,可以通过以下几种方法来解决:
示例代码:
jobs:
build:
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Cache dependencies
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install dependencies
run: npm ci
这个示例使用了 GitHub Actions 的缓存功能。它会在每次构建之前检查缓存是否存在,并且只有当缓存失效时才会重新安装依赖项。这样可以避免每次构建都重新下载和安装依赖项,提高构建的速度。
示例代码:
jobs:
build:
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Run tests
run: npm run test
- name: Deploy to production
if: github.ref == 'refs/heads/main'
run: npm run deploy
这个示例中,使用了一个条件语句来决定是否执行部署操作。只有当代码提交到 main
分支时,才会执行部署操作。这样可以避免在每次提交代码时都进行部署,节省了资源和时间。
示例代码:
jobs:
build:
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Build and test
run: |
if git diff --name-only ${{ github.base_ref }}..${{ github.head_ref }} | grep -q "src/"; then
npm run build
npm run test
else
echo "No changes in src/ directory. Skipping build and test."
fi
这个示例中,使用了 git diff
命令来检查有没有 src/ 目录下的文件发生了变化。只有当有变化时,才会执行构建和测试操作。这样可以避免没有必要的构建和测试,提高了构建的效率。
以上是一些常见的解决方法,你可以根据自己的需求和实际情况选择合适的方法来避免CI中的冗余构建和测试。