Amit
Amit

Reputation: 6304

GitHub actions "extend" existing job

I would like to have some github actions workflow, which should check linting, check if building the code is successful, and if so run tests.

My first "job" is to install the dependencies. Every job needs that done, so I do the following in every job:

- uses: actions/checkout@v2

- name: Cache functions node_modules
  uses: actions/cache@v2
  with:
    path: node_modules
    key: ${{ runner.os }}-${{ hashFiles('package.json') }}

- name: Install dependencies
  run: npm ci

Is there a way to define this as job dependencies, and then have another job, lint extending this job? There's a cache, so it won't re-install, but it feels like long code repetition for no reason.

enter image description here

Upvotes: 5

Views: 5218

Answers (1)

Krzysztof Madej
Krzysztof Madej

Reputation: 40849

NOTE Initially it was not possible to us uses in composite actions it is possible now for some time. For more details please check here

If you want to apply DRY rule here you should check composite run steps

You can now create reusable actions using shell scripts and even mix multiple shell languages in the same action. You probably have a lot of shell script to automate many tasks, now you can easily turn them into an action and reuse them for different workflows.

You can use it as follow:

main file:

jobs:
  build:
    runs-on: windows-latest
    steps:
    - uses: actions/checkout@v2
    - uses: octocat/say-hello@v1
      with: 
        os: ${{ runner.os }}

octocat/say-hello/action.yml:

inputs:
  name: 
    os: 'Your os'
    default: 'No os default'
runs:
  using: "composite"
  steps: 
    - uses: actions/checkout@v2

    - name: Cache functions node_modules
      uses: actions/cache@v2
      with:
        path: node_modules
        key: ${{ inputs.os }}-${{ hashFiles('package.json') }}

    - name: Install dependencies
      run: npm ci

ANd you if plan to keep composite in the same repo as main workflow then refer to it as

    - uses: ./.github/actions/say-hello

for this folder structure:

enter image description here

Upvotes: 5

Related Questions