首页 > 解决方案 > 如何在 GitHub Actions 中的运行之间缓存已安装的工具?

问题描述

我需要运行poetry version以获取pyproject.toml每次推送的版本以掌握触摸pyproject.toml。但是,由于 Poetry 没有安装在 GitHub Actions runner 虚拟环境中,所以我还需要先安装它,然后才能运行任何 Poetry 命令。我想缓存这个工具安装,这样我就不必在每次运行时都安装它并用完 Actions 分钟。我需要运行的唯一 Poetry 命令是poetry version,所以我不担心该工具已过时 - 它只需要解析pyproject.toml并获取项目版本号。我也不确定将什么用作key缓存操作-我认为它可以是静态的

所需的操作顺序类似于:

  1. 查看回购。
  2. 检查诗歌缓存。如果未安装,请安装它。
  3. 运行poetry version

标签: continuous-integrationcontinuous-deploymentgithub-actionspython-poetry

解决方案


key输入actions/cache@v2可以是一个字符串——给它一些任意的东西。path输入是工具的位置。

潜在的陷阱:

  • 请注意,该path参数不解析环境变量,如$HOME,但波浪号 ( ~) 可用于表示主目录。
  • 每次运行时都必须将诗歌添加到 PATH 之前,因为在运行之间不保留默认环境变量。
  • Poetry 可能会抱怨它很快就会放弃对 Python2 的支持——为了确保它与 Python 3 一起运行,请确保使用任何 Python 3 版本设置运行。
on:
  push:
    branches:
      - master
    paths:
      - 'pyproject.toml'

jobs:
  pyproject-version:
    runs-on: 'ubuntu-latest'
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Setup Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.7'
      # Perma-cache Poetry since we only need it for checking pyproject version
      - name: Cache Poetry
        id: cache-poetry
        uses: actions/cache@v2
        with:
          path: ~/.poetry
          key: poetry
      # Only runs when key from caching step changes
      - name: Install latest version of Poetry
        if: steps.cache-poetry.outputs.cache-hit != 'true'
        run: |
          curl -sSL https://install.python-poetry.org | python -
      # Poetry still needs to be re-prepended to the PATH on each run, since
      # PATH does not persist between runs.
      - name: Add Poetry to $PATH
        run: |
          echo "$HOME/.poetry/bin" >> $GITHUB_PATH
      - name: Get pyproject version
        run: poetry version

推荐阅读