Flutter CI/CD Gitlab 缓存问题

时间:2021-02-10 23:53:56

标签: flutter gitlab-ci

我目前正在我自己的 MacBook 上的 gitlab-runner 上运行我的 cicd,我的 cicd 工作正常,但我试图通过防止在不同阶段多次调用“flutter pub get”来减少一些时间。我尝试缓存要在第二阶段使用的 .pub-cache 文件夹,但它失败了。下面是我的 gitlab-ci.yml:-

stages:
  - static_analysis
  - build_android

Static Analysis:
  stage: static_analysis
  script:
    - flutter pub get
    - flutter analyze
  cache:
    untracked: true
    paths:
      - ~/.pub-cache
  tags:
    - flutter

Build Android:
  stage: build_android
  script:
    - cd android
    - bundle exec fastlane saving_app
  tags:
    - flutter

我现在仍然需要在我的“build_android”阶段调用“flutter pub get”才能使管道成功运行,因为缓存当前不起作用。

1 个答案:

答案 0 :(得分:0)

运行器缓存不能用于在作业阶段之间传递工件。它们适用于以下用例,例如,您需要安装 npm 依赖项,然后将 npm_modules 目录传递到另一个阶段。该定义可能如下所示:

stages:
  - build
  - deploy

Build NPM Dependencies:
  stage: build
  script:
    - npm install # puts downloaded dependencies in ./npm_modules
  artifacts:
    paths:
      - npm_modules
    expire_in: 2 hours

Deploy App:
  stage: deploy
  script:
    - ls # npm_modules is here
    - ./my-deploy-script.sh 

工件在创建后的所有后续阶段由每个作业下载。因此,如果我们在构建和部署之间有一个“打包”阶段,则将在每个步骤中下载 npm 依赖项。我们可以使用 dependencies 关键字来控制:

...
Deploy App:
  stage: deploy
  dependencies: [“Build NPM Dependencies”]
  ...

这也可以是 [] 以防止作业中的所有工件。

您需要使用 artifacts 在其他阶段传递您的 .pub-cache 目录。那么缓存有什么用呢?在我们的 NPM 依赖项示例中,对于每个管道,我们都必须安装依赖项,无论我们的需求是否发生变化。您可以仅在某些文件已更改或未更改的情况下运行作业,但这样我们所需的工件将不存在。这就是缓存发挥作用的地方:

stages:
  - build
  - deploy

Build NPM Dependencies:
  stage: build
  script:
    - npm install # puts downloaded dependencies in ./npm_modules
  artifacts:
    paths:
      - npm_modules
    expire_in: 2 hours
  cache:
    paths:
      - .pub-cache
    key: ${CI_COMMIT_REF_NAME}_pub-cache

Deploy App:
  stage: deploy
  script:
    - ls # npm_modules is here
    - ./my-deploy-script.sh

现在,当此作业运行时,它会检查保存分支或标签名称的 $CI_COMMIT_REF_NAME 变量,以查看是否存在该键的缓存。如果没有,它将运行该作业。如果是,它将下载缓存的项目并像刚刚构建一样使用它。这一切都由 key 关键字控制,因此您必须根据需要对其进行调整。

您可以在此处找到有关缓存和工件之间区别的信息:https://docs.gitlab.com/ee/ci/caching/#cache-vs-artifacts

您可以在此处找到有关使用缓存的详细信息:https://docs.gitlab.com/ee/ci/yaml/#cache

有关工件的详细信息如下:https://docs.gitlab.com/ee/ci/yaml/#artifacts