atlasaction

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2025 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Versioned workflow Commands
	CmdMigratePush  = "migrate/push"
	CmdMigrateLint  = "migrate/lint"
	CmdMigrateApply = "migrate/apply"
	CmdMigrateDown  = "migrate/down"
	CmdMigrateTest  = "migrate/test"
	// Declarative workflow Commands
	CmdSchemaPush        = "schema/push"
	CmdSchemaTest        = "schema/test"
	CmdSchemaPlan        = "schema/plan"
	CmdSchemaPlanApprove = "schema/plan/approve"
	CmdSchemaApply       = "schema/apply"
	// Montioring Commands
	CmdMonitorSchema = "monitor/schema"
)
View Source
const (
	StatePending  = "PENDING_USER"
	StateApproved = "APPROVED"
	StateAborted  = "ABORTED"
	StateApplied  = "APPLIED"
)

Variables

View Source
var (
	CommentsTmpl = template.Must(
		template.New("comments").
			Funcs(template.FuncMap{
				"execTime":     execTime,
				"appliedStmts": appliedStmts,
				"filterIssues": filterIssues,
				"stepIsError":  stepIsError,
				"stmtsDetected": func(plan *atlasexec.SchemaPlanFile) string {
					switch l := len(plan.Stmts); {
					case l == 0:
						return "No statements detected"
					case l == 1:
						return "1 new statement detected"
					default:
						return fmt.Sprintf("%d new statements detected", l)
					}
				},
				"filesDetected": func(files []*atlasexec.FileReport) string {
					switch l := len(files); {
					case l == 0:
						return "No migration files detected"
					case l == 1:
						return "1 new migration file detected"
					default:
						return fmt.Sprintf("%d new migration files detected", l)
					}
				},
				"fileNames": func(files []*atlasexec.FileReport) []string {
					names := make([]string, len(files))
					for i, f := range files {
						names[i] = f.Name
					}
					return names
				},
				"stepSummary": func(s *atlasexec.StepReport) string {
					if s.Text == "" {
						return s.Name
					}
					return s.Name + "\n" + s.Text
				},
				"stepDetails": func(s *atlasexec.StepReport) string {
					if s.Result == nil {
						return s.Error
					}
					var details []string
					for _, r := range s.Result.Reports {
						if t := r.Text; t != "" {
							details = append(details, fmt.Sprintf("**%s%s**", strings.ToUpper(t[:1]), t[1:]))
						}
						for _, d := range r.Diagnostics {
							if d.Code == "" {
								details = append(details, d.Text)
							} else {
								details = append(details, fmt.Sprintf("%[1]s [(%[2]s)](https://atlasgo.io/lint/analyzers#%[2]s)", d.Text, d.Code))
							}
						}
					}
					return strings.Join(details, "\n")
				},
				"firstUpper": func(s string) string {
					if s == "" {
						return ""
					}
					return strings.ToUpper(s[:1]) + s[1:]
				},
				"assetsImage": func(s string) (string, error) {
					u, err := url.Parse("https://release.ariga.io/images/assets")
					if err != nil {
						return "", err
					}
					u = u.JoinPath(s)
					u.RawQuery = "v=1"
					return u.String(), nil
				},
				"join": strings.Join,
				"codeblock": func(lang, code string) string {
					return fmt.Sprintf("\n\n```%s\n%s\n```\n\n", lang, strings.Trim(code, "\n"))
				},
				"details": func(label, details string) string {
					return fmt.Sprintf("<details><summary>%s</summary>%s</details>", label, details)
				},
				"link": func(text, href string) string {
					return fmt.Sprintf(`<a href=%q target="_blank">%s</a>`, href, text)
				},
				"image": func(args ...any) (string, error) {
					var attrs string
					var src any
					switch len(args) {
					case 1:
						src, attrs = args[0], fmt.Sprintf("src=%q", args...)
					case 2:
						src, attrs = args[1], fmt.Sprintf("width=%[1]q height=%[1]q src=%[2]q", args...)
					case 3:
						src, attrs = args[2], fmt.Sprintf("width=%q height=%q src=%q", args...)
					case 4:
						src, attrs = args[3], fmt.Sprintf("width=%q height=%q alt=%q src=%q", args...)
					default:
						return "", fmt.Errorf("invalid number of arguments %d", len(args))
					}

					return fmt.Sprintf(`<picture><source media="(prefers-color-scheme: light)" srcset=%q><img %s/></picture>`, src, attrs), nil
				},
				"nl2br": func(s string) string { return strings.ReplaceAll(s, "\n", "<br/>") },
				"nl2sp": func(s string) string { return strings.ReplaceAll(s, "\n", " ") },
			}).
			ParseFS(comments, "comments/*"),
	)
)
View Source
var ErrNoSCM = errors.New("atlasaction: no SCM client found")

ErrNoSCM is returned when no SCM client is found.

Functions

func BitbucketClient added in v1.4.0

func BitbucketClient(workspace, repoSlug, token string) (*bbClient, error)

BitbucketClient returns a new Bitbucket client that implements SCMClient.

func GitHubClient added in v1.4.0

func GitHubClient(repo, baseURL, token string) (*ghClient, error)

func GitLabClient added in v1.4.0

func GitLabClient(project, baseURL, token string) (*glClient, error)

func LintReport added in v1.4.0

func LintReport(commit string, r *atlasexec.SummaryReport) (*bitbucket.CommitReport, error)

LintReport generates a commit report for the given commit ID

func NewBitBucketPipe added in v1.3.10

func NewBitBucketPipe(getenv func(string) string, w io.Writer) *bbPipe

NewBitBucketPipe returns a new Action for BitBucket.

func NewGHAction added in v1.1.0

func NewGHAction(getenv func(string) string, w io.Writer) *ghAction

NewGHAction returns a new Action for GitHub Actions.

func NewGitlabCI added in v1.3.5

func NewGitlabCI(getenv func(string) string, w io.Writer) *gitlabCI

NewGitlabCI returns a new Action for Gitlab CI.

func OldAgentHash added in v1.3.9

func OldAgentHash(src string) string

OldAgentHash computes a hash of the input. Used by the agent to determine if a new snapshot is needed.

Only here for backwards compatability as for new snapshots the Atlas CLI computed hash is used.

func RenderTemplate added in v1.3.0

func RenderTemplate(name string, data any) (string, error)

RenderTemplate renders the given template with the data.

Types

type Action added in v1.1.0

type Action interface {
	Logger
	// GetType returns the type of atlasexec trigger Type. e.g. "GITHUB_ACTION"
	// The value is used to identify the type on CI-Run page in Atlas Cloud.
	GetType() atlasexec.TriggerType
	// Getenv returns the value of the environment variable with the given name.
	Getenv(string) string
	// GetInput returns the value of the input with the given name.
	GetInput(string) string
	// SetOutput sets the value of the output with the given name.
	SetOutput(string, string)
	// GetTriggerContext returns the context of the trigger event.
	GetTriggerContext(context.Context) (*TriggerContext, error)
}

Action interface for Atlas.

func NewCircleCIOrb added in v1.1.0

func NewCircleCIOrb(getenv func(string) string, w io.Writer) Action

New returns a new Action for GitHub Actions.

type Actions added in v1.2.0

type Actions struct {
	Action
	Version     string
	Atlas       AtlasExec
	CloudClient func(string, string, *atlasexec.Version) CloudClient
}

Actions holds the runtime for the actions to run. This helps to inject the runtime dependencies. Like the SCM client, Atlas client, etc.

func New added in v1.3.0

func New(opts ...Option) (*Actions, error)

New creates a new Actions based on the environment.

func (*Actions) DeployRunContext added in v1.2.0

func (a *Actions) DeployRunContext() *atlasexec.DeployRunContext

DeployRunContext returns the run context for the `migrate/apply`, and `migrate/down` actions.

func (*Actions) GetArrayInput added in v1.3.0

func (a *Actions) GetArrayInput(name string) []string

GetArrayInput returns the array input with the given name. The input should be a string with new line separated values. Example: ```yaml

input: |-
  value1
  value2

```

func (*Actions) GetAtlasURLInput added in v1.3.0

func (a *Actions) GetAtlasURLInput(name string, paramsName ...string) string

GetAtlasURLInput returns the atlas URL input with the given name. paramsName is the list of input names to be added as query parameters.

func (*Actions) GetBoolInput added in v1.2.0

func (a *Actions) GetBoolInput(name string) bool

GetBoolInput returns the boolean input with the given name. The input should be a string representation of boolean. (e.g. "true" or "false")

func (*Actions) GetDurationInput added in v1.2.0

func (a *Actions) GetDurationInput(name string) time.Duration

GetDurationInput returns the duration input with the given name. The input should be a string representation of time.Duration. (e.g. "1s")

func (*Actions) GetURLInput added in v1.3.9

func (a *Actions) GetURLInput(name string) (*url.URL, error)

GetURLInput tries to parse the input as URL. In case of a parsing error, this function ensures the error does not leak any sensitive information.

func (*Actions) GetUin64Input added in v1.2.0

func (a *Actions) GetUin64Input(name string) uint64

GetUin64Input returns the uint64 input with the given name. The input should be a string representation of uint64. (e.g. "123")

func (*Actions) GetVarsInput added in v1.2.0

func (a *Actions) GetVarsInput(name string) atlasexec.VarArgs

GetVarsInput returns the vars input with the given name. The input should be a JSON string. Example: ```yaml

input: |-
  {
    "key1": "value1",
    "key2": "value2"
  }

```

func (*Actions) MigrateApply added in v1.2.0

func (a *Actions) MigrateApply(ctx context.Context) error

MigrateApply runs the GitHub Action for "ariga/atlas-action/migrate/apply".

func (*Actions) MigrateDown added in v1.2.0

func (a *Actions) MigrateDown(ctx context.Context) (err error)

MigrateDown runs the GitHub Action for "ariga/atlas-action/migrate/down".

func (*Actions) MigrateLint added in v1.2.0

func (a *Actions) MigrateLint(ctx context.Context) error

MigrateLint runs the GitHub Action for "ariga/atlas-action/migrate/lint"

func (*Actions) MigratePush added in v1.2.0

func (a *Actions) MigratePush(ctx context.Context) error

MigratePush runs the GitHub Action for "ariga/atlas-action/migrate/push"

func (*Actions) MigrateTest added in v1.2.0

func (a *Actions) MigrateTest(ctx context.Context) error

MigrateTest runs the GitHub Action for "ariga/atlas-action/migrate/test"

func (*Actions) MonitorSchema added in v1.3.9

func (a *Actions) MonitorSchema(ctx context.Context) error

MonitorSchema runs the Action for "ariga/atlas-action/monitor/schema"

func (*Actions) RequiredInputs added in v1.3.0

func (a *Actions) RequiredInputs(input ...string) error

RequiredInputs returns an error if any of the given inputs are missing.

func (*Actions) Run added in v1.3.0

func (a *Actions) Run(ctx context.Context, act string) error

Run runs the action based on the command name.

func (*Actions) SchemaApply added in v1.3.0

func (a *Actions) SchemaApply(ctx context.Context) error

SchemaApply runs the GitHub Action for "ariga/atlas-action/schema/apply"

func (*Actions) SchemaPlan added in v1.3.0

func (a *Actions) SchemaPlan(ctx context.Context) error

SchemaPlan runs the GitHub Action for "ariga/atlas-action/schema/plan"

func (*Actions) SchemaPlanApprove added in v1.3.0

func (a *Actions) SchemaPlanApprove(ctx context.Context) error

SchemaPlanApprove runs the GitHub Action for "ariga/atlas-action/schema/plan/approve"

func (*Actions) SchemaPush added in v1.3.0

func (a *Actions) SchemaPush(ctx context.Context) error

SchemaPush runs the GitHub Action for "ariga/atlas-action/schema/push"

func (*Actions) SchemaTest added in v1.2.0

func (a *Actions) SchemaTest(ctx context.Context) error

SchemaTest runs the GitHub Action for "ariga/atlas-action/schema/test"

func (*Actions) WorkingDir added in v1.2.0

func (a *Actions) WorkingDir() string

WorkingDir returns the working directory for the action.

type Actor added in v1.0.10

type Actor struct {
	Name string // Username of the actor.
	ID   string // ID of the actor on the SCM.
}

Actor holds the actor information.

type AtlasExec added in v1.2.0

type AtlasExec interface {
	// Version returns the version of the atlas binary.
	Version(ctx context.Context) (*atlasexec.Version, error)
	// Login runs the `login` command.
	Login(ctx context.Context, params *atlasexec.LoginParams) error
	// MigrateStatus runs the `migrate status` command.
	MigrateStatus(context.Context, *atlasexec.MigrateStatusParams) (*atlasexec.MigrateStatus, error)
	// MigrateApplySlice runs the `migrate apply` command and returns the successful runs.
	MigrateApplySlice(context.Context, *atlasexec.MigrateApplyParams) ([]*atlasexec.MigrateApply, error)
	// MigrateDown runs the `migrate down` command.
	MigrateDown(context.Context, *atlasexec.MigrateDownParams) (*atlasexec.MigrateDown, error)
	// MigrateLintError runs the `migrate lint` command and fails if there are lint errors.
	MigrateLintError(context.Context, *atlasexec.MigrateLintParams) error
	// MigratePush runs the `migrate push` command.
	MigratePush(context.Context, *atlasexec.MigratePushParams) (string, error)
	// MigrateTest runs the `migrate test` command.
	MigrateTest(context.Context, *atlasexec.MigrateTestParams) (string, error)
	// SchemaInspect runs the `schema inspect` command.
	SchemaInspect(ctx context.Context, params *atlasexec.SchemaInspectParams) (string, error)
	// SchemaPush runs the `schema push` command.
	SchemaPush(context.Context, *atlasexec.SchemaPushParams) (*atlasexec.SchemaPush, error)
	// SchemaTest runs the `schema test` command.
	SchemaTest(context.Context, *atlasexec.SchemaTestParams) (string, error)
	// SchemaPlan runs the `schema plan` command.
	SchemaPlan(context.Context, *atlasexec.SchemaPlanParams) (*atlasexec.SchemaPlan, error)
	// SchemaPlanList runs the `schema plan list` command.
	SchemaPlanList(context.Context, *atlasexec.SchemaPlanListParams) ([]atlasexec.SchemaPlanFile, error)
	// SchemaPlanLint runs the `schema plan lint` command.
	SchemaPlanLint(context.Context, *atlasexec.SchemaPlanLintParams) (*atlasexec.SchemaPlan, error)
	// SchemaPlanApprove runs the `schema plan approve` command.
	SchemaPlanApprove(context.Context, *atlasexec.SchemaPlanApproveParams) (*atlasexec.SchemaPlanApprove, error)
	// SchemaApplySlice runs the `schema apply` command.
	SchemaApplySlice(context.Context, *atlasexec.SchemaApplyParams) ([]*atlasexec.SchemaApply, error)
}

AtlasExec is the interface for the atlas exec client.

type CloudClient added in v1.3.9

type CloudClient interface {
	// SnapshotHash returns the latest snapshot hash for a monitored schema.
	SnapshotHash(context.Context, *cloud.SnapshotHashInput) (string, error)
	// PushSnapshot pushes a new snapshot version of a monitored schema to the cloud.
	PushSnapshot(context.Context, *cloud.PushSnapshotInput) (string, error)
}

CloudClient lets an action talk to Atlas Cloud.

type Logger added in v1.1.0

type Logger interface {
	// Infof logs an info message.
	Infof(string, ...interface{})
	// Warningf logs a warning message.
	Warningf(string, ...interface{})
	// Errorf logs an error message.
	Errorf(string, ...interface{})
	// Fatalf logs a fatal error message and exits the action.
	Fatalf(string, ...interface{})
}

type Option added in v1.3.9

type Option func(*config)

func WithAction added in v1.3.9

func WithAction(a Action) Option

WithAction sets the Action to use.

func WithAtlas added in v1.3.9

func WithAtlas(a AtlasExec) Option

WithAtlas sets the AtlasExec to use.

func WithAtlasPath added in v1.3.10

func WithAtlasPath(bin string) Option

WithAtlasPath sets the path to the atlas binary.

func WithCloudClient added in v1.3.9

func WithCloudClient[T CloudClient](cc func(token, version, cliVersion string) T) Option

WithCloudClient specifies how to obtain a CloudClient given the name of the token input variable.

func WithGetenv added in v1.3.9

func WithGetenv(getenv func(string) string) Option

WithGetenv specifies how to obtain environment variables.

func WithOut added in v1.3.9

func WithOut(out io.Writer) Option

WithOut specifies where to print to.

func WithRuntimeAction added in v1.3.10

func WithRuntimeAction() Option

WithRuntimeAction detects the action based on the environment.

func WithVersion added in v1.3.9

func WithVersion(v string) Option

WithVersion specifies the version of the Actions.

type PullRequest added in v1.1.0

type PullRequest struct {
	Number int    // Pull Request Number
	URL    string // URL of the pull request. e.g "https://github.com/ariga/atlas-action/pull/1"
	Commit string // Latest commit SHA.
	Body   string // Body (description) of the pull request.
}

PullRequest holds the pull request information.

func (*PullRequest) AtlasDirectives added in v1.3.5

func (p *PullRequest) AtlasDirectives() (ds []string)

AtlasDirectives returns any directives that are present in the pull request body. For example:

/atlas:nolint destructive

type Reporter added in v1.4.0

type Reporter interface {
	MigrateApply(context.Context, *atlasexec.MigrateApply)
	MigrateLint(context.Context, *atlasexec.SummaryReport)
	SchemaPlan(context.Context, *atlasexec.SchemaPlan)
	SchemaApply(context.Context, *atlasexec.SchemaApply)
}

Reporter is an interface for reporting the status of the actions.

type SCM added in v1.1.0

type SCM struct {
	Type   atlasexec.SCMType // Type of the SCM, e.g. "GITHUB" / "GITLAB" / "BITBUCKET".
	APIURL string            // APIURL is the base URL for the SCM API.
}

SCM holds the source control management system information.

type SCMClient added in v1.3.5

type SCMClient interface {
	// CommentLint comments on the pull request with the lint report.
	CommentLint(context.Context, *TriggerContext, *atlasexec.SummaryReport) error
	// CommentPlan comments on the pull request with the schema plan.
	CommentPlan(context.Context, *TriggerContext, *atlasexec.SchemaPlan) error
}

SCMClient contains methods for interacting with SCM platforms (GitHub, Gitlab etc...).

type Suggestion added in v1.2.0

type Suggestion struct {
	ID        string // Suggestion ID.
	Path      string // File path.
	StartLine int    // Start line numbers for the suggestion.
	Line      int    // End line number for the suggestion.
	Comment   string // Comment body.
}

type TriggerContext added in v1.1.0

type TriggerContext struct {
	Act         Action       // Act is the action that is running.
	SCM         SCM          // SCM is the source control management system.
	Repo        string       // Repo is the repository name. e.g. "ariga/atlas-action".
	RepoURL     string       // RepoURL is full URL of the repository. e.g. "https://github.com/ariga/atlas-action".
	Branch      string       // Branch name.
	Commit      string       // Commit SHA.
	PullRequest *PullRequest // PullRequest will be available if the event is "pull_request".
	Actor       *Actor       // Actor is the user who triggered the action.
	RerunCmd    string       // RerunCmd is the command to rerun the action.
}

TriggerContext holds the context of the environment the action is running in.

func (*TriggerContext) GetRunContext added in v1.4.0

func (tc *TriggerContext) GetRunContext() *atlasexec.RunContext

GetRunContext returns the run context for the action.

func (*TriggerContext) SCMClient added in v1.4.0

func (tc *TriggerContext) SCMClient() (SCMClient, error)

SCMClient returns a Client to interact with the SCM.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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