diff --git a/CHANGELOG.md b/CHANGELOG.md index 775f0ab..3c495a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,38 @@ Notable changes, newest first. Release notes on GitHub list every commit; this file collects what users and scripts need to know. +## Unreleased + +### New + +- `norcube cms validate [path]` checks a Norcube CMS site from its + repository, offline and without a sign-in: the schema in `.norcube/cms/` + (YAML, `$ref`, field types and knobs, options, bounds, regexes, + `visibleIf` paths, storages, preview), every content file against its + collection (the editor's rules: required, shapes, array item kinds and + bounds, regex, length, uniqueness, custom validators, out-of-schema + keys) and the links between files (two files at one URL, links no page + produces, missing images, dangling references). `--only + schema|content|links` narrows the run, `--collection` limits it to one + collection, `--fail-on warning|error|none` picks what fails the exit + code. The checks come from the public + [cms-schema](https://github.com/norcubeplatform/cms-schema) module, so a + site's CI runs exactly what the editor runs. + +### Changes + +- Built with Go 1.26.11, which fixes GO-2026-6859 in the standard library. + +### Changes for scripts + +- New error code `invalid` (exit 1): `cms validate` found findings at the + severity `--fail-on` asks it to fail on; `details` holds the counts and + stdout the report. +- `cms validate -o json` prints `{schemaVersion, path, findings[], + summary{files, schemaFiles, errors, warnings}}`; each finding has `file`, + `path`, `severity`, `rule`, `message` and optionally `hint`. Rule ids + are frozen in the cms-schema module. + ## 0.26.0 (2026-11-07) ### New diff --git a/README.md b/README.md index cc91307..6ffef3f 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ norcube langsync namespaces list # LangSync namespaces norcube domainradar check acme.dev # is a domain free? norcube monitor status # open incidents and monitors that need attention norcube billing usage estimate # this month's charges so far +norcube cms validate ./site # check a CMS site's schema and content, offline norcube doctor # something not working? start here ``` diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 3dfd66a..d24b0ce 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -204,7 +204,7 @@ exit codes may not. | Exit | Codes | Meaning | | --- | --- | --- | | 0 | | Success | -| 1 | `error`, `server_error`, `job_failed`, `unhealthy` | General failure; a waited-for job ended unsuccessfully (`details` holds the job); a `--fail-on` state was found (`monitor status`, `details` holds the report) | +| 1 | `error`, `server_error`, `job_failed`, `unhealthy`, `invalid` | General failure; a waited-for job ended unsuccessfully (`details` holds the job); a `--fail-on` state was found (`monitor status`, `details` holds the report); a local check found findings at the `--fail-on` severity (`cms validate`, `details` holds the counts, stdout the report) | | 2 | `usage_error`, `validation_failed`, `org_not_found` | Fix the command line or input; also any prompt without a terminal | | 3 | `not_found` | The API answered 404 | | 4 | `login_required` | Not signed in, session expired or revoked, CI token expired, revoked or unknown | @@ -732,7 +732,7 @@ flag; [CHANGELOG.md](../CHANGELOG.md) says when each arrived. | `billing` | `status`; `subscriptions list`; `usage estimate | metrics`; `invoices list | download`; `budget get | set` | | `monitor` | `status` (`--fail-on`); `monitors list | get | create | update | delete | pause | resume | run` (`--wait`), `monitors bulk pause | resume | delete`, `monitors results list`, `monitors status-changes list`, `monitors stats get`, `monitors availability get`, `monitors certificate get`, `monitors alerts get | set`; `incidents list | get | acknowledge | summary`; `channels list | get | create | update | delete | test | verify`, `channels deliveries list`; `status-pages list | get | create | update | delete | publish | unpublish | preview-link`, `status-pages layout get | set`, `status-pages incidents list | get | create | update`, `status-pages incidents updates create`, `status-pages subscribers list | delete`; `maintenance list | get | create | update | cancel | finish` | | PromptHub | No command group; `nrc api prompthub ...` | -| CMS | None (CMS has no public API) | +| `cms` | `validate` (`--only schema|content|links`, `--collection`, `--fail-on`), offline on a site checkout; the CMS has no public API, so there are no resource commands | CI token scopes, as defined by Norcube Auth and listed by `nrc auth ci-token scopes`: `backup.read`, `backup.write` (run backups @@ -800,6 +800,7 @@ changelog, and the owner's decisions in the planning sessions of | 2026-11-06 | Maintenance windows in the CLI: `monitor maintenance`. The resource is a mass noun, an exception to the plural rule of P1, because "maintenances" isn't a word and "maintenance windows" is long to type for something used in deploy scripts; `maintenance-windows` is an alias. A window is named by id only: titles repeat by design. `--state` filters on the field the result calls `state` (the API's query parameter is `status`), with the API's values. There is no `delete`: the API deletes only a cancelled window, a completed one explains a gap in uptime and goes by itself after two years, and `cancel` already takes a window out of everything people see; `nrc api` reaches the endpoint. `finish` is a new verb, because `cancel` would say the work didn't happen. `cancel` confirms, since it mails whoever was told; `finish` doesn't and has no `--yes`, because ending a silence is the safe direction and it must run unattended at the end of a deploy. Notifications are explicit in the request, because the API takes no defaults: the flags default to on, as the owner decided, and `--no-notify` turns off all three. `monitor status` keeps a monitor among `problems` when what is wrong is a calendar condition or a watched aspect, because a window doesn't hold those | Owner's brief. Rejected: a bare `2h` meaning two hours ahead, since `ParseTimeArg` reads the same spelling as two hours ago | owner | | 2026-11-06 | `-o id` prints only the result's id. Deploy scripts capture what they create with `id=$(... -o id)`, and `-o text` prints the state as well, so it would need `cut`. It is a global output value rather than a flag of one command, so it means the same everywhere (P1, P13) | Named in the owner's maintenance windows plan. Rejected: `--query id -o text` as the documented form, which still works but is too long for the one thing every script needs | owner | | 2026-11-05 | `--auto-post` is the one page setting `create` doesn't require: the flag came after 0.23.0, so requiring it would break scripts that create pages, and the API keeps it off unless asked. `--notify` is sent only when given, and exists only on writes that add an update | Compatibility rule P10; owner's brief | owner | +| 2026-11-15 | `cms validate`: a `cms` group whose first command works on a site checkout, offline, with no sign-in. The checks live in the public `github.com/norcubeplatform/cms-schema` module, which the CMS service and the dashboard's fixtures share, so the CLI is a thin wrapper and cannot drift from the editor. `--fail-on` defaults to `error` (unlike `monitor status`, whose default is `none`) because a validator that exits 0 on errors would be useless in CI; findings keep their severity whatever `--fail-on` says. A failed run uses the new code `invalid`, not `unhealthy`: `unhealthy` describes a service's state, `invalid` what the command checked. The report is printed before the error so CI keeps it. The path argument completes directories only | Owner's brief: validate a whole site against every page, locally and in CI, with the rules the editor runs. Rejected: putting the checks in the CLI module (the private backend would then depend on the CLI's releases and dependency graph); a `--strict` flag (the tree already has `--fail-on` for this); naming the command `cms schema validate` (content and links are checked too) | owner | --- diff --git a/go.mod b/go.mod index 0a35a57..18558e2 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/norcubeplatform/cli go 1.26.1 -toolchain go1.26.10 +toolchain go1.26.11 require ( github.com/charmbracelet/huh v1.0.0 @@ -12,6 +12,7 @@ require ( github.com/gofrs/flock v0.13.0 github.com/google/uuid v1.6.0 github.com/jmespath-community/go-jmespath v1.1.1 + github.com/norcubeplatform/cms-schema v0.1.1 github.com/oapi-codegen/runtime v1.4.0 github.com/pelletier/go-toml/v2 v2.3.1 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c diff --git a/go.sum b/go.sum index bd05717..2cb619c 100644 --- a/go.sum +++ b/go.sum @@ -129,6 +129,8 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= +github.com/norcubeplatform/cms-schema v0.1.1 h1:19HHWyqDrTGG2THK54TvzngCdhUNxWFywsuUrhLzAbU= +github.com/norcubeplatform/cms-schema v0.1.1/go.mod h1:fY05NpvoygKgMBZjj3+R6KI1vko9CSJPJKS02n6WRh0= github.com/oapi-codegen/runtime v1.4.0 h1:KLOSFOp7UzkbS7Cs1ms6NBEKYr0WmH2wZG0KKbd2er4= github.com/oapi-codegen/runtime v1.4.0/go.mod h1:5sw5fxCDmnOzKNYmkVNF8d34kyUeejJEY8HNT2WaPec= github.com/oasdiff/yaml v0.1.1 h1:6nHx+pn9gBRM6YpBlFZFQGCCd1nuvqOBtTD3KKTgGxY= diff --git a/internal/cli/cms/cmd.go b/internal/cli/cms/cmd.go new file mode 100644 index 0000000..4dc2394 --- /dev/null +++ b/internal/cli/cms/cmd.go @@ -0,0 +1,23 @@ +// Package cms implements the `norcube cms ...` command tree. Norcube CMS +// edits content that lives in the site's own git repository, so these +// commands work on a checkout of the site, offline: no sign-in, no +// organization, no network. The checks are the ones the editor runs, +// shared through the public cms-schema module, so a site that passes here +// opens cleanly in the CMS. +package cms + +import "github.com/spf13/cobra" + +// NewCmd returns the `cms` parent command with all subcommands. +func NewCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "cms", + Short: "Check a Norcube CMS site's schema and content from its repository", + Long: `Norcube CMS keeps a site's schema in .norcube/cms/ and its content in the +site's own repository. These commands read a checkout of that repository +and need no sign-in: run them on your machine before you push, or in the +site's CI to block a change that breaks the content model.`, + } + cmd.AddCommand(newValidateCmd()) + return cmd +} diff --git a/internal/cli/cms/validate.go b/internal/cli/cms/validate.go new file mode 100644 index 0000000..e44c09d --- /dev/null +++ b/internal/cli/cms/validate.go @@ -0,0 +1,198 @@ +package cms + +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cms-schema/load" + "github.com/norcubeplatform/cms-schema/report" + "github.com/norcubeplatform/cms-schema/validate" + + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/output" +) + +// What `validate --fail-on` accepts, from the strictest to none. +var validateFailOn = []string{failOnWarning, failOnError, failOnNone} + +const ( + failOnError = "error" + failOnWarning = "warning" + failOnNone = "none" +) + +// validateScopes are the values of --only, in the order the checks run. +var validateScopes = []string{validate.ScopeSchema, validate.ScopeContent, validate.ScopeLinks} + +// validateReportVersion is the version of the `cms validate -o json` +// document. Within a version changes are additive only. +const validateReportVersion = 1 + +// validateReport is what `cms validate -o json` prints. +type validateReport struct { + SchemaVersion int `json:"schemaVersion" yaml:"schemaVersion"` + // Path is the site directory as given on the command line. + Path string `json:"path" yaml:"path"` + // Findings are sorted by file, path and severity. Each names a rule + // from the frozen list in the cms-schema module. + Findings []report.Finding `json:"findings" yaml:"findings"` + Summary validateSummary `json:"summary" yaml:"summary"` +} + +// validateSummary counts what the run looked at and found. +type validateSummary struct { + // Files is the number of content files checked, SchemaFiles the + // number of schema files loaded. + Files int `json:"files" yaml:"files"` + SchemaFiles int `json:"schemaFiles" yaml:"schemaFiles"` + Errors int `json:"errors" yaml:"errors"` + Warnings int `json:"warnings" yaml:"warnings"` +} + +func newValidateCmd() *cobra.Command { + var ( + only []string + collection string + failOn string + ) + cmd := &cobra.Command{ + Use: "validate [path]", + Annotations: cmdutil.Reads(), + Short: "Check a site's CMS schema and content the way the editor does", + Long: `Reads the site checkout at path (default: the current directory) and +reports what the Norcube CMS editor would: schema files that do not load +or contradict themselves, content that breaks a field's rules, and links, +images and references that point at nothing. Nothing is sent anywhere; +the command needs no sign-in. + +Three groups of checks run, selectable with --only: + schema .norcube/cms/ loads: YAML, $ref, field types and knobs, select + options, bounds, regexes, visibleIf paths, storages, preview + content every content file against its collection: required, value + shapes, array item kinds and bounds, regex, length, uniqueness, + custom validators, out-of-schema keys + links the site as a whole: two files at one URL, links no page + produces, missing images and files, dangling references + +Each finding names the file, the field path inside it, a severity and a +rule id (schema.unresolved_ref, content.required, links.missing_asset…). +Rule ids are stable; match on them in scripts. + +The exit code follows --fail-on: with "error" (the default) the command +exits 1 when any finding is an error, with "warning" when any finding +exists, with "none" it always exits 0 and only reports. A path that is +not a CMS site exits 3.`, + Example: ` norcube cms validate + norcube cms validate ./site --fail-on warning + norcube cms validate --only schema + # In CI, keep the report as an artifact + norcube cms validate -o json > cms-validate.json + norcube cms validate -o json --query "findings[?rule=='links.missing_asset'].file"`, + Args: cobra.MaximumNArgs(1), + ValidArgsFunction: func(*cobra.Command, []string, string) ([]cobra.Completion, cobra.ShellCompDirective) { + return nil, cobra.ShellCompDirectiveFilterDirs + }, + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + for _, o := range only { + if err := oneOf("--only", o, validateScopes); err != nil { + return nil, err + } + } + if err := oneOf("--fail-on", failOn, validateFailOn); err != nil { + return nil, err + } + path := "." + if len(args) == 1 { + path = args[0] + } + info, err := os.Stat(path) + switch { + case errors.Is(err, os.ErrNotExist): + return nil, clierr.Usage(fmt.Errorf("%s: no such directory", path)) + case err != nil: + return nil, err + case !info.IsDir(): + return nil, clierr.Usage(fmt.Errorf("%s is a file; pass the site's directory", path)) + } + + res, err := validate.Site(os.DirFS(path), validate.Options{Only: only, Collection: collection}) + if errors.Is(err, load.ErrNotASite) { + return nil, &clierr.Error{ + Code: clierr.CodeNotFound, + Message: fmt.Sprintf("%s holds no Norcube CMS site: no %s and no %s", path, load.ConfigFile, load.LegacyConfigFile), + Hint: "Run the command from the site's root, or pass its path.", + Err: err, + } + } + if err != nil { + return nil, err + } + + rep := validateReport{ + SchemaVersion: validateReportVersion, + Path: path, + Findings: res.Findings, + Summary: validateSummary{Files: res.Files, SchemaFiles: res.SchemaFiles, Errors: res.Errors, Warnings: res.Warnings}, + } + if rep.Findings == nil { + rep.Findings = []report.Finding{} + } + view := output.View[report.Finding]{ + Value: rep, + Table: output.Table[report.Finding]{ + Headers: []string{"SEVERITY", "FILE", "PATH", "RULE", "MESSAGE"}, + Rows: func(f report.Finding) []string { + return []string{string(f.Severity), f.File, f.Path, string(f.Rule), f.Message} + }, + Items: rep.Findings, + }, + } + fmt.Fprintf(cmd.ErrOrStderr(), "%d content %s, %d schema %s: %d %s, %d %s\n", + res.Files, plural(res.Files, "file"), res.SchemaFiles, plural(res.SchemaFiles, "file"), + res.Errors, plural(res.Errors, "error"), res.Warnings, plural(res.Warnings, "warning")) + + fail := (failOn == failOnError && res.Errors > 0) || + (failOn == failOnWarning && (res.Errors > 0 || res.Warnings > 0)) + if !fail { + return view, nil + } + if err := cmdutil.Print(cmd, view); err != nil { + return nil, err + } + return nil, &clierr.Error{ + Code: clierr.CodeInvalid, + Message: fmt.Sprintf("%s does not pass: %d %s, %d %s", path, res.Errors, plural(res.Errors, "error"), res.Warnings, plural(res.Warnings, "warning")), + Hint: "Fix the findings above, or pass --fail-on none to report without failing.", + Details: rep.Summary, + } + }), + } + cmd.Flags().StringSliceVar(&only, "only", nil, "Run only these checks: schema, content, links (repeatable or comma-separated; default all)") + cmd.Flags().StringVar(&collection, "collection", "", "Check the content and links of one collection only, by its key") + cmd.Flags().StringVar(&failOn, "fail-on", failOnError, "Exit 1 on findings of this severity or worse: warning, error or none") + cmdutil.FlagEnum(cmd, "only", validateScopes...) + cmdutil.FlagEnum(cmd, "fail-on", validateFailOn...) + return cmd +} + +// oneOf rejects a flag value outside its allowed list before any work. +func oneOf(flag, v string, allowed []string) error { + for _, a := range allowed { + if v == a { + return nil + } + } + return clierr.Usage(fmt.Errorf("%s %q: one of %s", flag, v, strings.Join(allowed, ", "))) +} + +func plural(n int, word string) string { + if n == 1 { + return word + } + return word + "s" +} diff --git a/internal/cli/cms_test.go b/internal/cli/cms_test.go new file mode 100644 index 0000000..95ea5db --- /dev/null +++ b/internal/cli/cms_test.go @@ -0,0 +1,140 @@ +package cli + +import ( + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/config" +) + +// cms validate needs no session: an empty, isolated config is enough. +func cmsEnv(t *testing.T) { + t.Helper() + isolatedConfig(t, func(*config.File) {}) +} + +func TestCmsValidateExitCodes(t *testing.T) { + t.Run("errors fail by default", func(t *testing.T) { + cmsEnv(t) + out, stderr, err := run(t, "cms", "validate", "testdata/cms-site-broken", "-o", "json") + if err == nil { + t.Fatal("expected an error") + } + e := Describe(err) + if e.Code != clierr.CodeInvalid || e.ExitCode() != clierr.ExitError { + t.Fatalf("code %q exit %d", e.Code, e.ExitCode()) + } + // The report is still printed, so CI keeps the findings. + var rep struct { + Findings []struct { + File, Path, Rule, Severity string + } + Summary struct{ Errors, Warnings int } + } + if jerr := json.Unmarshal([]byte(out), &rep); jerr != nil { + t.Fatalf("stdout is not the JSON report: %v\n%s", jerr, out) + } + hasRequired := false + for _, f := range rep.Findings { + if f.Rule == "content.required" && f.Path == "title" { + hasRequired = true + } + } + if rep.Summary.Errors != 1 || !hasRequired { + t.Fatalf("report: %+v", rep) + } + if !strings.Contains(stderr, "1 error") { + t.Errorf("summary missing on stderr: %q", stderr) + } + }) + t.Run("fail-on none always passes", func(t *testing.T) { + cmsEnv(t) + if _, _, err := run(t, "cms", "validate", "testdata/cms-site-broken", "--fail-on", "none", "-o", "json"); err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + t.Run("fail-on warning fails on warnings", func(t *testing.T) { + cmsEnv(t) + _, _, err := run(t, "cms", "validate", "testdata/cms-site", "--fail-on", "warning", "-o", "json") + if e := Describe(err); e == nil || e.Code != clierr.CodeInvalid { + t.Fatalf("got %v", err) + } + }) + t.Run("warnings alone pass by default", func(t *testing.T) { + cmsEnv(t) + if _, _, err := run(t, "cms", "validate", "testdata/cms-site", "-o", "json"); err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) +} + +func TestCmsValidateRejectsBadInvocations(t *testing.T) { + cases := []struct { + name string + args []string + code string + exit int + }{ + {"not a site", []string{"cms", "validate", "testdata"}, clierr.CodeNotFound, clierr.ExitNotFound}, + {"missing directory", []string{"cms", "validate", "testdata/nope"}, clierr.CodeUsage, clierr.ExitUsage}, + {"a file, not a directory", []string{"cms", "validate", "testdata/cms-site/.norcube/cms/config.yml"}, clierr.CodeUsage, clierr.ExitUsage}, + {"unknown scope", []string{"cms", "validate", "testdata/cms-site", "--only", "everything"}, clierr.CodeUsage, clierr.ExitUsage}, + {"unknown fail-on", []string{"cms", "validate", "testdata/cms-site", "--fail-on", "sometimes"}, clierr.CodeUsage, clierr.ExitUsage}, + {"two paths", []string{"cms", "validate", "a", "b"}, clierr.CodeUsage, clierr.ExitUsage}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + cmsEnv(t) + _, _, err := run(t, c.args...) + e := Describe(err) + if e == nil || e.Code != c.code || e.ExitCode() != c.exit { + t.Fatalf("got %v (code %v)", err, e) + } + }) + } +} + +func TestCmsValidateOnlyAndCollection(t *testing.T) { + cmsEnv(t) + out, _, err := run(t, "cms", "validate", "testdata/cms-site", "--only", "schema", "-o", "json") + if err != nil { + t.Fatal(err) + } + var rep struct { + Findings []any + Summary struct{ Files int } + } + if err := json.Unmarshal([]byte(out), &rep); err != nil { + t.Fatal(err) + } + if rep.Summary.Files != 0 || len(rep.Findings) != 0 { + t.Fatalf("schema-only run touched content: %+v", rep) + } + out, _, err = run(t, "cms", "validate", "testdata/cms-site", "--collection", "ghost", "-o", "json") + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(out), &rep); err != nil { + t.Fatal(err) + } + if rep.Summary.Files != 0 { + t.Fatalf("an unknown collection should match no file: %+v", rep) + } +} + +func TestCmsValidateIsLocal(t *testing.T) { + // No endpoint, no token, no network: the command must not care. + cmsEnv(t) + t.Setenv("NORCUBE_TOKEN", "") + if _, _, err := run(t, "cms", "validate", "testdata/cms-site", "--endpoint-url", "auth=http://127.0.0.1:9", "-o", "json"); err != nil { + t.Fatalf("a local command reached for the network: %v", err) + } + var notASite *clierr.Error + _, _, err := run(t, "cms", "validate", "testdata") + if !errors.As(err, ¬ASite) || notASite.Code != clierr.CodeNotFound { + t.Fatalf("got %v", err) + } +} diff --git a/internal/cli/golden_test.go b/internal/cli/golden_test.go index 62226e1..7aef499 100644 --- a/internal/cli/golden_test.go +++ b/internal/cli/golden_test.go @@ -206,6 +206,7 @@ func TestGoldenOutput(t *testing.T) { {"auth-sessions-list", []string{"auth", "sessions", "list"}}, {"auth-ci-token-list", []string{"auth", "ci-token", "list"}}, {"auth-ci-token-scopes", []string{"auth", "ci-token", "scopes"}}, + {"cms-validate", []string{"cms", "validate", "testdata/cms-site"}}, } for _, c := range commands { for format, ext := range goldenFormats { diff --git a/internal/cli/root.go b/internal/cli/root.go index 74ca3b5..9e52eef 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -12,6 +12,7 @@ import ( "github.com/norcubeplatform/cli/internal/buildinfo" "github.com/norcubeplatform/cli/internal/cli/backup" "github.com/norcubeplatform/cli/internal/cli/billing" + "github.com/norcubeplatform/cli/internal/cli/cms" "github.com/norcubeplatform/cli/internal/cli/domainradar" "github.com/norcubeplatform/cli/internal/cli/langsync" "github.com/norcubeplatform/cli/internal/cli/monitor" @@ -108,6 +109,7 @@ func NewRootCmd() *cobra.Command { domainradar.NewCmd(), billing.NewCmd(), monitor.NewCmd(), + cms.NewCmd(), ) markUsageErrors(cmd) completion.Bind(flags) diff --git a/internal/cli/testdata/cms-site-broken/.norcube/cms/collections/pages.yml b/internal/cli/testdata/cms-site-broken/.norcube/cms/collections/pages.yml new file mode 100644 index 0000000..fce8a58 --- /dev/null +++ b/internal/cli/testdata/cms-site-broken/.norcube/cms/collections/pages.yml @@ -0,0 +1,15 @@ +label: Pages +path: src/content/pages +previewPath: '/{slug}/' +localeFrom: none +fields: + - key: title + type: text + label: Title + required: true + - key: slug + type: text + label: Slug + - key: link + type: link + label: Link diff --git a/internal/cli/testdata/cms-site-broken/.norcube/cms/config.yml b/internal/cli/testdata/cms-site-broken/.norcube/cms/config.yml new file mode 100644 index 0000000..de05552 --- /dev/null +++ b/internal/cli/testdata/cms-site-broken/.norcube/cms/config.yml @@ -0,0 +1,5 @@ +pagesDir: src/content/pages +knownPaths: ['/api/*'] +preview: + defaultLocale: en + locales: [en] diff --git a/internal/cli/testdata/cms-site-broken/src/content/pages/index.md b/internal/cli/testdata/cms-site-broken/src/content/pages/index.md new file mode 100644 index 0000000..4b7a583 --- /dev/null +++ b/internal/cli/testdata/cms-site-broken/src/content/pages/index.md @@ -0,0 +1,4 @@ +--- +title: '' +link: /about/ +--- diff --git a/internal/cli/testdata/cms-site/.norcube/cms/collections/pages.yml b/internal/cli/testdata/cms-site/.norcube/cms/collections/pages.yml new file mode 100644 index 0000000..fce8a58 --- /dev/null +++ b/internal/cli/testdata/cms-site/.norcube/cms/collections/pages.yml @@ -0,0 +1,15 @@ +label: Pages +path: src/content/pages +previewPath: '/{slug}/' +localeFrom: none +fields: + - key: title + type: text + label: Title + required: true + - key: slug + type: text + label: Slug + - key: link + type: link + label: Link diff --git a/internal/cli/testdata/cms-site/.norcube/cms/config.yml b/internal/cli/testdata/cms-site/.norcube/cms/config.yml new file mode 100644 index 0000000..de05552 --- /dev/null +++ b/internal/cli/testdata/cms-site/.norcube/cms/config.yml @@ -0,0 +1,5 @@ +pagesDir: src/content/pages +knownPaths: ['/api/*'] +preview: + defaultLocale: en + locales: [en] diff --git a/internal/cli/testdata/cms-site/src/content/pages/contact.md b/internal/cli/testdata/cms-site/src/content/pages/contact.md new file mode 100644 index 0000000..43f8f68 --- /dev/null +++ b/internal/cli/testdata/cms-site/src/content/pages/contact.md @@ -0,0 +1,5 @@ +--- +title: Contact +link: /api/health +draft: true +--- diff --git a/internal/cli/testdata/cms-site/src/content/pages/index.md b/internal/cli/testdata/cms-site/src/content/pages/index.md new file mode 100644 index 0000000..b190f63 --- /dev/null +++ b/internal/cli/testdata/cms-site/src/content/pages/index.md @@ -0,0 +1,5 @@ +--- +title: Home +slug: '' +link: /about/ +--- diff --git a/internal/cli/testdata/golden/cms-validate.json b/internal/cli/testdata/golden/cms-validate.json new file mode 100644 index 0000000..5e18fe1 --- /dev/null +++ b/internal/cli/testdata/golden/cms-validate.json @@ -0,0 +1,27 @@ +{ + "schemaVersion": 1, + "path": "testdata/cms-site", + "findings": [ + { + "file": "src/content/pages/contact.md", + "severity": "warning", + "rule": "content.extra_keys", + "message": "keys draft are not in the schema", + "hint": "They show in the editor's out-of-schema panel. Add them to the schema or remove them." + }, + { + "file": "src/content/pages/index.md", + "path": "link", + "severity": "warning", + "rule": "links.unresolved_link", + "message": "links to /about/, which no content file produces", + "hint": "If the site serves this route from code, add it to knownPaths in config.yml; otherwise fix the link." + } + ], + "summary": { + "files": 2, + "schemaFiles": 2, + "errors": 0, + "warnings": 2 + } +} diff --git a/internal/cli/testdata/golden/cms-validate.tsv b/internal/cli/testdata/golden/cms-validate.tsv new file mode 100644 index 0000000..fd7e5b7 --- /dev/null +++ b/internal/cli/testdata/golden/cms-validate.tsv @@ -0,0 +1,2 @@ +warning src/content/pages/contact.md content.extra_keys keys draft are not in the schema +warning src/content/pages/index.md link links.unresolved_link links to /about/, which no content file produces diff --git a/internal/cli/testdata/golden/cms-validate.txt b/internal/cli/testdata/golden/cms-validate.txt new file mode 100644 index 0000000..c4dea09 --- /dev/null +++ b/internal/cli/testdata/golden/cms-validate.txt @@ -0,0 +1,3 @@ +SEVERITY FILE PATH RULE MESSAGE +warning src/content/pages/contact.md content.extra_keys keys draft are not in the schema +warning src/content/pages/index.md link links.unresolved_link links to /about/, which no content file produces diff --git a/internal/cli/testdata/golden/cms-validate.yaml b/internal/cli/testdata/golden/cms-validate.yaml new file mode 100644 index 0000000..63761de --- /dev/null +++ b/internal/cli/testdata/golden/cms-validate.yaml @@ -0,0 +1,19 @@ +findings: + - file: src/content/pages/contact.md + hint: They show in the editor's out-of-schema panel. Add them to the schema or remove them. + message: keys draft are not in the schema + rule: content.extra_keys + severity: warning + - file: src/content/pages/index.md + hint: If the site serves this route from code, add it to knownPaths in config.yml; otherwise fix the link. + message: links to /about/, which no content file produces + path: link + rule: links.unresolved_link + severity: warning +path: testdata/cms-site +schemaVersion: 1 +summary: + errors: 0 + files: 2 + schemaFiles: 2 + warnings: 2 diff --git a/internal/clierr/clierr_test.go b/internal/clierr/clierr_test.go index ce12672..37b3b46 100644 --- a/internal/clierr/clierr_test.go +++ b/internal/clierr/clierr_test.go @@ -31,7 +31,7 @@ func TestIsUsage(t *testing.T) { // Codes that report an outcome rather than a failure of the CLI exit 1. func TestOutcomeCodesExitOne(t *testing.T) { - for _, c := range []string{CodeJobFailed, CodeUnhealthy} { + for _, c := range []string{CodeJobFailed, CodeUnhealthy, CodeInvalid} { if got := ExitFor(c); got != ExitError { t.Errorf("%s exits %d, want %d", c, got, ExitError) } diff --git a/internal/clierr/error.go b/internal/clierr/error.go index 53841bb..be7d65e 100644 --- a/internal/clierr/error.go +++ b/internal/clierr/error.go @@ -29,6 +29,10 @@ const ( // (`monitor status --fail-on`) found it, e.g. an open critical // incident. Exit code 1; details hold what it found. CodeUnhealthy = "unhealthy" + // CodeInvalid: a command that checks something local (`cms validate`) + // found findings at the severity --fail-on asks it to fail on. Exit + // code 1; details hold the counts, the result on stdout the findings. + CodeInvalid = "invalid" ) // Error is a failure described for both people and scripts. Printed as