Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/crossplane/composition/simulate.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,5 @@ func (c *simulateCmd) Run(sigCtx context.Context, k *kong.Context, logger loggin
if err := simulate.RejectDuplicateNames(comps); err != nil {
return err
}
return c.Flags.Run(sigCtx, k, logger, sp, &simulate.Inputs{Compositions: comps, Selection: &c.CompositionFlags})
return simulate.NewRunner(&c.Flags).Run(sigCtx, k, logger, sp, &simulate.Inputs{Compositions: comps, Selection: &c.CompositionFlags})
}
6 changes: 3 additions & 3 deletions cmd/crossplane/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ import (
"github.com/crossplane/cli/v2/cmd/crossplane/xr"
"github.com/crossplane/cli/v2/cmd/crossplane/xrd"
"github.com/crossplane/cli/v2/internal/config"
"github.com/crossplane/cli/v2/internal/exitcode"
"github.com/crossplane/cli/v2/internal/maturity"
isimulate "github.com/crossplane/cli/v2/internal/simulate"
"github.com/crossplane/cli/v2/internal/terminal"
clixpkg "github.com/crossplane/cli/v2/internal/xpkg"

Expand Down Expand Up @@ -122,7 +122,7 @@ func main() {
flagVal, err := configFlag(os.Args[1:])
if err != nil {
fmt.Fprintf(os.Stderr, "crossplane: %v\n", err)
os.Exit(isimulate.ExitCodeUsage)
os.Exit(exitcode.ExitCodeUsage)
}
cfgPath := config.ResolvePath(flagVal)

Expand Down Expand Up @@ -181,7 +181,7 @@ func main() {
stop()
// A silent ExitError is a result, such as changes found, not an error,
// so it exits with its code and prints nothing.
code, silent := isimulate.SilentExit(err)
code, silent := exitcode.SilentExit(err)
if interrupted {
// Exit with the conventional 128+SIGINT status.
if err != nil && !silent {
Expand Down
3 changes: 2 additions & 1 deletion cmd/crossplane/project/integration_plan_output_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"

dp "github.com/crossplane/cli/v2/internal/diff/diffprocessor"
"github.com/crossplane/cli/v2/internal/exitcode"
"github.com/crossplane/cli/v2/internal/plan"
"github.com/crossplane/cli/v2/internal/simulate"
"github.com/crossplane/cli/v2/internal/testutils/integration"
Expand Down Expand Up @@ -598,7 +599,7 @@ func TestSimulateNameRejected(t *testing.T) {
reason: "namespace/name with --namespace is ambiguous and is rejected.",
args: []string{"--namespace=default", "--name=default/test-resource"},
wantErr: "can't be combined with --namespace",
wantCode: simulate.ExitCodeUsage,
wantCode: exitcode.ExitCodeUsage,
},
"NamePartiallyUnmatchedFailsBeforeRendering": {
reason: "one --name no composite matches fails the run, and no plan is rendered.",
Expand Down
2 changes: 1 addition & 1 deletion cmd/crossplane/project/simulate.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func (c *simulateCmd) Help() string {
// Run previews the project's compositions against the cluster, with its
// functions built locally.
func (c *simulateCmd) Run(sigCtx context.Context, k *kong.Context, logger logging.Logger, sp terminal.SpinnerPrinter, cliCfg *config.Config) error {
return c.Flags.Run(sigCtx, k, logger, sp, &simulate.Inputs{Build: func(ctx context.Context) (*simulate.Built, error) {
return simulate.NewRunner(&c.Flags).Run(sigCtx, k, logger, sp, &simulate.Inputs{Build: func(ctx context.Context) (*simulate.Built, error) {
return c.buildProject(ctx, logger, sp, cliCfg)
}, Selection: &c.CompositionFlags})
}
Expand Down
5 changes: 3 additions & 2 deletions cmd/crossplane/simulate/simulate.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import (
k8 "github.com/crossplane/cli/v2/internal/diff/client/kubernetes"
"github.com/crossplane/cli/v2/internal/diffserver"
"github.com/crossplane/cli/v2/internal/docker"
"github.com/crossplane/cli/v2/internal/exitcode"
"github.com/crossplane/cli/v2/internal/kube"
"github.com/crossplane/cli/v2/internal/plan"
isimulate "github.com/crossplane/cli/v2/internal/simulate"
Expand Down Expand Up @@ -158,15 +159,15 @@ func (c *Cmd) Run(ctx context.Context, k *kong.Context, logger logging.Logger, s
}

// exitStatus ranks the plans' outcome: an error, which exits 1, when any
// plan errored; otherwise a silent isimulate.ExitError that exits 3 when a plan
// plan errored; otherwise a silent exitcode.ExitError that exits 3 when a plan
// would change anything; otherwise nil.
func exitStatus(plans []*plan.ResourcePlan) error {
s := plan.Summarize(plans)
if s.Errored > 0 {
return errors.Errorf("cannot plan %d of %d resources; see their errors in the output", s.Errored, len(plans))
}
if s.Changes() > 0 {
return isimulate.ExitError{Code: isimulate.ExitCodeChanges}
return exitcode.ExitError{Code: isimulate.ExitCodeChanges}
}
return nil
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/crossplane/simulate/simulate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import (

"github.com/google/go-cmp/cmp"

"github.com/crossplane/cli/v2/internal/exitcode"
"github.com/crossplane/cli/v2/internal/plan"
isimulate "github.com/crossplane/cli/v2/internal/simulate"
)

func TestExitStatus(t *testing.T) {
Expand Down Expand Up @@ -62,7 +62,7 @@ func TestExitStatus(t *testing.T) {
// other error with 1.
got := 0
err := exitStatus(tc.args.plans)
if code, ok := isimulate.SilentExit(err); ok {
if code, ok := exitcode.SilentExit(err); ok {
got = code
} else if err != nil {
got = 1
Expand Down
2 changes: 1 addition & 1 deletion cmd/crossplane/xr/simulate.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,5 @@ func (c *simulateCmd) Run(sigCtx context.Context, k *kong.Context, logger loggin
if err != nil {
return err
}
return c.Flags.Run(sigCtx, k, logger, sp, &simulate.Inputs{Composites: xrs})
return simulate.NewRunner(&c.Flags).Run(sigCtx, k, logger, sp, &simulate.Inputs{Composites: xrs})
}
77 changes: 77 additions & 0 deletions internal/exitcode/exit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
Copyright 2026 The Crossplane 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 exitcode holds the usage exit status and the ExitError the commands
// share.
package exitcode

import "errors"

// ExitCodeUsage is the status kong exits with on a parse error. Kong does
// not export it, so it is mirrored here for the flag errors main finds
// before Parse.
const ExitCodeUsage = 80

// ExitError is an error that sets the command's exit status; it implements
// kong.ExitCoder. With a nil Err it reports a result that is not an error,
// such as changes found: main exits with Code without printing anything.
// Return it by value and unwrapped: main exits silently only when the
// returned error carries no message besides a silent ExitError, so one
// wrapped with a message or joined with another error, or a pointer, is
// printed as an error.
type ExitError struct {
// Err is the error to print, or nil to exit silently.
Err error

// Code is the status to exit with.
Code int
}

// Error returns Err's message, or an empty string when Err is nil.
func (e ExitError) Error() string {
if e.Err == nil {
return ""
}
return e.Err.Error()
}

// ExitCode implements kong.ExitCoder.
func (e ExitError) ExitCode() int {
return e.Code
}

// Unwrap returns Err.
func (e ExitError) Unwrap() error {
return e.Err
}

// Silent reports whether e exits without printing anything.
func (e ExitError) Silent() bool {
return e.Err == nil
}

// SilentExit returns the code of a silent ExitError value in err's chain
// when err has no message of its own, and false otherwise. kong's
// Context.Run joins the command's error with its AfterRun hooks' errors, so
// the check can't require err to be the ExitError itself; requiring an empty
// message still keeps a wrapping or joined error from being swallowed.
func SilentExit(err error) (int, bool) {
var e ExitError
if err == nil || err.Error() != "" || !errors.As(err, &e) || !e.Silent() {
return 0, false
}
return e.Code, true
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package simulate
package exitcode

import (
"testing"
Expand All @@ -38,12 +38,12 @@ func TestSilentExit(t *testing.T) {
want want
}{
"Nil": {reason: "No error isn't a silent exit.", args: args{err: nil}},
"Silent": {reason: "A silent ExitError value exits silently with its code.", args: args{err: ExitError{Code: ExitCodeChanges}}, want: want{code: ExitCodeChanges, silent: true}},
"Silent": {reason: "A silent ExitError value exits silently with its code.", args: args{err: ExitError{Code: ExitCodeUsage}}, want: want{code: ExitCodeUsage, silent: true}},
"WithErr": {reason: "An ExitError with an error is printed.", args: args{err: ExitError{Code: 2, Err: errors.New("boom")}}},
"Wrapped": {reason: "A wrapped silent ExitError is printed, so the wrapper's message isn't lost.", args: args{err: errors.Wrap(ExitError{Code: ExitCodeChanges}, "boom")}},
"KongJoin": {reason: "kong's Run joins a silent ExitError with nil hook errors, which still exits silently.", args: args{err: errors.Join(ExitError{Code: ExitCodeChanges}, nil)}, want: want{code: ExitCodeChanges, silent: true}},
"Joined": {reason: "A silent ExitError joined with a real error is printed.", args: args{err: errors.Join(ExitError{Code: ExitCodeChanges}, errors.New("boom"))}},
"Pointer": {reason: "A pointer isn't matched; ExitError must be returned by value.", args: args{err: &ExitError{Code: ExitCodeChanges}}},
"Wrapped": {reason: "A wrapped silent ExitError is printed, so the wrapper's message isn't lost.", args: args{err: errors.Wrap(ExitError{Code: ExitCodeUsage}, "boom")}},
"KongJoin": {reason: "kong's Run joins a silent ExitError with nil hook errors, which still exits silently.", args: args{err: errors.Join(ExitError{Code: ExitCodeUsage}, nil)}, want: want{code: ExitCodeUsage, silent: true}},
"Joined": {reason: "A silent ExitError joined with a real error is printed.", args: args{err: errors.Join(ExitError{Code: ExitCodeUsage}, errors.New("boom"))}},
"Pointer": {reason: "A pointer isn't matched; ExitError must be returned by value.", args: args{err: &ExitError{Code: ExitCodeUsage}}},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion internal/simulate/annotate.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ const probe = "CROSSPLANE-PROBE-7f3c"
// are the field's, because sigsyaml writes keys sorted, so the lines before
// and after a value don't depend on it, and the line diff keeps lines whole.
//
// ponytail: a field is found only where setPath reaches it, so a keyed
// NOTE: a field is found only where setPath reaches it, so a keyed
// item or index the desired side lacks gets no mark in a modified diff, and a
// keyed segment matching several items marks the first "+" line from the
// first match to the last. The header, the summary and -o plan still say
Expand Down
59 changes: 1 addition & 58 deletions internal/simulate/exit.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,68 +16,11 @@ limitations under the License.

package simulate

import "errors"

// Exit statuses the simulate commands share.
// Exit statuses of the simulate commands.
const (
// ExitCodeUsage is the status kong exits with on a parse error. Kong does
// not export it, so it is mirrored here for the flag errors main finds
// before Parse.
ExitCodeUsage = 80
// ExitCodeSchemaValidation means only schema validation failed.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would keep the simulate-specific exit codes in the simulate package, just moving the global ones (like Usage) and the shared machinery.

ExitCodeSchemaValidation = 2
// ExitCodeChanges is the status a simulate command exits with when the
// simulation succeeded and found changes.
ExitCodeChanges = 3
)

// ExitError is an error that sets the command's exit status; it implements
// kong.ExitCoder. With a nil Err it reports a result that is not an error,
// such as changes found: main exits with Code without printing anything.
// Return it by value and unwrapped: main exits silently only when the
// returned error carries no message besides a silent ExitError, so one
// wrapped with a message or joined with another error, or a pointer, is
// printed as an error.
type ExitError struct {
// Err is the error to print, or nil to exit silently.
Err error

// Code is the status to exit with.
Code int
}

// Error returns Err's message, or an empty string when Err is nil.
func (e ExitError) Error() string {
if e.Err == nil {
return ""
}
return e.Err.Error()
}

// ExitCode implements kong.ExitCoder.
func (e ExitError) ExitCode() int {
return e.Code
}

// Unwrap returns Err.
func (e ExitError) Unwrap() error {
return e.Err
}

// Silent reports whether e exits without printing anything.
func (e ExitError) Silent() bool {
return e.Err == nil
}

// SilentExit returns the code of a silent ExitError value in err's chain
// when err has no message of its own, and false otherwise. kong's
// Context.Run joins the command's error with its AfterRun hooks' errors, so
// the check can't require err to be the ExitError itself; requiring an empty
// message still keeps a wrapping or joined error from being swallowed.
func SilentExit(err error) (int, bool) {
var e ExitError
if err == nil || err.Error() != "" || !errors.As(err, &e) || !e.Silent() {
return 0, false
}
return e.Code, true
}
13 changes: 1 addition & 12 deletions internal/simulate/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,23 @@ package simulate
import (
"time"

un "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
k8stypes "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"

"github.com/crossplane/crossplane-runtime/v2/pkg/errors"

dp "github.com/crossplane/cli/v2/internal/diff/diffprocessor"
"github.com/crossplane/cli/v2/internal/diffserver"
"github.com/crossplane/cli/v2/internal/kube"
xprender "github.com/crossplane/cli/v2/pkg/render"
)

// Flags are the flags, and the run state, of a simulate command.
// Flags are the flags of a simulate command.
type Flags struct {
// EngineFlags select the crossplane render backend, as for render. Its
// SessionID labels the diff server containers; the render's containers
// are labelled with the run's own ID, which reclaims them.
xprender.EngineFlags `prefix:"" set:"session_id_help=Session ID to apply as the simulate.crossplane.io/session label on diff server containers. Defaults to a random per-process ID. Ignored with --skip-plan."`

// Run sets these; nil with --skip-plan (servers also when Hooks.Router is set).
xrPlanner *XRPlanner
// keep is the equal-diff filter the engine and xrPlanner share.
keep func(*un.Unstructured) bool
servers *diffserver.Manager
// noServersNoted is set once the "no diff servers" line is printed.
noServersNoted bool
// sel is Inputs.Selection, which Run copies in; zero without one.
sel CompositionFlags
CacheDir string `env:"CROSSPLANE_XPKG_CACHE" help:"Directory for cached xpkg package contents (functions and providers)." name:"cache-dir"`

Context string `help:"Kubernetes context to simulate against. Defaults to the current context." predictor:"context" short:"c"`
Expand Down
Loading