@actions/core 中文文档教程

发布于 3年前 浏览 17 项目主页 更新于 3年前

@actions/core

用于设置结果、日志记录、注册机密和跨操作导出变量的核心

Usage

Import the package

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

// typescript
import * as core from '@actions/core';

Inputs/Outputs

函数根据 yaml 1.2 规范 解析布尔值。 如果 required 设置为 false,则输入应在 action.yml 中具有默认值。

可以使用 setOutput 设置输出,这使得它们可以映射到其他操作的输入,以确保它们是解耦的。

const myInput = core.getInput('inputName', { required: true });
const myBooleanInput = core.getBooleanInput('booleanInputName', { required: true });
const myMultilineInput = core.getMultilineInput('multilineInputName', { required: true });
core.setOutput('outputKey', 'outputVal');

Exporting variables

由于每个步骤都在单独的进程中运行,因此您可以使用 exportVariable 将其添加到此步骤和未来步骤的环境块中。

core.exportVariable('envVar', 'Val');

Setting a secret

设置秘密会向运行器注册秘密,以确保它在日志中被屏蔽。

core.setSecret('myPassword');

PATH Manipulation

要使工具的路径在剩余作业的路径中可用(不改变机器或容器状态),请使用 addPath。 跑步者将把给定的路径放在作业路径的前面。

core.addPath('/path/to/mytool');

Exit codes

您应该使用此库为您的操作设置失败的退出代码。 如果未设置状态并且脚本运行完成,这将导致成功。

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

try {
  // Do stuff
}
catch (err) {
  // setFailed logs the message and sets a failing exit code
  core.setFailed(`Action failed with error ${err}`);
}

请注意,setNeutral 尚未在操作 V2 中实现,但正在计划等效功能。

Logging

最后,这个库提供了一些用于日志记录的实用程序。 请注意,默认情况下,调试日志记录在日志中是隐藏的。 可以通过启用 Step Debug Logs 来切换此行为。

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

const myInput = core.getInput('input');
try {
  core.debug('Inside try block');

  if (!myInput) {
    core.warning('myInput was not set');
  }

  if (core.isDebug()) {
    // curl -v https://github.com
  } else {
    // curl https://github.com
  }

  // Do stuff
  core.info('Output to the actions build log')

  core.notice('This is a message that will also emit an annotation')
}
catch (err) {
  core.error(`Error ${err}, action may still succeed though`);
}

该库还可以将大块输出包装在可折叠组中。

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

// Manually wrap output
core.startGroup('Do some function')
doSomeFunction()
core.endGroup()

// Wrap an asynchronous function call
const result = await core.group('Do something async', async () => {
  const response = await doSomeHTTPRequest()
  return response
})

Annotations

这个库有 3 个方法可以生成注释

core.error('This is a bad error. This will also fail the build.')

core.warning('Something went wrong, but it\'s not bad enough to fail the build.')

core.notice('Something happened that you might want to know about.')

这些将在 Actions 页面和 Pull Requests 中出现在 UI 中。 它们看起来像这样:

Annotations Image

这些注释也可以附加到源文件的特定行和列以准确显示发生问题的地方。

这些选项是:

export interface AnnotationProperties {
  /**
   * A title for the annotation.
   */
  title?: string

  /**
   * The name of the file for which the annotation should be created.
   */
  file?: string

  /**
   * The start line for the annotation.
   */
  startLine?: number

  /**
   * The end line for the annotation. Defaults to `startLine` when `startLine` is provided.
   */
  endLine?: number

  /**
   * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
   */
  startColumn?: number

  /**
   * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
   * Defaults to `startColumn` when `startColumn` is provided.
   */
  endColumn?: number
}

Styling output

通过标准 ANSI 转义码 在操作日志中支持彩色输出。 支持 3/4 位、8 位和 24 位颜色。

前景色:

// 3/4 bit
core.info('\u001b[35mThis foreground will be magenta')

// 8 bit
core.info('\u001b[38;5;6mThis foreground will be cyan')

// 24 bit
core.info('\u001b[38;2;255;0;0mThis foreground will be bright red')

背景色:

// 3/4 bit
core.info('\u001b[43mThis background will be yellow');

// 8 bit
core.info('\u001b[48;5;6mThis background will be cyan')

// 24 bit
core.info('\u001b[48;2;255;0;0mThis background will be bright red')

特殊样式:

core.info('\u001b[1mBold text')
core.info('\u001b[3mItalic text')
core.info('\u001b[4mUnderlined text')

ANSI 转义码可以相互组合:

core.info('\u001b[31;46mRed foreground with a cyan background and \u001b[1mbold text at the end');

注意:转义码在每一行的开头重置

core.info('\u001b[35mThis foreground will be magenta')
core.info('This foreground will reset to the default')

手动输入转义码可能有点困难,但您可以使用第三方模块,例如 < a href="https://github.com/chalk/ansi-styles">ansi-styles。

const style = require('ansi-styles');
core.info(style.color.ansi16m.hex('#abcdef') + 'Hello world!')

Action state

您可以使用此库保存状态并获取状态以在给定包装器操作之间共享信息:

action.yml

name: 'Wrapper action sample'
inputs:
  name:
    default: 'GitHub'
runs:
  using: 'node12'
  main: 'main.js'
  post: 'cleanup.js'

在操作的 main.js

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

core.saveState("pidToKill", 12345);

在操作的 cleanup .js

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

var pid = core.getState("pidToKill");

process.kill(pid);

OIDC Token

您可以使用这些方法与 GitHub OIDC 提供商交互并获取 JWT ID 令牌,这将有助于从第三方云提供商获取访问令牌。

方法名称:getIDToken()

输入

受众:可选

输出

A JWT< /a> ID Token

在动作的 main.ts 中:

const core = require('@actions/core');
async function getIDTokenAction(): Promise<void> {

   const audience = core.getInput('audience', {required: false})

   const id_token1 = await core.getIDToken()            // ID Token with default audience
   const id_token2 = await core.getIDToken(audience)    // ID token with custom audience

   // this id_token can be used to get access token from third party cloud providers
}
getIDTokenAction()

在动作的 actions.yml 中:

name: 'GetIDToken'
description: 'Get ID token from Github OIDC provider'
inputs:
  audience:  
    description: 'Audience for which the ID token is intended for'
    required: false
outputs:
  id_token1: 
    description: 'ID token obtained from OIDC provider'
  id_token2: 
    description: 'ID token obtained from OIDC provider'
runs:
  using: 'node12'
  main: 'dist/index.js'

@actions/core

Core functions for setting results, logging, registering secrets and exporting variables across actions

Usage

Import the package

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

// typescript
import * as core from '@actions/core';

Inputs/Outputs

Action inputs can be read with getInput which returns a string or getBooleanInput which parses a boolean based on the yaml 1.2 specification. If required set to be false, the input should have a default value in action.yml.

Outputs can be set with setOutput which makes them available to be mapped into inputs of other actions to ensure they are decoupled.

const myInput = core.getInput('inputName', { required: true });
const myBooleanInput = core.getBooleanInput('booleanInputName', { required: true });
const myMultilineInput = core.getMultilineInput('multilineInputName', { required: true });
core.setOutput('outputKey', 'outputVal');

Exporting variables

Since each step runs in a separate process, you can use exportVariable to add it to this step and future steps environment blocks.

core.exportVariable('envVar', 'Val');

Setting a secret

Setting a secret registers the secret with the runner to ensure it is masked in logs.

core.setSecret('myPassword');

PATH Manipulation

To make a tool's path available in the path for the remainder of the job (without altering the machine or containers state), use addPath. The runner will prepend the path given to the jobs PATH.

core.addPath('/path/to/mytool');

Exit codes

You should use this library to set the failing exit code for your action. If status is not set and the script runs to completion, that will lead to a success.

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

try {
  // Do stuff
}
catch (err) {
  // setFailed logs the message and sets a failing exit code
  core.setFailed(`Action failed with error ${err}`);
}

Note that setNeutral is not yet implemented in actions V2 but equivalent functionality is being planned.

Logging

Finally, this library provides some utilities for logging. Note that debug logging is hidden from the logs by default. This behavior can be toggled by enabling the Step Debug Logs.

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

const myInput = core.getInput('input');
try {
  core.debug('Inside try block');

  if (!myInput) {
    core.warning('myInput was not set');
  }

  if (core.isDebug()) {
    // curl -v https://github.com
  } else {
    // curl https://github.com
  }

  // Do stuff
  core.info('Output to the actions build log')

  core.notice('This is a message that will also emit an annotation')
}
catch (err) {
  core.error(`Error ${err}, action may still succeed though`);
}

This library can also wrap chunks of output in foldable groups.

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

// Manually wrap output
core.startGroup('Do some function')
doSomeFunction()
core.endGroup()

// Wrap an asynchronous function call
const result = await core.group('Do something async', async () => {
  const response = await doSomeHTTPRequest()
  return response
})

Annotations

This library has 3 methods that will produce annotations.

core.error('This is a bad error. This will also fail the build.')

core.warning('Something went wrong, but it\'s not bad enough to fail the build.')

core.notice('Something happened that you might want to know about.')

These will surface to the UI in the Actions page and on Pull Requests. They look something like this:

Annotations Image

These annotations can also be attached to particular lines and columns of your source files to show exactly where a problem is occuring.

These options are:

export interface AnnotationProperties {
  /**
   * A title for the annotation.
   */
  title?: string

  /**
   * The name of the file for which the annotation should be created.
   */
  file?: string

  /**
   * The start line for the annotation.
   */
  startLine?: number

  /**
   * The end line for the annotation. Defaults to `startLine` when `startLine` is provided.
   */
  endLine?: number

  /**
   * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
   */
  startColumn?: number

  /**
   * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
   * Defaults to `startColumn` when `startColumn` is provided.
   */
  endColumn?: number
}

Styling output

Colored output is supported in the Action logs via standard ANSI escape codes. 3/4 bit, 8 bit and 24 bit colors are all supported.

Foreground colors:

// 3/4 bit
core.info('\u001b[35mThis foreground will be magenta')

// 8 bit
core.info('\u001b[38;5;6mThis foreground will be cyan')

// 24 bit
core.info('\u001b[38;2;255;0;0mThis foreground will be bright red')

Background colors:

// 3/4 bit
core.info('\u001b[43mThis background will be yellow');

// 8 bit
core.info('\u001b[48;5;6mThis background will be cyan')

// 24 bit
core.info('\u001b[48;2;255;0;0mThis background will be bright red')

Special styles:

core.info('\u001b[1mBold text')
core.info('\u001b[3mItalic text')
core.info('\u001b[4mUnderlined text')

ANSI escape codes can be combined with one another:

core.info('\u001b[31;46mRed foreground with a cyan background and \u001b[1mbold text at the end');

Note: Escape codes reset at the start of each line

core.info('\u001b[35mThis foreground will be magenta')
core.info('This foreground will reset to the default')

Manually typing escape codes can be a little difficult, but you can use third party modules such as ansi-styles.

const style = require('ansi-styles');
core.info(style.color.ansi16m.hex('#abcdef') + 'Hello world!')

Action state

You can use this library to save state and get state for sharing information between a given wrapper action:

action.yml:

name: 'Wrapper action sample'
inputs:
  name:
    default: 'GitHub'
runs:
  using: 'node12'
  main: 'main.js'
  post: 'cleanup.js'

In action's main.js:

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

core.saveState("pidToKill", 12345);

In action's cleanup.js:

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

var pid = core.getState("pidToKill");

process.kill(pid);

OIDC Token

You can use these methods to interact with the GitHub OIDC provider and get a JWT ID token which would help to get access token from third party cloud providers.

Method Name: getIDToken()

Inputs

audience : optional

Outputs

A JWT ID Token

In action's main.ts:

const core = require('@actions/core');
async function getIDTokenAction(): Promise<void> {

   const audience = core.getInput('audience', {required: false})

   const id_token1 = await core.getIDToken()            // ID Token with default audience
   const id_token2 = await core.getIDToken(audience)    // ID token with custom audience

   // this id_token can be used to get access token from third party cloud providers
}
getIDTokenAction()

In action's actions.yml:

name: 'GetIDToken'
description: 'Get ID token from Github OIDC provider'
inputs:
  audience:  
    description: 'Audience for which the ID token is intended for'
    required: false
outputs:
  id_token1: 
    description: 'ID token obtained from OIDC provider'
  id_token2: 
    description: 'ID token obtained from OIDC provider'
runs:
  using: 'node12'
  main: 'dist/index.js'
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文