Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
f1919c8
feat(diff): render supplied composites in DiffComposition
jcogilvie Nov 24, 2026
dd372a5
feat(simulate): assign --resource-file inputs to project Compositions
jcogilvie Nov 24, 2026
e85b3a1
fix(simulate): name the input flag in simulate input errors
jcogilvie Nov 24, 2026
0d3ba9c
fix(simulate): read Composition fields at the engine's paths on assign
jcogilvie Nov 24, 2026
440456c
test(diff): test that a supplied claim renders once with its XR
jcogilvie Nov 24, 2026
6e525fa
feat(simulate): render --resource-file inputs against their Compositions
jcogilvie Nov 24, 2026
e6e683e
feat(project): add project simulate --resource-file
jcogilvie Nov 24, 2026
26c5a9c
feat(simulate): note new project Compositions that nothing renders
jcogilvie Nov 24, 2026
c3907d3
docs(project): document and integration-test simulate --resource-file
jcogilvie Nov 24, 2026
9ef27b1
feat(simulate): default, dedupe and enforce --resource-file Compositions
jcogilvie Nov 24, 2026
9f1f53a
test(project): test that --resource-file - reads standard input
jcogilvie Nov 24, 2026
3f8848d
docs(project): document --resource-file defaulting and identity
jcogilvie Nov 24, 2026
0ecc13d
feat(diff): tell supplied composites apart from live ones in diffs
jcogilvie Nov 24, 2026
b823166
feat(simulate): mark --resource-file composites as supplied in results
jcogilvie Nov 24, 2026
47c16a7
feat(simulate): label --resource-file composites in text output
jcogilvie Nov 24, 2026
234f1d6
refactor(simulate): use maps.Copy when merging assigned composites
jcogilvie Nov 24, 2026
baebae3
refactor(diff): split composition diff helpers to satisfy lint
jcogilvie Nov 24, 2026
6bd9c0d
fix(simulate): accept generateName-only --resource-file inputs
jcogilvie Nov 24, 2026
f543172
fix(diff): keep the filtered breakdown when supplied composites render
jcogilvie Nov 24, 2026
94cf86a
fix(diff): decide whether a supplied composite is live from the cluster
jcogilvie Nov 24, 2026
b78b9cd
refactor(diff): move the cluster composite lookup to its own interface
jcogilvie Nov 24, 2026
2dc25cd
refactor(diff): add ClusterComposite to the DiffProcessor interface
jcogilvie Nov 24, 2026
59ff32a
refactor(diff): key supplied composites by a version-independent key
jcogilvie Nov 24, 2026
0a0aa5d
refactor(diff): build the skipped-analysis sentences once
jcogilvie Nov 24, 2026
a5c8a6e
docs(diff): note the repeated backing-composite resolve for new claims
jcogilvie Nov 24, 2026
b5a3654
chore(diff): satisfy lint for CompositeKey and DiffProcessor
jcogilvie Nov 24, 2026
fd6ead2
refactor(simulate): reuse the diff XRD and field readers in assignment
jcogilvie Nov 24, 2026
de5b197
docs(simulate): cross-reference the two Composition selection chains
jcogilvie Nov 24, 2026
039e4a0
refactor(simulate): share the cluster path's label matching
jcogilvie Nov 24, 2026
b874624
docs(diff): say processSingleComposition's map is keyed by CompositeKey
jcogilvie Nov 24, 2026
044957b
refactor(diff): split DiffProcessor by consumer
jcogilvie Nov 25, 2026
6abcbec
refactor(diff): drop the skip path's duplicate empty-kept return
jcogilvie Nov 25, 2026
51ca5e7
fix(diff): read a live supplied XR's pin from its effective composite
jcogilvie Nov 25, 2026
6bfc32c
fix(diff): report a supplied claim's unresolved pin under a skipped a…
jcogilvie Nov 25, 2026
c7b6b75
fix(diff): read a live supplied XR's update policy from its effective…
jcogilvie Nov 25, 2026
6ad200c
fix(diff): keep main's wording for a claim's unresolved pin
jcogilvie Nov 25, 2026
8122e54
fix(diff): classify a live supplied composite by its effective compos…
jcogilvie Nov 25, 2026
dc55853
docs(diff): describe unresolved as covering live supplied composites
jcogilvie Nov 25, 2026
1911cc5
refactor(diff): move a live supplied composite's resolve out of class…
jcogilvie Nov 25, 2026
d9bc080
test(testutils): add XRD builder options for apiVersion, scope and co…
jcogilvie Nov 25, 2026
e1b0818
test(simulate): build assign test inputs and XRDs with testutils buil…
jcogilvie Nov 25, 2026
aff196b
test(simulate): build the new-composition hint XR with testutils
jcogilvie Nov 25, 2026
e0d3d00
test(testutils): add a WithFindComposites option to the mock composit…
jcogilvie Nov 25, 2026
ac66114
test(diff): build supplied-composite test inputs with builders and sh…
jcogilvie Nov 25, 2026
b17171e
test(diff): return fresh copies from the found helper on each call
jcogilvie Nov 25, 2026
7e8e539
feat(diff): add SelectComposition, Crossplane's selection order
jcogilvie Nov 25, 2026
3d28b75
refactor(simulate): select Compositions with SelectComposition
jcogilvie Nov 25, 2026
f2cb872
docs(xr): say xr simulate selects Compositions as Crossplane does
jcogilvie Nov 25, 2026
ea1a47e
fix(diff): skip the XRD default for an empty compositionSelector
jcogilvie Nov 25, 2026
d996b57
test(diff): test malformed compositionRef and selector errors
jcogilvie Nov 25, 2026
3f65687
fix(diff): let a nested XR's enforced Composition override its ref
jcogilvie Nov 25, 2026
61f8f9a
docs(xr): separate the selection paragraph and note empty selectors
jcogilvie Nov 25, 2026
a715711
fix(diff): read a nested XR's compositionRef at its XRD's paths
jcogilvie Nov 25, 2026
9045358
test(simulate): build the selection test definition client with the b…
jcogilvie Nov 25, 2026
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
4 changes: 2 additions & 2 deletions cmd/crossplane/composition/simulate.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ func (c *simulateCmd) Help() string {
// Run previews the Compositions -f names against the cluster, with the
// cluster's functions.
func (c *simulateCmd) Run(sigCtx context.Context, k *kong.Context, logger logging.Logger, sp terminal.SpinnerPrinter) error {
comps, err := simulate.LoadInputs(c.Input, func(r *un.Unstructured) error {
comps, err := simulate.LoadInputs(simulate.FlagInput, c.Input, func(r *un.Unstructured) error {
if r.GroupVersionKind() != apiextensionsv1.CompositionGroupVersionKind {
return simulate.RejectInput(r, "composition simulate takes Composition files")
return simulate.RejectInput(r, simulate.FlagInput, "composition simulate takes Composition files")
}
return nil
})
Expand Down
14 changes: 14 additions & 0 deletions cmd/crossplane/project/help/simulate.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,20 @@ the project's functions in place of the cluster's functions of the same name.
`--max-concurrency` caps the concurrent function builds, and `--cache-dir` sets
where package contents are cached.

`--resource-file` adds composite resource or claim files to render against
the project's Compositions, for example to preview what a new Composition
would create. It takes a file or directory, a comma-separated list of paths,
and can be repeated; `-` reads standard input. Each input is matched to a
project Composition the way Crossplane selects one: its XRD's enforced
Composition, then its `compositionRef`, then its `compositionSelector`, then
its XRD's default Composition, then the only Composition for its type. Its
XRD must be installed in the cluster. `--namespace` sets the namespace of an
input that has none but doesn't filter the inputs; without it, such an input
gets the kubeconfig context's namespace. Each input must have its own kind,
namespace and name. The inputs render alongside the composite resources the
run discovers or `--name` selects; an input with the same kind, namespace and
name as a composite resource in the cluster diffs against it.

For example, a run with `--skip-plan` whose project changes a Composition
prints a plan like this:

Expand Down
6 changes: 6 additions & 0 deletions cmd/crossplane/project/help/simulate_examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ Simulate two composite resources in different namespaces:
crossplane project simulate --name=team-a/my-database --name=team-b/my-database
```

Preview what a new Composition would create for a composite resource file:

```shell
crossplane project simulate --resource-file=examples/my-database.yaml
```

Print the plan as JSON:

```shell
Expand Down
47 changes: 47 additions & 0 deletions cmd/crossplane/project/integration_project_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"encoding/json"
"os"
"path/filepath"
"slices"
"testing"

diffv1alpha1 "github.com/crossplane/upjet/v2/proto/diff/v1alpha1"
Expand Down Expand Up @@ -58,6 +59,8 @@ type projectTestCase struct {
// router, when set, routes provider plans instead of diff servers and
// the run does not pass --skip-plan.
router simulate.Router
// expectedNote, when set, must be one of the -o json notes.
expectedNote string
}

func TestProjectSimulateIntegration(t *testing.T) {
Expand Down Expand Up @@ -183,6 +186,47 @@ func TestProjectSimulateIntegration(t *testing.T) {
{Path: "spec.forProvider.configData", Actual: val("existing-value"), Planned: val("embedded-existing-value")},
},
},
"NewCompositionResourceFile": {
reason: "A Composition the cluster lacks renders a --resource-file XR against it: the XR and its composed resources are creates, and the XR, which nothing in the cluster has, re-points no live composite.",
setupFiles: []string{
"../../../internal/testutils/integration/testdata/comp/resources/xrd.yaml",
"../../../internal/testutils/integration/testdata/comp/resources/functions.yaml",
},
project: "plain",
extraArgs: []string{"--resource-file", "../../../internal/testutils/integration/testdata/comp/resources/existing-xr-1.yaml"},
expectedExitCode: dp.ExitCodeDiffDetected,
expectedResult: planShape{
Summary: plan.Summary{Create: 3},
Composites: []simulate.CompositeResult{{Ref: xnop, Status: simulate.CompositeChanged, Composition: &comp, Supplied: true}},
Compositions: compositions(0),
Plans: []planEntry{
{Kind: "Composition", Name: comp.Name, Action: plan.ActionCreate},
{Kind: "XDownstreamResource", Name: "test-resource", Action: plan.ActionCreate, Composite: "test-resource"},
{Kind: "XNopResource", Name: "test-resource", Action: plan.ActionCreate, Composite: "test-resource"},
},
},
expectedChanges: []plan.FieldChange{
{Path: "metadata.annotations[crossplane.io/composition-resource-name]", Planned: val("nop-resource")},
{Path: "metadata.labels[crossplane.io/composite]", Planned: val("test-resource")},
{Path: "spec.forProvider.configData", Planned: val("updated-existing-value")},
{Path: "spec.forProvider.resourceTier", Planned: val("premium")},
},
},
"NewCompositionHint": {
reason: "A Composition the cluster lacks, with no composites and no --resource-file, notes how to preview what it would create.",
setupFiles: []string{
"../../../internal/testutils/integration/testdata/comp/resources/xrd.yaml",
"../../../internal/testutils/integration/testdata/comp/resources/functions.yaml",
},
project: "plain",
expectedExitCode: dp.ExitCodeDiffDetected,
expectedResult: planShape{
Summary: plan.Summary{Create: 1},
Compositions: compositions(0),
Plans: []planEntry{{Kind: "Composition", Name: comp.Name, Action: plan.ActionCreate}},
},
expectedNote: "Composition " + comp.Name + " is new; no composite resources exist to render. Pass a composite resource or claim file with --resource-file to preview what it would create.",
},
}

for name, tc := range cases {
Expand Down Expand Up @@ -226,6 +270,9 @@ func TestProjectSimulateIntegration(t *testing.T) {
if diff := cmp.Diff(tc.expectedResult, summarize(res)); diff != "" {
t.Errorf("\n%s\nsimulate -o json: -want, +got:\n%s", tc.reason, diff)
}
if tc.expectedNote != "" && !slices.Contains(res.Notes, tc.expectedNote) {
t.Errorf("\n%s\nsimulate -o json: want note %q, got notes %q", tc.reason, tc.expectedNote, res.Notes)
}
var got []plan.FieldChange
for _, p := range res.Plans {
if p.Kind == "XDownstreamResource" && p.Name == "test-resource" {
Expand Down
35 changes: 34 additions & 1 deletion cmd/crossplane/project/simulate.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,13 @@ import (

"github.com/alecthomas/kong"
"github.com/spf13/afero"
un "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"

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

apiextensionsv1 "github.com/crossplane/crossplane/apis/v2/apiextensions/v1"

"github.com/crossplane/cli/v2/internal/config"
"github.com/crossplane/cli/v2/internal/dependency"
"github.com/crossplane/cli/v2/internal/project"
Expand Down Expand Up @@ -54,8 +57,13 @@ type SimulateCmd struct {

MaxConcurrency uint `default:"8" help:"Max concurrent function builds."`
ProjectFile string `default:"${project_file}" help:"Path to project definition." short:"f"`

ResourceFile []string `help:"Composite resource or claim file or directory to render against the project's Compositions. Takes a comma-separated list of paths, and can be repeated. - reads standard input." placeholder:"PATH" predictor:"yaml_file_or_directory"`
}

// takes is what --resource-file takes, for simulate.RejectInput.
const takes = "--resource-file takes composite resource or claim files"

// Help returns help for the simulate command.
func (c *SimulateCmd) Help() string {
return simulateHelp + simulate.Help(true) + simulateExamples
Expand All @@ -64,9 +72,34 @@ 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 {
xrs, err := c.loadResourceFiles()
if err != nil {
return err
}
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})
}, ResourceFile: xrs, Selection: &c.CompositionFlags})
}

// loadResourceFiles loads the --resource-file inputs, rejecting Compositions,
// project files and Lists as xr simulate does. The cluster's XRDs confirm the
// rest are composite resources or claims once Run connects.
func (c *SimulateCmd) loadResourceFiles() ([]*un.Unstructured, error) {
if len(c.ResourceFile) == 0 {
return nil, nil
}
return simulate.LoadInputs(simulate.FlagResourceFile, c.ResourceFile, func(r *un.Unstructured) error {
gvk := r.GroupVersionKind()
switch {
case gvk == apiextensionsv1.CompositionGroupVersionKind:
return simulate.RejectInput(r, simulate.FlagResourceFile, takes+"; the project's Compositions are under its APIs path")
case gvk.GroupVersion().String() == projectfile.APIVersion && gvk.Kind == projectfile.Kind:
return simulate.RejectInput(r, simulate.FlagResourceFile, takes+"; pass the project file with -f")
case r.IsList() || gvk.Kind == "List":
return simulate.RejectInput(r, simulate.FlagResourceFile, takes)
}
return nil
})
}

// buildProject returns the project's compositions, its locally built
Expand Down
79 changes: 78 additions & 1 deletion cmd/crossplane/project/simulate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,10 @@ func TestSimulateFlags(t *testing.T) {
"--include-pinned", "--max-iterations", "3", "--timeout", "2m",
"--max-concurrency", "2", "-o", "json", "--crossplane-version", "v2.3.4",
"--as", "jane", "--as-group", "admins",
"--resource-file", "a.yaml,b", "--resource-file", "-",
},
want: want{cmd: &SimulateCmd{
MaxConcurrency: 2, ProjectFile: "p.yaml",
MaxConcurrency: 2, ProjectFile: "p.yaml", ResourceFile: []string{"a.yaml", "b", "-"},
Context: "staging",
MaxIterations: 3,
Timeout: 2 * time.Minute,
Expand Down Expand Up @@ -379,6 +380,82 @@ func TestSimulateFlags(t *testing.T) {
}
}

func TestSimulateLoadResourceFiles(t *testing.T) {
type args struct {
yaml string
stdin bool
}
type want struct {
names []string
err string
}
cases := map[string]struct {
reason string
args args
want want
}{
"Composite": {
reason: "A candidate composite resource or claim is loaded.",
args: args{yaml: "apiVersion: example.org/v1\nkind: Bucket\nmetadata:\n name: b\n"},
want: want{names: []string{"b"}},
},
"Stdin": {
reason: "- reads the inputs from standard input.",
args: args{yaml: "apiVersion: example.org/v1\nkind: Bucket\nmetadata:\n name: s\n", stdin: true},
want: want{names: []string{"s"}},
},
"Composition": {
reason: "A Composition is rejected; the project supplies them.",
args: args{yaml: "apiVersion: apiextensions.crossplane.io/v1\nkind: Composition\nmetadata:\n name: c\n"},
want: want{err: `--resource-file inputs include Composition "c" (apiextensions.crossplane.io/v1); --resource-file takes composite resource or claim files; the project's Compositions are under its APIs path`},
},
"ProjectFile": {
reason: "A project file is rejected.",
args: args{yaml: "apiVersion: dev.crossplane.io/v1alpha1\nkind: Project\nmetadata:\n name: p\n"},
want: want{err: `--resource-file inputs include Project "p" (dev.crossplane.io/v1alpha1); --resource-file takes composite resource or claim files; pass the project file with -f`},
},
"List": {
reason: "A List is rejected with the hint to split it.",
args: args{yaml: "apiVersion: v1\nkind: List\nmetadata:\n name: l\nitems: []\n"},
want: want{err: `--resource-file inputs include List "l" (v1); --resource-file takes composite resource or claim files; pass its items as separate YAML documents instead of a List`},
},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "in.yaml")
if err := os.WriteFile(path, []byte(tc.args.yaml), 0o600); err != nil {
t.Fatal(err)
}
if tc.args.stdin {
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
old := os.Stdin
os.Stdin = f
t.Cleanup(func() { os.Stdin = old })
path = "-"
}
got, err := (&SimulateCmd{ResourceFile: []string{path}}).loadResourceFiles()
gotErr := ""
if err != nil {
gotErr = err.Error()
}
if diff := cmp.Diff(tc.want.err, gotErr); diff != "" {
t.Errorf("\n%s\nloadResourceFiles(): -want err, +got err:\n%s", tc.reason, diff)
}
names := make([]string, 0, len(got))
for _, r := range got {
names = append(names, r.GetName())
}
if diff := cmp.Diff(tc.want.names, names, cmpopts.EquateEmpty()); diff != "" {
t.Errorf("\n%s\nloadResourceFiles(): -want, +got:\n%s", tc.reason, diff)
}
})
}
}

func TestSimulateBuildProjectRejectsComposition(t *testing.T) {
path := filepath.Join(t.TempDir(), "comp.yaml")
comp := "apiVersion: apiextensions.crossplane.io/v1\nkind: Composition\nmetadata:\n name: c\nspec:\n compositeTypeRef:\n apiVersion: example.org/v1\n kind: XThing\n"
Expand Down
8 changes: 8 additions & 0 deletions cmd/crossplane/xr/help/simulate.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ directly, use `crossplane resource simulate`. A claim is simulated as its
composite resource, and its result is listed under the claim's name. A claim or
namespaced composite resource with no `metadata.namespace` is simulated in the
current context's namespace, as `kubectl apply` would.

Each one is rendered with the Composition Crossplane would select for it: its
XRD's `enforcedCompositionRef`, then its `compositionRef`, its
`compositionSelector`, its XRD's `defaultCompositionRef`, then the only
Composition of its type. A `compositionSelector` with no labels skips the
`defaultCompositionRef`, as in Crossplane; Crossplane then picks any Composition
of the type at random, so the simulation needs it to be the only one.

Functions come from the cluster. `--cache-dir` sets where provider package
contents are cached.

8 changes: 4 additions & 4 deletions cmd/crossplane/xr/simulate.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,15 @@ func (c *simulateCmd) Help() string {
func (c *simulateCmd) Run(sigCtx context.Context, k *kong.Context, logger logging.Logger, sp terminal.SpinnerPrinter) error {
// Anything but a Composition or project file is a candidate composite
// resource or claim; checkComposites confirms it against the cluster's XRDs.
xrs, err := simulate.LoadInputs(c.Input, func(r *un.Unstructured) error {
xrs, err := simulate.LoadInputs(simulate.FlagInput, c.Input, func(r *un.Unstructured) error {
gvk := r.GroupVersionKind()
switch {
case gvk == apiextensionsv1.CompositionGroupVersionKind:
return simulate.RejectInput(r, takes+"; composition simulate takes Composition files")
return simulate.RejectInput(r, simulate.FlagInput, takes+"; composition simulate takes Composition files")
case gvk.GroupVersion().String() == projectfile.APIVersion && gvk.Kind == projectfile.Kind:
return simulate.RejectInput(r, takes+"; project simulate takes a project file")
return simulate.RejectInput(r, simulate.FlagInput, takes+"; project simulate takes a project file")
case r.IsList() || gvk.Kind == "List":
return simulate.RejectInput(r, takes)
return simulate.RejectInput(r, simulate.FlagInput, takes)
}
return nil
})
Expand Down
11 changes: 10 additions & 1 deletion design/one-pager-cli-simulate.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,13 @@ The flow:
1. **Discover.** Parse the project file, find the Compositions under the
project's API paths, and list the XRs on the target cluster whose type
each Composition composes. `--namespace` and `--name` scope the run.
`--resource-file` adds XR or claim files, matched to a project
Composition the way Crossplane selects one (the XRD's enforced
Composition, `compositionRef`, selector, the XRD's default, the sole
match), so a new Composition with no XRs yet can still be previewed.
Their XRDs must be installed in the cluster; `--namespace` defaults their
namespace without filtering them; an input with the same kind, namespace
and name as a cluster XR diffs against it.
2. **Prepare.** Build the project's embedded functions locally, exactly as
`project run` does, so the simulation reflects the code in the working
tree. Resolve the project's provider dependencies and start their diff
Expand Down Expand Up @@ -236,7 +243,9 @@ ask the providers what the delta means".
A project is one source of those local inputs, not a requirement.
Not everyone uses projects, and a changed Composition is worth previewing
either way, so `crossplane composition simulate -f` takes Composition files
and `crossplane xr simulate -f` takes XR or claim files. The
and `crossplane xr simulate -f` takes XR or claim files, each rendered
with the cluster Composition Crossplane would select for it, in the order
step 1 gives (the XRD's enforced and default Compositions included). The
flow stays the same with the inputs swapped: the changed Composition
comes from the file, the XRs it matches are discovered on the cluster
exactly as in step 1, the functions its pipeline calls run from the
Expand Down
Loading
Loading