我们经常发布文档更新,此页面的翻译可能仍在进行中。有关最新信息,请访问英文文档。如果此页面上的翻译有问题,请告诉我们

Creating a JavaScript action

In this guide, you'll learn how to build a JavaScript action using the actions toolkit.

本文内容:

简介

The action you build will print "Hello World" in the logs or "Hello [who-to-greet]" if you provide a custom name. 更多信息请参阅 actions/toolkit 仓库。

Once you complete this project, you should understand how to build your own JavaScript action and test it in a workflow.

基本要求

Before you begin, you'll need to download Node.js and create a GitHub repository.

  1. Download and install Node.js 12.x, which includes npm.

    https://nodejs.org/en/download/current/

  2. Create a new repository on GitHub. You can choose any repository name or use "hello-world-javascript-action" like this example. 您可以在项目推送到 GitHub 之后添加这些文件。 For more information, see "Create a new repository."

  3. Clone your repository to your computer. 更多信息请参阅“克隆仓库”。

  4. From your terminal, change directories into your new repository.

cd hello-world-javascript-action
  1. From your terminal, initialize the directory with a package.json file.

    npm init -y

Create an action metadata file

Create a new file action.yml in the hello-world-javascript-action directory with the following example code.

action.yml

name: 'Hello World'
description: 'Greet someone and record the time'
inputs:
  who-to-greet:  # id of input
    description: 'Who to greet'
    required: true
    default: 'World'
outputs:
  time: # id of output
    description: 'The time we greeted you'
runs:
  using: 'node12'
  main: 'index.js'

This file defines the who-to-greet input and time output. It also tells the action runner how to start running this JavaScript action.

Add actions toolkit packages

The actions toolkit is a collection of Node.js packages that allow you to quickly build JavaScript actions with more consistency. The toolkit @actions/core package provides an interface to the logging commands, input and output variables, exit statuses, and debug messages. For more information, see "Development tools for GitHub Actions" and "Virtual environments for GitHub Actions."

The toolkit also offers a @actions/github package that returns an authenticated Octokit REST client and access to GitHub Actions contexts. For more information, see the Octokit library and "Contexts and expression syntax for GitHub Actions."

The toolkit offers more than the core and github packages. 更多信息请参阅 actions/toolkit 仓库。

At your terminal, install the actions toolkit core and github packages.

npm install @actions/core
npm install @actions/github

Now you should see a node_modules directory with the modules you just installed and a package-lock.json file with the installed module dependencies and the versions of each installed module.

Write the action code

This action uses the toolkit to get the who-to-greet input variable required in the action's metadata file and prints "Hello [who-to-greet]" in a debug message in the log. Next, the script gets the current time and sets it as an output variable that actions running later in a job can use.

GitHub Actions provide context information about the webhook event, Git refs, workflow, action, and the person who triggered the workflow. To access the context information, you can use the github package. The action you'll write will print the webhook event payload the log.

Add a new file called index.js, with the following code.

index.js

const core = require('@actions/core');
const github = require('@actions/github');

try {
  // `who-to-greet` input defined in action metadata file
  const nameToGreet = core.getInput('who-to-greet');
  console.log(`Hello ${nameToGreet}!`);
  const time = (new Date()).toTimeString();
  core.setOutput("time", time);
  // Get the JSON webhook payload for the event that triggered the workflow
  const payload = JSON.stringify(github.context.payload, undefined, 2)
  console.log(`The event payload: ${payload}`);
} catch (error) {
  core.setFailed(error.message);
}

Create a README

To let people know how to use your action, you can create a README file. A README is most helpful when you plan to share your action publicly, but is also a great way to remind you or your team how to use the action.

In your hello-world-javascript-action directory, create a README.md file that specifies the following information:

README.md

# Hello world javascript action

This action prints "Hello World" or "Hello" + the name of a person to greet to the log.

## Inputs

### `who-to-greet`

**Required** The name of the person to greet. Default `"World"`.

## Outputs

### `time`

The time we greeted you.

## Example usage

uses: actions/hello-world-javascript-action@v1
with:
  who-to-greet: 'Mona the Octocat'

Commit and push your action to GitHub

GitHub downloads each action run in a workflow during runtime and executes it as a complete package of code before you can use workflow commands like run to interact with the virtual machine. This means you must include any package dependencies required to run the JavaScript code. You'll need to check in the toolkit core and github packages to your action's repository.

From your terminal, commit your action.yml, index.js, node_modules, package.json, package-lock.json, and README.md files. If you added a .gitignore file that lists node_modules, you'll need to remove that line to commit the node_modules directory.

git add action.yml index.js node_modules/* package.json package-lock.json README.md
git commit -m "My first action is ready"
git push

As an alternative to checking in your node_modules directory you can use a tool called zeit/ncc to compile your code and modules into one file used for distribution.

  1. Install zeit/ncc by running this command in your terminal. npm i -g @zeit/ncc

  2. Compile your index.js file. ncc build index.js

    You'll see a new dist/index.js file with your code and the compiled modules.

  3. Change the main keyword in your action.yml file to use the new dist/index.js file. main: 'dist/index.js'

  4. If you already checked in your node_modules directory, remove it. rm -rf node_modules/*

  5. From your terminal, commit the updates to your action.yml, dist/index.js, and node_modules files.

git add action.yml dist/index.js node_modules/*
git commit -m "Use zeit/ncc"
git push

Testing out your action in a workflow

Now you're ready to test your action out in a workflow. When an action is in a private repository, the action can only be used in workflows in the same repository. Public actions can be used by workflows in any repository.

使用公共操作的示例

The following workflow code uses the completed hello world action in the actions/hello-world-javascript-action repository. Copy the workflow code into a .github/workflows/main.yml file, but replace the actions/hello-world-javascript-action repository with the repository you created. You can also replace the who-to-greet input with your name.

.github/workflows/main.yml

on: [push]

jobs:
  hello_world_job:
    runs-on: ubuntu-latest
    name: A job to say hello
    steps:

    - name: Hello world action step
      id: hello
      uses: actions/hello-world-javascript-action@v1
      with:
        who-to-greet: 'Mona the Octocat'
    # Use the output from the `hello` step
    - name: Get the output time
      run: echo "The time was ${{ steps.hello.outputs.time }}"

Example using a private action

Copy the workflow code into a .github/workflows/main.yml file in your action's repository. You can also replace the who-to-greet input with your name.

.github/workflows/main.yml

on: [push]

jobs:
  hello_world_job:
    runs-on: ubuntu-latest
    name: A job to say hello
    steps:

      - name: Checkout
        uses: actions/checkout@v1
      - name: Hello world action step
        uses: ./ # Uses an action in the root directory
        id: hello
        with:
          who-to-greet: 'Mona the Octocat'
      # Use the output from the `hello` step
      - name: Get the output time
        run: echo "The time was ${{ steps.hello.outputs.time }}"

From your repository, click the Actions tab, and select the latest workflow run. You should see "Hello Mona the Octocat" or the name you used for the who-to-greet input and the timestamp printed in the log.

A screenshot of using your action in a workflow

问问别人

找不到要找的内容?

联系我们