command/format: be resilient to incomplete schema when formatting state

In all real cases the schemas should be populated here, but we don't want
to panic in UI rendering code if there's a bug here.

This can also be tripped up by tests with incomplete mocks. It's
unfortunate that this can therefore mask some problems in tests, but tests
can protect against it by asserting on specific output text rather than
just assuming that a zero exit status is a pass.
This commit is contained in:
Martin Atkins 2018-10-11 10:51:54 -07:00
parent a6f399517b
commit 34ebde0b95
1 changed files with 18 additions and 0 deletions

View File

@ -116,9 +116,22 @@ func formatStateModule(
var schema *configschema.Block
provider := m.Resources[key].ProviderConfig.ProviderConfig.StringCompact()
if _, exists := schemas.Providers[provider]; !exists {
// This should never happen in normal use because we should've
// loaded all of the schemas and checked things prior to this
// point. We can't return errors here, but since this is UI code
// we will try to do _something_ reasonable.
p.buf.WriteString(fmt.Sprintf("# missing schema for provider %q\n\n", provider))
continue
}
switch addr.Mode {
case addrs.ManagedResourceMode:
if _, exists := schemas.Providers[provider].ResourceTypes[addr.Type]; !exists {
p.buf.WriteString(fmt.Sprintf("# missing schema for provider %q resource type %s\n\n", provider, addr.Type))
continue
}
p.buf.WriteString(fmt.Sprintf(
"resource %q %q {\n",
addr.Type,
@ -126,6 +139,11 @@ func formatStateModule(
))
schema = schemas.Providers[provider].ResourceTypes[addr.Type]
case addrs.DataResourceMode:
if _, exists := schemas.Providers[provider].ResourceTypes[addr.Type]; !exists {
p.buf.WriteString(fmt.Sprintf("# missing schema for provider %q data source %s\n\n", provider, addr.Type))
continue
}
p.buf.WriteString(fmt.Sprintf(
"data %q %q {\n",
addr.Type,