diff --git a/internal/pkg/modules/notify.go b/internal/pkg/modules/notify.go index cf40fa0..f445515 100644 --- a/internal/pkg/modules/notify.go +++ b/internal/pkg/modules/notify.go @@ -167,15 +167,7 @@ func nestedProblems(field string, err error) []string { if !errors.As(err, &pe) { return []string{field + ": " + err.Error()} } - problems := make([]string, len(pe.Problems)) - for i, problem := range pe.Problems { - if rest, ok := strings.CutPrefix(problem, "body: "); ok { - problems[i] = field + ": " + rest - continue - } - problems[i] = field + "." + problem - } - return problems + return pe.Within(field) } // parsePriority reads a priority given as 1-5 or by name. nil is the diff --git a/internal/pkg/modules/registry.go b/internal/pkg/modules/registry.go index 1baaeb5..44c48dc 100644 --- a/internal/pkg/modules/registry.go +++ b/internal/pkg/modules/registry.go @@ -32,6 +32,22 @@ func (e *PayloadError) Error() string { return "invalid payload: " + strings.Join(e.Problems, "; ") } +// Within returns the problems as problems of field, the place that holds +// the payload in a larger object: "done[0]: ..." becomes +// "field.done[0]: ...", and a problem with the whole payload, +// "body: ...", becomes "field: ...". +func (e *PayloadError) Within(field string) []string { + problems := make([]string, len(e.Problems)) + for i, problem := range e.Problems { + if rest, ok := strings.CutPrefix(problem, "body: "); ok { + problems[i] = field + ": " + rest + continue + } + problems[i] = field + "." + problem + } + return problems +} + // Env is what a module may know when it builds a receipt: the time it is // built at, how times print and how notifications are laid out. A module // never reads the clock itself, so that its output is reproducible. diff --git a/internal/pkg/modules/registry_test.go b/internal/pkg/modules/registry_test.go index f4afcbf..a11e2a4 100644 --- a/internal/pkg/modules/registry_test.go +++ b/internal/pkg/modules/registry_test.go @@ -79,6 +79,24 @@ func TestRegistryRefusals(t *testing.T) { } } +// A payload's problems name their field from the place that holds the +// payload, and a problem with the whole payload names that place. +func TestPayloadErrorWithin(t *testing.T) { + err := &modules.PayloadError{Problems: []string{ + "body: expected a JSON object, got array", + "done[0]: index 5 is out of range", + `"we ird": unknown field`, + }} + want := []string{ + "payload: expected a JSON object, got array", + "payload.done[0]: index 5 is out of range", + `payload."we ird": unknown field`, + } + if got := err.Within("payload"); strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("Within = %q, want %q", got, want) + } +} + func TestEnvStamp(t *testing.T) { london, err := time.LoadLocation("Europe/London") if err != nil {