githubactions

package module
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2021 License: Apache-2.0 Imports: 12 Imported by: 211

README

GitHub Actions SDK (Go)

GoDoc GitHub Actions

This library provides an SDK for authoring GitHub Actions in Go. It has no external dependencies and provides a Go-like interface for interacting with GitHub Actions' build system.

Installation

Download the library:

$ go get -u github.com/sethvargo/go-githubactions/...

Usage

The easiest way to use the library is by importing it and invoking the functions at the root:

import (
  "github.com/sethvargo/go-githubactions"
)

func main() {
  val := githubactions.GetInput("val")
  if val == "" {
    githubactions.Fatalf("missing 'val'")
  }
}

You can also create an instance with custom fields that will be included in log messages:

import (
  "github.com/sethvargo/go-githubactions"
)

func main() {
  actions := githubactions.WithFieldsMap(map[string]string{
    "file": "myfile.js",
    "line": "100",
  })

  val := actions.GetInput("val")
  if val == "" {
    actions.Fatalf("missing 'val'")
  }
}

For more examples and API documentation, please see the Go docs.

Publishing

By default, GitHub Actions expects actions to be written in Node.js. For other languages like Go, you need to provide a Dockerfile and entrypoint instructions in an action.yml file:

# Dockerfile
FROM golang:1.13
RUN go build -o /bin/app .
ENTRYPOINT ["/bin/app"]
# action.yml
name: My action
author: My name
description: My description

runs:
  using: docker
  image: Dockerfile

And then users can import your action by the repository name:

steps:
- name: My action
  uses: username/repo@latest

However, this will clone the entire repo and compile the Go code each time the action runs. Worse, it uses the Go base container which is a few hundred MBs and includes a ton of unnecessary things.

Fortunately, GitHub Actions can also source from a Docker container directly from Docker Hub:

steps:
- name: My action
  uses: docker://username/repo:latest

Now we can precompile and publish our Go Action as a Docker container, but we need to make it much, much smaller first. This can be achieved using multi-stage Docker builds:

FROM golang:1.13 AS builder

ENV GO111MODULE=on \
  CGO_ENABLED=0 \
  GOOS=linux \
  GOARCH=amd64

RUN apt-get -qq update && \
  apt-get -yqq install upx

WORKDIR /src
COPY . .

RUN go build \
  -a \
  -ldflags "-s -w -extldflags '-static'" \
  -installsuffix cgo \
  -tags netgo \
  -mod vendor \
  -o /bin/app \
  . \
  && strip /bin/app \
  && upx -q -9 /bin/app

RUN echo "nobody:x:65534:65534:Nobody:/:" > /etc_passwd



FROM scratch

COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /etc_passwd /etc/passwd
COPY --from=builder --chown=65534:0 /bin/app /app

USER nobody
ENTRYPOINT ["/app"]

The first step, uses a fat container to build, strip, and compress the compiled Go binary. Then, in the second step, the compiled and compressed binary is copied into a scratch (bare) container along with some SSL certificates and a nobody user in which to execute the container.

This will usually produce an image that is < 10MB in size, making for much faster builds.

Documentation

Overview

Package githubactions provides an SDK for authoring GitHub Actions in Go. It has no external dependencies and provides a Go-like interface for interacting with GitHub Actions' build system.

Package githubactions provides an SDK for authoring GitHub Actions in Go. It has no external dependencies and provides a Go-like interface for interacting with GitHub Actions' build system.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddMask

func AddMask(p string)

AddMask adds a new field mask for the given string "p". After called, future attempts to log "p" will be replaced with "***" in log output.

func AddMatcher

func AddMatcher(p string)

AddMatcher adds a new matcher with the given file path.

func AddPath

func AddPath(p string)

AddPath adds the string "p" to the path for the invocation.

func Debugf

func Debugf(msg string, args ...interface{})

Debugf prints a debug-level message. The arguments follow the standard Printf arguments.

func EndGroup

func EndGroup()

EndGroup ends the current group.

func Errorf

func Errorf(msg string, args ...interface{})

Errorf prints a error-level message. The arguments follow the standard Printf arguments.

func Fatalf

func Fatalf(msg string, args ...interface{})

Fatalf prints a error-level message and exits. This is equivalent to Errorf followed by os.Exit(1).

func GetIDToken added in v0.5.0

func GetIDToken(ctx context.Context, audience string) (string, error)

GetIDToken returns the GitHub OIDC token from the GitHub Actions runtime.

func GetInput

func GetInput(i string) string

GetInput gets the input by the given name.

func Group

func Group(t string)

Group starts a new collapsable region up to the next ungroup invocation.

func Infof added in v0.4.0

func Infof(msg string, args ...interface{})

Infof prints a info-level message. The arguments follow the standard Printf arguments.

func IssueCommand added in v0.3.0

func IssueCommand(cmd *Command)

IssueCommand issues an arbitrary GitHub actions Command.

func IssueFileCommand added in v0.3.0

func IssueFileCommand(cmd *Command) error

IssueFileCommand issues a new GitHub actions Command using environment files.

func RemoveMatcher

func RemoveMatcher(o string)

RemoveMatcher removes a matcher with the given owner name.

func SaveState

func SaveState(k, v string)

SaveState saves state to be used in the "finally" post job entry point.

func SetEnv

func SetEnv(k, v string)

SetEnv sets an environment variable.

func SetOutput

func SetOutput(k, v string)

SetOutput sets an output parameter.

func Warningf

func Warningf(msg string, args ...interface{})

Warningf prints a warning-level message. The arguments follow the standard Printf arguments.

Types

type Action

type Action struct {
	// contains filtered or unexported fields
}

Action is an internal wrapper around GitHub Actions' output and magic strings.

func New

func New(opts ...Option) *Action

New creates a new wrapper with helpers for outputting information in GitHub actions format.

Example
a = githubactions.New()

func NewWithWriter deprecated

func NewWithWriter(w io.Writer) *Action

NewWithWriter creates a wrapper using the given writer. This is useful for tests. The given writer cannot add any prefixes to the string, since GitHub requires these special strings to match a very particular format.

Deprecated: Use New() with WithWriter instead.

func WithFieldsMap

func WithFieldsMap(m map[string]string) *Action

WithFieldsMap includes the provided fields in log output. The fields in "m" are automatically converted to k=v pairs and sorted.

func WithFieldsSlice

func WithFieldsSlice(f []string) *Action

WithFieldsSlice includes the provided fields in log output. "f" must be a slice of k=v pairs. The given slice will be sorted.

func (*Action) AddMask

func (c *Action) AddMask(p string)

AddMask adds a new field mask for the given string "p". After called, future attempts to log "p" will be replaced with "***" in log output.

Example
a := githubactions.New()
a.AddMask("my-password")

func (*Action) AddMatcher

func (c *Action) AddMatcher(p string)

AddMatcher adds a new matcher with the given file path.

func (*Action) AddPath

func (c *Action) AddPath(p string)

AddPath adds the string "p" to the path for the invocation. It attempts to issue a file command at first. If that fails, it falls back to the regular (now deprecated) 'add-path' command, which may stop working in the future. The deprecated fallback may be useful for users running an older version of GitHub runner.

https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#adding-a-system-path https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/

Example
a := githubactions.New()
a.AddPath("/tmp/myapp")

func (*Action) Debugf

func (c *Action) Debugf(msg string, args ...interface{})

Debugf prints a debug-level message. The arguments follow the standard Printf arguments.

Example
a := githubactions.New()
a.Debugf("a debug message")
Example (FieldsMap)
a := githubactions.New()
m := map[string]string{
	"file": "app.go",
	"line": "100",
}
a.WithFieldsMap(m).Debugf("a debug message")
Example (FieldsSlice)
a := githubactions.New()
s := []string{"file=app.go", "line=100"}
a.WithFieldsSlice(s).Debugf("a debug message")

func (*Action) EndGroup

func (c *Action) EndGroup()

EndGroup ends the current group.

func (*Action) Errorf

func (c *Action) Errorf(msg string, args ...interface{})

Errorf prints a error-level message. The arguments follow the standard Printf arguments.

Example
a := githubactions.New()
a.Errorf("an error message")
Example (FieldsMap)
a := githubactions.New()
m := map[string]string{
	"file": "app.go",
	"line": "100",
}
a.WithFieldsMap(m).Errorf("an error message")
Example (FieldsSlice)
a := githubactions.New()
s := []string{"file=app.go", "line=100"}
a.WithFieldsSlice(s).Errorf("an error message")

func (*Action) Fatalf

func (c *Action) Fatalf(msg string, args ...interface{})

Fatalf prints a error-level message and exits. This is equivalent to Errorf followed by os.Exit(1).

func (*Action) GetIDToken added in v0.5.0

func (c *Action) GetIDToken(ctx context.Context, audience string) (string, error)

GetIDToken returns the GitHub OIDC token from the GitHub Actions runtime.

Example
ctx := context.Background()

a := githubactions.New()
token, err := a.GetIDToken(ctx, "my-aud")
if err != nil {
	// handle error
}
_ = token

func (*Action) GetInput

func (c *Action) GetInput(i string) string

GetInput gets the input by the given name.

func (*Action) Group

func (c *Action) Group(t string)

Group starts a new collapsable region up to the next ungroup invocation.

func (*Action) Infof added in v0.4.0

func (c *Action) Infof(msg string, args ...interface{})

Infof prints a info-level message. The arguments follow the standard Printf arguments.

func (*Action) IssueCommand added in v0.3.0

func (c *Action) IssueCommand(cmd *Command)

IssueCommand issues a new GitHub actions Command.

func (*Action) IssueFileCommand added in v0.3.0

func (c *Action) IssueFileCommand(cmd *Command) error

IssueFileCommand issues a new GitHub actions Command using environment files.

https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#environment-files

The TypeScript equivalent function:

https://github.com/actions/toolkit/blob/4f7fb6513a355689f69f0849edeb369a4dc81729/packages/core/src/file-command.ts#L10-L23

IssueFileCommand currently ignores the 'CommandProperties' field provided with the 'Command' argument as it's scope is unclear in the current TypeScript implementation.

func (*Action) RemoveMatcher

func (c *Action) RemoveMatcher(o string)

RemoveMatcher removes a matcher with the given owner name.

func (*Action) SaveState

func (c *Action) SaveState(k, v string)

SaveState saves state to be used in the "finally" post job entry point.

func (*Action) SetEnv

func (c *Action) SetEnv(k, v string)

SetEnv sets an environment variable. It attempts to issue a file command at first. If that fails, it falls back to the regular (now deprecated) 'set-env' command, which may stop working in the future. The deprecated fallback may be useful for users running an older version of GitHub runner.

https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/

Example
a := githubactions.New()
a.SetEnv("MY_THING", "my value")

func (*Action) SetOutput

func (c *Action) SetOutput(k, v string)

SetOutput sets an output parameter.

Example
a := githubactions.New()
a.SetOutput("filepath", "/tmp/file-xyz1234")

func (*Action) Warningf

func (c *Action) Warningf(msg string, args ...interface{})

Warningf prints a warning-level message. The arguments follow the standard Printf arguments.

Example
a := githubactions.New()
a.Warningf("a warning message")
Example (FieldsMap)
a := githubactions.New()
m := map[string]string{
	"file": "app.go",
	"line": "100",
}
a.WithFieldsMap(m).Warningf("a warning message")
Example (FieldsSlice)
a := githubactions.New()
s := []string{"file=app.go", "line=100"}
a.WithFieldsSlice(s).Warningf("a warning message")

func (*Action) WithFieldsMap

func (c *Action) WithFieldsMap(m map[string]string) *Action

WithFieldsMap includes the provided fields in log output. The fields in "m" are automatically converted to k=v pairs and sorted.

func (*Action) WithFieldsSlice

func (c *Action) WithFieldsSlice(f []string) *Action

WithFieldsSlice includes the provided fields in log output. "f" must be a slice of k=v pairs. The given slice will be sorted. It panics if any of the string in the given slice does not construct a valid 'key=value' pair.

type Command added in v0.3.0

type Command struct {
	Name       string
	Message    string
	Properties CommandProperties
}

Command can be issued by a GitHub action by writing to `stdout` with following format.

::name key=value,key=value::message

Examples:
  ::warning::This is the message
  ::set-env name=MY_VAR::some value

func (*Command) String added in v0.3.0

func (cmd *Command) String() string

String encodes the Command to a string in the following format:

::name key=value,key=value::message

type CommandProperties added in v0.3.0

type CommandProperties map[string]string

CommandProperties is a named "map[string]string" type to hold key-value pairs passed to an actions command.

func (*CommandProperties) String added in v0.3.0

func (props *CommandProperties) String() string

String encodes the CommandProperties to a string as comma separated 'key=value' pairs. The pairs are joined in a chronological order.

type GetenvFunc added in v0.4.0

type GetenvFunc func(k string) string

GetenvFunc is an abstraction to make tests feasible for commands that interact with environment variables.

type Option added in v0.4.0

type Option func(*Action) *Action

Option is a modifier for an Action

func WithFields added in v0.4.0

func WithFields(fields CommandProperties) Option

WithFields sets the extra command field on an Action.

func WithGetenv added in v0.4.0

func WithGetenv(getenv GetenvFunc) Option

WithGetenv sets the `Getenv` function on an Action. By default, this will be `os.Getenv` from the standard library.

func WithHTTPClient added in v0.5.0

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets a custom HTTP client on the action. This is only used when the action makes output HTTP requests (such as generating an OIDC token).

func WithWriter added in v0.4.0

func WithWriter(w io.Writer) Option

WithWriter sets the writer function on an Action. By default, this will be `os.Stdout` from the standard library.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL