diff --git a/README.md b/README.md index b6d0bc52fa..ca4782e38e 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,7 @@ The following commands help you understand and effectively use the Tekton CLI: - [`tkn hub:`](docs/cmd/tkn_hub.md) Search and install Tekton Resources from [Hub](https://hub.tekton.dev) - [`tkn pipeline:`](docs/cmd/tkn_pipeline.md) Parent command of the Pipeline command group. - [`tkn pipelinerun:`](docs/cmd/tkn_pipelinerun.md) Parent command of the Pipelinerun command group. +- [`tkn stepaction:`](docs/cmd/tkn_stepaction.md) Parent command of the StepAction command group. - [`tkn task:`](docs/cmd/tkn_task.md) Parent command of the Task command group. - [`tkn taskrun:`](docs/cmd/tkn_taskrun.md) Parent command of the Taskrun command group. - [`tkn triggerbinding:`](docs/cmd/tkn_triggerbinding.md) Parent command of the Triggerbinding command group. diff --git a/docs/cmd/tkn.md b/docs/cmd/tkn.md index baa43b9694..c8c6b5250b 100644 --- a/docs/cmd/tkn.md +++ b/docs/cmd/tkn.md @@ -28,6 +28,7 @@ CLI for tekton pipelines * [tkn hub](tkn_hub.md) - Interact with artifacthub * [tkn pipeline](tkn_pipeline.md) - Manage pipelines * [tkn pipelinerun](tkn_pipelinerun.md) - Manage PipelineRuns +* [tkn stepaction](tkn_stepaction.md) - Manage StepActions * [tkn task](tkn_task.md) - Manage Tasks * [tkn taskrun](tkn_taskrun.md) - Manage TaskRuns * [tkn triggerbinding](tkn_triggerbinding.md) - Manage TriggerBindings diff --git a/docs/cmd/tkn_stepaction.md b/docs/cmd/tkn_stepaction.md new file mode 100644 index 0000000000..ca0a16dfa9 --- /dev/null +++ b/docs/cmd/tkn_stepaction.md @@ -0,0 +1,33 @@ +## tkn stepaction + +Manage StepActions + +***Aliases**: stepactions* + +### Usage + +``` +tkn stepaction +``` + +### Synopsis + +Manage StepActions + +### Options + +``` + -c, --context string name of the kubeconfig context to use (default: kubectl config current-context) + -h, --help help for stepaction + -k, --kubeconfig string kubectl config file (default: $HOME/.kube/config) + -n, --namespace string namespace to use (default: from $KUBECONFIG) + -C, --no-color disable coloring (default: false) +``` + +### SEE ALSO + +* [tkn](tkn.md) - CLI for tekton pipelines +* [tkn stepaction delete](tkn_stepaction_delete.md) - Delete StepActions in a namespace +* [tkn stepaction describe](tkn_stepaction_describe.md) - Describe a StepAction in a namespace +* [tkn stepaction list](tkn_stepaction_list.md) - Lists StepActions in a namespace + diff --git a/docs/cmd/tkn_stepaction_delete.md b/docs/cmd/tkn_stepaction_delete.md new file mode 100644 index 0000000000..83abff3bff --- /dev/null +++ b/docs/cmd/tkn_stepaction_delete.md @@ -0,0 +1,55 @@ +## tkn stepaction delete + +Delete StepActions in a namespace + +***Aliases**: rm* + +### Usage + +``` +tkn stepaction delete +``` + +### Synopsis + +Delete StepActions in a namespace + +### Examples + +Delete StepAction with name 'foo' in namespace 'bar': + + tkn stepaction delete foo -n bar + +or + + tkn stepaction rm foo -n bar + +Delete a StepAction and print the result as JSON: + + tkn stepaction delete foo -n bar -o json + +Delete a StepAction and print the result as YAML: + + tkn stepaction delete foo -n bar -o yaml + + +### Options + +``` + -h, --help help for delete + -o, --output string Output format. One of: json|yaml +``` + +### Options inherited from parent commands + +``` + -c, --context string name of the kubeconfig context to use (default: kubectl config current-context) + -k, --kubeconfig string kubectl config file (default: $HOME/.kube/config) + -n, --namespace string namespace to use (default: from $KUBECONFIG) + -C, --no-color disable coloring (default: false) +``` + +### SEE ALSO + +* [tkn stepaction](tkn_stepaction.md) - Manage StepActions + diff --git a/docs/cmd/tkn_stepaction_describe.md b/docs/cmd/tkn_stepaction_describe.md new file mode 100644 index 0000000000..9bc055386d --- /dev/null +++ b/docs/cmd/tkn_stepaction_describe.md @@ -0,0 +1,60 @@ +## tkn stepaction describe + +Describe a StepAction in a namespace + +***Aliases**: desc* + +### Usage + +``` +tkn stepaction describe +``` + +### Synopsis + +Describe a StepAction in a namespace + +### Examples + +Describe a StepAction of name 'foo' in namespace 'bar': + + tkn stepaction describe foo -n bar + +or + + tkn stepaction desc foo -n bar + +Describe a StepAction as JSON: + + tkn stepaction describe foo -n bar -o json + +Describe a StepAction as YAML: + + tkn stepaction describe foo -n bar -o yaml + + +### Options + +``` + --allow-missing-template-keys If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. (default true) + -F, --fzf use fzf to select a StepAction to describe + -h, --help help for describe + --limit int lists number of StepActions when selecting a StepAction to describe (default 5) + -o, --output string Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). + --show-managed-fields If true, keep the managedFields when printing objects in JSON or YAML format. + --template string Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. +``` + +### Options inherited from parent commands + +``` + -c, --context string name of the kubeconfig context to use (default: kubectl config current-context) + -k, --kubeconfig string kubectl config file (default: $HOME/.kube/config) + -n, --namespace string namespace to use (default: from $KUBECONFIG) + -C, --no-color disable coloring (default: false) +``` + +### SEE ALSO + +* [tkn stepaction](tkn_stepaction.md) - Manage StepActions + diff --git a/docs/cmd/tkn_stepaction_list.md b/docs/cmd/tkn_stepaction_list.md new file mode 100644 index 0000000000..c2dd95b105 --- /dev/null +++ b/docs/cmd/tkn_stepaction_list.md @@ -0,0 +1,59 @@ +## tkn stepaction list + +Lists StepActions in a namespace + +***Aliases**: ls* + +### Usage + +``` +tkn stepaction list +``` + +### Synopsis + +Lists StepActions in a namespace + +### Examples + +List all StepActions in namespace 'bar': + + tkn stepaction list -n bar + +List StepActions as a JSON array: + + tkn stepaction list -o json + +List StepActions as a YAML array: + + tkn stepaction list -o yaml + + +### Options + +``` + -A, --all-namespaces list StepActions from all namespaces + --allow-missing-template-keys If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. (default true) + -h, --help help for list + --label string A selector (label query) to filter on, supports '=', '==', and '!=' + --limit int Limits the number of StepActions. If the limit value is 0 returns all + --no-headers do not print column headers with output (default print column headers with output) + -o, --output string Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file). + --reverse list StepActions in reverse order + --show-managed-fields If true, keep the managedFields when printing objects in JSON or YAML format. + --template string Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. +``` + +### Options inherited from parent commands + +``` + -c, --context string name of the kubeconfig context to use (default: kubectl config current-context) + -k, --kubeconfig string kubectl config file (default: $HOME/.kube/config) + -n, --namespace string namespace to use (default: from $KUBECONFIG) + -C, --no-color disable coloring (default: false) +``` + +### SEE ALSO + +* [tkn stepaction](tkn_stepaction.md) - Manage StepActions + diff --git a/docs/man/man1/tkn-stepaction-delete.1 b/docs/man/man1/tkn-stepaction-delete.1 new file mode 100644 index 0000000000..b3392cbc78 --- /dev/null +++ b/docs/man/man1/tkn-stepaction-delete.1 @@ -0,0 +1,101 @@ +.TH "TKN\-STEPACTION\-DELETE" "1" "" "Auto generated by spf13/cobra" "" +.nh +.ad l + + +.SH NAME +.PP +tkn\-stepaction\-delete \- Delete StepActions in a namespace + + +.SH SYNOPSIS +.PP +\fBtkn stepaction delete\fP + + +.SH DESCRIPTION +.PP +Delete StepActions in a namespace + + +.SH OPTIONS +.PP +\fB\-h\fP, \fB\-\-help\fP[=false] + help for delete + +.PP +\fB\-o\fP, \fB\-\-output\fP="" + Output format. One of: json|yaml + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB\-c\fP, \fB\-\-context\fP="" + name of the kubeconfig context to use (default: kubectl config current\-context) + +.PP +\fB\-k\fP, \fB\-\-kubeconfig\fP="" + kubectl config file (default: $HOME/.kube/config) + +.PP +\fB\-n\fP, \fB\-\-namespace\fP="" + namespace to use (default: from $KUBECONFIG) + +.PP +\fB\-C\fP, \fB\-\-no\-color\fP[=false] + disable coloring (default: false) + + +.SH EXAMPLE +.PP +Delete StepAction with name 'foo' in namespace 'bar': + +.PP +.RS + +.nf +tkn stepaction delete foo \-n bar + +.fi +.RE + +.PP +or + +.PP +.RS + +.nf +tkn stepaction rm foo \-n bar + +.fi +.RE + +.PP +Delete a StepAction and print the result as JSON: + +.PP +.RS + +.nf +tkn stepaction delete foo \-n bar \-o json + +.fi +.RE + +.PP +Delete a StepAction and print the result as YAML: + +.PP +.RS + +.nf +tkn stepaction delete foo \-n bar \-o yaml + +.fi +.RE + + +.SH SEE ALSO +.PP +\fBtkn\-stepaction(1)\fP diff --git a/docs/man/man1/tkn-stepaction-describe.1 b/docs/man/man1/tkn-stepaction-describe.1 new file mode 100644 index 0000000000..3524f7c422 --- /dev/null +++ b/docs/man/man1/tkn-stepaction-describe.1 @@ -0,0 +1,122 @@ +.TH "TKN\-STEPACTION\-DESCRIBE" "1" "" "Auto generated by spf13/cobra" "" +.nh +.ad l + + +.SH NAME +.PP +tkn\-stepaction\-describe \- Describe a StepAction in a namespace + + +.SH SYNOPSIS +.PP +\fBtkn stepaction describe\fP + + +.SH DESCRIPTION +.PP +Describe a StepAction in a namespace + + +.SH OPTIONS +.PP +\fB\-\-allow\-missing\-template\-keys\fP[=true] + If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. + +.PP +\fB\-F\fP, \fB\-\-fzf\fP[=false] + use fzf to select a StepAction to describe + +.PP +\fB\-h\fP, \fB\-\-help\fP[=false] + help for describe + +.PP +\fB\-\-limit\fP=5 + lists number of StepActions when selecting a StepAction to describe + +.PP +\fB\-o\fP, \fB\-\-output\fP="" + Output format. One of: (json, yaml, name, go\-template, go\-template\-file, template, templatefile, jsonpath, jsonpath\-as\-json, jsonpath\-file). + +.PP +\fB\-\-show\-managed\-fields\fP[=false] + If true, keep the managedFields when printing objects in JSON or YAML format. + +.PP +\fB\-\-template\fP="" + Template string or path to template file to use when \-o=go\-template, \-o=go\-template\-file. The template format is golang templates [ +\[la]http://golang.org/pkg/text/template/#pkg-overview\[ra]]. + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB\-c\fP, \fB\-\-context\fP="" + name of the kubeconfig context to use (default: kubectl config current\-context) + +.PP +\fB\-k\fP, \fB\-\-kubeconfig\fP="" + kubectl config file (default: $HOME/.kube/config) + +.PP +\fB\-n\fP, \fB\-\-namespace\fP="" + namespace to use (default: from $KUBECONFIG) + +.PP +\fB\-C\fP, \fB\-\-no\-color\fP[=false] + disable coloring (default: false) + + +.SH EXAMPLE +.PP +Describe a StepAction of name 'foo' in namespace 'bar': + +.PP +.RS + +.nf +tkn stepaction describe foo \-n bar + +.fi +.RE + +.PP +or + +.PP +.RS + +.nf +tkn stepaction desc foo \-n bar + +.fi +.RE + +.PP +Describe a StepAction as JSON: + +.PP +.RS + +.nf +tkn stepaction describe foo \-n bar \-o json + +.fi +.RE + +.PP +Describe a StepAction as YAML: + +.PP +.RS + +.nf +tkn stepaction describe foo \-n bar \-o yaml + +.fi +.RE + + +.SH SEE ALSO +.PP +\fBtkn\-stepaction(1)\fP diff --git a/docs/man/man1/tkn-stepaction-list.1 b/docs/man/man1/tkn-stepaction-list.1 new file mode 100644 index 0000000000..45c66b2cf7 --- /dev/null +++ b/docs/man/man1/tkn-stepaction-list.1 @@ -0,0 +1,122 @@ +.TH "TKN\-STEPACTION\-LIST" "1" "" "Auto generated by spf13/cobra" "" +.nh +.ad l + + +.SH NAME +.PP +tkn\-stepaction\-list \- Lists StepActions in a namespace + + +.SH SYNOPSIS +.PP +\fBtkn stepaction list\fP + + +.SH DESCRIPTION +.PP +Lists StepActions in a namespace + + +.SH OPTIONS +.PP +\fB\-A\fP, \fB\-\-all\-namespaces\fP[=false] + list StepActions from all namespaces + +.PP +\fB\-\-allow\-missing\-template\-keys\fP[=true] + If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. + +.PP +\fB\-h\fP, \fB\-\-help\fP[=false] + help for list + +.PP +\fB\-\-label\fP="" + A selector (label query) to filter on, supports '=', '==', and '!=' + +.PP +\fB\-\-limit\fP=0 + Limits the number of StepActions. If the limit value is 0 returns all + +.PP +\fB\-\-no\-headers\fP[=false] + do not print column headers with output (default print column headers with output) + +.PP +\fB\-o\fP, \fB\-\-output\fP="" + Output format. One of: (json, yaml, name, go\-template, go\-template\-file, template, templatefile, jsonpath, jsonpath\-as\-json, jsonpath\-file). + +.PP +\fB\-\-reverse\fP[=false] + list StepActions in reverse order + +.PP +\fB\-\-show\-managed\-fields\fP[=false] + If true, keep the managedFields when printing objects in JSON or YAML format. + +.PP +\fB\-\-template\fP="" + Template string or path to template file to use when \-o=go\-template, \-o=go\-template\-file. The template format is golang templates [ +\[la]http://golang.org/pkg/text/template/#pkg-overview\[ra]]. + + +.SH OPTIONS INHERITED FROM PARENT COMMANDS +.PP +\fB\-c\fP, \fB\-\-context\fP="" + name of the kubeconfig context to use (default: kubectl config current\-context) + +.PP +\fB\-k\fP, \fB\-\-kubeconfig\fP="" + kubectl config file (default: $HOME/.kube/config) + +.PP +\fB\-n\fP, \fB\-\-namespace\fP="" + namespace to use (default: from $KUBECONFIG) + +.PP +\fB\-C\fP, \fB\-\-no\-color\fP[=false] + disable coloring (default: false) + + +.SH EXAMPLE +.PP +List all StepActions in namespace 'bar': + +.PP +.RS + +.nf +tkn stepaction list \-n bar + +.fi +.RE + +.PP +List StepActions as a JSON array: + +.PP +.RS + +.nf +tkn stepaction list \-o json + +.fi +.RE + +.PP +List StepActions as a YAML array: + +.PP +.RS + +.nf +tkn stepaction list \-o yaml + +.fi +.RE + + +.SH SEE ALSO +.PP +\fBtkn\-stepaction(1)\fP diff --git a/docs/man/man1/tkn-stepaction.1 b/docs/man/man1/tkn-stepaction.1 new file mode 100644 index 0000000000..f1046f8345 --- /dev/null +++ b/docs/man/man1/tkn-stepaction.1 @@ -0,0 +1,45 @@ +.TH "TKN\-STEPACTION" "1" "" "Auto generated by spf13/cobra" "" +.nh +.ad l + + +.SH NAME +.PP +tkn\-stepaction \- Manage StepActions + + +.SH SYNOPSIS +.PP +\fBtkn stepaction\fP + + +.SH DESCRIPTION +.PP +Manage StepActions + + +.SH OPTIONS +.PP +\fB\-c\fP, \fB\-\-context\fP="" + name of the kubeconfig context to use (default: kubectl config current\-context) + +.PP +\fB\-h\fP, \fB\-\-help\fP[=false] + help for stepaction + +.PP +\fB\-k\fP, \fB\-\-kubeconfig\fP="" + kubectl config file (default: $HOME/.kube/config) + +.PP +\fB\-n\fP, \fB\-\-namespace\fP="" + namespace to use (default: from $KUBECONFIG) + +.PP +\fB\-C\fP, \fB\-\-no\-color\fP[=false] + disable coloring (default: false) + + +.SH SEE ALSO +.PP +\fBtkn(1)\fP, \fBtkn\-stepaction\-delete(1)\fP, \fBtkn\-stepaction\-describe(1)\fP, \fBtkn\-stepaction\-list(1)\fP diff --git a/docs/man/man1/tkn.1 b/docs/man/man1/tkn.1 index 25881394bd..1b0b3a6080 100644 --- a/docs/man/man1/tkn.1 +++ b/docs/man/man1/tkn.1 @@ -26,4 +26,4 @@ CLI for tekton pipelines .SH SEE ALSO .PP -\fBtkn\-bundle(1)\fP, \fBtkn\-clustertriggerbinding(1)\fP, \fBtkn\-completion(1)\fP, \fBtkn\-customrun(1)\fP, \fBtkn\-eventlistener(1)\fP, \fBtkn\-hub(1)\fP, \fBtkn\-pipeline(1)\fP, \fBtkn\-pipelinerun(1)\fP, \fBtkn\-task(1)\fP, \fBtkn\-taskrun(1)\fP, \fBtkn\-triggerbinding(1)\fP, \fBtkn\-triggertemplate(1)\fP, \fBtkn\-version(1)\fP +\fBtkn\-bundle(1)\fP, \fBtkn\-clustertriggerbinding(1)\fP, \fBtkn\-completion(1)\fP, \fBtkn\-customrun(1)\fP, \fBtkn\-eventlistener(1)\fP, \fBtkn\-hub(1)\fP, \fBtkn\-pipeline(1)\fP, \fBtkn\-pipelinerun(1)\fP, \fBtkn\-stepaction(1)\fP, \fBtkn\-task(1)\fP, \fBtkn\-taskrun(1)\fP, \fBtkn\-triggerbinding(1)\fP, \fBtkn\-triggertemplate(1)\fP, \fBtkn\-version(1)\fP diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index d84dfea33f..2a7570f82f 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -34,6 +34,7 @@ import ( hub "github.com/tektoncd/cli/pkg/cmd/hub/cmd" "github.com/tektoncd/cli/pkg/cmd/pipeline" "github.com/tektoncd/cli/pkg/cmd/pipelinerun" + "github.com/tektoncd/cli/pkg/cmd/stepaction" "github.com/tektoncd/cli/pkg/cmd/task" "github.com/tektoncd/cli/pkg/cmd/taskrun" "github.com/tektoncd/cli/pkg/cmd/triggerbinding" @@ -117,6 +118,7 @@ func Root(p cli.Params) *cobra.Command { eventlistener.Command(p), pipeline.Command(p), pipelinerun.Command(p), + stepaction.Command(p), task.Command(p), taskrun.Command(p), customrun.Command(p), diff --git a/pkg/cmd/stepaction/delete.go b/pkg/cmd/stepaction/delete.go new file mode 100644 index 0000000000..897b4a11fe --- /dev/null +++ b/pkg/cmd/stepaction/delete.go @@ -0,0 +1,130 @@ +// Copyright © 2026 The Tekton Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package stepaction + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + "github.com/tektoncd/cli/pkg/actions" + "github.com/tektoncd/cli/pkg/cli" + "github.com/tektoncd/cli/pkg/exitcode" + "github.com/tektoncd/cli/pkg/formatted" + "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + "go.uber.org/multierr" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func stepActionExists(client *cli.Clients, namespace, name string) error { + var sa *v1beta1.StepAction + if err := actions.GetV1(stepactionGroupResource, client, name, namespace, metav1.GetOptions{}, &sa); err != nil { + if !errors.IsNotFound(err) { + return err + } + return &exitcode.Error{Code: exitcode.NotFound, Message: fmt.Sprintf("StepAction %s not found in namespace %s", name, namespace), Err: err} + } + return nil +} + +func deleteCommand(p cli.Params) *cobra.Command { + eg := `Delete StepAction with name 'foo' in namespace 'bar': + + tkn stepaction delete foo -n bar + +or + + tkn stepaction rm foo -n bar + +Delete a StepAction and print the result as JSON: + + tkn stepaction delete foo -n bar -o json + +Delete a StepAction and print the result as YAML: + + tkn stepaction delete foo -n bar -o yaml +` + + output := "" + + c := &cobra.Command{ + Use: "delete", + Aliases: []string{"rm"}, + Short: "Delete StepActions in a namespace", + Example: eg, + Args: cobra.MinimumNArgs(1), + Annotations: map[string]string{ + "commandType": "main", + }, + RunE: func(cmd *cobra.Command, args []string) error { + s := &cli.Stream{ + In: cmd.InOrStdin(), + Out: cmd.OutOrStdout(), + Err: cmd.OutOrStderr(), + } + + if output != "" { + output = formatted.NormalizeOutput(output) + if !formatted.IsStructured(output) { + return exitcode.New(exitcode.InvalidInput, "invalid output format %q: must be json or yaml", output) + } + } + + return deleteStepActions(s, p, args, output) + }, + } + + c.Flags().StringVarP(&output, "output", "o", "", formatted.OutputFlagUsage) + return c +} + +func deleteStepActions(s *cli.Stream, p cli.Params, names []string, output string) error { + cs, err := p.Clients() + if err != nil { + return fmt.Errorf("failed to create tekton client: %w", err) + } + namespace := p.Namespace() + var deleted []string + var deleteErr error + for _, name := range names { + if err := stepActionExists(cs, namespace, name); err != nil { + deleteErr = multierr.Append(deleteErr, err) + continue + } + if err := deleteStepAction(cs, namespace, name); err != nil { + deleteErr = multierr.Append(deleteErr, err) + continue + } + deleted = append(deleted, name) + if !formatted.IsStructured(output) { + fmt.Fprintf(s.Out, "StepAction '%s' deleted successfully from namespace '%s'\n", name, namespace) + } + } + + if formatted.IsStructured(output) { + if err := formatted.PrintStructuredOutput(s.Out, output, formatted.NewDeleteResult(deleted)); err != nil { + return err + } + } + return deleteErr +} + +func deleteStepAction(cs *cli.Clients, namespace, name string) error { + if err := cs.Dynamic.Resource(stepactionGroupResource).Namespace(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{}); err != nil { + return fmt.Errorf("failed to delete StepAction %s: %w", name, err) + } + return nil +} diff --git a/pkg/cmd/stepaction/describe.go b/pkg/cmd/stepaction/describe.go new file mode 100644 index 0000000000..fcb3e3e1aa --- /dev/null +++ b/pkg/cmd/stepaction/describe.go @@ -0,0 +1,256 @@ +// Copyright © 2026 The Tekton Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package stepaction + +import ( + "fmt" + "io" + "os" + "sort" + "text/tabwriter" + "text/template" + + "github.com/spf13/cobra" + "github.com/tektoncd/cli/pkg/actions" + "github.com/tektoncd/cli/pkg/cli" + "github.com/tektoncd/cli/pkg/formatted" + "github.com/tektoncd/cli/pkg/options" + "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + cliopts "k8s.io/cli-runtime/pkg/genericclioptions" +) + +const ( + describeTemplate = `{{decorate "bold" "Name"}}: {{ .StepAction.Name }} +{{decorate "bold" "Namespace"}}: {{ .StepAction.Namespace }} +{{- if ne .StepAction.Spec.Description "" }} +{{decorate "bold" "Description"}}: {{ .StepAction.Spec.Description }} +{{- end }} +{{- if ne .StepAction.Spec.Image "" }} +{{decorate "bold" "Image"}}: {{ .StepAction.Spec.Image }} +{{- end }} +{{- if ne (len .StepAction.Spec.Command) 0 }} +{{decorate "bold" "Command"}}: {{ .StepAction.Spec.Command }} +{{- end }} +{{- if ne (len .StepAction.Spec.Args) 0 }} +{{decorate "bold" "Args"}}: {{ .StepAction.Spec.Args }} +{{- end }} +{{- if ne .StepAction.Spec.WorkingDir "" }} +{{decorate "bold" "Working Dir"}}: {{ .StepAction.Spec.WorkingDir }} +{{- end }} +{{- if ne .StepAction.Spec.Script "" }} +{{decorate "bold" "Script"}}: {{ "set" }} +{{- end }} +{{- $l := len .StepAction.Labels }}{{ if ne $l 0 }} +{{decorate "bold" "Labels"}}: +{{- range $k, $v := .StepAction.Labels }} + {{ $k }}={{ $v }} +{{- end }} +{{- end }} +{{- $annotations := removeLastAppliedConfig .StepAction.Annotations -}} +{{- if $annotations }} +{{decorate "bold" "Annotations"}}: +{{- range $k, $v := $annotations }} + {{ $k }}={{ $v }} +{{- end }} +{{- end }} + +{{- if ne (len .StepAction.Spec.Params) 0 }} + +{{decorate "params" ""}}{{decorate "underline bold" "Params\n"}} + NAME TYPE DESCRIPTION DEFAULT VALUE +{{- range $p := .StepAction.Spec.Params }} +{{- if not $p.Default }} + {{decorate "bullet" $p.Name }} {{ $p.Type }} {{ formatDesc $p.Description }} {{ "---" }} +{{- else }} +{{- if eq $p.Type "string" }} + {{decorate "bullet" $p.Name }} {{ $p.Type }} {{ formatDesc $p.Description }} {{ $p.Default.StringVal }} +{{- else if eq $p.Type "array" }} + {{decorate "bullet" $p.Name }} {{ $p.Type }} {{ formatDesc $p.Description }} {{ $p.Default.ArrayVal }} +{{- else }} + {{decorate "bullet" $p.Name }} {{ $p.Type }} {{ formatDesc $p.Description }} {{ $p.Default.ObjectVal }} +{{- end }} +{{- end }} +{{- end }} +{{- end }} + +{{- if ne (len .StepAction.Spec.Results) 0 }} + +{{decorate "results" ""}}{{decorate "underline bold" "Results\n"}} + NAME TYPE DESCRIPTION +{{- range $result := .StepAction.Spec.Results }} + {{ decorate "bullet" $result.Name }} {{ resultType $result.Type }} {{ formatDesc $result.Description }} +{{- end }} +{{- end }} +` + defaultStepActionDescribeLimit = 5 +) + +func describeCommand(p cli.Params) *cobra.Command { + opts := &options.DescribeOptions{Params: p} + f := cliopts.NewPrintFlags("describe") + eg := `Describe a StepAction of name 'foo' in namespace 'bar': + + tkn stepaction describe foo -n bar + +or + + tkn stepaction desc foo -n bar + +Describe a StepAction as JSON: + + tkn stepaction describe foo -n bar -o json + +Describe a StepAction as YAML: + + tkn stepaction describe foo -n bar -o yaml +` + + c := &cobra.Command{ + Use: "describe", + Aliases: []string{"desc"}, + Short: "Describe a StepAction in a namespace", + Example: eg, + SilenceUsage: true, + Annotations: map[string]string{ + "commandType": "main", + }, + ValidArgsFunction: formatted.ParentCompletion, + RunE: func(cmd *cobra.Command, args []string) error { + output, err := cmd.LocalFlags().GetString("output") + if err != nil { + return fmt.Errorf("output option not set properly: %v", err) + } + + if !opts.Fzf { + if _, ok := os.LookupEnv("TKN_USE_FZF"); ok { + opts.Fzf = true + } + } + + cs, err := p.Clients() + if err != nil { + return err + } + + if len(args) == 0 { + names, err := getAllStepActionNames(cs, p.Namespace(), opts.Limit) + if err != nil { + return err + } + if len(names) == 1 { + opts.StepActionName = names[0] + } else if err := askStepActionName(opts, names); err != nil { + return err + } + } else { + opts.StepActionName = args[0] + } + + if output != "" { + printer, err := f.ToPrinter() + if err != nil { + return err + } + return actions.PrintObjectV1(stepactionGroupResource, opts.StepActionName, cmd.OutOrStdout(), cs, printer, p.Namespace()) + } + + return printStepActionDescription(cmd.OutOrStdout(), cs, p.Namespace(), opts.StepActionName) + }, + } + + c.Flags().IntVarP(&opts.Limit, "limit", "", defaultStepActionDescribeLimit, "lists number of StepActions when selecting a StepAction to describe") + c.Flags().BoolVarP(&opts.Fzf, "fzf", "F", false, "use fzf to select a StepAction to describe") + + f.AddFlags(c) + + return c +} + +func askStepActionName(opts *options.DescribeOptions, names []string) error { + if err := opts.ValidateOpts(); err != nil { + return err + } + if len(names) == 0 { + return fmt.Errorf("no StepActions found") + } + if opts.Fzf { + return opts.FuzzyAsk(options.ResourceNameStepAction, names) + } + return opts.Ask(options.ResourceNameStepAction, names) +} + +// getAllStepActionNames returns the StepAction names in a namespace in sorted +// order, keeping at most limit entries when limit is positive +func getAllStepActionNames(c *cli.Clients, ns string, limit int) ([]string, error) { + var sas *v1beta1.StepActionList + if err := actions.ListV1(stepactionGroupResource, c, metav1.ListOptions{}, ns, &sas); err != nil { + return nil, fmt.Errorf("failed to list StepActions from namespace %s: %w", ns, err) + } + + names := make([]string, 0, len(sas.Items)) + for _, sa := range sas.Items { + names = append(names, sa.Name) + } + sort.Strings(names) + if limit > 0 && len(names) > limit { + names = names[:limit] + } + return names, nil +} + +func getStepAction(c *cli.Clients, name, ns string) (*v1beta1.StepAction, error) { + var sa v1beta1.StepAction + if err := actions.GetV1(stepactionGroupResource, c, name, ns, metav1.GetOptions{}, &sa); err != nil { + return nil, err + } + return &sa, nil +} + +func printStepActionDescription(out io.Writer, c *cli.Clients, ns, name string) error { + sa, err := getStepAction(c, name, ns) + if err != nil { + return fmt.Errorf("failed to get StepAction %s: %w", name, err) + } + + data := struct { + StepAction *v1beta1.StepAction + }{ + StepAction: sa, + } + + funcMap := template.FuncMap{ + "decorate": formatted.DecorateAttr, + "formatDesc": formatted.FormatDesc, + "removeLastAppliedConfig": formatted.RemoveLastAppliedConfig, + "resultType": resultType, + } + + w := tabwriter.NewWriter(out, 0, 5, 3, ' ', tabwriter.TabIndent) + t := template.Must(template.New("Describe StepAction").Funcs(funcMap).Parse(describeTemplate)) + if err := t.Execute(w, data); err != nil { + return err + } + return w.Flush() +} + +// resultType shows the result type, which defaults to string when not set +func resultType(t interface{}) string { + s := fmt.Sprint(t) + if s == "" { + return "string" + } + return s +} diff --git a/pkg/cmd/stepaction/list.go b/pkg/cmd/stepaction/list.go new file mode 100644 index 0000000000..5e4b9a5a52 --- /dev/null +++ b/pkg/cmd/stepaction/list.go @@ -0,0 +1,206 @@ +// Copyright © 2026 The Tekton Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package stepaction + +import ( + "fmt" + "os" + "sort" + "text/tabwriter" + "text/template" + + "github.com/jonboulle/clockwork" + "github.com/spf13/cobra" + "github.com/tektoncd/cli/pkg/actions" + "github.com/tektoncd/cli/pkg/cli" + "github.com/tektoncd/cli/pkg/exitcode" + "github.com/tektoncd/cli/pkg/formatted" + "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + cliopts "k8s.io/cli-runtime/pkg/genericclioptions" +) + +const listTemplate = `{{- $sal := len .StepActions.Items -}}{{- if eq $sal 0 -}} +No StepActions found +{{ else -}} +{{- if not $.NoHeaders -}} +{{- if $.AllNamespaces -}} +NAMESPACE NAME DESCRIPTION AGE +{{ else -}} +NAME DESCRIPTION AGE +{{ end -}} +{{- end -}} +{{- range $_, $sa := .StepActions.Items -}}{{- if $.AllNamespaces -}} +{{ $sa.Namespace }} {{ $sa.Name }} {{ formatDesc $sa.Spec.Description }} {{ formatAge $sa.CreationTimestamp $.Time }} +{{ else -}} +{{ $sa.Name }} {{ formatDesc $sa.Spec.Description }} {{ formatAge $sa.CreationTimestamp $.Time }} +{{ end -}}{{- end -}} +{{- end -}} +` + +type listOptions struct { + Limit int + LabelSelector string + Reverse bool + AllNamespaces bool + NoHeaders bool +} + +func listCommand(p cli.Params) *cobra.Command { + opts := &listOptions{Limit: 0} + f := cliopts.NewPrintFlags("list") + eg := `List all StepActions in namespace 'bar': + + tkn stepaction list -n bar + +List StepActions as a JSON array: + + tkn stepaction list -o json + +List StepActions as a YAML array: + + tkn stepaction list -o yaml +` + + c := &cobra.Command{ + Use: "list", + Aliases: []string{"ls"}, + Short: "Lists StepActions in a namespace", + Annotations: map[string]string{ + "commandType": "main", + }, + Example: eg, + RunE: func(cmd *cobra.Command, _ []string) error { + if opts.Limit < 0 { + return exitcode.New(exitcode.InvalidInput, "limit was %d but must be a positive number", opts.Limit) + } + + sas, err := list(p, opts.Limit, opts.LabelSelector, opts.AllNamespaces) + if err != nil { + return fmt.Errorf("failed to list StepActions from namespace %s: %w", p.Namespace(), err) + } + + if opts.Reverse { + reverse(sas) + } + + output, err := cmd.LocalFlags().GetString("output") + if err != nil { + return fmt.Errorf("output option not set properly: %v", err) + } + if output == "name" { + w := cmd.OutOrStdout() + for _, sa := range sas.Items { + if _, err := fmt.Fprintf(w, "stepaction.tekton.dev/%s\n", sa.Name); err != nil { + return err + } + } + return nil + } else if output != "" { + printer, err := f.ToPrinter() + if err != nil { + return err + } + return printer.PrintObj(sas, cmd.OutOrStdout()) + } + + stream := &cli.Stream{ + Out: cmd.OutOrStdout(), + Err: cmd.OutOrStderr(), + } + if err := printFormatted(stream, sas, p.Time(), opts.AllNamespaces, opts.NoHeaders); err != nil { + fmt.Fprint(os.Stderr, "failed to print StepActions \n") + return err + } + return nil + }, + } + + f.AddFlags(c) + c.Flags().IntVarP(&opts.Limit, "limit", "", 0, "Limits the number of StepActions. If the limit value is 0 returns all") + c.Flags().StringVarP(&opts.LabelSelector, "label", "", opts.LabelSelector, "A selector (label query) to filter on, supports '=', '==', and '!='") + c.Flags().BoolVarP(&opts.Reverse, "reverse", "", opts.Reverse, "list StepActions in reverse order") + c.Flags().BoolVarP(&opts.AllNamespaces, "all-namespaces", "A", opts.AllNamespaces, "list StepActions from all namespaces") + c.Flags().BoolVarP(&opts.NoHeaders, "no-headers", "", opts.NoHeaders, "do not print column headers with output (default print column headers with output)") + return c +} + +func reverse(sas *v1beta1.StepActionList) { + for i, j := 0, len(sas.Items)-1; i < j; i, j = i+1, j-1 { + sas.Items[i], sas.Items[j] = sas.Items[j], sas.Items[i] + } +} + +func list(p cli.Params, limit int, labelSelector string, allNamespaces bool) (*v1beta1.StepActionList, error) { + options := metav1.ListOptions{} + if labelSelector != "" { + options.LabelSelector = labelSelector + } + + cs, err := p.Clients() + if err != nil { + return nil, err + } + + ns := p.Namespace() + if allNamespaces { + ns = "" + } + + var sas *v1beta1.StepActionList + if err := actions.ListV1(stepactionGroupResource, cs, options, ns, &sas); err != nil { + return nil, err + } + + // StepActions have no run time, so keep a stable order by namespace and name + sort.SliceStable(sas.Items, func(i, j int) bool { + if sas.Items[i].Namespace != sas.Items[j].Namespace { + return sas.Items[i].Namespace < sas.Items[j].Namespace + } + return sas.Items[i].Name < sas.Items[j].Name + }) + + if limit > 0 && len(sas.Items) > limit { + sas.Items = sas.Items[:limit] + } + + return sas, nil +} + +func printFormatted(s *cli.Stream, sas *v1beta1.StepActionList, c clockwork.Clock, allNamespaces bool, noHeaders bool) error { + data := struct { + StepActions *v1beta1.StepActionList + Time clockwork.Clock + AllNamespaces bool + NoHeaders bool + }{ + StepActions: sas, + Time: c, + AllNamespaces: allNamespaces, + NoHeaders: noHeaders, + } + + funcMap := template.FuncMap{ + "formatAge": formatted.Age, + "formatDesc": formatted.FormatDesc, + } + + w := tabwriter.NewWriter(s.Out, 0, 5, 3, ' ', tabwriter.TabIndent) + t := template.Must(template.New("List StepActions").Funcs(funcMap).Parse(listTemplate)) + if err := t.Execute(w, data); err != nil { + return err + } + return w.Flush() +} diff --git a/pkg/cmd/stepaction/stepaction.go b/pkg/cmd/stepaction/stepaction.go new file mode 100644 index 0000000000..619961bfa2 --- /dev/null +++ b/pkg/cmd/stepaction/stepaction.go @@ -0,0 +1,46 @@ +// Copyright © 2026 The Tekton Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package stepaction + +import ( + "github.com/spf13/cobra" + "github.com/tektoncd/cli/pkg/cli" + "github.com/tektoncd/cli/pkg/cli/prerun" + "github.com/tektoncd/cli/pkg/flags" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var stepactionGroupResource = schema.GroupVersionResource{Group: "tekton.dev", Version: "v1beta1", Resource: "stepactions"} + +func Command(p cli.Params) *cobra.Command { + cmd := &cobra.Command{ + Use: "stepaction", + Aliases: []string{"stepactions"}, + Short: "Manage StepActions", + Annotations: map[string]string{ + "commandType": "main", + }, + PersistentPreRunE: prerun.PersistentPreRunE(p), + } + + flags.AddTektonOptions(cmd) + cmd.AddCommand( + deleteCommand(p), + describeCommand(p), + listCommand(p), + ) + + return cmd +} diff --git a/pkg/cmd/stepaction/stepaction_test.go b/pkg/cmd/stepaction/stepaction_test.go new file mode 100644 index 0000000000..ebd6bb9fee --- /dev/null +++ b/pkg/cmd/stepaction/stepaction_test.go @@ -0,0 +1,297 @@ +// Copyright © 2026 The Tekton Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package stepaction + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/jonboulle/clockwork" + "github.com/spf13/cobra" + "github.com/tektoncd/cli/pkg/exitcode" + "github.com/tektoncd/cli/pkg/test" + cb "github.com/tektoncd/cli/pkg/test/builder" + testDynamic "github.com/tektoncd/cli/pkg/test/dynamic" + v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + pipelinetest "github.com/tektoncd/pipeline/test" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic" +) + +const versionv1beta1 = "v1beta1" + +func testStepActions(now time.Time) []*v1beta1.StepAction { + return []*v1beta1.StepAction{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "kaniko", + Namespace: "foo", + CreationTimestamp: metav1.Time{Time: now}, + }, + Spec: v1beta1.StepActionSpec{ + Description: "Builds an image", + Image: "gcr.io/kaniko-project/executor", + }, + }, + { + ObjectMeta: metav1.ObjectMeta{ + Name: "git-clone", + Namespace: "foo", + Labels: map[string]string{"app": "git"}, + CreationTimestamp: metav1.Time{Time: now}, + }, + Spec: v1beta1.StepActionSpec{ + Description: "Clones a repo", + Image: "alpine/git", + Command: []string{"git"}, + Args: []string{"clone"}, + Params: v1.ParamSpecs{ + {Name: "url", Type: v1.ParamTypeString, Description: "repo url"}, + {Name: "revision", Type: v1.ParamTypeString, Description: "git revision", Default: v1.NewStructuredValues("main")}, + }, + Results: []v1.StepResult{ + {Name: "commit", Description: "the cloned commit"}, + }, + }, + }, + { + ObjectMeta: metav1.ObjectMeta{ + Name: "lint", + Namespace: "bar", + CreationTimestamp: metav1.Time{Time: now}, + }, + Spec: v1beta1.StepActionSpec{ + Description: "Runs a linter", + Image: "golangci/golangci-lint", + }, + }, + } +} + +func newDynamicClient(t *testing.T, sas []*v1beta1.StepAction) dynamic.Interface { + t.Helper() + tdc := testDynamic.Options{} + objs := make([]runtime.Object, 0, len(sas)) + for _, sa := range sas { + objs = append(objs, cb.UnstructuredV1beta1StepAction(sa, versionv1beta1)) + } + dc, err := tdc.Client(objs...) + if err != nil { + t.Fatalf("unable to create dynamic client: %v", err) + } + return dc +} + +func newCommand(t *testing.T, now time.Time, dc dynamic.Interface) *cobra.Command { + t.Helper() + clock := clockwork.NewFakeClockAt(now) + clock.Advance(time.Hour) + ns := []*corev1.Namespace{ + {ObjectMeta: metav1.ObjectMeta{Name: "foo"}}, + {ObjectMeta: metav1.ObjectMeta{Name: "bar"}}, + } + cs, _ := test.SeedTestData(t, pipelinetest.Data{Namespaces: ns}) + cs.Pipeline.Resources = cb.APIResourceList(versionv1beta1, []string{"stepaction"}) + p := &test.Params{Tekton: cs.Pipeline, Clock: clock, Kube: cs.Kube, Dynamic: dc} + return Command(p) +} + +func TestStepActionList(t *testing.T) { + now := time.Now() + dc := newDynamicClient(t, testStepActions(now)) + + out, err := test.ExecuteCommand(newCommand(t, now, dc), "list", "-n", "foo") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + lines := strings.Split(strings.TrimSpace(out), "\n") + if len(lines) != 3 { + t.Fatalf("expected a header and 2 rows, got %q", out) + } + if got := strings.Fields(lines[0]); strings.Join(got, " ") != "NAME DESCRIPTION AGE" { + t.Errorf("unexpected header %q", lines[0]) + } + if !strings.HasPrefix(lines[1], "git-clone ") || !strings.Contains(lines[1], "Clones a repo") { + t.Errorf("unexpected first row %q", lines[1]) + } + if !strings.HasPrefix(lines[2], "kaniko ") || !strings.Contains(lines[2], "Builds an image") { + t.Errorf("unexpected second row %q", lines[2]) + } + if strings.Contains(out, "lint") { + t.Errorf("StepAction from another namespace was listed: %q", out) + } +} + +func TestStepActionListOptions(t *testing.T) { + now := time.Now() + + tests := []struct { + name string + args []string + check func(t *testing.T, out string) + }{ + { + name: "all namespaces", + args: []string{"list", "-A"}, + check: func(t *testing.T, out string) { + lines := strings.Split(strings.TrimSpace(out), "\n") + if len(lines) != 4 || !strings.HasPrefix(lines[0], "NAMESPACE ") { + t.Fatalf("unexpected output %q", out) + } + if !strings.HasPrefix(lines[1], "bar ") || !strings.Contains(lines[1], "lint") { + t.Errorf("expected namespace bar first, got %q", lines[1]) + } + }, + }, + { + name: "no headers and reverse", + args: []string{"list", "-n", "foo", "--no-headers", "--reverse"}, + check: func(t *testing.T, out string) { + lines := strings.Split(strings.TrimSpace(out), "\n") + if len(lines) != 2 || !strings.HasPrefix(lines[0], "kaniko ") { + t.Errorf("unexpected output %q", out) + } + }, + }, + { + name: "limit", + args: []string{"list", "-n", "foo", "--limit", "1"}, + check: func(t *testing.T, out string) { + lines := strings.Split(strings.TrimSpace(out), "\n") + if len(lines) != 2 || !strings.HasPrefix(lines[1], "git-clone ") { + t.Errorf("unexpected output %q", out) + } + }, + }, + { + name: "output name", + args: []string{"list", "-n", "foo", "-o", "name"}, + check: func(t *testing.T, out string) { + want := "stepaction.tekton.dev/git-clone\nstepaction.tekton.dev/kaniko\n" + if out != want { + t.Errorf("output = %q, want %q", out, want) + } + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dc := newDynamicClient(t, testStepActions(now)) + out, err := test.ExecuteCommand(newCommand(t, now, dc), tt.args...) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + tt.check(t, out) + }) + } +} + +func TestStepActionListEmpty(t *testing.T) { + now := time.Now() + dc := newDynamicClient(t, nil) + out, err := test.ExecuteCommand(newCommand(t, now, dc), "list", "-n", "foo") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if out != "No StepActions found\n" { + t.Errorf("output = %q", out) + } +} + +func TestStepActionListNegativeLimit(t *testing.T) { + now := time.Now() + dc := newDynamicClient(t, nil) + if _, err := test.ExecuteCommand(newCommand(t, now, dc), "list", "-n", "foo", "--limit", "-1"); err == nil { + t.Error("expected an error for a negative limit") + } +} + +func TestStepActionDescribe(t *testing.T) { + now := time.Now() + dc := newDynamicClient(t, testStepActions(now)) + + out, err := test.ExecuteCommand(newCommand(t, now, dc), "describe", "git-clone", "-n", "foo") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + for _, want := range []string{ + "git-clone", "foo", "Clones a repo", "alpine/git", "[git]", "[clone]", + "app=git", "url", "repo url", "---", "revision", "main", + "commit", "string", "the cloned commit", + } { + if !strings.Contains(out, want) { + t.Errorf("describe output is missing %q:\n%s", want, out) + } + } +} + +func TestStepActionDescribeNotFound(t *testing.T) { + now := time.Now() + dc := newDynamicClient(t, testStepActions(now)) + _, err := test.ExecuteCommand(newCommand(t, now, dc), "describe", "missing", "-n", "foo") + if err == nil || !strings.Contains(err.Error(), "failed to get StepAction missing") { + t.Errorf("unexpected error: %v", err) + } +} + +func TestStepActionDelete(t *testing.T) { + now := time.Now() + dc := newDynamicClient(t, testStepActions(now)) + + out, err := test.ExecuteCommand(newCommand(t, now, dc), "delete", "kaniko", "-n", "foo") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if out != "StepAction 'kaniko' deleted successfully from namespace 'foo'\n" { + t.Errorf("output = %q", out) + } + if _, err := dc.Resource(stepactionGroupResource).Namespace("foo").Get(context.TODO(), "kaniko", metav1.GetOptions{}); err == nil { + t.Error("StepAction kaniko still exists") + } + if _, err := dc.Resource(stepactionGroupResource).Namespace("foo").Get(context.TODO(), "git-clone", metav1.GetOptions{}); err != nil { + t.Errorf("StepAction git-clone should still exist: %v", err) + } +} + +func TestStepActionDeleteMissing(t *testing.T) { + now := time.Now() + dc := newDynamicClient(t, testStepActions(now)) + + _, err := test.ExecuteCommand(newCommand(t, now, dc), "delete", "missing", "kaniko", "-n", "foo") + if err == nil || !strings.Contains(err.Error(), "StepAction missing not found in namespace foo") { + t.Errorf("unexpected error: %v", err) + } + if got := exitcode.CodeFrom(err); got != exitcode.NotFound { + t.Errorf("exit code = %d, want %d", got, exitcode.NotFound) + } + // the existing one is still deleted + if _, err := dc.Resource(stepactionGroupResource).Namespace("foo").Get(context.TODO(), "kaniko", metav1.GetOptions{}); err == nil { + t.Error("StepAction kaniko still exists") + } +} + +func TestStepActionDeleteRequiresName(t *testing.T) { + now := time.Now() + dc := newDynamicClient(t, nil) + if _, err := test.ExecuteCommand(newCommand(t, now, dc), "delete", "-n", "foo"); err == nil { + t.Error("expected an error without a StepAction name") + } +} diff --git a/pkg/cmd/testdata/TestPluginList.golden b/pkg/cmd/testdata/TestPluginList.golden index ed08e97d9a..abfb718c8e 100644 --- a/pkg/cmd/testdata/TestPluginList.golden +++ b/pkg/cmd/testdata/TestPluginList.golden @@ -13,6 +13,7 @@ Available Commands: hub Interact with artifacthub pipeline Manage pipelines pipelinerun Manage PipelineRuns + stepaction Manage StepActions task Manage Tasks taskrun Manage TaskRuns triggerbinding Manage TriggerBindings diff --git a/pkg/options/describe.go b/pkg/options/describe.go index 21f9e7bb98..0367e976c5 100644 --- a/pkg/options/describe.go +++ b/pkg/options/describe.go @@ -37,6 +37,7 @@ type DescribeOptions struct { TaskName string TaskrunName string CustomRunName string + StepActionName string Tasks []string TriggerTemplateName string TriggerBindingName string @@ -96,6 +97,8 @@ func (opts *DescribeOptions) Ask(resource string, options []string) error { opts.TaskrunName = strings.Fields(ans)[0] case ResourceNameCustomRun: opts.CustomRunName = strings.Fields(ans)[0] + case ResourceNameStepAction: + opts.StepActionName = ans case ResourceNameTriggerTemplate: opts.TriggerTemplateName = ans case ResourceNameTriggerBinding: @@ -154,7 +157,7 @@ func (opts *DescribeOptions) FuzzyAsk(resource string, options []string) error { return err } ans := options[idx[0]] - fmt.Println(ans) + announceSelection(ans) switch resource { case ResourceNamePipeline: opts.PipelineName = ans @@ -166,6 +169,8 @@ func (opts *DescribeOptions) FuzzyAsk(resource string, options []string) error { opts.TaskrunName = strings.Fields(ans)[0] case ResourceNameCustomRun: opts.CustomRunName = strings.Fields(ans)[0] + case ResourceNameStepAction: + opts.StepActionName = ans case ResourceNameTriggerTemplate: opts.TriggerTemplateName = ans case ResourceNameTriggerBinding: @@ -178,3 +183,9 @@ func (opts *DescribeOptions) FuzzyAsk(resource string, options []string) error { return nil } + +// announceSelection echoes the chosen name on stderr so that stdout only +// carries the requested object (for example with -o json). +func announceSelection(ans string) { + fmt.Fprintln(os.Stderr, ans) +} diff --git a/pkg/options/describe_test.go b/pkg/options/describe_test.go index a1bca47c3e..63f833104d 100644 --- a/pkg/options/describe_test.go +++ b/pkg/options/describe_test.go @@ -15,6 +15,8 @@ package options import ( + "io" + "os" "testing" "github.com/AlecAivazis/survey/v2/terminal" @@ -484,3 +486,29 @@ func TestDescribeOptions_Ask(t *testing.T) { }) } } + +func TestAnnounceSelectionWritesToStderr(t *testing.T) { + outR, outW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + errR, errW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + oldOut, oldErr := os.Stdout, os.Stderr + os.Stdout, os.Stderr = outW, errW + announceSelection("my-stepaction") + os.Stdout, os.Stderr = oldOut, oldErr + outW.Close() + errW.Close() + + gotOut, _ := io.ReadAll(outR) + gotErr, _ := io.ReadAll(errR) + if len(gotOut) != 0 { + t.Errorf("expected nothing on stdout, got %q", gotOut) + } + if string(gotErr) != "my-stepaction\n" { + t.Errorf("expected selection on stderr, got %q", gotErr) + } +} diff --git a/pkg/options/resource_names.go b/pkg/options/resource_names.go index 5202179159..9c7d5bb60d 100644 --- a/pkg/options/resource_names.go +++ b/pkg/options/resource_names.go @@ -6,6 +6,7 @@ const ( ResourceNameTask = "task" ResourceNameTaskRun = "taskrun" ResourceNameCustomRun = "customrun" + ResourceNameStepAction = "stepaction" ResourceNameTriggerTemplate = "triggertemplate" ResourceNameTriggerBinding = "triggerbinding" ResourceNameClusterTriggerBinding = "clustertriggerbinding" diff --git a/pkg/test/builder/unstructured.go b/pkg/test/builder/unstructured.go index a0a3538df9..9efb910217 100644 --- a/pkg/test/builder/unstructured.go +++ b/pkg/test/builder/unstructured.go @@ -94,6 +94,15 @@ func UnstructuredV1beta1CustomRun(customrun *v1beta1.CustomRun, version string) } } +func UnstructuredV1beta1StepAction(stepaction *v1beta1.StepAction, version string) *unstructured.Unstructured { + stepaction.APIVersion = "tekton.dev/" + version + stepaction.Kind = "StepAction" + object, _ := runtime.DefaultUnstructuredConverter.ToUnstructured(stepaction) + return &unstructured.Unstructured{ + Object: object, + } +} + func UnstructuredV1beta1T(task *v1beta1.Task, version string) *unstructured.Unstructured { task.APIVersion = "tekton.dev/" + version task.Kind = "task" diff --git a/pkg/test/dynamic/clientset/tekton.go b/pkg/test/dynamic/clientset/tekton.go index 756aa629b7..8c7f171d9b 100644 --- a/pkg/test/dynamic/clientset/tekton.go +++ b/pkg/test/dynamic/clientset/tekton.go @@ -22,7 +22,7 @@ import ( ) var allowedTektonTypes = map[string][]string{ - "v1beta1": {"pipelineruns", "taskruns", "pipelines", "tasks", "conditions", "customruns"}, + "v1beta1": {"pipelineruns", "taskruns", "pipelines", "tasks", "conditions", "customruns", "stepactions"}, "v1": {"pipelineruns", "taskruns", "pipelines", "tasks"}, } diff --git a/pkg/test/dynamic/dynamictestclient.go b/pkg/test/dynamic/dynamictestclient.go index 47f9b9d405..d53fdfcb8d 100644 --- a/pkg/test/dynamic/dynamictestclient.go +++ b/pkg/test/dynamic/dynamictestclient.go @@ -47,6 +47,7 @@ func (opt *Options) Client(objects ...runtime.Object) (dynamic.Interface, error) {Group: "tekton.dev", Version: "v1beta1", Resource: "tasks"}: "TaskList", {Group: "tekton.dev", Version: "v1beta1", Resource: "taskruns"}: "TaskRunList", {Group: "tekton.dev", Version: "v1beta1", Resource: "customruns"}: "CustomRunList", + {Group: "tekton.dev", Version: "v1beta1", Resource: "stepactions"}: "StepActionList", {Group: "tekton.dev", Version: "v1beta1", Resource: "pipelines"}: "PipelineList", {Group: "tekton.dev", Version: "v1beta1", Resource: "pipelineruns"}: "PipelineRunList", {Group: "tekton.dev", Version: "v1", Resource: "tasks"}: "TaskList",