diff --git a/.golangci.yml b/.golangci.yml index 79b264d..5bfffb4 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -122,6 +122,7 @@ issues: - gosec - scopelint - unparam + - goconst # - text: "should have a package comment" # linters: diff --git a/README.md b/README.md index 933eec6..1ead785 100644 --- a/README.md +++ b/README.md @@ -294,9 +294,7 @@ func buildTerraformDocs(path string, tmpl string) (string, error) { config := print.DefaultConfig() config.ModuleRoot = path // module root path (can be relative or absolute) - _, options := config.Extract() - - module, err := terraform.LoadWithOptions(options) + module, err := terraform.LoadWithOptions(config) if err != nil { return "", err } diff --git a/docs/reference/asciidoc-document.md b/docs/reference/asciidoc-document.md index e547d3c..0d26d6d 100644 --- a/docs/reference/asciidoc-document.md +++ b/docs/reference/asciidoc-document.md @@ -484,4 +484,8 @@ generates the following output: Description: It's unquoted output. + ## This is an example of a footer + + It looks exactly like a header, but is placed at the end of the document + [examples]: https://github.com/terraform-docs/terraform-docs/tree/master/examples diff --git a/docs/reference/asciidoc-table.md b/docs/reference/asciidoc-table.md index 21b0c00..b343f96 100644 --- a/docs/reference/asciidoc-table.md +++ b/docs/reference/asciidoc-table.md @@ -421,4 +421,8 @@ generates the following output: |[[output_unquoted]] <> |It's unquoted output. |=== + ## This is an example of a footer + + It looks exactly like a header, but is placed at the end of the document + [examples]: https://github.com/terraform-docs/terraform-docs/tree/master/examples diff --git a/docs/reference/json.md b/docs/reference/json.md index a7eebdf..6659c84 100644 --- a/docs/reference/json.md +++ b/docs/reference/json.md @@ -57,7 +57,7 @@ generates the following output: { "header": "Usage:\n\nExample of 'foo_bar' module in `foo_bar.tf`.\n\n- list item 1\n- list item 2\n\nEven inline **formatting** in _here_ is possible.\nand some [link](https://domain.com/)\n\n* list item 3\n* list item 4\n\n```hcl\nmodule \"foo_bar\" {\n source = \"github.com/foo/bar\"\n\n id = \"1234567890\"\n name = \"baz\"\n\n zones = [\"us-east-1\", \"us-west-1\"]\n\n tags = {\n Name = \"baz\"\n Created-By = \"first.last@email.com\"\n Date-Created = \"20180101\"\n }\n}\n```\n\nHere is some trailing text after code block,\nfollowed by another line of text.\n\n| Name | Description |\n|------|-----------------|\n| Foo | Foo description |\n| Bar | Bar description |", - "footer": "", + "footer": "## This is an example of a footer\n\nIt looks exactly like a header, but is placed at the end of the document", "inputs": [ { "name": "bool-1", diff --git a/docs/reference/markdown-document.md b/docs/reference/markdown-document.md index 0a9c38e..b614611 100644 --- a/docs/reference/markdown-document.md +++ b/docs/reference/markdown-document.md @@ -486,4 +486,8 @@ generates the following output: Description: It's unquoted output. + ## This is an example of a footer + + It looks exactly like a header, but is placed at the end of the document + [examples]: https://github.com/terraform-docs/terraform-docs/tree/master/examples diff --git a/docs/reference/markdown-table.md b/docs/reference/markdown-table.md index e022355..f3775a8 100644 --- a/docs/reference/markdown-table.md +++ b/docs/reference/markdown-table.md @@ -184,4 +184,8 @@ generates the following output: | [output-2](#output\_output-2) | It's output number two. | | [unquoted](#output\_unquoted) | It's unquoted output. | + ## This is an example of a footer + + It looks exactly like a header, but is placed at the end of the document + [examples]: https://github.com/terraform-docs/terraform-docs/tree/master/examples diff --git a/docs/reference/pretty.md b/docs/reference/pretty.md index db52246..d3e798d 100644 --- a/docs/reference/pretty.md +++ b/docs/reference/pretty.md @@ -259,4 +259,8 @@ generates the following output: output.unquoted It's unquoted output. + ## This is an example of a footer + + It looks exactly like a header, but is placed at the end of the document + [examples]: https://github.com/terraform-docs/terraform-docs/tree/master/examples diff --git a/docs/reference/toml.md b/docs/reference/toml.md index 30a4770..75c3eb6 100644 --- a/docs/reference/toml.md +++ b/docs/reference/toml.md @@ -55,7 +55,7 @@ terraform-docs toml --footer-from footer.md ./examples/ generates the following output: header = "Usage:\n\nExample of 'foo_bar' module in `foo_bar.tf`.\n\n- list item 1\n- list item 2\n\nEven inline **formatting** in _here_ is possible.\nand some [link](https://domain.com/)\n\n* list item 3\n* list item 4\n\n```hcl\nmodule \"foo_bar\" {\n source = \"github.com/foo/bar\"\n\n id = \"1234567890\"\n name = \"baz\"\n\n zones = [\"us-east-1\", \"us-west-1\"]\n\n tags = {\n Name = \"baz\"\n Created-By = \"first.last@email.com\"\n Date-Created = \"20180101\"\n }\n}\n```\n\nHere is some trailing text after code block,\nfollowed by another line of text.\n\n| Name | Description |\n|------|-----------------|\n| Foo | Foo description |\n| Bar | Bar description |" - footer = "" + footer = "## This is an example of a footer\n\nIt looks exactly like a header, but is placed at the end of the document" [[inputs]] name = "bool-1" diff --git a/docs/reference/xml.md b/docs/reference/xml.md index 23e6cc4..9788b53 100644 --- a/docs/reference/xml.md +++ b/docs/reference/xml.md @@ -56,7 +56,7 @@ generates the following output:
Usage: Example of 'foo_bar' module in `foo_bar.tf`. - list item 1 - list item 2 Even inline **formatting** in _here_ is possible. and some [link](https://domain.com/) * list item 3 * list item 4 ```hcl module "foo_bar" { source = "github.com/foo/bar" id = "1234567890" name = "baz" zones = ["us-east-1", "us-west-1"] tags = { Name = "baz" Created-By = "first.last@email.com" Date-Created = "20180101" } } ``` Here is some trailing text after code block, followed by another line of text. | Name | Description | |------|-----------------| | Foo | Foo description | | Bar | Bar description |
-
+
## This is an example of a footer It looks exactly like a header, but is placed at the end of the document
bool-1 diff --git a/docs/reference/yaml.md b/docs/reference/yaml.md index 8780a89..79a1667 100644 --- a/docs/reference/yaml.md +++ b/docs/reference/yaml.md @@ -92,7 +92,10 @@ generates the following output: |------|-----------------| | Foo | Foo description | | Bar | Bar description | - footer: "" + footer: |- + ## This is an example of a footer + + It looks exactly like a header, but is placed at the end of the document inputs: - name: bool-1 type: bool diff --git a/format/asciidoc_document.go b/format/asciidoc_document.go index 150a255..8b789a6 100644 --- a/format/asciidoc_document.go +++ b/format/asciidoc_document.go @@ -28,17 +28,15 @@ type asciidocDocument struct { config *print.Config template *template.Template - settings *print.Settings } // NewAsciidocDocument returns new instance of Asciidoc Document. func NewAsciidocDocument(config *print.Config) Type { - settings, _ := config.Extract() items := readTemplateItems(asciidocsDocumentFS, "asciidoc_document") - settings.EscapeCharacters = false + config.Settings.Escape = false - tt := template.New(settings, items...) + tt := template.New(config, items...) tt.CustomFunc(gotemplate.FuncMap{ "type": func(t string) string { result, extraline := PrintFencedAsciidocCodeBlock(t, "hcl") @@ -58,7 +56,7 @@ func NewAsciidocDocument(config *print.Config) Type { return result }, "isRequired": func() bool { - return settings.ShowRequired + return config.Settings.Required }, }) @@ -66,7 +64,6 @@ func NewAsciidocDocument(config *print.Config) Type { Generator: print.NewGenerator("json", config.ModuleRoot), config: config, template: tt, - settings: settings, } } diff --git a/format/asciidoc_document_test.go b/format/asciidoc_document_test.go index 460dce0..ac25c02 100644 --- a/format/asciidoc_document_test.go +++ b/format/asciidoc_document_test.go @@ -17,158 +17,125 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestAsciidocDocument(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.WithSections(), }, "Empty": { - settings: testutil.WithSections(), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideEmpty": { - settings: testutil.WithSections(testutil.WithHideEmpty()), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.WithHideEmpty(), + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideAll": { - settings: print.Settings{}, - options: terraform.Options{ - ShowHeader: false, // Since we don't show the header, the file won't be loaded at all - HeaderFromFile: "bad.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = false // Since we don't show the header, the file won't be loaded at all + c.HeaderFrom = "bad.tf" + }), }, // Settings "WithRequired": { - settings: testutil.WithSections( - print.Settings{ - ShowRequired: true, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.Required = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithAnchor": { - settings: testutil.WithSections( - print.Settings{ - ShowAnchor: true, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.Anchor = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithoutDefault": { - settings: print.Settings{ - ShowInputs: true, - ShowDefault: false, - ShowType: true, - }, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = false + c.Settings.Type = true + }), }, "WithoutType": { - settings: print.Settings{ - ShowInputs: true, - ShowDefault: true, - ShowType: false, - }, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = true + c.Settings.Type = false + }), }, "IndentationOfFour": { - settings: testutil.WithSections( - print.Settings{ - IndentLevel: 4, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.Indent = 4 + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "OutputValues": { - settings: print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: true, - }, - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = true + }), }, "OutputValuesNoSensitivity": { - settings: print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: false, - }, - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = false + }), }, // Only section "OnlyDataSources": { - settings: print.Settings{ShowDataSources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.DataSources = true }), }, "OnlyHeader": { - settings: print.Settings{ShowHeader: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Header = true }), }, "OnlyFooter": { - settings: print.Settings{ShowFooter: true}, - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "footer.md" + }), }, "OnlyInputs": { - settings: print.Settings{ - ShowInputs: true, - ShowDefault: true, - ShowType: true, - }, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = true + c.Settings.Type = true + }), }, "OnlyOutputs": { - settings: print.Settings{ShowOutputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Outputs = true }), }, "OnlyModulecalls": { - settings: print.Settings{ShowModuleCalls: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.ModuleCalls = true }), }, "OnlyProviders": { - settings: print.Settings{ShowProviders: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Providers = true }), }, "OnlyRequirements": { - settings: print.Settings{ShowRequirements: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Requirements = true }), }, "OnlyResources": { - settings: print.Settings{ShowResources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Resources = true }), }, } for name, tt := range tests { @@ -178,13 +145,10 @@ func TestAsciidocDocument(t *testing.T) { expected, err := testutil.GetExpected("asciidoc", "document-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewAsciidocDocument(tt.settings.ToConfig()) + formatter := NewAsciidocDocument(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/asciidoc_table.go b/format/asciidoc_table.go index 28871cc..8ab1759 100644 --- a/format/asciidoc_table.go +++ b/format/asciidoc_table.go @@ -28,17 +28,15 @@ type asciidocTable struct { config *print.Config template *template.Template - settings *print.Settings } // NewAsciidocTable returns new instance of Asciidoc Table. func NewAsciidocTable(config *print.Config) Type { - settings, _ := config.Extract() items := readTemplateItems(asciidocTableFS, "asciidoc_table") - settings.EscapeCharacters = false + config.Settings.Escape = false - tt := template.New(settings, items...) + tt := template.New(config, items...) tt.CustomFunc(gotemplate.FuncMap{ "type": func(t string) string { inputType, _ := PrintFencedCodeBlock(t, "") @@ -57,7 +55,6 @@ func NewAsciidocTable(config *print.Config) Type { Generator: print.NewGenerator("json", config.ModuleRoot), config: config, template: tt, - settings: settings, } } diff --git a/format/asciidoc_table_test.go b/format/asciidoc_table_test.go index 31626da..5bb884e 100644 --- a/format/asciidoc_table_test.go +++ b/format/asciidoc_table_test.go @@ -17,158 +17,125 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestAsciidocTable(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.WithSections(), }, "Empty": { - settings: testutil.WithSections(), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideEmpty": { - settings: testutil.WithSections(testutil.WithHideEmpty()), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.WithHideEmpty(), + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideAll": { - settings: print.Settings{}, - options: terraform.Options{ - ShowHeader: false, // Since we don't show the header, the file won't be loaded at all - HeaderFromFile: "bad.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = false // Since we don't show the header, the file won't be loaded at all + c.HeaderFrom = "bad.tf" + }), }, // Settings "WithRequired": { - settings: testutil.WithSections( - print.Settings{ - ShowRequired: true, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.Required = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithAnchor": { - settings: testutil.WithSections( - print.Settings{ - ShowAnchor: true, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.Anchor = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithoutDefault": { - settings: print.Settings{ - ShowInputs: true, - ShowDefault: false, - ShowType: true, - }, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = false + c.Settings.Type = true + }), }, "WithoutType": { - settings: print.Settings{ - ShowInputs: true, - ShowDefault: true, - ShowType: false, - }, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = true + c.Settings.Type = false + }), }, "IndentationOfFour": { - settings: testutil.WithSections( - print.Settings{ - IndentLevel: 4, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.Indent = 4 + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "OutputValues": { - settings: print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: true, - }, - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = true + }), }, "OutputValuesNoSensitivity": { - settings: print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: false, - }, - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = false + }), }, // Only section "OnlyDataSources": { - settings: print.Settings{ShowDataSources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.DataSources = true }), }, "OnlyHeader": { - settings: print.Settings{ShowHeader: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Header = true }), }, "OnlyFooter": { - settings: print.Settings{ShowFooter: true}, - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "footer.md" + }), }, "OnlyInputs": { - settings: print.Settings{ - ShowInputs: true, - ShowDefault: true, - ShowType: true, - }, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = true + c.Settings.Type = true + }), }, "OnlyOutputs": { - settings: print.Settings{ShowOutputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Outputs = true }), }, "OnlyModulecalls": { - settings: print.Settings{ShowModuleCalls: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.ModuleCalls = true }), }, "OnlyProviders": { - settings: print.Settings{ShowProviders: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Providers = true }), }, "OnlyRequirements": { - settings: print.Settings{ShowRequirements: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Requirements = true }), }, "OnlyResources": { - settings: print.Settings{ShowResources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Resources = true }), }, } for name, tt := range tests { @@ -178,13 +145,10 @@ func TestAsciidocTable(t *testing.T) { expected, err := testutil.GetExpected("asciidoc", "table-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewAsciidocTable(tt.settings.ToConfig()) + formatter := NewAsciidocTable(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/common_test.go b/format/common_test.go index cad58e7..07cad3e 100644 --- a/format/common_test.go +++ b/format/common_test.go @@ -17,46 +17,40 @@ import ( "github.com/stretchr/testify/assert" "github.com/terraform-docs/terraform-docs/internal/testutil" - "github.com/terraform-docs/terraform-docs/terraform" + "github.com/terraform-docs/terraform-docs/print" ) func TestCommonSort(t *testing.T) { tests := map[string]struct { - options terraform.Options + config print.Config }{ "NoSort": { - options: terraform.Options{}, + config: *print.NewConfig(), }, "SortByName": { - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Name: true, - }, - }, + config: testutil.With(func(c *print.Config) { + c.Sort.Enabled = true + c.Sort.By = print.SortName + }), }, "SortByRequired": { - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Required: true, - }, - }, + config: testutil.With(func(c *print.Config) { + c.Sort.Enabled = true + c.Sort.By = print.SortRequired + }), }, "SortByType": { - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Type: true, - }, - }, + config: testutil.With(func(c *print.Config) { + c.Sort.Enabled = true + c.Sort.By = print.SortType + }), }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { assert := assert.New(t) - options, err := terraform.NewOptions().With(&tt.options) - assert.Nil(err) - - module, err := testutil.GetModule(options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) type Expected struct { @@ -100,27 +94,31 @@ func TestCommonSort(t *testing.T) { func TestCommonHeaderFrom(t *testing.T) { tests := map[string]struct { - options terraform.Options + config print.Config }{ "HeaderFromADOCFile": { - options: terraform.Options{ - HeaderFromFile: "doc.adoc", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = true + c.HeaderFrom = "doc.adoc" + }), }, "HeaderFromMDFile": { - options: terraform.Options{ - HeaderFromFile: "doc.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = true + c.HeaderFrom = "doc.md" + }), }, "HeaderFromTFFile": { - options: terraform.Options{ - HeaderFromFile: "doc.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = true + c.HeaderFrom = "doc.tf" + }), }, "HeaderFromTXTFile": { - options: terraform.Options{ - HeaderFromFile: "doc.txt", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = true + c.HeaderFrom = "doc.txt" + }), }, } for name, tt := range tests { @@ -130,10 +128,7 @@ func TestCommonHeaderFrom(t *testing.T) { expected, err := testutil.GetExpected("common", "header-"+name) assert.Nil(err) - options, err := terraform.NewOptions().WithOverwrite(&tt.options) - assert.Nil(err) - - module, err := testutil.GetModule(options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) assert.Equal(expected, module.Header) @@ -143,31 +138,31 @@ func TestCommonHeaderFrom(t *testing.T) { func TestCommonFooterFrom(t *testing.T) { tests := map[string]struct { - options terraform.Options + config print.Config }{ "FooterFromADOCFile": { - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "doc.adoc", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "doc.adoc" + }), }, "FooterFromMDFile": { - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "doc.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "doc.md" + }), }, "FooterFromTFFile": { - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "doc.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "doc.tf" + }), }, "FooterFromTXTFile": { - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "doc.txt", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "doc.txt" + }), }, } for name, tt := range tests { @@ -177,10 +172,7 @@ func TestCommonFooterFrom(t *testing.T) { expected, err := testutil.GetExpected("common", "footer-"+name) assert.Nil(err) - options, err := terraform.NewOptions().WithOverwrite(&tt.options) - assert.Nil(err) - - module, err := testutil.GetModule(options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) assert.Equal(expected, module.Footer) diff --git a/format/doc.go b/format/doc.go index a7beda3..a85442b 100644 --- a/format/doc.go +++ b/format/doc.go @@ -12,7 +12,7 @@ the root directory of this source tree. // // Usage // -// A specific format can be instantiated either for `format.New()` function or +// A specific format can be instantiated either with `format.New()` function or // directly calling its function (e.g. `NewMarkdownTable`, etc) // // config := print.DefaultConfig() @@ -28,7 +28,6 @@ the root directory of this source tree. // return err // } // -// // output, err := formatter.ExecuteTemplate("") // if err != nil { // return err diff --git a/format/json.go b/format/json.go index c56c2d3..cc5f1a7 100644 --- a/format/json.go +++ b/format/json.go @@ -23,29 +23,25 @@ import ( type json struct { *print.Generator - config *print.Config - settings *print.Settings + config *print.Config } // NewJSON returns new instance of JSON. func NewJSON(config *print.Config) Type { - settings, _ := config.Extract() - return &json{ Generator: print.NewGenerator("json", config.ModuleRoot), config: config, - settings: settings, } } // Generate a Terraform module as json. func (j *json) Generate(module *terraform.Module) error { - copy := copySections(j.settings, module) + copy := copySections(j.config, module) buffer := new(bytes.Buffer) encoder := jsonsdk.NewEncoder(buffer) encoder.SetIndent("", " ") - encoder.SetEscapeHTML(j.settings.EscapeCharacters) + encoder.SetEscapeHTML(j.config.Settings.Escape) if err := encoder.Encode(copy); err != nil { return err diff --git a/format/json_test.go b/format/json_test.go index 3f0de03..3aa627e 100644 --- a/format/json_test.go +++ b/format/json_test.go @@ -17,99 +17,77 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestJson(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.WithSections(), }, "Empty": { - settings: testutil.WithSections(), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideAll": { - settings: print.Settings{}, - options: terraform.Options{ - ShowHeader: false, // Since we don't show the header, the file won't be loaded at all - HeaderFromFile: "bad.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = false // Since we don't show the header, the file won't be loaded at all + c.HeaderFrom = "bad.tf" + }), }, // Settings "EscapeCharacters": { - settings: testutil.WithSections( - print.Settings{ - EscapeCharacters: true, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.Escape = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "OutputValues": { - settings: print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: true, - }, - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = true + }), }, // Only section "OnlyDataSources": { - settings: print.Settings{ShowDataSources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.DataSources = true }), }, "OnlyHeader": { - settings: print.Settings{ShowHeader: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Header = true }), }, "OnlyFooter": { - settings: print.Settings{ShowFooter: true}, - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "footer.md" + }), }, "OnlyInputs": { - settings: print.Settings{ShowInputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Inputs = true }), }, "OnlyOutputs": { - settings: print.Settings{ShowOutputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Outputs = true }), }, "OnlyModulecalls": { - settings: print.Settings{ShowModuleCalls: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.ModuleCalls = true }), }, "OnlyProviders": { - settings: print.Settings{ShowProviders: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Providers = true }), }, "OnlyRequirements": { - settings: print.Settings{ShowRequirements: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Requirements = true }), }, "OnlyResources": { - settings: print.Settings{ShowResources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Resources = true }), }, } for name, tt := range tests { @@ -119,13 +97,10 @@ func TestJson(t *testing.T) { expected, err := testutil.GetExpected("json", "json-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewJSON(tt.settings.ToConfig()) + formatter := NewJSON(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/markdown_document.go b/format/markdown_document.go index 9e201bf..977eaf8 100644 --- a/format/markdown_document.go +++ b/format/markdown_document.go @@ -28,15 +28,13 @@ type markdownDocument struct { config *print.Config template *template.Template - settings *print.Settings } // NewMarkdownDocument returns new instance of Markdown Document. func NewMarkdownDocument(config *print.Config) Type { - settings, _ := config.Extract() items := readTemplateItems(markdownDocumentFS, "markdown_document") - tt := template.New(settings, items...) + tt := template.New(config, items...) tt.CustomFunc(gotemplate.FuncMap{ "type": func(t string) string { result, extraline := PrintFencedCodeBlock(t, "hcl") @@ -56,7 +54,7 @@ func NewMarkdownDocument(config *print.Config) Type { return result }, "isRequired": func() bool { - return settings.ShowRequired + return config.Settings.Required }, }) @@ -64,7 +62,6 @@ func NewMarkdownDocument(config *print.Config) Type { Generator: print.NewGenerator("json", config.ModuleRoot), config: config, template: tt, - settings: settings, } } diff --git a/format/markdown_document_test.go b/format/markdown_document_test.go index fb8c5ec..232c130 100644 --- a/format/markdown_document_test.go +++ b/format/markdown_document_test.go @@ -17,206 +17,162 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestMarkdownDocument(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(testutil.WithHTML()), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.WithSections( + testutil.WithHTML(), + ), }, "Empty": { - settings: testutil.WithSections(testutil.WithHTML()), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.WithHTML(), + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideEmpty": { - settings: testutil.WithSections(testutil.WithHideEmpty()), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.WithHideEmpty(), + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideAll": { - settings: print.Settings{}, - options: terraform.Options{ - ShowHeader: false, // Since we don't show the header, the file won't be loaded at all - HeaderFromFile: "bad.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = false // Since we don't show the header, the file won't be loaded at all + c.HeaderFrom = "bad.tf" + }), }, // Settings "WithRequired": { - settings: testutil.WithSections( + config: testutil.WithSections( testutil.WithHTML(), - print.Settings{ - ShowRequired: true, - }, + testutil.With(func(c *print.Config) { + c.Settings.Required = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithAnchor": { - settings: testutil.WithSections( + config: testutil.WithSections( testutil.WithHTML(), - print.Settings{ - ShowAnchor: true, - }, + testutil.With(func(c *print.Config) { + c.Settings.Anchor = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithoutHTML": { - settings: testutil.WithSections( - print.Settings{ - ShowHTML: false, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.HTML = false + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithoutHTMLWithAnchor": { - settings: testutil.WithSections( - print.Settings{ - ShowHTML: false, - ShowAnchor: true, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.HTML = false + c.Settings.Anchor = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithoutDefault": { - settings: testutil.WithHTML( - print.Settings{ - ShowInputs: true, - ShowDefault: false, - ShowType: true, - }, + config: testutil.WithHTML( + testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = false + c.Settings.Type = true + }), ), - options: terraform.Options{}, }, "WithoutType": { - settings: testutil.WithHTML( - print.Settings{ - ShowInputs: true, - ShowDefault: true, - ShowType: false, - }, + config: testutil.WithHTML( + testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = true + c.Settings.Type = false + }), ), - options: terraform.Options{}, }, "EscapeCharacters": { - settings: testutil.WithSections( + config: testutil.WithSections( testutil.WithHTML(), - print.Settings{ - EscapeCharacters: true, - }, + testutil.With(func(c *print.Config) { + c.Settings.Escape = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "IndentationOfFour": { - settings: testutil.WithSections( + config: testutil.WithSections( testutil.WithHTML(), - print.Settings{ - IndentLevel: 4, - }, + testutil.With(func(c *print.Config) { + c.Settings.Indent = 4 + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "OutputValues": { - settings: testutil.WithHTML( - print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: true, - }, + config: testutil.WithHTML( + testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = true + }), ), - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, }, "OutputValuesNoSensitivity": { - settings: testutil.WithHTML( - print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: false, - }, + config: testutil.WithHTML( + testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = false + }), ), - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, }, // Only section "OnlyDataSources": { - settings: print.Settings{ShowDataSources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.DataSources = true }), }, "OnlyHeader": { - settings: print.Settings{ShowHeader: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Header = true }), }, "OnlyFooter": { - settings: print.Settings{ShowFooter: true}, - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "footer.md" + }), }, "OnlyInputs": { - settings: testutil.WithHTML( - print.Settings{ - ShowInputs: true, - ShowDefault: true, - ShowType: true, - }, - ), - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = true + c.Settings.Type = true + }), }, "OnlyOutputs": { - settings: print.Settings{ShowOutputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Outputs = true }), }, "OnlyModulecalls": { - settings: print.Settings{ShowModuleCalls: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.ModuleCalls = true }), }, "OnlyProviders": { - settings: print.Settings{ShowProviders: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Providers = true }), }, "OnlyRequirements": { - settings: print.Settings{ShowRequirements: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Requirements = true }), }, "OnlyResources": { - settings: print.Settings{ShowResources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Resources = true }), }, } for name, tt := range tests { @@ -226,13 +182,10 @@ func TestMarkdownDocument(t *testing.T) { expected, err := testutil.GetExpected("markdown", "document-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewMarkdownDocument(tt.settings.ToConfig()) + formatter := NewMarkdownDocument(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/markdown_table.go b/format/markdown_table.go index 17e1379..4ab1783 100644 --- a/format/markdown_table.go +++ b/format/markdown_table.go @@ -28,15 +28,13 @@ type markdownTable struct { config *print.Config template *template.Template - settings *print.Settings } // NewMarkdownTable returns new instance of Markdown Table. func NewMarkdownTable(config *print.Config) Type { - settings, _ := config.Extract() items := readTemplateItems(markdownTableFS, "markdown_table") - tt := template.New(settings, items...) + tt := template.New(config, items...) tt.CustomFunc(gotemplate.FuncMap{ "type": func(t string) string { inputType, _ := PrintFencedCodeBlock(t, "") @@ -55,7 +53,6 @@ func NewMarkdownTable(config *print.Config) Type { Generator: print.NewGenerator("markdown table", config.ModuleRoot), config: config, template: tt, - settings: settings, } } diff --git a/format/markdown_table_test.go b/format/markdown_table_test.go index 42bbe05..0527370 100644 --- a/format/markdown_table_test.go +++ b/format/markdown_table_test.go @@ -17,206 +17,162 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestMarkdownTable(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(testutil.WithHTML()), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.WithSections( + testutil.WithHTML(), + ), }, "Empty": { - settings: testutil.WithSections(testutil.WithHTML()), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.WithHTML(), + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideEmpty": { - settings: testutil.WithSections(testutil.WithHideEmpty()), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.WithHideEmpty(), + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideAll": { - settings: print.Settings{}, - options: terraform.Options{ - ShowHeader: false, // Since we don't show the header, the file won't be loaded at all - HeaderFromFile: "bad.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = false // Since we don't show the header, the file won't be loaded at all + c.HeaderFrom = "bad.tf" + }), }, // Settings "WithRequired": { - settings: testutil.WithSections( + config: testutil.WithSections( testutil.WithHTML(), - print.Settings{ - ShowRequired: true, - }, + testutil.With(func(c *print.Config) { + c.Settings.Required = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithAnchor": { - settings: testutil.WithSections( + config: testutil.WithSections( testutil.WithHTML(), - print.Settings{ - ShowAnchor: true, - }, + testutil.With(func(c *print.Config) { + c.Settings.Anchor = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithoutHTML": { - settings: testutil.WithSections( - print.Settings{ - ShowHTML: false, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.HTML = false + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithoutHTMLWithAnchor": { - settings: testutil.WithSections( - print.Settings{ - ShowHTML: false, - ShowAnchor: true, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.HTML = false + c.Settings.Anchor = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "WithoutDefault": { - settings: testutil.WithHTML( - print.Settings{ - ShowInputs: true, - ShowDefault: false, - ShowType: true, - }, + config: testutil.WithHTML( + testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = false + c.Settings.Type = true + }), ), - options: terraform.Options{}, }, "WithoutType": { - settings: testutil.WithHTML( - print.Settings{ - ShowInputs: true, - ShowDefault: true, - ShowType: false, - }, + config: testutil.WithHTML( + testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = true + c.Settings.Type = false + }), ), - options: terraform.Options{}, }, "EscapeCharacters": { - settings: testutil.WithSections( + config: testutil.WithSections( testutil.WithHTML(), - print.Settings{ - EscapeCharacters: true, - }, + testutil.With(func(c *print.Config) { + c.Settings.Escape = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "IndentationOfFour": { - settings: testutil.WithSections( + config: testutil.WithSections( testutil.WithHTML(), - print.Settings{ - IndentLevel: 4, - }, + testutil.With(func(c *print.Config) { + c.Settings.Indent = 4 + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "OutputValues": { - settings: testutil.WithHTML( - print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: true, - }, + config: testutil.WithHTML( + testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = true + }), ), - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, }, "OutputValuesNoSensitivity": { - settings: testutil.WithHTML( - print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: false, - }, + config: testutil.WithHTML( + testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = false + }), ), - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, }, // Only section "OnlyDataSources": { - settings: print.Settings{ShowDataSources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.DataSources = true }), }, "OnlyHeader": { - settings: print.Settings{ShowHeader: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Header = true }), }, "OnlyFooter": { - settings: print.Settings{ShowFooter: true}, - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "footer.md" + }), }, "OnlyInputs": { - settings: testutil.WithHTML( - print.Settings{ - ShowInputs: true, - ShowDefault: true, - ShowType: true, - }, - ), - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Sections.Inputs = true + c.Settings.Default = true + c.Settings.Type = true + }), }, "OnlyOutputs": { - settings: print.Settings{ShowOutputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Outputs = true }), }, "OnlyModulecalls": { - settings: print.Settings{ShowModuleCalls: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.ModuleCalls = true }), }, "OnlyProviders": { - settings: print.Settings{ShowProviders: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Providers = true }), }, "OnlyRequirements": { - settings: print.Settings{ShowRequirements: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Requirements = true }), }, "OnlyResources": { - settings: print.Settings{ShowResources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Resources = true }), }, } for name, tt := range tests { @@ -226,13 +182,10 @@ func TestMarkdownTable(t *testing.T) { expected, err := testutil.GetExpected("markdown", "table-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewMarkdownTable(tt.settings.ToConfig()) + formatter := NewMarkdownTable(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/pretty.go b/format/pretty.go index fb44e5a..462f9c2 100644 --- a/format/pretty.go +++ b/format/pretty.go @@ -30,21 +30,18 @@ type pretty struct { config *print.Config template *template.Template - settings *print.Settings } // NewPretty returns new instance of Pretty. func NewPretty(config *print.Config) Type { - settings, _ := config.Extract() - - tt := template.New(settings, &template.Item{ + tt := template.New(config, &template.Item{ Name: "pretty", Text: string(prettyTpl), }) tt.CustomFunc(gotemplate.FuncMap{ "colorize": func(c string, s string) string { r := "\033[0m" - if !settings.ShowColor { + if !config.Settings.Color { c = "" r = "" } @@ -56,7 +53,6 @@ func NewPretty(config *print.Config) Type { Generator: print.NewGenerator("pretty", config.ModuleRoot), config: config, template: tt, - settings: settings, } } diff --git a/format/pretty_test.go b/format/pretty_test.go index 4c05506..7ce60ff 100644 --- a/format/pretty_test.go +++ b/format/pretty_test.go @@ -17,99 +17,77 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestPretty(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.WithSections(), }, "Empty": { - settings: testutil.WithSections(), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideAll": { - settings: print.Settings{}, - options: terraform.Options{ - ShowHeader: false, // Since we don't show the header, the file won't be loaded at all - HeaderFromFile: "bad.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = false // Since we don't show the header, the file won't be loaded at all + c.HeaderFrom = "bad.tf" + }), }, // Settings "WithColor": { - settings: testutil.WithSections( - print.Settings{ - ShowColor: true, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.Color = true + }), ), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, }, "OutputValues": { - settings: print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: true, - }, - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = true + }), }, // Only section "OnlyDataSources": { - settings: print.Settings{ShowDataSources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.DataSources = true }), }, "OnlyHeader": { - settings: print.Settings{ShowHeader: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Header = true }), }, "OnlyFooter": { - settings: print.Settings{ShowFooter: true}, - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "footer.md" + }), }, "OnlyInputs": { - settings: print.Settings{ShowInputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Inputs = true }), }, "OnlyOutputs": { - settings: print.Settings{ShowOutputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Outputs = true }), }, "OnlyModulecalls": { - settings: print.Settings{ShowModuleCalls: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.ModuleCalls = true }), }, "OnlyProviders": { - settings: print.Settings{ShowProviders: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Providers = true }), }, "OnlyRequirements": { - settings: print.Settings{ShowRequirements: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Requirements = true }), }, "OnlyResources": { - settings: print.Settings{ShowResources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Resources = true }), }, } for name, tt := range tests { @@ -119,13 +97,10 @@ func TestPretty(t *testing.T) { expected, err := testutil.GetExpected("pretty", "pretty-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewPretty(tt.settings.ToConfig()) + formatter := NewPretty(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/templates/asciidoc_document_footer.tmpl b/format/templates/asciidoc_document_footer.tmpl index 5f9cdcd..ac90697 100644 --- a/format/templates/asciidoc_document_footer.tmpl +++ b/format/templates/asciidoc_document_footer.tmpl @@ -1,4 +1,4 @@ -{{- if .Settings.ShowFooter -}} +{{- if .Config.Sections.Footer -}} {{- with .Module.Footer -}} {{ sanitizeSection . }} {{ printf "\n" }} diff --git a/format/templates/asciidoc_document_header.tmpl b/format/templates/asciidoc_document_header.tmpl index 5e2d737..0f4f997 100644 --- a/format/templates/asciidoc_document_header.tmpl +++ b/format/templates/asciidoc_document_header.tmpl @@ -1,4 +1,4 @@ -{{- if .Settings.ShowHeader -}} +{{- if .Config.Sections.Header -}} {{- with .Module.Header -}} {{ sanitizeSection . }} {{ printf "\n" }} diff --git a/format/templates/asciidoc_document_inputs.tmpl b/format/templates/asciidoc_document_inputs.tmpl index de5975c..b3fceb8 100644 --- a/format/templates/asciidoc_document_inputs.tmpl +++ b/format/templates/asciidoc_document_inputs.tmpl @@ -1,7 +1,7 @@ -{{- if .Settings.ShowInputs -}} - {{- if .Settings.ShowRequired -}} +{{- if .Config.Sections.Inputs -}} + {{- if .Config.Settings.Required -}} {{- if not .Module.RequiredInputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Required Inputs No required inputs. @@ -16,11 +16,11 @@ Description: {{ tostring .Description | sanitizeDoc }} - {{ if $.Settings.ShowType -}} + {{ if $.Config.Settings.Type -}} Type: {{ tostring .Type | type }} {{- end }} - {{ if $.Settings.ShowDefault }} + {{ if $.Config.Settings.Default }} {{ if or .HasDefault (not isRequired) }} Default: {{ default "n/a" .GetValue | value }} {{- end }} @@ -28,7 +28,7 @@ {{- end }} {{- end }} {{- if not .Module.OptionalInputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Optional Inputs No optional inputs. @@ -43,11 +43,11 @@ Description: {{ tostring .Description | sanitizeDoc }} - {{ if $.Settings.ShowType -}} + {{ if $.Config.Settings.Type -}} Type: {{ tostring .Type | type }} {{- end }} - {{ if $.Settings.ShowDefault }} + {{ if $.Config.Settings.Default }} {{ if or .HasDefault (not isRequired) }} Default: {{ default "n/a" .GetValue | value }} {{- end }} @@ -56,7 +56,7 @@ {{ end }} {{ else -}} {{- if not .Module.Inputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Inputs No inputs. @@ -71,11 +71,11 @@ Description: {{ tostring .Description | sanitizeDoc }} - {{ if $.Settings.ShowType -}} + {{ if $.Config.Settings.Type -}} Type: {{ tostring .Type | type }} {{- end }} - {{ if $.Settings.ShowDefault }} + {{ if $.Config.Settings.Default }} {{ if or .HasDefault (not isRequired) }} Default: {{ default "n/a" .GetValue | value }} {{- end }} diff --git a/format/templates/asciidoc_document_modules.tmpl b/format/templates/asciidoc_document_modules.tmpl index 57ff782..fa094aa 100644 --- a/format/templates/asciidoc_document_modules.tmpl +++ b/format/templates/asciidoc_document_modules.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowModuleCalls -}} +{{- if .Config.Sections.ModuleCalls -}} {{- if not .Module.ModuleCalls -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Modules No modules. diff --git a/format/templates/asciidoc_document_outputs.tmpl b/format/templates/asciidoc_document_outputs.tmpl index c72535c..008a192 100644 --- a/format/templates/asciidoc_document_outputs.tmpl +++ b/format/templates/asciidoc_document_outputs.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowOutputs -}} +{{- if .Config.Sections.Outputs -}} {{- if not .Module.Outputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Outputs No outputs. @@ -15,11 +15,11 @@ Description: {{ tostring .Description | sanitizeDoc }} - {{ if $.Settings.OutputValues }} + {{ if $.Config.OutputValues.Enabled }} {{- $sensitive := ternary .Sensitive "" .GetValue -}} Value: {{ value $sensitive | sanitizeDoc }} - {{ if $.Settings.ShowSensitivity -}} + {{ if $.Config.Settings.Sensitive -}} Sensitive: {{ ternary (.Sensitive) "yes" "no" }} {{- end }} {{ end }} diff --git a/format/templates/asciidoc_document_providers.tmpl b/format/templates/asciidoc_document_providers.tmpl index 1b8cbb2..3af721d 100644 --- a/format/templates/asciidoc_document_providers.tmpl +++ b/format/templates/asciidoc_document_providers.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowProviders -}} +{{- if .Config.Sections.Providers -}} {{- if not .Module.Providers -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Providers No providers. diff --git a/format/templates/asciidoc_document_requirements.tmpl b/format/templates/asciidoc_document_requirements.tmpl index 3b83622..4db1e04 100644 --- a/format/templates/asciidoc_document_requirements.tmpl +++ b/format/templates/asciidoc_document_requirements.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowRequirements -}} +{{- if .Config.Sections.Requirements -}} {{- if not .Module.Requirements -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Requirements No requirements. diff --git a/format/templates/asciidoc_document_resources.tmpl b/format/templates/asciidoc_document_resources.tmpl index dd2d2b6..b5f0864 100644 --- a/format/templates/asciidoc_document_resources.tmpl +++ b/format/templates/asciidoc_document_resources.tmpl @@ -1,6 +1,6 @@ -{{- if or .Settings.ShowResources .Settings.ShowDataSources -}} +{{- if or .Config.Sections.Resources .Config.Sections.DataSources -}} {{- if not .Module.Resources -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Resources No resources. @@ -10,8 +10,8 @@ The following resources are used by this module: {{ range .Module.Resources }} - {{- $isResource := and $.Settings.ShowResources ( eq "resource" (printf "%s" .GetMode)) }} - {{- $isDataResource := and $.Settings.ShowDataSources ( eq "data source" (printf "%s" .GetMode)) }} + {{- $isResource := and $.Config.Sections.Resources ( eq "resource" (printf "%s" .GetMode)) }} + {{- $isDataResource := and $.Config.Sections.DataSources ( eq "data source" (printf "%s" .GetMode)) }} {{- if or $isResource $isDataResource }} {{- $fullspec := ternary .URL (printf "%s[%s]" .URL .Spec) .Spec }} - {{ $fullspec }} {{ printf "(%s)" .GetMode -}} diff --git a/format/templates/asciidoc_table_footer.tmpl b/format/templates/asciidoc_table_footer.tmpl index 5f9cdcd..ac90697 100644 --- a/format/templates/asciidoc_table_footer.tmpl +++ b/format/templates/asciidoc_table_footer.tmpl @@ -1,4 +1,4 @@ -{{- if .Settings.ShowFooter -}} +{{- if .Config.Sections.Footer -}} {{- with .Module.Footer -}} {{ sanitizeSection . }} {{ printf "\n" }} diff --git a/format/templates/asciidoc_table_header.tmpl b/format/templates/asciidoc_table_header.tmpl index 5e2d737..0f4f997 100644 --- a/format/templates/asciidoc_table_header.tmpl +++ b/format/templates/asciidoc_table_header.tmpl @@ -1,4 +1,4 @@ -{{- if .Settings.ShowHeader -}} +{{- if .Config.Sections.Header -}} {{- with .Module.Header -}} {{ sanitizeSection . }} {{ printf "\n" }} diff --git a/format/templates/asciidoc_table_inputs.tmpl b/format/templates/asciidoc_table_inputs.tmpl index d876d17..67c76ec 100644 --- a/format/templates/asciidoc_table_inputs.tmpl +++ b/format/templates/asciidoc_table_inputs.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowInputs -}} +{{- if .Config.Sections.Inputs -}} {{- if not .Module.Inputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Inputs No inputs. @@ -8,18 +8,18 @@ {{ else }} {{- indent 0 "=" }} Inputs - [cols="a,a{{ if .Settings.ShowType }},a{{ end }}{{ if .Settings.ShowDefault }},a{{ end }}{{ if .Settings.ShowRequired }},a{{ end }}",options="header,autowidth"] + [cols="a,a{{ if .Config.Settings.Type }},a{{ end }}{{ if .Config.Settings.Default }},a{{ end }}{{ if .Config.Settings.Required }},a{{ end }}",options="header,autowidth"] |=== |Name |Description - {{- if .Settings.ShowType }} |Type{{ end }} - {{- if .Settings.ShowDefault }} |Default{{ end }} - {{- if .Settings.ShowRequired }} |Required{{ end }} + {{- if .Config.Settings.Type }} |Type{{ end }} + {{- if .Config.Settings.Default }} |Default{{ end }} + {{- if .Config.Settings.Required }} |Required{{ end }} {{- range .Module.Inputs }} |{{ anchorNameAsciidoc "input" .Name }} |{{ tostring .Description | sanitizeAsciidocTbl }} - {{- if $.Settings.ShowType }}{{ printf "\n" }}|{{ tostring .Type | type | sanitizeAsciidocTbl }}{{ end }} - {{- if $.Settings.ShowDefault }}{{ printf "\n" }}|{{ value .GetValue | sanitizeAsciidocTbl }}{{ end }} - {{- if $.Settings.ShowRequired }}{{ printf "\n" }}|{{ ternary .Required "yes" "no" }}{{ end }} + {{- if $.Config.Settings.Type }}{{ printf "\n" }}|{{ tostring .Type | type | sanitizeAsciidocTbl }}{{ end }} + {{- if $.Config.Settings.Default }}{{ printf "\n" }}|{{ value .GetValue | sanitizeAsciidocTbl }}{{ end }} + {{- if $.Config.Settings.Required }}{{ printf "\n" }}|{{ ternary .Required "yes" "no" }}{{ end }} {{ end }} |=== {{ end }} diff --git a/format/templates/asciidoc_table_modules.tmpl b/format/templates/asciidoc_table_modules.tmpl index a3f5626..860f61e 100644 --- a/format/templates/asciidoc_table_modules.tmpl +++ b/format/templates/asciidoc_table_modules.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowModuleCalls -}} +{{- if .Config.Sections.ModuleCalls -}} {{- if not .Module.ModuleCalls -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Modules No modules. diff --git a/format/templates/asciidoc_table_outputs.tmpl b/format/templates/asciidoc_table_outputs.tmpl index 47ec139..d6fa96f 100644 --- a/format/templates/asciidoc_table_outputs.tmpl +++ b/format/templates/asciidoc_table_outputs.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowOutputs -}} +{{- if .Config.Sections.Outputs -}} {{- if not .Module.Outputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Outputs No outputs. @@ -8,15 +8,15 @@ {{ else }} {{- indent 0 "=" }} Outputs - [cols="a,a{{ if .Settings.OutputValues }},a{{ if $.Settings.ShowSensitivity }},a{{ end }}{{ end }}",options="header,autowidth"] + [cols="a,a{{ if .Config.OutputValues.Enabled }},a{{ if $.Config.Settings.Sensitive }},a{{ end }}{{ end }}",options="header,autowidth"] |=== - |Name |Description{{ if .Settings.OutputValues }} |Value{{ if $.Settings.ShowSensitivity }} |Sensitive{{ end }}{{ end }} + |Name |Description{{ if .Config.OutputValues.Enabled }} |Value{{ if $.Config.Settings.Sensitive }} |Sensitive{{ end }}{{ end }} {{- range .Module.Outputs }} |{{ anchorNameAsciidoc "output" .Name }} |{{ tostring .Description | sanitizeAsciidocTbl }} - {{- if $.Settings.OutputValues -}} + {{- if $.Config.OutputValues.Enabled -}} {{- $sensitive := ternary .Sensitive "" .GetValue -}} {{ printf " " }}|{{ value $sensitive }} - {{- if $.Settings.ShowSensitivity -}} + {{- if $.Config.Settings.Sensitive -}} {{ printf " " }}|{{ ternary .Sensitive "yes" "no" }} {{- end -}} {{- end -}} diff --git a/format/templates/asciidoc_table_providers.tmpl b/format/templates/asciidoc_table_providers.tmpl index ad1b898..c831ca0 100644 --- a/format/templates/asciidoc_table_providers.tmpl +++ b/format/templates/asciidoc_table_providers.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowProviders -}} +{{- if .Config.Sections.Providers -}} {{- if not .Module.Providers -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Providers No providers. diff --git a/format/templates/asciidoc_table_requirements.tmpl b/format/templates/asciidoc_table_requirements.tmpl index 701cd17..fe92038 100644 --- a/format/templates/asciidoc_table_requirements.tmpl +++ b/format/templates/asciidoc_table_requirements.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowRequirements -}} +{{- if .Config.Sections.Requirements -}} {{- if not .Module.Requirements -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Requirements No requirements. diff --git a/format/templates/asciidoc_table_resources.tmpl b/format/templates/asciidoc_table_resources.tmpl index 4459976..9d373d0 100644 --- a/format/templates/asciidoc_table_resources.tmpl +++ b/format/templates/asciidoc_table_resources.tmpl @@ -1,6 +1,6 @@ -{{- if or .Settings.ShowResources .Settings.ShowDataSources -}} +{{- if or .Config.Sections.Resources .Config.Sections.DataSources -}} {{- if not .Module.Resources -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "=" }} Resources No resources. @@ -12,8 +12,8 @@ |=== |Name |Type {{- range .Module.Resources }} - {{- $isResource := and $.Settings.ShowResources ( eq "resource" (printf "%s" .GetMode)) }} - {{- $isDataResource := and $.Settings.ShowDataSources ( eq "data source" (printf "%s" .GetMode)) }} + {{- $isResource := and $.Config.Sections.Resources ( eq "resource" (printf "%s" .GetMode)) }} + {{- $isDataResource := and $.Config.Sections.DataSources ( eq "data source" (printf "%s" .GetMode)) }} {{- if or $isResource $isDataResource }} {{- $fullspec := ternary .URL (printf "%s[%s]" .URL .Spec) .Spec }} |{{ $fullspec }} |{{ .GetMode }} diff --git a/format/templates/markdown_document_footer.tmpl b/format/templates/markdown_document_footer.tmpl index 5f9cdcd..ac90697 100644 --- a/format/templates/markdown_document_footer.tmpl +++ b/format/templates/markdown_document_footer.tmpl @@ -1,4 +1,4 @@ -{{- if .Settings.ShowFooter -}} +{{- if .Config.Sections.Footer -}} {{- with .Module.Footer -}} {{ sanitizeSection . }} {{ printf "\n" }} diff --git a/format/templates/markdown_document_header.tmpl b/format/templates/markdown_document_header.tmpl index 5e2d737..0f4f997 100644 --- a/format/templates/markdown_document_header.tmpl +++ b/format/templates/markdown_document_header.tmpl @@ -1,4 +1,4 @@ -{{- if .Settings.ShowHeader -}} +{{- if .Config.Sections.Header -}} {{- with .Module.Header -}} {{ sanitizeSection . }} {{ printf "\n" }} diff --git a/format/templates/markdown_document_inputs.tmpl b/format/templates/markdown_document_inputs.tmpl index 0da9b71..cfd789b 100644 --- a/format/templates/markdown_document_inputs.tmpl +++ b/format/templates/markdown_document_inputs.tmpl @@ -1,7 +1,7 @@ -{{- if .Settings.ShowInputs -}} - {{- if .Settings.ShowRequired -}} +{{- if .Config.Sections.Inputs -}} + {{- if .Config.Settings.Required -}} {{- if not .Module.RequiredInputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Required Inputs No required inputs. @@ -16,11 +16,11 @@ Description: {{ tostring .Description | sanitizeDoc }} - {{ if $.Settings.ShowType -}} + {{ if $.Config.Settings.Type -}} Type: {{ tostring .Type | type }} {{- end }} - {{ if $.Settings.ShowDefault }} + {{ if $.Config.Settings.Default }} {{ if or .HasDefault (not isRequired) }} Default: {{ default "n/a" .GetValue | value }} {{- end }} @@ -28,7 +28,7 @@ {{- end }} {{- end }} {{- if not .Module.OptionalInputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Optional Inputs No optional inputs. @@ -43,11 +43,11 @@ Description: {{ tostring .Description | sanitizeDoc }} - {{ if $.Settings.ShowType -}} + {{ if $.Config.Settings.Type -}} Type: {{ tostring .Type | type }} {{- end }} - {{ if $.Settings.ShowDefault }} + {{ if $.Config.Settings.Default }} {{ if or .HasDefault (not isRequired) }} Default: {{ default "n/a" .GetValue | value }} {{- end }} @@ -56,7 +56,7 @@ {{ end }} {{ else -}} {{- if not .Module.Inputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Inputs No inputs. @@ -71,11 +71,11 @@ Description: {{ tostring .Description | sanitizeDoc }} - {{ if $.Settings.ShowType -}} + {{ if $.Config.Settings.Type -}} Type: {{ tostring .Type | type }} {{- end }} - {{ if $.Settings.ShowDefault }} + {{ if $.Config.Settings.Default }} {{ if or .HasDefault (not isRequired) }} Default: {{ default "n/a" .GetValue | value }} {{- end }} diff --git a/format/templates/markdown_document_modules.tmpl b/format/templates/markdown_document_modules.tmpl index 57aaa8e..fc0a5a9 100644 --- a/format/templates/markdown_document_modules.tmpl +++ b/format/templates/markdown_document_modules.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowModuleCalls -}} +{{- if .Config.Sections.ModuleCalls -}} {{- if not .Module.ModuleCalls -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Modules No modules. diff --git a/format/templates/markdown_document_outputs.tmpl b/format/templates/markdown_document_outputs.tmpl index 01cea9f..739f978 100644 --- a/format/templates/markdown_document_outputs.tmpl +++ b/format/templates/markdown_document_outputs.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowOutputs -}} +{{- if .Config.Sections.Outputs -}} {{- if not .Module.Outputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Outputs No outputs. @@ -15,11 +15,11 @@ Description: {{ tostring .Description | sanitizeDoc }} - {{ if $.Settings.OutputValues }} + {{ if $.Config.OutputValues.Enabled }} {{- $sensitive := ternary .Sensitive "" .GetValue -}} Value: {{ value $sensitive | sanitizeDoc }} - {{ if $.Settings.ShowSensitivity -}} + {{ if $.Config.Settings.Sensitive -}} Sensitive: {{ ternary (.Sensitive) "yes" "no" }} {{- end }} {{ end }} diff --git a/format/templates/markdown_document_providers.tmpl b/format/templates/markdown_document_providers.tmpl index f32abf3..f47a9bd 100644 --- a/format/templates/markdown_document_providers.tmpl +++ b/format/templates/markdown_document_providers.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowProviders -}} +{{- if .Config.Sections.Providers -}} {{- if not .Module.Providers -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Providers No providers. diff --git a/format/templates/markdown_document_requirements.tmpl b/format/templates/markdown_document_requirements.tmpl index f8d14df..c2ed2a3 100644 --- a/format/templates/markdown_document_requirements.tmpl +++ b/format/templates/markdown_document_requirements.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowRequirements -}} +{{- if .Config.Sections.Requirements -}} {{- if not .Module.Requirements -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Requirements No requirements. diff --git a/format/templates/markdown_document_resources.tmpl b/format/templates/markdown_document_resources.tmpl index dd4e719..57eeee9 100644 --- a/format/templates/markdown_document_resources.tmpl +++ b/format/templates/markdown_document_resources.tmpl @@ -1,6 +1,6 @@ -{{- if or .Settings.ShowResources .Settings.ShowDataSources -}} +{{- if or .Config.Sections.Resources .Config.Sections.DataSources -}} {{- if not .Module.Resources -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Resources No resources. @@ -10,8 +10,8 @@ The following resources are used by this module: {{ range .Module.Resources }} - {{- $isResource := and $.Settings.ShowResources ( eq "resource" (printf "%s" .GetMode)) }} - {{- $isDataResource := and $.Settings.ShowDataSources ( eq "data source" (printf "%s" .GetMode)) }} + {{- $isResource := and $.Config.Sections.Resources ( eq "resource" (printf "%s" .GetMode)) }} + {{- $isDataResource := and $.Config.Sections.DataSources ( eq "data source" (printf "%s" .GetMode)) }} {{- if or $isResource $isDataResource }} {{- $fullspec := ternary .URL (printf "[%s](%s)" .Spec .URL) .Spec }} - {{ $fullspec }} {{ printf "(%s)" .GetMode -}} diff --git a/format/templates/markdown_table_footer.tmpl b/format/templates/markdown_table_footer.tmpl index 5f9cdcd..ac90697 100644 --- a/format/templates/markdown_table_footer.tmpl +++ b/format/templates/markdown_table_footer.tmpl @@ -1,4 +1,4 @@ -{{- if .Settings.ShowFooter -}} +{{- if .Config.Sections.Footer -}} {{- with .Module.Footer -}} {{ sanitizeSection . }} {{ printf "\n" }} diff --git a/format/templates/markdown_table_header.tmpl b/format/templates/markdown_table_header.tmpl index 5e2d737..0f4f997 100644 --- a/format/templates/markdown_table_header.tmpl +++ b/format/templates/markdown_table_header.tmpl @@ -1,4 +1,4 @@ -{{- if .Settings.ShowHeader -}} +{{- if .Config.Sections.Header -}} {{- with .Module.Header -}} {{ sanitizeSection . }} {{ printf "\n" }} diff --git a/format/templates/markdown_table_inputs.tmpl b/format/templates/markdown_table_inputs.tmpl index abe21cf..fb78923 100644 --- a/format/templates/markdown_table_inputs.tmpl +++ b/format/templates/markdown_table_inputs.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowInputs -}} +{{- if .Config.Sections.Inputs -}} {{- if not .Module.Inputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Inputs No inputs. @@ -9,22 +9,22 @@ {{- indent 0 "#" }} Inputs | Name | Description | - {{- if .Settings.ShowType }} Type |{{ end }} - {{- if .Settings.ShowDefault }} Default |{{ end }} - {{- if .Settings.ShowRequired }} Required |{{ end }} + {{- if .Config.Settings.Type }} Type |{{ end }} + {{- if .Config.Settings.Default }} Default |{{ end }} + {{- if .Config.Settings.Required }} Required |{{ end }} |------|-------------| - {{- if .Settings.ShowType }}------|{{ end }} - {{- if .Settings.ShowDefault }}---------|{{ end }} - {{- if .Settings.ShowRequired }}:--------:|{{ end }} + {{- if .Config.Settings.Type }}------|{{ end }} + {{- if .Config.Settings.Default }}---------|{{ end }} + {{- if .Config.Settings.Required }}:--------:|{{ end }} {{- range .Module.Inputs }} | {{ anchorNameMarkdown "input" .Name }} | {{ tostring .Description | sanitizeMarkdownTbl }} | - {{- if $.Settings.ShowType -}} + {{- if $.Config.Settings.Type -}} {{ printf " " }}{{ tostring .Type | type | sanitizeMarkdownTbl }} | {{- end -}} - {{- if $.Settings.ShowDefault -}} + {{- if $.Config.Settings.Default -}} {{ printf " " }}{{ value .GetValue | sanitizeMarkdownTbl }} | {{- end -}} - {{- if $.Settings.ShowRequired -}} + {{- if $.Config.Settings.Required -}} {{ printf " " }}{{ ternary .Required "yes" "no" }} | {{- end -}} {{- end }} diff --git a/format/templates/markdown_table_modules.tmpl b/format/templates/markdown_table_modules.tmpl index 044aba9..891778c 100644 --- a/format/templates/markdown_table_modules.tmpl +++ b/format/templates/markdown_table_modules.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowModuleCalls -}} +{{- if .Config.Sections.ModuleCalls -}} {{- if not .Module.ModuleCalls -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Modules No modules. diff --git a/format/templates/markdown_table_outputs.tmpl b/format/templates/markdown_table_outputs.tmpl index 54e2be8..dd44e08 100644 --- a/format/templates/markdown_table_outputs.tmpl +++ b/format/templates/markdown_table_outputs.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowOutputs -}} +{{- if .Config.Sections.Outputs -}} {{- if not .Module.Outputs -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Outputs No outputs. @@ -8,14 +8,14 @@ {{ else }} {{- indent 0 "#" }} Outputs - | Name | Description |{{ if .Settings.OutputValues }} Value |{{ if $.Settings.ShowSensitivity }} Sensitive |{{ end }}{{ end }} - |------|-------------|{{ if .Settings.OutputValues }}-------|{{ if $.Settings.ShowSensitivity }}:---------:|{{ end }}{{ end }} + | Name | Description |{{ if .Config.OutputValues.Enabled }} Value |{{ if $.Config.Settings.Sensitive }} Sensitive |{{ end }}{{ end }} + |------|-------------|{{ if .Config.OutputValues.Enabled }}-------|{{ if $.Config.Settings.Sensitive }}:---------:|{{ end }}{{ end }} {{- range .Module.Outputs }} | {{ anchorNameMarkdown "output" .Name }} | {{ tostring .Description | sanitizeMarkdownTbl }} | - {{- if $.Settings.OutputValues -}} + {{- if $.Config.OutputValues.Enabled -}} {{- $sensitive := ternary .Sensitive "" .GetValue -}} {{ printf " " }}{{ value $sensitive | sanitizeMarkdownTbl }} | - {{- if $.Settings.ShowSensitivity -}} + {{- if $.Config.Settings.Sensitive -}} {{ printf " " }}{{ ternary .Sensitive "yes" "no" }} | {{- end -}} {{- end -}} diff --git a/format/templates/markdown_table_providers.tmpl b/format/templates/markdown_table_providers.tmpl index 50d8c4e..35a3d04 100644 --- a/format/templates/markdown_table_providers.tmpl +++ b/format/templates/markdown_table_providers.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowProviders -}} +{{- if .Config.Sections.Providers -}} {{- if not .Module.Providers -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Providers No providers. diff --git a/format/templates/markdown_table_requirements.tmpl b/format/templates/markdown_table_requirements.tmpl index 4903eb5..b77dbd2 100644 --- a/format/templates/markdown_table_requirements.tmpl +++ b/format/templates/markdown_table_requirements.tmpl @@ -1,6 +1,6 @@ -{{- if .Settings.ShowRequirements -}} +{{- if .Config.Sections.Requirements -}} {{- if not .Module.Requirements -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Requirements No requirements. diff --git a/format/templates/markdown_table_resources.tmpl b/format/templates/markdown_table_resources.tmpl index 326a157..eb6b131 100644 --- a/format/templates/markdown_table_resources.tmpl +++ b/format/templates/markdown_table_resources.tmpl @@ -1,6 +1,6 @@ -{{- if or .Settings.ShowResources .Settings.ShowDataSources -}} +{{- if or .Config.Sections.Resources .Config.Sections.DataSources -}} {{- if not .Module.Resources -}} - {{- if not .Settings.HideEmpty -}} + {{- if not .Config.Settings.HideEmpty -}} {{- indent 0 "#" }} Resources No resources. @@ -11,8 +11,8 @@ | Name | Type | |------|------| {{- range .Module.Resources }} - {{- $isResource := and $.Settings.ShowResources ( eq "resource" (printf "%s" .GetMode)) }} - {{- $isDataResource := and $.Settings.ShowDataSources ( eq "data source" (printf "%s" .GetMode)) }} + {{- $isResource := and $.Config.Sections.Resources ( eq "resource" (printf "%s" .GetMode)) }} + {{- $isDataResource := and $.Config.Sections.DataSources ( eq "data source" (printf "%s" .GetMode)) }} {{- if or $isResource $isDataResource }} {{- $fullspec := ternary .URL (printf "[%s](%s)" .Spec .URL) .Spec }} | {{ $fullspec }} | {{ .GetMode }} | diff --git a/format/templates/pretty.tmpl b/format/templates/pretty.tmpl index 8e8f199..26d4e97 100644 --- a/format/templates/pretty.tmpl +++ b/format/templates/pretty.tmpl @@ -1,11 +1,11 @@ -{{- if .Settings.ShowHeader -}} +{{- if .Config.Sections.Header -}} {{- with .Module.Header -}} {{ colorize "\033[90m" . }} {{ end -}} {{- printf "\n\n" -}} {{ end -}} -{{- if .Settings.ShowRequirements -}} +{{- if .Config.Sections.Requirements -}} {{- with .Module.Requirements }} {{- range . }} {{- $version := ternary (tostring .Version) (printf " (%s)" .Version) "" }} @@ -15,7 +15,7 @@ {{- printf "\n\n" -}} {{ end -}} -{{- if .Settings.ShowProviders -}} +{{- if .Config.Sections.Providers -}} {{- with .Module.Providers }} {{- range . }} {{- $version := ternary (tostring .Version) (printf " (%s)" .Version) "" }} @@ -25,7 +25,7 @@ {{- printf "\n\n" -}} {{ end -}} -{{- if .Settings.ShowModuleCalls -}} +{{- if .Config.Sections.ModuleCalls -}} {{- with .Module.ModuleCalls }} {{- range . }} {{- printf "module.%s" .Name | colorize "\033[36m" }}{{ printf " (%s)" .FullName }} @@ -34,11 +34,11 @@ {{- printf "\n\n" -}} {{ end -}} -{{- if or .Settings.ShowResources .Settings.ShowDataSources -}} +{{- if or .Config.Sections.Resources .Config.Sections.DataSources -}} {{- with .Module.Resources }} {{- range . }} - {{- $isResource := and $.Settings.ShowResources ( eq "resource" (printf "%s" .GetMode)) }} - {{- $isDataResource := and $.Settings.ShowDataSources ( eq "data source" (printf "%s" .GetMode)) }} + {{- $isResource := and $.Config.Sections.Resources ( eq "resource" (printf "%s" .GetMode)) }} + {{- $isDataResource := and $.Config.Sections.DataSources ( eq "data source" (printf "%s" .GetMode)) }} {{- $url := ternary .URL (printf " (%s)" .URL) "" }} {{- if $isResource }} {{- printf "resource.%s (%s)" .Spec .GetMode | colorize "\033[36m" }}{{ $url }} @@ -50,7 +50,7 @@ {{ end }} {{ end }} -{{- if .Settings.ShowInputs -}} +{{- if .Config.Sections.Inputs -}} {{- with .Module.Inputs }} {{- range . }} {{- printf "input.%s" .Name | colorize "\033[36m" }} ({{ default "required" .GetValue }}) @@ -61,11 +61,11 @@ {{- printf "\n" -}} {{ end -}} -{{- if .Settings.ShowOutputs -}} +{{- if .Config.Sections.Outputs -}} {{- with .Module.Outputs }} {{- range . }} {{- printf "output.%s" .Name | colorize "\033[36m" }} - {{- if $.Settings.OutputValues -}} + {{- if $.Config.OutputValues.Enabled -}} {{- printf " " -}} ({{ ternary .Sensitive "" .GetValue }}) {{- end }} @@ -75,7 +75,7 @@ {{ end -}} {{ end -}} -{{- if .Settings.ShowFooter -}} +{{- if .Config.Sections.Footer -}} {{- with .Module.Footer -}} {{ colorize "\033[90m" . }} {{ end -}} diff --git a/format/testdata/markdown/table-OnlyInputs.golden b/format/testdata/markdown/table-OnlyInputs.golden index 58c4726..18338df 100644 --- a/format/testdata/markdown/table-OnlyInputs.golden +++ b/format/testdata/markdown/table-OnlyInputs.golden @@ -16,14 +16,14 @@ | number-1 | It's number number one. | `number` | `42` | | map-3 | n/a | `map` | `{}` | | map-2 | It's map number two. | `map` | n/a | -| map-1 | It's map number one. | `map` |
{
"a": 1,
"b": 2,
"c": 3
}
| +| map-1 | It's map number one. | `map` | ```{ "a": 1, "b": 2, "c": 3 }``` | | list-3 | n/a | `list` | `[]` | | list-2 | It's list number two. | `list` | n/a | -| list-1 | It's list number one. | `list` |
[
"a",
"b",
"c"
]
| +| list-1 | It's list number one. | `list` | ```[ "a", "b", "c" ]``` | | input_with_underscores | A variable with underscores. | `any` | n/a | | input-with-pipe | It includes v1 \| v2 \| v3 | `string` | `"v1"` | -| input-with-code-block | This is a complicated one. We need a newline.
And an example in a code block
default     = [
"machine rack01:neptune"
]
| `list` |
[
"name rack:location"
]
| -| long_type | This description is itself markdown.

It spans over multiple lines. |
object({
name = string,
foo = object({ foo = string, bar = string }),
bar = object({ foo = string, bar = string }),
fizz = list(string),
buzz = list(string)
})
|
{
"bar": {
"bar": "bar",
"foo": "bar"
},
"buzz": [
"fizz",
"buzz"
],
"fizz": [],
"foo": {
"bar": "foo",
"foo": "foo"
},
"name": "hello"
}
| +| input-with-code-block | This is a complicated one. We need a newline. And an example in a code block ```default = [ "machine rack01:neptune" ]``` | `list` | ```[ "name rack:location" ]``` | +| long_type | This description is itself markdown. It spans over multiple lines. | ```object({ name = string, foo = object({ foo = string, bar = string }), bar = object({ foo = string, bar = string }), fizz = list(string), buzz = list(string) })``` | ```{ "bar": { "bar": "bar", "foo": "bar" }, "buzz": [ "fizz", "buzz" ], "fizz": [], "foo": { "bar": "foo", "foo": "foo" }, "name": "hello" }``` | | no-escape-default-value | The description contains `something_with_underscore`. Defaults to 'VALUE_WITH_UNDERSCORE'. | `string` | `"VALUE_WITH_UNDERSCORE"` | | with-url | The description contains url. https://www.domain.com/foo/bar_baz.html | `string` | `""` | | string_default_empty | n/a | `string` | `""` | diff --git a/format/testdata/tfvars/hcl-PrintDescription.golden b/format/testdata/tfvars/hcl-PrintDescription.golden index 941003c..f40767c 100644 --- a/format/testdata/tfvars/hcl-PrintDescription.golden +++ b/format/testdata/tfvars/hcl-PrintDescription.golden @@ -1,30 +1,59 @@ - -# A variable with underscores. -input_with_underscores = "" - -# It's list number two. -list-2 = "" - -# It's map number two. -map-2 = "" - -# It's number number two. -number-2 = "" - -# It's string number two. -string-2 = "" - -string_no_default = "" -unquoted = "" - -# It's bool number one. -bool-1 = true +unquoted = "" +bool-3 = true # It's bool number two. bool-2 = false -bool-3 = true -bool_default_false = false +# It's bool number one. +bool-1 = true + +string-3 = "" + +# It's string number two. +string-2 = "" + +# It's string number one. +string-1 = "bar" + +string-special-chars = "\\.<>[]{}_-" +number-3 = "19" +number-4 = 15.75 + +# It's number number two. +number-2 = "" + +# It's number number one. +number-1 = 42 + +map-3 = {} + +# It's map number two. +map-2 = "" + +# It's map number one. +map-1 = { + "a": 1, + "b": 2, + "c": 3 +} + +list-3 = [] + +# It's list number two. +list-2 = "" + +# It's list number one. +list-1 = [ + "a", + "b", + "c" +] + +# A variable with underscores. +input_with_underscores = "" + +# It includes v1 | v2 | v3 +input-with-pipe = "v1" # This is a complicated one. We need a newline. # And an example in a code block @@ -38,19 +67,6 @@ input-with-code-block = [ "name rack:location" ] -# It includes v1 | v2 | v3 -input-with-pipe = "v1" - -# It's list number one. -list-1 = [ - "a", - "b", - "c" -] - -list-3 = [] -list_default_empty = [] - # This description is itself markdown. # # It spans over multiple lines. @@ -72,33 +88,16 @@ long_type = { "name": "hello" } -# It's map number one. -map-1 = { - "a": 1, - "b": 2, - "c": 3 -} - -map-3 = {} - # The description contains `something_with_underscore`. Defaults to 'VALUE_WITH_UNDERSCORE'. no-escape-default-value = "VALUE_WITH_UNDERSCORE" -# It's number number one. -number-1 = 42 +# The description contains url. https://www.domain.com/foo/bar_baz.html +with-url = "" -number-3 = "19" -number-4 = 15.75 -number_default_zero = 0 -object_default_empty = {} - -# It's string number one. -string-1 = "bar" - -string-3 = "" -string-special-chars = "\\.<>[]{}_-" string_default_empty = "" string_default_null = "" - -# The description contains url. https://www.domain.com/foo/bar_baz.html -with-url = "" \ No newline at end of file +string_no_default = "" +number_default_zero = 0 +bool_default_false = false +list_default_empty = [] +object_default_empty = {} \ No newline at end of file diff --git a/format/tfvars_hcl.go b/format/tfvars_hcl.go index 29728be..c487e32 100644 --- a/format/tfvars_hcl.go +++ b/format/tfvars_hcl.go @@ -31,16 +31,13 @@ type tfvarsHCL struct { config *print.Config template *template.Template - settings *print.Settings } var padding []int // NewTfvarsHCL returns new instance of TfvarsHCL. func NewTfvarsHCL(config *print.Config) Type { - settings, _ := config.Extract() - - tt := template.New(settings, &template.Item{ + tt := template.New(config, &template.Item{ Name: "tfvars", Text: string(tfvarsHCLTpl), }) @@ -58,7 +55,7 @@ func NewTfvarsHCL(config *print.Config) Type { return "\n# " + strings.ReplaceAll(string(s), "\n", "\n# ") }, "showDescription": func() bool { - return settings.ShowDescription + return config.Settings.Description }, }) @@ -66,13 +63,12 @@ func NewTfvarsHCL(config *print.Config) Type { Generator: print.NewGenerator("tfvars hcl", config.ModuleRoot), config: config, template: tt, - settings: settings, } } // Generate a Terraform module as Terraform tfvars HCL. func (h *tfvarsHCL) Generate(module *terraform.Module) error { - alignments(module.Inputs, h.settings) + alignments(module.Inputs, h.config) rendered, err := h.template.Render("tfvars", module) if err != nil { @@ -90,12 +86,12 @@ func isMultilineFormat(input *terraform.Input) bool { return (isList || isMap) && input.Default.Length() > 0 } -func alignments(inputs []*terraform.Input, settings *print.Settings) { +func alignments(inputs []*terraform.Input, config *print.Config) { padding = make([]int, len(inputs)) maxlen := 0 index := 0 for i, input := range inputs { - isDescribed := settings.ShowDescription && input.Description.Length() > 0 + isDescribed := config.Settings.Description && input.Description.Length() > 0 l := len(input.Name) if isMultilineFormat(input) || isDescribed { for j := index; j < i; j++ { diff --git a/format/tfvars_hcl_test.go b/format/tfvars_hcl_test.go index be9b17e..8c84ee0 100644 --- a/format/tfvars_hcl_test.go +++ b/format/tfvars_hcl_test.go @@ -17,78 +17,69 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestTfvarsHcl(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(), - options: terraform.Options{}, + config: testutil.WithSections(), }, "Empty": { - settings: testutil.WithSections(), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, // Settings "EscapeCharacters": { - settings: print.Settings{EscapeCharacters: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Settings.Escape = true + }), }, "PrintDescription": { - settings: testutil.WithSections( - print.Settings{ - ShowDescription: true, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Settings.Description = true + }), ), - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Name: true, - Required: true, - }, - }, }, "SortByName": { - settings: testutil.WithSections(), - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Name: true, - }, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Sort.Enabled = true + c.Sort.By = print.SortName + }), + ), }, "SortByRequired": { - settings: testutil.WithSections(), - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Name: true, - Required: true, - }, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Sort.Enabled = true + c.Sort.By = print.SortRequired + }), + ), }, "SortByType": { - settings: testutil.WithSections(), - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Type: true, - }, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Sort.Enabled = true + c.Sort.By = print.SortType + }), + ), }, // No section "NoInputs": { - settings: testutil.WithSections( - print.Settings{ - ShowInputs: false, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Sections.Inputs = false + }), ), - options: terraform.Options{}, }, } for name, tt := range tests { @@ -98,13 +89,10 @@ func TestTfvarsHcl(t *testing.T) { expected, err := testutil.GetExpected("tfvars", "hcl-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewTfvarsHCL(tt.settings.ToConfig()) + formatter := NewTfvarsHCL(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/tfvars_json.go b/format/tfvars_json.go index f90ecff..adaf252 100644 --- a/format/tfvars_json.go +++ b/format/tfvars_json.go @@ -25,18 +25,14 @@ import ( type tfvarsJSON struct { *print.Generator - config *print.Config - settings *print.Settings + config *print.Config } // NewTfvarsJSON returns new instance of TfvarsJSON. func NewTfvarsJSON(config *print.Config) Type { - settings, _ := config.Extract() - return &tfvarsJSON{ Generator: print.NewGenerator("tfvars json", config.ModuleRoot), config: config, - settings: settings, } } diff --git a/format/tfvars_json_test.go b/format/tfvars_json_test.go index ede0db1..2b255d1 100644 --- a/format/tfvars_json_test.go +++ b/format/tfvars_json_test.go @@ -15,65 +15,62 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestTfvarsJson(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(), - options: terraform.Options{}, + config: testutil.WithSections(), }, "Empty": { - settings: testutil.WithSections(), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, // Settings "EscapeCharacters": { - settings: print.Settings{EscapeCharacters: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { + c.Settings.Escape = true + }), }, "SortByName": { - settings: testutil.WithSections(), - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Name: true, - }, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Sort.Enabled = true + c.Sort.By = print.SortName + }), + ), }, "SortByRequired": { - settings: testutil.WithSections(), - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Name: true, - Required: true, - }, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Sort.Enabled = true + c.Sort.By = print.SortRequired + }), + ), }, "SortByType": { - settings: testutil.WithSections(), - options: terraform.Options{ - SortBy: &terraform.SortBy{ - Type: true, - }, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Sort.Enabled = true + c.Sort.By = print.SortType + }), + ), }, // No section "NoInputs": { - settings: testutil.WithSections( - print.Settings{ - ShowInputs: false, - }, + config: testutil.WithSections( + testutil.With(func(c *print.Config) { + c.Sections.Inputs = false + }), ), - options: terraform.Options{}, }, } for name, tt := range tests { @@ -83,13 +80,10 @@ func TestTfvarsJson(t *testing.T) { expected, err := testutil.GetExpected("tfvars", "json-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewTfvarsJSON(tt.settings.ToConfig()) + formatter := NewTfvarsJSON(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/toml.go b/format/toml.go index c01058b..d9b44c3 100644 --- a/format/toml.go +++ b/format/toml.go @@ -24,24 +24,20 @@ import ( type toml struct { *print.Generator - config *print.Config - settings *print.Settings + config *print.Config } // NewTOML returns new instance of TOML. func NewTOML(config *print.Config) Type { - settings, _ := config.Extract() - return &toml{ Generator: print.NewGenerator("toml", config.ModuleRoot), config: config, - settings: settings, } } // Generate a Terraform module as toml. func (t *toml) Generate(module *terraform.Module) error { - copy := copySections(t.settings, module) + copy := copySections(t.config, module) buffer := new(bytes.Buffer) encoder := tomlsdk.NewEncoder(buffer) diff --git a/format/toml_test.go b/format/toml_test.go index 845b9a0..0a92515 100644 --- a/format/toml_test.go +++ b/format/toml_test.go @@ -17,88 +17,70 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestToml(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.WithSections(), }, "Empty": { - settings: testutil.WithSections(), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideAll": { - settings: print.Settings{}, - options: terraform.Options{ - ShowHeader: false, // Since we don't show the header, the file won't be loaded at all - HeaderFromFile: "bad.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = false // Since we don't show the header, the file won't be loaded at all + c.HeaderFrom = "bad.tf" + }), }, // Settings "OutputValues": { - settings: print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: true, - }, - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = true + }), }, // Only section "OnlyDataSources": { - settings: print.Settings{ShowDataSources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.DataSources = true }), }, "OnlyHeader": { - settings: print.Settings{ShowHeader: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Header = true }), }, "OnlyFooter": { - settings: print.Settings{ShowFooter: true}, - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "footer.md" + }), }, "OnlyInputs": { - settings: print.Settings{ShowInputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Inputs = true }), }, "OnlyOutputs": { - settings: print.Settings{ShowOutputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Outputs = true }), }, "OnlyModulecalls": { - settings: print.Settings{ShowModuleCalls: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.ModuleCalls = true }), }, "OnlyProviders": { - settings: print.Settings{ShowProviders: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Providers = true }), }, "OnlyRequirements": { - settings: print.Settings{ShowRequirements: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Requirements = true }), }, "OnlyResources": { - settings: print.Settings{ShowResources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Resources = true }), }, } for name, tt := range tests { @@ -108,13 +90,10 @@ func TestToml(t *testing.T) { expected, err := testutil.GetExpected("toml", "toml-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewTOML(tt.settings.ToConfig()) + formatter := NewTOML(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/type.go b/format/type.go index 121c58c..19a1579 100644 --- a/format/type.go +++ b/format/type.go @@ -55,7 +55,6 @@ func register(e map[string]initializerFn) { // format.Engine based on the provided 'name', for example for name // of 'json' it will return '*format.JSON' through 'format.NewJSON' // function. -// func New(name string, settings *print.Settings) (Generator, error) { func New(config *print.Config) (Type, error) { name := config.Formatter fn, ok := initializers[name] diff --git a/format/util.go b/format/util.go index 9be51f9..e8c2b5e 100644 --- a/format/util.go +++ b/format/util.go @@ -103,7 +103,7 @@ func readTemplateItems(efs embed.FS, prefix string) []*template.Item { } // copySections sets the sections that'll be printed -func copySections(settings *print.Settings, src *terraform.Module) *terraform.Module { +func copySections(config *print.Config, src *terraform.Module) *terraform.Module { dest := &terraform.Module{ Header: "", Footer: "", @@ -115,42 +115,42 @@ func copySections(settings *print.Settings, src *terraform.Module) *terraform.Mo Resources: make([]*terraform.Resource, 0), } - if settings.ShowHeader { + if config.Sections.Header { dest.Header = src.Header } - if settings.ShowFooter { + if config.Sections.Footer { dest.Footer = src.Footer } - if settings.ShowInputs { + if config.Sections.Inputs { dest.Inputs = src.Inputs } - if settings.ShowModuleCalls { + if config.Sections.ModuleCalls { dest.ModuleCalls = src.ModuleCalls } - if settings.ShowOutputs { + if config.Sections.Outputs { dest.Outputs = src.Outputs } - if settings.ShowProviders { + if config.Sections.Providers { dest.Providers = src.Providers } - if settings.ShowRequirements { + if config.Sections.Requirements { dest.Requirements = src.Requirements } - if settings.ShowResources || settings.ShowDataSources { - dest.Resources = filterResourcesByMode(settings, src.Resources) + if config.Sections.Resources || config.Sections.DataSources { + dest.Resources = filterResourcesByMode(config, src.Resources) } return dest } // filterResourcesByMode returns the managed or data resources defined by the show argument -func filterResourcesByMode(settings *print.Settings, module []*terraform.Resource) []*terraform.Resource { +func filterResourcesByMode(config *print.Config, module []*terraform.Resource) []*terraform.Resource { resources := make([]*terraform.Resource, 0) for _, r := range module { - if settings.ShowResources && r.Mode == "managed" { + if config.Sections.Resources && r.Mode == "managed" { resources = append(resources, r) } - if settings.ShowDataSources && r.Mode == "data" { + if config.Sections.DataSources && r.Mode == "data" { resources = append(resources, r) } } diff --git a/format/xml.go b/format/xml.go index efe8323..7091a82 100644 --- a/format/xml.go +++ b/format/xml.go @@ -22,24 +22,20 @@ import ( type xml struct { *print.Generator - config *print.Config - settings *print.Settings + config *print.Config } // NewXML returns new instance of XML. func NewXML(config *print.Config) Type { - settings, _ := config.Extract() - return &xml{ Generator: print.NewGenerator("xml", config.ModuleRoot), config: config, - settings: settings, } } // Generate a Terraform module as xml. func (x *xml) Generate(module *terraform.Module) error { - copy := copySections(x.settings, module) + copy := copySections(x.config, module) out, err := xmlsdk.MarshalIndent(copy, "", " ") if err != nil { diff --git a/format/xml_test.go b/format/xml_test.go index 2d51a9c..081291c 100644 --- a/format/xml_test.go +++ b/format/xml_test.go @@ -17,88 +17,70 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestXml(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.WithSections(), }, "Empty": { - settings: testutil.WithSections(), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideAll": { - settings: print.Settings{}, - options: terraform.Options{ - ShowHeader: false, // Since we don't show the header, the file won't be loaded at all - HeaderFromFile: "bad.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = false // Since we don't show the header, the file won't be loaded at all + c.HeaderFrom = "bad.tf" + }), }, // Settings "OutputValues": { - settings: print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: true, - }, - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = true + }), }, // Only section "OnlyDataSources": { - settings: print.Settings{ShowDataSources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.DataSources = true }), }, "OnlyHeader": { - settings: print.Settings{ShowHeader: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Header = true }), }, "OnlyFooter": { - settings: print.Settings{ShowFooter: true}, - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "footer.md" + }), }, "OnlyInputs": { - settings: print.Settings{ShowInputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Inputs = true }), }, "OnlyOutputs": { - settings: print.Settings{ShowOutputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Outputs = true }), }, "OnlyModulecalls": { - settings: print.Settings{ShowModuleCalls: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.ModuleCalls = true }), }, "OnlyProviders": { - settings: print.Settings{ShowProviders: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Providers = true }), }, "OnlyRequirements": { - settings: print.Settings{ShowRequirements: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Requirements = true }), }, "OnlyResources": { - settings: print.Settings{ShowResources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Resources = true }), }, } for name, tt := range tests { @@ -108,13 +90,10 @@ func TestXml(t *testing.T) { expected, err := testutil.GetExpected("xml", "xml-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewXML(tt.settings.ToConfig()) + formatter := NewXML(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/format/yaml.go b/format/yaml.go index c022e41..16245fb 100644 --- a/format/yaml.go +++ b/format/yaml.go @@ -24,24 +24,20 @@ import ( type yaml struct { *print.Generator - config *print.Config - settings *print.Settings + config *print.Config } // NewYAML returns new instance of YAML. func NewYAML(config *print.Config) Type { - settings, _ := config.Extract() - return &yaml{ Generator: print.NewGenerator("yaml", config.ModuleRoot), config: config, - settings: settings, } } // Generate a Terraform module as YAML. func (y *yaml) Generate(module *terraform.Module) error { - copy := copySections(y.settings, module) + copy := copySections(y.config, module) buffer := new(bytes.Buffer) encoder := yamlv3.NewEncoder(buffer) diff --git a/format/yaml_test.go b/format/yaml_test.go index 02bc8da..be6f642 100644 --- a/format/yaml_test.go +++ b/format/yaml_test.go @@ -17,88 +17,70 @@ import ( "github.com/terraform-docs/terraform-docs/internal/testutil" "github.com/terraform-docs/terraform-docs/print" - "github.com/terraform-docs/terraform-docs/terraform" ) func TestYaml(t *testing.T) { tests := map[string]struct { - settings print.Settings - options terraform.Options + config print.Config }{ // Base "Base": { - settings: testutil.WithSections(), - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.WithSections(), }, "Empty": { - settings: testutil.WithSections(), - options: terraform.Options{ - Path: "empty", - }, + config: testutil.WithDefaultSections( + testutil.With(func(c *print.Config) { + c.ModuleRoot = "empty" + }), + ), }, "HideAll": { - settings: print.Settings{}, - options: terraform.Options{ - ShowHeader: false, // Since we don't show the header, the file won't be loaded at all - HeaderFromFile: "bad.tf", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Header = false // Since we don't show the header, the file won't be loaded at all + c.HeaderFrom = "bad.tf" + }), }, // Settings "OutputValues": { - settings: print.Settings{ - ShowOutputs: true, - OutputValues: true, - ShowSensitivity: true, - }, - options: terraform.Options{ - OutputValues: true, - OutputValuesPath: "output_values.json", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Outputs = true + c.OutputValues.Enabled = true + c.OutputValues.From = "output_values.json" + c.Settings.Sensitive = true + }), }, // Only section "OnlyDataSources": { - settings: print.Settings{ShowDataSources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.DataSources = true }), }, "OnlyHeader": { - settings: print.Settings{ShowHeader: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Header = true }), }, "OnlyFooter": { - settings: print.Settings{ShowFooter: true}, - options: terraform.Options{ - ShowFooter: true, - FooterFromFile: "footer.md", - }, + config: testutil.With(func(c *print.Config) { + c.Sections.Footer = true + c.FooterFrom = "footer.md" + }), }, "OnlyInputs": { - settings: print.Settings{ShowInputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Inputs = true }), }, "OnlyOutputs": { - settings: print.Settings{ShowOutputs: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Outputs = true }), }, "OnlyModulecalls": { - settings: print.Settings{ShowModuleCalls: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.ModuleCalls = true }), }, "OnlyProviders": { - settings: print.Settings{ShowProviders: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Providers = true }), }, "OnlyRequirements": { - settings: print.Settings{ShowRequirements: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Requirements = true }), }, "OnlyResources": { - settings: print.Settings{ShowResources: true}, - options: terraform.Options{}, + config: testutil.With(func(c *print.Config) { c.Sections.Resources = true }), }, } for name, tt := range tests { @@ -108,13 +90,10 @@ func TestYaml(t *testing.T) { expected, err := testutil.GetExpected("yaml", "yaml-"+name) assert.Nil(err) - options, err := terraform.NewOptions().With(&tt.options) + module, err := testutil.GetModule(&tt.config) assert.Nil(err) - module, err := testutil.GetModule(options) - assert.Nil(err) - - formatter := NewYAML(tt.settings.ToConfig()) + formatter := NewYAML(&tt.config) err = formatter.Generate(module) assert.Nil(err) diff --git a/internal/cli/run.go b/internal/cli/run.go index 4af099a..bcb8ab2 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -295,9 +295,7 @@ func checkConstraint(versionRange string, currentVersion string) error { // Config and generates the output content for the module (and submodules if available) // and write the result to the output (either stdout or a file). func generateContent(config *print.Config) error { - settings, options := config.Extract() - - module, err := terraform.LoadWithOptions(options) + module, err := terraform.LoadWithOptions(config) if err != nil { return err } @@ -320,7 +318,7 @@ func generateContent(config *print.Config) error { content, cerr := client.Execute(pluginsdk.ExecuteArgs{ Module: module.Convert(), - Settings: settings.Convert(), + Settings: nil, // TODO settings.Convert(), }) if cerr != nil { return cerr diff --git a/internal/testutil/config.go b/internal/testutil/config.go new file mode 100644 index 0000000..3ccd91f --- /dev/null +++ b/internal/testutil/config.go @@ -0,0 +1,93 @@ +/* +Copyright 2021 The terraform-docs Authors. + +Licensed under the MIT license (the "License"); you may not +use this file except in compliance with the License. + +You may obtain a copy of the License at the LICENSE file in +the root directory of this source tree. +*/ + +package testutil + +import ( + "github.com/imdario/mergo" + + "github.com/terraform-docs/terraform-docs/print" +) + +func baseConfig() print.Config { + base := print.NewConfig() + base.Settings.ReadComments = true + + return *base +} + +func baseSections() print.Config { + base := baseConfig() + + base.Sections.DataSources = true + base.Sections.Header = true + base.Sections.Inputs = true + base.Sections.ModuleCalls = true + base.Sections.Outputs = true + base.Sections.Providers = true + base.Sections.Requirements = true + base.Sections.Resources = true + + base.Settings.Default = true + base.Settings.Type = true + + return base +} + +// With appends items to provided print.Config. +func With(fn func(*print.Config)) print.Config { + base := baseConfig() + fn(&base) + + return base +} + +// WithSections shows all sections (including footer) to provided print.Config. +func WithSections(override ...print.Config) print.Config { + base := baseSections() + + base.Sections.Footer = true + base.FooterFrom = "footer.md" + + return apply(base, override...) +} + +// WithDefaultSections shows default sections (everything except footer) to provided print.Config. +func WithDefaultSections(override ...print.Config) print.Config { + base := baseSections() + + return apply(base, override...) +} + +// WithHTML sets HTML to provided print.Config. +func WithHTML(override ...print.Config) print.Config { + base := baseConfig() + base.Settings.HTML = true + + return apply(base, override...) +} + +// WithHideEmpty sets HideEmpty to provided print.Config. +func WithHideEmpty(override ...print.Config) print.Config { + base := baseConfig() + base.Settings.HideEmpty = true + + return apply(base, override...) +} + +func apply(base print.Config, override ...print.Config) print.Config { //nolint:gocritic + dest := base + for i := range override { + if err := mergo.Merge(&dest, override[i]); err != nil { + return base + } + } + return dest +} diff --git a/internal/testutil/settings.go b/internal/testutil/settings.go deleted file mode 100644 index 71f95c9..0000000 --- a/internal/testutil/settings.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2021 The terraform-docs Authors. - -Licensed under the MIT license (the "License"); you may not -use this file except in compliance with the License. - -You may obtain a copy of the License at the LICENSE file in -the root directory of this source tree. -*/ - -package testutil - -import ( - "github.com/imdario/mergo" - - "github.com/terraform-docs/terraform-docs/print" -) - -// WithSections appends show all sections to provided Settings. -func WithSections(override ...print.Settings) print.Settings { - base := print.Settings{ - ShowDataSources: true, - ShowFooter: true, - ShowHeader: true, - ShowInputs: true, - ShowModuleCalls: true, - ShowOutputs: true, - ShowProviders: true, - ShowRequirements: true, - ShowResources: true, - - ShowDefault: true, - ShowType: true, - } - return apply(base, override...) -} - -// WithHTML appends ShowHTML to provided Settings. -func WithHTML(override ...print.Settings) print.Settings { - base := print.Settings{ - ShowHTML: true, - } - return apply(base, override...) -} - -// WithHideEmpty appends HideEmpty to provided Settings. -func WithHideEmpty(override ...print.Settings) print.Settings { - base := print.Settings{ - HideEmpty: true, - } - return apply(base, override...) -} - -func apply(base print.Settings, override ...print.Settings) print.Settings { - dest := base - for i := range override { - if err := mergo.Merge(&dest, override[i]); err != nil { - return base - } - } - return dest - -} diff --git a/internal/testutil/testing.go b/internal/testutil/testing.go index 46fd7a8..620022b 100644 --- a/internal/testutil/testing.go +++ b/internal/testutil/testing.go @@ -16,23 +16,27 @@ import ( "path/filepath" "runtime" + "github.com/terraform-docs/terraform-docs/print" "github.com/terraform-docs/terraform-docs/terraform" ) // GetModule returns 'example' Module -func GetModule(options *terraform.Options) (*terraform.Module, error) { - path, err := getExampleFolder(options.Path) +func GetModule(config *print.Config) (*terraform.Module, error) { + path, err := getExampleFolder(config.ModuleRoot) if err != nil { return nil, err } - options.Path = path - if options.OutputValues { - options.OutputValuesPath = filepath.Join(path, options.OutputValuesPath) + config.ModuleRoot = path + + if config.OutputValues.Enabled { + config.OutputValues.From = filepath.Join(path, config.OutputValues.From) } - tfmodule, err := terraform.LoadWithOptions(options) + + tfmodule, err := terraform.LoadWithOptions(config) if err != nil { return nil, err } + return tfmodule, nil } diff --git a/print/config.go b/print/config.go index ab59953..fa299bb 100644 --- a/print/config.go +++ b/print/config.go @@ -13,8 +13,6 @@ package print import ( "fmt" "strings" - - "github.com/terraform-docs/terraform-docs/terraform" ) // Config represents all the available config options that can be accessed and @@ -40,6 +38,7 @@ type Config struct { // NewConfig returns neew instancee of Config with empty values. func NewConfig() *Config { return &Config{ + HeaderFrom: "main.tf", Sections: sections{}, Output: output{}, OutputValues: outputvalues{}, @@ -106,7 +105,7 @@ type sections struct { Header bool Footer bool Inputs bool - Modulecalls bool + ModuleCalls bool Outputs bool Providers bool Requirements bool @@ -118,15 +117,15 @@ func defaultSections() sections { Show: []string{}, Hide: []string{}, - DataSources: true, - Header: true, + DataSources: false, + Header: false, Footer: false, - Inputs: true, - Modulecalls: true, - Outputs: true, - Providers: true, - Requirements: true, - Resources: true, + Inputs: false, + ModuleCalls: false, + Outputs: false, + Providers: false, + Requirements: false, + Resources: false, } } @@ -321,16 +320,17 @@ func (o *outputvalues) validate() error { return nil } +// Sort types. const ( - sortName = "name" - sortRequired = "required" - sortType = "type" + SortName = "name" + SortRequired = "required" + SortType = "type" ) var allSorts = []string{ - sortName, - sortRequired, - sortType, + SortName, + SortRequired, + SortType, } // SortTypes list. @@ -344,7 +344,7 @@ type sort struct { func defaultSort() sort { return sort{ Enabled: true, - By: sortName, + By: SortName, } } @@ -399,7 +399,7 @@ func (c *Config) Parse() { c.Sections.DataSources = c.Sections.visibility("data-sources") c.Sections.Header = c.Sections.visibility("header") c.Sections.Inputs = c.Sections.visibility("inputs") - c.Sections.Modulecalls = c.Sections.visibility("modules") + c.Sections.ModuleCalls = c.Sections.visibility("modules") c.Sections.Outputs = c.Sections.visibility("outputs") c.Sections.Providers = c.Sections.visibility("providers") c.Sections.Requirements = c.Sections.visibility("requirements") @@ -452,62 +452,3 @@ func (c *Config) Validate() error { return nil } - -// Extract and build print.Settings and terraform.Options out of Config. -func (c *Config) Extract() (*Settings, *terraform.Options) { - settings := DefaultSettings() - options := terraform.NewOptions() - - // path - options.Path = c.ModuleRoot - - // header-from - settings.ShowHeader = c.Sections.Header - options.ShowHeader = settings.ShowHeader - options.HeaderFromFile = c.HeaderFrom - - // footer-from - settings.ShowFooter = c.Sections.Footer - options.ShowFooter = settings.ShowFooter - options.FooterFromFile = c.FooterFrom - - // terraform.lock.hcl file - options.UseLockFile = c.Settings.LockFile - - // sections - settings.ShowDataSources = c.Sections.DataSources - settings.ShowInputs = c.Sections.Inputs - settings.ShowModuleCalls = c.Sections.Modulecalls - settings.ShowOutputs = c.Sections.Outputs - settings.ShowProviders = c.Sections.Providers - settings.ShowRequirements = c.Sections.Requirements - settings.ShowResources = c.Sections.Resources - settings.HideEmpty = c.Settings.HideEmpty - - // output values - settings.OutputValues = c.OutputValues.Enabled - options.OutputValues = c.OutputValues.Enabled - options.OutputValuesPath = c.OutputValues.From - - // sort - options.SortBy.Name = c.Sort.Enabled && c.Sort.By == sortName - options.SortBy.Required = c.Sort.Enabled && c.Sort.By == sortRequired - options.SortBy.Type = c.Sort.Enabled && c.Sort.By == sortType - - // read comments - options.ReadComments = c.Settings.ReadComments - - // settings - settings.EscapeCharacters = c.Settings.Escape - settings.IndentLevel = c.Settings.Indent - settings.ShowAnchor = c.Settings.Anchor - settings.ShowDescription = c.Settings.Description - settings.ShowColor = c.Settings.Color - settings.ShowDefault = c.Settings.Default - settings.ShowHTML = c.Settings.HTML - settings.ShowRequired = c.Settings.Required - settings.ShowSensitivity = c.Settings.Sensitive - settings.ShowType = c.Settings.Type - - return settings, options -} diff --git a/print/config_test.go b/print/config_test.go index b01f33a..9cbda45 100644 --- a/print/config_test.go +++ b/print/config_test.go @@ -451,21 +451,21 @@ func TestConfigSort(t *testing.T) { }{ "name": { sort: sort{ - By: sortName, + By: SortName, }, wantErr: false, errMsg: "", }, "required": { sort: sort{ - By: sortRequired, + By: SortRequired, }, wantErr: false, errMsg: "", }, "type": { sort: sort{ - By: sortType, + By: SortType, }, wantErr: false, errMsg: "", diff --git a/print/settings.go b/print/settings.go deleted file mode 100644 index 995c019..0000000 --- a/print/settings.go +++ /dev/null @@ -1,227 +0,0 @@ -/* -Copyright 2021 The terraform-docs Authors. - -Licensed under the MIT license (the "License"); you may not -use this file except in compliance with the License. - -You may obtain a copy of the License at the LICENSE file in -the root directory of this source tree. -*/ - -package print - -import ( - printsdk "github.com/terraform-docs/plugin-sdk/print" -) - -// Settings represents all settings. -type Settings struct { - // EscapeCharacters escapes special characters (such as _ * in Markdown and > < in JSON) - // - // default: true - // scope: Markdown - EscapeCharacters bool - - // HideEmpty hide empty sections - // - // default: false - // scope: Asciidoc, Markdown - HideEmpty bool - - // IndentLevel control the indentation of headings [available: 1, 2, 3, 4, 5] - // - // default: 2 - // scope: Asciidoc, Markdown - IndentLevel int - - // OutputValues extract and show Output values from Terraform module output - // - // default: false - // scope: Global - OutputValues bool - - // ShowAnchor generate HTML anchor tag for elements - // - // default: true - // scope: Asciidoc, Markdown - ShowAnchor bool - - // ShowColor print "colorized" version of result in the terminal - // - // default: true - // scope: Pretty - ShowColor bool - - // ShowDataSources show the data sources on the "Resources" section - // - // default: true - // scope: Global - ShowDataSources bool - - // ShowDefault show "Default" as column (in table) or section (in document) - // - // default: true - // scope: Asciidoc, Markdown - ShowDefault bool - - // ShowDescription show "Descriptions" as comment on variables - // - // default: false - // scope: tfvars hcl - ShowDescription bool - - // ShowFooter show "Footer" module information - // - // default: false - // scope: Global - ShowFooter bool - - // ShowHeader show "Header" module information - // - // default: true - // scope: Global - ShowHeader bool - - // ShowHTML generate HTML tags (a, pre, br, ...) in the output - // - // default: true - // scope: Markdown - ShowHTML bool - - // ShowInputs show "Inputs" information - // - // default: true - // scope: Global - ShowInputs bool - - // ShowModuleCalls show "ModuleCalls" information - // - // default: true - // scope: Global - ShowModuleCalls bool - - // ShowOutputs show "Outputs" information - // - // default: true - // scope: Global - ShowOutputs bool - - // ShowProviders show "Providers" information - // - // default: true - // scope: Global - ShowProviders bool - - // ShowRequired show "Required" as column (in table) or section (in document) - // - // default: true - // scope: Asciidoc, Markdown - ShowRequired bool - - // ShowSensitivity show "Sensitive" as column (in table) or section (in document) - // - // default: true - // scope: Asciidoc, Markdown - ShowSensitivity bool - - // ShowRequirements show "Requirements" section - // - // default: true - // scope: Global - ShowRequirements bool - - // ShowResources show "Resources" section - // - // default: true - // scope: Global - ShowResources bool - - // ShowType show "Type" as column (in table) or section (in document) - // - // default: true - // scope: Asciidoc, Markdown - ShowType bool -} - -// DefaultSettings returns new instance of Settings. -func DefaultSettings() *Settings { - return &Settings{ - EscapeCharacters: true, - HideEmpty: false, - IndentLevel: 2, - OutputValues: false, - ShowAnchor: true, - ShowColor: true, - ShowDataSources: true, - ShowDefault: true, - ShowDescription: false, - ShowFooter: false, - ShowHeader: true, - ShowHTML: true, - ShowInputs: true, - ShowModuleCalls: true, - ShowOutputs: true, - ShowProviders: true, - ShowRequired: true, - ShowSensitivity: true, - ShowRequirements: true, - ShowResources: true, - ShowType: true, - } -} - -// ToConfig converts Settings to Config. -func (s *Settings) ToConfig() *Config { - config := NewConfig() - - config.Settings.Anchor = s.ShowAnchor - config.Settings.Color = s.ShowColor - config.Settings.Default = s.ShowDefault - config.Settings.Description = s.ShowDescription - config.Settings.Escape = s.EscapeCharacters - config.Settings.HideEmpty = s.HideEmpty - config.Settings.HTML = s.ShowHTML - config.Settings.Indent = s.IndentLevel - config.Settings.Required = s.ShowRequired - config.Settings.Sensitive = s.ShowSensitivity - config.Settings.Type = s.ShowType - - config.OutputValues.Enabled = s.OutputValues - - config.Sections.DataSources = s.ShowDataSources - config.Sections.Footer = s.ShowFooter - config.Sections.Header = s.ShowHeader - config.Sections.Inputs = s.ShowInputs - config.Sections.Outputs = s.ShowOutputs - config.Sections.Modulecalls = s.ShowModuleCalls - config.Sections.Providers = s.ShowProviders - config.Sections.Requirements = s.ShowRequirements - config.Sections.Resources = s.ShowResources - - return config -} - -// Convert Settings to its equivalent in plugin-sdk. -func (s *Settings) Convert() *printsdk.Settings { - return &printsdk.Settings{ - EscapeCharacters: s.EscapeCharacters, - HideEmpty: s.HideEmpty, - IndentLevel: s.IndentLevel, - OutputValues: s.OutputValues, - ShowColor: s.ShowColor, - ShowDataSources: s.ShowDataSources, - ShowDefault: s.ShowDefault, - ShowDescription: s.ShowDescription, - ShowFooter: s.ShowFooter, - ShowHeader: s.ShowHeader, - ShowInputs: s.ShowInputs, - ShowOutputs: s.ShowOutputs, - ShowModuleCalls: s.ShowModuleCalls, - ShowProviders: s.ShowProviders, - ShowRequired: s.ShowRequired, - ShowSensitivity: s.ShowSensitivity, - ShowRequirements: s.ShowRequirements, - ShowResources: s.ShowResources, - ShowType: s.ShowType, - } -} diff --git a/scripts/docs/generate.go b/scripts/docs/generate.go index 1796908..e0f9f2c 100644 --- a/scripts/docs/generate.go +++ b/scripts/docs/generate.go @@ -172,21 +172,15 @@ func example(ref *reference) error { ref.Usage = fmt.Sprintf("%s%s ./examples/", ref.Command, flag) config := print.DefaultConfig() + config.ModuleRoot = "./examples" config.Formatter = ref.Name config.Settings.Color = false - options := &terraform.Options{ - Path: "./examples", - ShowHeader: true, - HeaderFromFile: "main.tf", - ShowFooter: true, - FooterFromFile: "footer.md", - SortBy: &terraform.SortBy{ - Name: true, - }, - ReadComments: true, - } + config.Sections.Show = append(config.Sections.Show, "all") + config.Sections.Footer = true + config.FooterFrom = "footer.md" + config.Parse() - tfmodule, err := terraform.LoadWithOptions(options) + tfmodule, err := terraform.LoadWithOptions(config) if err != nil { log.Fatal(err) } diff --git a/template/anchor.go b/template/anchor.go index a10c46a..56a4950 100644 --- a/template/anchor.go +++ b/template/anchor.go @@ -12,17 +12,15 @@ package template import ( "fmt" - - "github.com/terraform-docs/terraform-docs/print" ) // CreateAnchorMarkdown creates HTML anchor for Markdown format. -func CreateAnchorMarkdown(t string, s string, settings *print.Settings) string { - sanitizedName := SanitizeName(s, settings) +func CreateAnchorMarkdown(prefix string, value string, anchor bool, escape bool) string { + sanitizedName := SanitizeName(value, escape) - if settings.ShowAnchor { - anchorName := fmt.Sprintf("%s_%s", t, s) - sanitizedAnchorName := SanitizeName(anchorName, settings) + if anchor { + anchorName := fmt.Sprintf("%s_%s", prefix, value) + sanitizedAnchorName := SanitizeName(anchorName, escape) // the link is purposely not sanitized as this breaks markdown formatting return fmt.Sprintf(" [%s](#%s)", anchorName, sanitizedName, sanitizedAnchorName) } @@ -31,12 +29,12 @@ func CreateAnchorMarkdown(t string, s string, settings *print.Settings) string { } // CreateAnchorAsciidoc creates HTML anchor for AsciiDoc format. -func CreateAnchorAsciidoc(t string, s string, settings *print.Settings) string { - sanitizedName := SanitizeName(s, settings) +func CreateAnchorAsciidoc(prefix string, value string, anchor bool, escape bool) string { + sanitizedName := SanitizeName(value, escape) - if settings.ShowAnchor { - anchorName := fmt.Sprintf("%s_%s", t, s) - sanitizedAnchorName := SanitizeName(anchorName, settings) + if anchor { + anchorName := fmt.Sprintf("%s_%s", prefix, value) + sanitizedAnchorName := SanitizeName(anchorName, escape) return fmt.Sprintf("[[%s]] <<%s,%s>>", sanitizedAnchorName, sanitizedAnchorName, sanitizedName) } diff --git a/template/anchor_test.go b/template/anchor_test.go index 6536ea1..07978b6 100644 --- a/template/anchor_test.go +++ b/template/anchor_test.go @@ -14,8 +14,6 @@ import ( "testing" "github.com/stretchr/testify/assert" - - "github.com/terraform-docs/terraform-docs/print" ) func TestAnchorMarkdown(t *testing.T) { @@ -58,11 +56,8 @@ func TestAnchorMarkdown(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{ - ShowAnchor: tt.anchor, - EscapeCharacters: tt.escape, - } - actual := CreateAnchorMarkdown(tt.typeSection, tt.name, settings) + + actual := CreateAnchorMarkdown(tt.typeSection, tt.name, tt.anchor, tt.escape) assert.Equal(tt.expected, actual) }) @@ -109,11 +104,8 @@ func TestAnchorAsciidoc(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{ - ShowAnchor: tt.anchor, - EscapeCharacters: tt.escape, - } - actual := CreateAnchorAsciidoc(tt.typeSection, tt.name, settings) + + actual := CreateAnchorAsciidoc(tt.typeSection, tt.name, tt.anchor, tt.escape) assert.Equal(tt.expected, actual) }) diff --git a/template/doc.go b/template/doc.go index bffbd29..bb79041 100644 --- a/template/doc.go +++ b/template/doc.go @@ -22,28 +22,28 @@ the root directory of this source tree. // ) // // const mainTpl =` -// {{- if .Settings.ShowHeader -}} +// {{- if .Config.Sections.Header -}} // {{- with .Module.Header -}} // {{ colorize "\033[90m" . }} // {{ end -}} // {{- printf "\n\n" -}} // {{ end -}}` // -// func render(settings *print.Settings, module *terraform.Module) (string, error) { -// tt := template.New(settings, &template.Item{ +// func render(config *print.Config, module *terraform.Module) (string, error) { +// tt := template.New(config, &template.Item{ // Name: "main", // Text: mainTpl, // }) // -// tt := template.New(settings, items...) +// tt := template.New(config, items...) // tt.CustomFunc(gotemplate.FuncMap{ -// "colorize": func(c string, s string) string { -// r := "\033[0m" -// if !settings.ShowColor { -// c = "" -// r = "" +// "colorize": func(color string, s string) string { +// reset := "\033[0m" +// if !config.Settings.Color { +// color = "" +// reset = "" // } -// return fmt.Sprintf("%s%s%s", c, s, r) +// return fmt.Sprintf("%s%s%s", color, s, reset) // }, // }) // diff --git a/template/sanitizer.go b/template/sanitizer.go index 9a2d80f..bf020d3 100644 --- a/template/sanitizer.go +++ b/template/sanitizer.go @@ -18,13 +18,12 @@ import ( "unicode" "mvdan.cc/xurls/v2" - - "github.com/terraform-docs/terraform-docs/print" ) -// SanitizeName escapes underscore character which have special meaning in Markdown. -func SanitizeName(name string, settings *print.Settings) string { - if settings.EscapeCharacters { +// SanitizeName escapes underscore character which have special meaning in +// Markdown. +func SanitizeName(name string, escape bool) string { + if escape { // Escape underscore name = strings.ReplaceAll(name, "_", "\\_") } @@ -37,7 +36,7 @@ func SanitizeName(name string, settings *print.Settings) string { // // IMPORTANT: SanitizeSection will never change the line-endings and preserve // them as they are provided by the users. -func SanitizeSection(s string, settings *print.Settings) string { +func SanitizeSection(s string, escape bool, html bool) string { if s == "" { return "n/a" } @@ -45,9 +44,9 @@ func SanitizeSection(s string, settings *print.Settings) string { s, "```", func(segment string, first bool, last bool) string { - segment = EscapeCharacters(segment, settings, false) - segment = ConvertMultiLineText(segment, false, true, settings.ShowHTML) - segment = NormalizeURLs(segment, settings) + segment = EscapeCharacters(segment, escape, false) + segment = ConvertMultiLineText(segment, false, true, html) + segment = NormalizeURLs(segment, escape) return segment }, func(segment string, first bool, last bool) string { @@ -73,8 +72,8 @@ func SanitizeSection(s string, settings *print.Settings) string { // SanitizeDocument converts passed 'string' to suitable Markdown or AsciiDoc // representation for a document. (including line-break, illegal characters, -// code blocks etc) -func SanitizeDocument(s string, settings *print.Settings) string { +// code blocks etc). +func SanitizeDocument(s string, escape bool, html bool) string { if s == "" { return "n/a" } @@ -82,9 +81,9 @@ func SanitizeDocument(s string, settings *print.Settings) string { s, "```", func(segment string, first bool, last bool) string { - segment = EscapeCharacters(segment, settings, false) - segment = ConvertMultiLineText(segment, false, false, settings.ShowHTML) - segment = NormalizeURLs(segment, settings) + segment = EscapeCharacters(segment, escape, false) + segment = ConvertMultiLineText(segment, false, false, html) + segment = NormalizeURLs(segment, escape) return segment }, func(segment string, first bool, last bool) string { @@ -100,8 +99,8 @@ func SanitizeDocument(s string, settings *print.Settings) string { } // SanitizeMarkdownTable converts passed 'string' to suitable Markdown representation -// for a table. (including line-break, illegal characters, code blocks etc) -func SanitizeMarkdownTable(s string, settings *print.Settings) string { +// for a table. (including line-break, illegal characters, code blocks etc). +func SanitizeMarkdownTable(s string, escape bool, html bool) string { if s == "" { return "n/a" } @@ -109,9 +108,9 @@ func SanitizeMarkdownTable(s string, settings *print.Settings) string { s, "```", func(segment string, first bool, last bool) string { - segment = EscapeCharacters(segment, settings, true) - segment = ConvertMultiLineText(segment, true, false, settings.ShowHTML) - segment = NormalizeURLs(segment, settings) + segment = EscapeCharacters(segment, escape, true) + segment = ConvertMultiLineText(segment, true, false, html) + segment = NormalizeURLs(segment, escape) return segment }, func(segment string, first bool, last bool) string { @@ -121,7 +120,7 @@ func SanitizeMarkdownTable(s string, settings *print.Settings) string { segment = strings.TrimSpace(segment) - if !settings.ShowHTML { + if !html { linebreak = "" codestart = " ```" codeend = "``` " @@ -146,8 +145,8 @@ func SanitizeMarkdownTable(s string, settings *print.Settings) string { } // SanitizeAsciidocTable converts passed 'string' to suitable AsciiDoc representation -// for a table. (including line-break, illegal characters, code blocks etc) -func SanitizeAsciidocTable(s string, settings *print.Settings) string { +// for a table. (including line-break, illegal characters, code blocks etc). +func SanitizeAsciidocTable(s string, escape bool, html bool) string { if s == "" { return "n/a" } @@ -155,8 +154,8 @@ func SanitizeAsciidocTable(s string, settings *print.Settings) string { s, "```", func(segment string, first bool, last bool) string { - segment = EscapeCharacters(segment, settings, true) - segment = NormalizeURLs(segment, settings) + segment = EscapeCharacters(segment, escape, true) + segment = NormalizeURLs(segment, escape) return segment }, func(segment string, first bool, last bool) string { @@ -220,8 +219,9 @@ func ConvertOneLineCodeBlock(s string) string { return strings.Join(result, " ") } -// EscapeCharacters escapes characters which have special meaning in Markdown into their corresponding literal. -func EscapeCharacters(s string, settings *print.Settings, escapePipe bool) string { +// EscapeCharacters escapes characters which have special meaning in Markdown into +// their corresponding literal. +func EscapeCharacters(s string, escape bool, escapePipe bool) string { // Escape pipe (only for 'markdown table' or 'asciidoc table') if escapePipe { s = processSegments( @@ -236,7 +236,7 @@ func EscapeCharacters(s string, settings *print.Settings, escapePipe bool) strin ) } - if settings.EscapeCharacters { + if escape { s = processSegments( s, "`", @@ -285,11 +285,11 @@ func EscapeCharacters(s string, settings *print.Settings, escapePipe bool) strin return s } -// NormalizeURLs runs after escape function and normalizes URL back -// to the original state. For example any underscore in the URL which -// got escaped by 'EscapeIllegalCharacters' will be reverted back. -func NormalizeURLs(s string, settings *print.Settings) string { - if settings.EscapeCharacters { +// NormalizeURLs runs after escape function and normalizes URL back to the original +// state. For example any underscore in the URL which got escaped by 'EscapeCharacters' +// will be reverted back. +func NormalizeURLs(s string, escape bool) string { + if escape { if urls := xurls.Strict().FindAllString(s, -1); len(urls) > 0 { for _, url := range urls { normalized := strings.ReplaceAll(url, "\\", "") diff --git a/template/sanitizer_test.go b/template/sanitizer_test.go index 53c4c85..8d494d6 100644 --- a/template/sanitizer_test.go +++ b/template/sanitizer_test.go @@ -16,8 +16,6 @@ import ( "testing" "github.com/stretchr/testify/assert" - - "github.com/terraform-docs/terraform-docs/print" ) func TestSanitizeName(t *testing.T) { @@ -97,10 +95,8 @@ func TestSanitizeName(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{ - EscapeCharacters: tt.escape, - } - actual := SanitizeName(tt.input, settings) + + actual := SanitizeName(tt.input, tt.escape) assert.Equal(tt.expected, actual) }) @@ -132,14 +128,11 @@ func TestSanitizeSection(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{ - EscapeCharacters: tt.escape, - } bytes, err := ioutil.ReadFile(filepath.Join("testdata", "section", tt.filename+".golden")) assert.Nil(err) - actual := SanitizeSection(string(bytes), settings) + actual := SanitizeSection(string(bytes), tt.escape, false) expected, err := ioutil.ReadFile(filepath.Join("testdata", "section", tt.filename+".expected")) assert.Nil(err) @@ -174,14 +167,11 @@ func TestSanitizeDocument(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{ - EscapeCharacters: tt.escape, - } bytes, err := ioutil.ReadFile(filepath.Join("testdata", "document", tt.filename+".golden")) assert.Nil(err) - actual := SanitizeDocument(string(bytes), settings) + actual := SanitizeDocument(string(bytes), tt.escape, false) expected, err := ioutil.ReadFile(filepath.Join("testdata", "document", tt.filename+".expected")) assert.Nil(err) @@ -238,15 +228,11 @@ func TestSanitizeMarkdownTable(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{ - ShowHTML: tt.html, - EscapeCharacters: tt.escape, - } bytes, err := ioutil.ReadFile(filepath.Join("testdata", "table", tt.filename+".golden")) assert.Nil(err) - actual := SanitizeMarkdownTable(string(bytes), settings) + actual := SanitizeMarkdownTable(string(bytes), tt.escape, tt.html) expected, err := ioutil.ReadFile(filepath.Join("testdata", "table", tt.expected+".markdown.expected")) assert.Nil(err) @@ -281,14 +267,11 @@ func TestSanitizeAsciidocTable(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{ - EscapeCharacters: tt.escape, - } bytes, err := ioutil.ReadFile(filepath.Join("testdata", "table", tt.filename+".golden")) assert.Nil(err) - actual := SanitizeAsciidocTable(string(bytes), settings) + actual := SanitizeAsciidocTable(string(bytes), tt.escape, false) expected, err := ioutil.ReadFile(filepath.Join("testdata", "table", tt.filename+".asciidoc.expected")) assert.Nil(err) @@ -426,7 +409,7 @@ func TestConvertMultiLineText(t *testing.T) { } } -func TestEscapeIllegalCharacters(t *testing.T) { +func TestEscapeCharacters(t *testing.T) { tests := []struct { name string input string @@ -578,10 +561,8 @@ func TestEscapeIllegalCharacters(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{ - EscapeCharacters: tt.escapeChars, - } - actual := EscapeCharacters(tt.input, settings, tt.escapePipe) + + actual := EscapeCharacters(tt.input, tt.escapeChars, tt.escapePipe) assert.Equal(tt.expected, actual) }) @@ -635,10 +616,8 @@ func TestNormalizeURLs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{ - EscapeCharacters: tt.escape, - } - actual := NormalizeURLs(tt.input, settings) + + actual := NormalizeURLs(tt.input, tt.escape) assert.Equal(tt.expected, actual) }) diff --git a/template/template.go b/template/template.go index 3caf9f0..ee6d71c 100644 --- a/template/template.go +++ b/template/template.go @@ -30,19 +30,19 @@ type Item struct { // Template represents a new Template with given name and content to be rendered // with provided settings with use of built-in and custom functions. type Template struct { - items []*Item - settings *print.Settings + items []*Item + config *print.Config funcMap gotemplate.FuncMap customFunc gotemplate.FuncMap } // New returns new instance of Template. -func New(settings *print.Settings, items ...*Item) *Template { +func New(config *print.Config, items ...*Item) *Template { return &Template{ items: items, - settings: settings, - funcMap: builtinFuncs(settings), + config: config, + funcMap: builtinFuncs(config), customFunc: make(gotemplate.FuncMap), } } @@ -96,11 +96,11 @@ func (t *Template) Render(name string, module *terraform.Module) (string, error) } if err := tmpl.ExecuteTemplate(&buffer, item.Name, struct { - Module *terraform.Module - Settings *print.Settings + Module *terraform.Module + Config *print.Config }{ - Module: module, - Settings: t.settings, + Module: module, + Config: t.config, }); err != nil { return "", err } @@ -123,19 +123,19 @@ func (t *Template) findByName(name string) *Item { return nil } -func builtinFuncs(settings *print.Settings) gotemplate.FuncMap { // nolint:gocyclo +func builtinFuncs(config *print.Config) gotemplate.FuncMap { // nolint:gocyclo return gotemplate.FuncMap{ - "default": func(d string, s string) string { - if s != "" { - return s + "default": func(_default string, value string) string { + if value != "" { + return value } - return d + return _default }, - "indent": func(l int, char string) string { - return GenerateIndentation(l, char, settings) + "indent": func(extra int, char string) string { + return GenerateIndentation(config.Settings.Indent, extra, char) }, - "name": func(n string) string { - return SanitizeName(n, settings) + "name": func(name string) string { + return SanitizeName(name, config.Settings.Escape) }, "ternary": func(condition interface{}, trueValue string, falseValue string) string { var c bool @@ -190,24 +190,24 @@ func builtinFuncs(settings *print.Settings) gotemplate.FuncMap { // nolint:gocyc // sanitize "sanitizeSection": func(s string) string { - return SanitizeSection(s, settings) + return SanitizeSection(s, config.Settings.Escape, config.Settings.HTML) }, "sanitizeDoc": func(s string) string { - return SanitizeDocument(s, settings) + return SanitizeDocument(s, config.Settings.Escape, config.Settings.HTML) }, "sanitizeMarkdownTbl": func(s string) string { - return SanitizeMarkdownTable(s, settings) + return SanitizeMarkdownTable(s, config.Settings.Escape, config.Settings.HTML) }, "sanitizeAsciidocTbl": func(s string) string { - return SanitizeAsciidocTable(s, settings) + return SanitizeAsciidocTable(s, config.Settings.Escape, config.Settings.HTML) }, // anchors - "anchorNameMarkdown": func(s string, t string) string { - return CreateAnchorMarkdown(s, t, settings) + "anchorNameMarkdown": func(prefix string, value string) string { + return CreateAnchorMarkdown(prefix, value, config.Settings.Anchor, config.Settings.Escape) }, - "anchorNameAsciidoc": func(s string, t string) string { - return CreateAnchorAsciidoc(s, t, settings) + "anchorNameAsciidoc": func(prefix string, value string) string { + return CreateAnchorAsciidoc(prefix, value, config.Settings.Anchor, config.Settings.Escape) }, } } @@ -228,11 +228,10 @@ func normalize(s string) string { // GenerateIndentation generates indentation of Markdown and AsciiDoc headers // with base level of provided 'settings.IndentLevel' plus any extra level needed // for subsection (e.g. 'Required Inputs' which is a subsection of 'Inputs' section) -func GenerateIndentation(extra int, char string, settings *print.Settings) string { +func GenerateIndentation(base int, extra int, char string) string { if char == "" { return "" } - var base = settings.IndentLevel if base < 1 || base > 5 { base = 2 } diff --git a/template/template_test.go b/template/template_test.go index 978a5da..431e14f 100644 --- a/template/template_test.go +++ b/template/template_test.go @@ -69,7 +69,7 @@ func TestTemplateRender(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - tpl := New(print.DefaultSettings(), tt.items...) + tpl := New(print.DefaultConfig(), tt.items...) tpl.CustomFunc(customFuncs) rendered, err := tpl.Render("", module) if tt.wantErr { @@ -418,9 +418,9 @@ func TestBuiltinFunc(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := print.DefaultSettings() - settings.EscapeCharacters = tt.escape - funcs := builtinFuncs(settings) + config := print.DefaultConfig() + config.Settings.Escape = tt.escape + funcs := builtinFuncs(config) fn, ok := funcs[tt.funcName] assert.Truef(ok, "function %s is not defined", tt.funcName) @@ -502,8 +502,7 @@ func TestGenerateIndentation(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - settings := &print.Settings{IndentLevel: tt.base} - actual := GenerateIndentation(tt.extra, "#", settings) + actual := GenerateIndentation(tt.base, tt.extra, "#") assert.Equal(tt.expected, actual) }) diff --git a/terraform/input.go b/terraform/input.go index 78a4842..fe125fc 100644 --- a/terraform/input.go +++ b/terraform/input.go @@ -19,6 +19,7 @@ import ( terraformsdk "github.com/terraform-docs/plugin-sdk/terraform" "github.com/terraform-docs/terraform-docs/internal/types" + "github.com/terraform-docs/terraform-docs/print" ) // Input represents a Terraform input. @@ -93,6 +94,23 @@ func sortInputsByType(x []*Input) { type inputs []*Input +func (ii inputs) sort(enabled bool, by string) { + if !enabled { + sortInputsByPosition(ii) + } else { + switch by { + case print.SortType: + sortInputsByType(ii) + case print.SortRequired: + sortInputsByRequired(ii) + case print.SortName: + sortInputsByName(ii) + default: + sortInputsByPosition(ii) + } + } +} + func (ii inputs) convert() []*terraformsdk.Input { list := []*terraformsdk.Input{} for _, i := range ii { diff --git a/terraform/load.go b/terraform/load.go index d6f6117..2c36f22 100644 --- a/terraform/load.go +++ b/terraform/load.go @@ -27,21 +27,22 @@ import ( "github.com/terraform-docs/terraform-config-inspect/tfconfig" "github.com/terraform-docs/terraform-docs/internal/reader" "github.com/terraform-docs/terraform-docs/internal/types" + "github.com/terraform-docs/terraform-docs/print" ) // LoadWithOptions returns new instance of Module with all the inputs and // outputs discovered from provided 'path' containing Terraform config -func LoadWithOptions(options *Options) (*Module, error) { - tfmodule, err := loadModule(options.Path) +func LoadWithOptions(config *print.Config) (*Module, error) { + tfmodule, err := loadModule(config.ModuleRoot) if err != nil { return nil, err } - module, err := loadModuleItems(tfmodule, options) + module, err := loadModuleItems(tfmodule, config) if err != nil { return nil, err } - sortItems(module, options.SortBy) + sortItems(module, config) return module, nil } @@ -53,24 +54,24 @@ func loadModule(path string) (*tfconfig.Module, error) { return module, nil } -func loadModuleItems(tfmodule *tfconfig.Module, options *Options) (*Module, error) { - header, err := loadHeader(options) +func loadModuleItems(tfmodule *tfconfig.Module, config *print.Config) (*Module, error) { + header, err := loadHeader(config) if err != nil { return nil, err } - footer, err := loadFooter(options) + footer, err := loadFooter(config) if err != nil { return nil, err } - inputs, required, optional := loadInputs(tfmodule, options) + inputs, required, optional := loadInputs(tfmodule, config) modulecalls := loadModulecalls(tfmodule) - outputs, err := loadOutputs(tfmodule, options) + outputs, err := loadOutputs(tfmodule, config) if err != nil { return nil, err } - providers := loadProviders(tfmodule, options) + providers := loadProviders(tfmodule, config) requirements := loadRequirements(tfmodule) resources := loadResources(tfmodule) @@ -114,21 +115,21 @@ func isFileFormatSupported(filename string, section string) (bool, error) { return false, fmt.Errorf("only .adoc, .md, .tf, and .txt formats are supported to read %s from", section) } -func loadHeader(options *Options) (string, error) { - if !options.ShowHeader { +func loadHeader(config *print.Config) (string, error) { + if !config.Sections.Header { return "", nil } - return loadSection(options, options.HeaderFromFile, "header") + return loadSection(config, config.HeaderFrom, "header") } -func loadFooter(options *Options) (string, error) { - if !options.ShowFooter { +func loadFooter(config *print.Config) (string, error) { + if !config.Sections.Footer { return "", nil } - return loadSection(options, options.FooterFromFile, "footer") + return loadSection(config, config.FooterFrom, "footer") } -func loadSection(options *Options, file string, section string) (string, error) { //nolint:gocyclo +func loadSection(config *print.Config, file string, section string) (string, error) { //nolint:gocyclo // NOTE(khos2ow): this function is over our cyclomatic complexity goal. // Be wary when adding branches, and look for functionality that could // be reasonably moved into an injected dependency. @@ -136,7 +137,7 @@ func loadSection(options *Options, file string, section string) (string, error) if section == "" { return "", errors.New("section is missing") } - filename := filepath.Join(options.Path, file) + filename := filepath.Join(config.ModuleRoot, file) if ok, err := isFileFormatSupported(file, section); !ok { return "", err } @@ -181,7 +182,7 @@ func loadSection(options *Options, file string, section string) (string, error) return strings.Join(sectionText, "\n"), nil } -func loadInputs(tfmodule *tfconfig.Module, options *Options) ([]*Input, []*Input, []*Input) { +func loadInputs(tfmodule *tfconfig.Module, config *print.Config) ([]*Input, []*Input, []*Input) { var inputs = make([]*Input, 0, len(tfmodule.Variables)) var required = make([]*Input, 0, len(tfmodule.Variables)) var optional = make([]*Input, 0, len(tfmodule.Variables)) @@ -189,7 +190,7 @@ func loadInputs(tfmodule *tfconfig.Module, options *Options) ([]*Input, []*Input for _, input := range tfmodule.Variables { // convert CRLF to LF early on (https://github.com/terraform-docs/terraform-docs/issues/305) inputDescription := strings.ReplaceAll(input.Description, "\r\n", "\n") - if inputDescription == "" && options.ReadComments { + if inputDescription == "" && config.Settings.ReadComments { inputDescription = loadComments(input.Pos.Filename, input.Pos.Line) } @@ -259,19 +260,19 @@ func loadModulecalls(tfmodule *tfconfig.Module) []*ModuleCall { return modules } -func loadOutputs(tfmodule *tfconfig.Module, options *Options) ([]*Output, error) { +func loadOutputs(tfmodule *tfconfig.Module, config *print.Config) ([]*Output, error) { outputs := make([]*Output, 0, len(tfmodule.Outputs)) values := make(map[string]*output) - if options.OutputValues { + if config.OutputValues.Enabled { var err error - values, err = loadOutputValues(options) + values, err = loadOutputValues(config) if err != nil { return nil, err } } for _, o := range tfmodule.Outputs { description := o.Description - if description == "" && options.ReadComments { + if description == "" && config.Settings.ReadComments { description = loadComments(o.Pos.Filename, o.Pos.Line) } output := &Output{ @@ -281,9 +282,9 @@ func loadOutputs(tfmodule *tfconfig.Module, options *Options) ([]*Output, error) Filename: o.Pos.Filename, Line: o.Pos.Line, }, - ShowValue: options.OutputValues, + ShowValue: config.OutputValues.Enabled, } - if options.OutputValues { + if config.OutputValues.Enabled { output.Sensitive = values[output.Name].Sensitive if values[output.Name].Sensitive { output.Value = types.ValueOf(``) @@ -296,17 +297,17 @@ func loadOutputs(tfmodule *tfconfig.Module, options *Options) ([]*Output, error) return outputs, nil } -func loadOutputValues(options *Options) (map[string]*output, error) { +func loadOutputValues(config *print.Config) (map[string]*output, error) { var out []byte var err error - if options.OutputValuesPath == "" { + if config.OutputValues.From == "" { cmd := exec.Command("terraform", "output", "-json") - cmd.Dir = options.Path + cmd.Dir = config.ModuleRoot if out, err = cmd.Output(); err != nil { return nil, fmt.Errorf("caught error while reading the terraform outputs: %w", err) } - } else if out, err = ioutil.ReadFile(options.OutputValuesPath); err != nil { - return nil, fmt.Errorf("caught error while reading the terraform outputs file at %s: %w", options.OutputValuesPath, err) + } else if out, err = ioutil.ReadFile(config.OutputValues.From); err != nil { + return nil, fmt.Errorf("caught error while reading the terraform outputs file at %s: %w", config.OutputValues.From, err) } var terraformOutputs map[string]*output err = json.Unmarshal(out, &terraformOutputs) @@ -316,7 +317,7 @@ func loadOutputValues(options *Options) (map[string]*output, error) { return terraformOutputs, err } -func loadProviders(tfmodule *tfconfig.Module, options *Options) []*Provider { +func loadProviders(tfmodule *tfconfig.Module, config *print.Config) []*Provider { type provider struct { Name string `hcl:"name,label"` Version string `hcl:"version"` @@ -328,10 +329,10 @@ func loadProviders(tfmodule *tfconfig.Module, options *Options) []*Provider { } lock := make(map[string]provider) - if options.UseLockFile { + if config.Settings.LockFile { var lf lockfile - filename := filepath.Join(options.Path, ".terraform.lock.hcl") + filename := filepath.Join(config.ModuleRoot, ".terraform.lock.hcl") if err := hclsimple.DecodeFile(filename, nil, &lf); err == nil { for i := range lf.Provider { segments := strings.Split(lf.Provider[i].Name, "/") @@ -486,55 +487,21 @@ func loadComments(filename string, lineNum int) string { return strings.Join(comment, " ") } -func sortItems(tfmodule *Module, sortby *SortBy) { //nolint:gocyclo - // NOTE(khos2ow): this function is over our cyclomatic complexity goal. - // Be wary when adding branches, and look for functionality that could - // be reasonably moved into an injected dependency. - +func sortItems(tfmodule *Module, config *print.Config) { // inputs - switch { - case sortby.Type: - sortInputsByType(tfmodule.Inputs) - sortInputsByType(tfmodule.RequiredInputs) - sortInputsByType(tfmodule.OptionalInputs) - case sortby.Required: - sortInputsByRequired(tfmodule.Inputs) - sortInputsByRequired(tfmodule.RequiredInputs) - sortInputsByRequired(tfmodule.OptionalInputs) - case sortby.Name: - sortInputsByName(tfmodule.Inputs) - sortInputsByName(tfmodule.RequiredInputs) - sortInputsByName(tfmodule.OptionalInputs) - default: - sortInputsByPosition(tfmodule.Inputs) - sortInputsByPosition(tfmodule.RequiredInputs) - sortInputsByPosition(tfmodule.OptionalInputs) - } + inputs(tfmodule.Inputs).sort(config.Sort.Enabled, config.Sort.By) + inputs(tfmodule.RequiredInputs).sort(config.Sort.Enabled, config.Sort.By) + inputs(tfmodule.OptionalInputs).sort(config.Sort.Enabled, config.Sort.By) // outputs - if sortby.Name || sortby.Required || sortby.Type { - sortOutputsByName(tfmodule.Outputs) - } else { - sortOutputsByPosition(tfmodule.Outputs) - } + outputs(tfmodule.Outputs).sort(config.Sort.Enabled, config.Sort.By) // providers - if sortby.Name || sortby.Required || sortby.Type { - sortProvidersByName(tfmodule.Providers) - } else { - sortProvidersByPosition(tfmodule.Providers) - } + providers(tfmodule.Providers).sort(config.Sort.Enabled, config.Sort.By) - // resources (always sorted) - sortResourcesByType(tfmodule.Resources) + // resources + resources(tfmodule.Resources).sort(config.Sort.Enabled, config.Sort.By) // modules - switch { - case sortby.Name || sortby.Required: - sortModulecallsByName(tfmodule.ModuleCalls) - case sortby.Type: - sortModulecallsBySource(tfmodule.ModuleCalls) - default: - sortModulecallsByPosition(tfmodule.ModuleCalls) - } + modulecalls(tfmodule.ModuleCalls).sort(config.Sort.Enabled, config.Sort.By) } diff --git a/terraform/load_test.go b/terraform/load_test.go index 7f0c394..e2c1802 100644 --- a/terraform/load_test.go +++ b/terraform/load_test.go @@ -17,15 +17,18 @@ import ( "testing" "github.com/stretchr/testify/assert" + + "github.com/terraform-docs/terraform-docs/print" ) func TestLoadModuleWithOptions(t *testing.T) { assert := assert.New(t) - options, _ := NewOptions().With(&Options{ - Path: filepath.Join("testdata", "full-example"), - }) - module, err := LoadWithOptions(options) + config := print.NewConfig() + config.ModuleRoot = filepath.Join("testdata", "full-example") + config.Sections.Header = true + + module, err := LoadWithOptions(config) assert.Nil(err) assert.Equal(true, module.HasHeader()) @@ -36,13 +39,11 @@ func TestLoadModuleWithOptions(t *testing.T) { assert.Equal(true, module.HasProviders()) assert.Equal(true, module.HasRequirements()) - options, _ = options.With(&Options{ - FooterFromFile: "doc.tf", - ShowFooter: true, - }) - // options.With and .WithOverwrite will not overwrite true with false - options.ShowHeader = false - module, err = LoadWithOptions(options) + config.Sections.Header = false + config.Sections.Footer = true + config.FooterFrom = "doc.tf" + + module, err = LoadWithOptions(config) assert.Nil(err) assert.Equal(true, module.HasFooter()) assert.Equal(false, module.HasHeader()) @@ -241,14 +242,15 @@ func TestLoadHeader(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - options, err := NewOptions().With(&Options{ - Path: filepath.Join("testdata", tt.testData), - ShowHeader: tt.showHeader, - }) - assert.Nil(err) + + config := print.NewConfig() + config.ModuleRoot = filepath.Join("testdata", tt.testData) + config.Sections.Header = tt.showHeader + expected, err := tt.expectedData() assert.Nil(err) - header, err := loadHeader(options) + + header, err := loadHeader(config) assert.Nil(err) assert.Equal(expected, header) }) @@ -287,15 +289,16 @@ func TestLoadFooter(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - options, err := NewOptions().With(&Options{ - Path: filepath.Join("testdata", tt.testData), - FooterFromFile: tt.footerFile, - ShowFooter: tt.showFooter, - }) - assert.Nil(err) + + config := print.NewConfig() + config.ModuleRoot = filepath.Join("testdata", tt.testData) + config.Sections.Footer = tt.showFooter + config.FooterFrom = tt.footerFile + expected, err := tt.expectedData() assert.Nil(err) - header, err := loadFooter(options) + + header, err := loadFooter(config) assert.Nil(err) assert.Equal(expected, header) }) @@ -433,8 +436,11 @@ func TestLoadSections(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - options := &Options{Path: filepath.Join("testdata", tt.path)} - actual, err := loadSection(options, tt.file, tt.section) + + config := print.NewConfig() + config.ModuleRoot = filepath.Join("testdata", tt.path) + + actual, err := loadSection(config, tt.file, tt.section) if tt.wantErr { assert.NotNil(err) assert.Equal(tt.errText, err.Error()) @@ -497,9 +503,10 @@ func TestLoadInputs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) + + config := print.NewConfig() module, _ := loadModule(filepath.Join("testdata", tt.path)) - options := NewOptions() - inputs, requireds, optionals := loadInputs(module, options) + inputs, requireds, optionals := loadInputs(module, config) assert.Equal(tt.expected.inputs, len(inputs)) assert.Equal(tt.expected.requireds, len(requireds)) @@ -556,9 +563,10 @@ func TestLoadInputsLineEnding(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) + + config := print.NewConfig() module, _ := loadModule(filepath.Join("testdata", tt.path)) - options := NewOptions() - inputs, _, _ := loadInputs(module, options) + inputs, _, _ := loadInputs(module, config) assert.Equal(1, len(inputs)) assert.Equal(tt.expected, string(inputs[0].Description)) @@ -593,9 +601,10 @@ func TestLoadOutputs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - options := NewOptions() + + config := print.NewConfig() module, _ := loadModule(filepath.Join("testdata", tt.path)) - outputs, err := loadOutputs(module, options) + outputs, err := loadOutputs(module, config) assert.Nil(err) assert.Equal(tt.expected.outputs, len(outputs)) @@ -645,12 +654,13 @@ func TestLoadOutputsValues(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - options, _ := NewOptions().With(&Options{ - OutputValues: true, - OutputValuesPath: filepath.Join("testdata", tt.path, tt.outputPath), - }) + + config := print.NewConfig() + config.OutputValues.Enabled = true + config.OutputValues.From = filepath.Join("testdata", tt.path, tt.outputPath) + module, _ := loadModule(filepath.Join("testdata", tt.path)) - outputs, err := loadOutputs(module, options) + outputs, err := loadOutputs(module, config) if tt.wantErr { assert.NotNil(err) @@ -711,12 +721,13 @@ func TestLoadProviders(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - options, _ := NewOptions().With(&Options{ - Path: filepath.Join("testdata", tt.path), - }) - options.UseLockFile = tt.lockfile + + config := print.NewConfig() + config.ModuleRoot = filepath.Join("testdata", tt.path) + config.Settings.LockFile = tt.lockfile + module, _ := loadModule(filepath.Join("testdata", tt.path)) - providers := loadProviders(module, options) + providers := loadProviders(module, config) actual := []string{} @@ -809,17 +820,19 @@ func TestReadComments(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) - options := NewOptions() - options.ReadComments = tt.readComments + + config := print.NewConfig() + config.Settings.ReadComments = tt.readComments + module, err := loadModule(filepath.Join("testdata", tt.path)) assert.Nil(err) - inputs, _, _ := loadInputs(module, options) + inputs, _, _ := loadInputs(module, config) assert.Equal(1, len(inputs)) assert.Equal(tt.expected, string(inputs[0].Description)) - outputs, _ := loadOutputs(module, options) + outputs, _ := loadOutputs(module, config) assert.Equal(1, len(outputs)) assert.Equal(tt.expected, string(outputs[0].Description)) }) @@ -835,15 +848,17 @@ func TestSortItems(t *testing.T) { providers []string } tests := []struct { - name string - path string - sort *SortBy - expected expected + name string + path string + sortenabled bool + sorttype string + expected expected }{ { - name: "sort module items", - path: "full-example", - sort: &SortBy{Name: false, Required: false, Type: false}, + name: "sort module items", + path: "full-example", + sortenabled: false, + sorttype: "", expected: expected{ inputs: []string{"D", "B", "E", "A", "C", "F", "G"}, required: []string{"A", "F"}, @@ -853,9 +868,36 @@ func TestSortItems(t *testing.T) { }, }, { - name: "sort module items", - path: "full-example", - sort: &SortBy{Name: true, Required: false, Type: false}, + name: "sort module items", + path: "full-example", + sortenabled: false, + sorttype: print.SortName, + expected: expected{ + inputs: []string{"D", "B", "E", "A", "C", "F", "G"}, + required: []string{"A", "F"}, + optional: []string{"D", "B", "E", "C", "G"}, + outputs: []string{"C", "A", "B"}, + providers: []string{"tls", "aws", "null"}, + }, + }, + { + name: "sort module items", + path: "full-example", + sortenabled: false, + sorttype: print.SortRequired, + expected: expected{ + inputs: []string{"D", "B", "E", "A", "C", "F", "G"}, + required: []string{"A", "F"}, + optional: []string{"D", "B", "E", "C", "G"}, + outputs: []string{"C", "A", "B"}, + providers: []string{"tls", "aws", "null"}, + }, + }, + { + name: "sort module items", + path: "full-example", + sortenabled: true, + sorttype: print.SortName, expected: expected{ inputs: []string{"A", "B", "C", "D", "E", "F", "G"}, required: []string{"A", "F"}, @@ -865,9 +907,10 @@ func TestSortItems(t *testing.T) { }, }, { - name: "sort module items", - path: "full-example", - sort: &SortBy{Name: false, Required: true, Type: false}, + name: "sort module items", + path: "full-example", + sortenabled: true, + sorttype: print.SortRequired, expected: expected{ inputs: []string{"A", "F", "B", "C", "D", "E", "G"}, required: []string{"A", "F"}, @@ -877,57 +920,10 @@ func TestSortItems(t *testing.T) { }, }, { - name: "sort module items", - path: "full-example", - sort: &SortBy{Name: false, Required: false, Type: true}, - expected: expected{ - inputs: []string{"A", "F", "G", "B", "C", "D", "E"}, - required: []string{"A", "F"}, - optional: []string{"G", "B", "C", "D", "E"}, - outputs: []string{"A", "B", "C"}, - providers: []string{"aws", "null", "tls"}, - }, - }, - { - name: "sort module items", - path: "full-example", - sort: &SortBy{Name: true, Required: true, Type: false}, - expected: expected{ - inputs: []string{"A", "F", "B", "C", "D", "E", "G"}, - required: []string{"A", "F"}, - optional: []string{"B", "C", "D", "E", "G"}, - outputs: []string{"A", "B", "C"}, - providers: []string{"aws", "null", "tls"}, - }, - }, - { - name: "sort module items", - path: "full-example", - sort: &SortBy{Name: true, Required: false, Type: true}, - expected: expected{ - inputs: []string{"A", "F", "G", "B", "C", "D", "E"}, - required: []string{"A", "F"}, - optional: []string{"G", "B", "C", "D", "E"}, - outputs: []string{"A", "B", "C"}, - providers: []string{"aws", "null", "tls"}, - }, - }, - { - name: "sort module items", - path: "full-example", - sort: &SortBy{Name: false, Required: true, Type: true}, - expected: expected{ - inputs: []string{"A", "F", "G", "B", "C", "D", "E"}, - required: []string{"A", "F"}, - optional: []string{"G", "B", "C", "D", "E"}, - outputs: []string{"A", "B", "C"}, - providers: []string{"aws", "null", "tls"}, - }, - }, - { - name: "sort module items", - path: "full-example", - sort: &SortBy{Name: true, Required: true, Type: true}, + name: "sort module items", + path: "full-example", + sortenabled: true, + sorttype: print.SortType, expected: expected{ inputs: []string{"A", "F", "G", "B", "C", "D", "E"}, required: []string{"A", "F"}, @@ -941,15 +937,17 @@ func TestSortItems(t *testing.T) { t.Run(tt.name, func(t *testing.T) { assert := assert.New(t) path := filepath.Join("testdata", tt.path) - options, _ := NewOptions().With(&Options{ - Path: path, - SortBy: tt.sort, - }) + + config := print.NewConfig() + config.ModuleRoot = path + config.Sort.Enabled = tt.sortenabled + config.Sort.By = tt.sorttype + tfmodule, _ := loadModule(path) - module, err := loadModuleItems(tfmodule, options) + module, err := loadModuleItems(tfmodule, config) assert.Nil(err) - sortItems(module, tt.sort) + sortItems(module, config) for i, v := range module.Inputs { assert.Equal(tt.expected.inputs[i], v.Name) diff --git a/terraform/modulecall.go b/terraform/modulecall.go index d96f4bd..36ac195 100644 --- a/terraform/modulecall.go +++ b/terraform/modulecall.go @@ -15,6 +15,7 @@ import ( "sort" terraformsdk "github.com/terraform-docs/plugin-sdk/terraform" + "github.com/terraform-docs/terraform-docs/print" ) // ModuleCall represents a submodule called by Terraform module. @@ -56,6 +57,21 @@ func sortModulecallsByPosition(x []*ModuleCall) { type modulecalls []*ModuleCall +func (mm modulecalls) sort(enabled bool, by string) { + if !enabled { + sortModulecallsByPosition(mm) + } else { + switch by { + case print.SortName, print.SortRequired: + sortModulecallsByName(mm) + case print.SortType: + sortModulecallsBySource(mm) + default: + sortModulecallsByPosition(mm) + } + } +} + func (mm modulecalls) convert() []*terraformsdk.ModuleCall { list := []*terraformsdk.ModuleCall{} for _, m := range mm { diff --git a/terraform/options.go b/terraform/options.go deleted file mode 100644 index 542b594..0000000 --- a/terraform/options.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2021 The terraform-docs Authors. - -Licensed under the MIT license (the "License"); you may not -use this file except in compliance with the License. - -You may obtain a copy of the License at the LICENSE file in -the root directory of this source tree. -*/ - -package terraform - -import ( - "errors" - - "github.com/imdario/mergo" -) - -// SortBy contains different sort criteria corresponding -// to available flags (e.g. name, required, etc) -type SortBy struct { - Name bool - Required bool - Type bool -} - -// Options contains required options to load a Module from path -type Options struct { - Path string - ShowHeader bool - HeaderFromFile string - ShowFooter bool - FooterFromFile string - UseLockFile bool - SortBy *SortBy - OutputValues bool - OutputValuesPath string - ReadComments bool -} - -// NewOptions returns new instance of Options -func NewOptions() *Options { - return &Options{ - Path: "", - ShowHeader: true, - HeaderFromFile: "main.tf", - ShowFooter: false, - FooterFromFile: "", - UseLockFile: true, - SortBy: &SortBy{Name: false, Required: false, Type: false}, - OutputValues: false, - OutputValuesPath: "", - ReadComments: true, - } -} - -// With override options with existing Options -func (o *Options) With(override *Options) (*Options, error) { - if override == nil { - return nil, errors.New("cannot use nil as override value") - } - if err := mergo.Merge(o, *override); err != nil { - return nil, err - } - return o, nil -} - -// WithOverwrite override options with existing Options and overwrites non-empty -// items in destination -func (o *Options) WithOverwrite(override *Options) (*Options, error) { - if override == nil { - return nil, errors.New("cannot use nil as override value") - } - if err := mergo.MergeWithOverwrite(o, *override); err != nil { - return nil, err - } - return o, nil -} diff --git a/terraform/options_test.go b/terraform/options_test.go deleted file mode 100644 index e13afa6..0000000 --- a/terraform/options_test.go +++ /dev/null @@ -1,117 +0,0 @@ -/* -Copyright 2021 The terraform-docs Authors. - -Licensed under the MIT license (the "License"); you may not -use this file except in compliance with the License. - -You may obtain a copy of the License at the LICENSE file in -the root directory of this source tree. -*/ - -package terraform - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestOptionsWith(t *testing.T) { - assert := assert.New(t) - - options := NewOptions() - - assert.Equal(options.Path, "") - assert.Equal(options.OutputValues, false) - assert.Equal(options.OutputValuesPath, "") - - _, err1 := options.With(&Options{ - Path: "/path/to/foo", - }) - assert.Nil(err1) - - assert.Equal(options.Path, "/path/to/foo") - assert.Equal(options.OutputValues, false) - assert.Equal(options.OutputValuesPath, "") - - _, err2 := options.With(&Options{ - OutputValues: true, - OutputValuesPath: "/path/to/output/values", - }) - assert.Nil(err2) - - assert.Equal(options.Path, "/path/to/foo") - assert.Equal(options.OutputValues, true) - assert.Equal(options.OutputValuesPath, "/path/to/output/values") - - _, err3 := options.With(&Options{ - Path: "", - OutputValues: false, - }) - assert.Nil(err3) - - assert.NotEqual(options.Path, "") - assert.NotEqual(options.OutputValues, false) -} - -func TestOptionsWithNil(t *testing.T) { - assert := assert.New(t) - options := NewOptions() - - _, err := options.With(nil) - - assert.NotNil(err) -} - -func TestOptionsWithOverwrite(t *testing.T) { - assert := assert.New(t) - - options := NewOptions() - - assert.Equal(options.Path, "") - assert.Equal(options.HeaderFromFile, "main.tf") - assert.Equal(options.OutputValues, false) - assert.Equal(options.OutputValuesPath, "") - - _, err1 := options.With(&Options{ - Path: "/path/to/foo", - }) - assert.Nil(err1) - - assert.Equal(options.Path, "/path/to/foo") - assert.Equal(options.HeaderFromFile, "main.tf") - assert.Equal(options.OutputValues, false) - assert.Equal(options.OutputValuesPath, "") - - _, err2 := options.WithOverwrite(&Options{ - HeaderFromFile: "doc.tf", - OutputValues: true, - OutputValuesPath: "/path/to/output/values", - }) - assert.Nil(err2) - - assert.Equal(options.Path, "/path/to/foo") - assert.Equal(options.HeaderFromFile, "doc.tf") - assert.Equal(options.OutputValues, true) - assert.Equal(options.OutputValuesPath, "/path/to/output/values") - - _, err3 := options.WithOverwrite(&Options{ - Path: "", - OutputValues: false, - }) - assert.Nil(err3) - - assert.NotEqual(options.Path, "") - assert.Equal(options.HeaderFromFile, "doc.tf") - assert.NotEqual(options.OutputValues, false) - assert.Equal(options.OutputValuesPath, "/path/to/output/values") -} - -func TestOptionsWithNilOverwrite(t *testing.T) { - assert := assert.New(t) - options := NewOptions() - - _, err := options.WithOverwrite(nil) - - assert.NotNil(err) -} diff --git a/terraform/output.go b/terraform/output.go index 2bd87f4..541a6db 100644 --- a/terraform/output.go +++ b/terraform/output.go @@ -146,6 +146,15 @@ func sortOutputsByPosition(x []*Output) { type outputs []*Output +func (oo outputs) sort(enabled bool, by string) { //nolint:unparam + if !enabled { + sortOutputsByPosition(oo) + } else { + // always sort by name if sorting is enabled + sortOutputsByName(oo) + } +} + func (oo outputs) convert() []*terraformsdk.Output { list := []*terraformsdk.Output{} for _, o := range oo { diff --git a/terraform/provider.go b/terraform/provider.go index f5e2893..87e7530 100644 --- a/terraform/provider.go +++ b/terraform/provider.go @@ -54,6 +54,15 @@ func sortProvidersByPosition(x []*Provider) { type providers []*Provider +func (pp providers) sort(enabled bool, by string) { //nolint:unparam + if !enabled { + sortProvidersByPosition(pp) + } else { + // always sort by name if sorting is enabled + sortProvidersByName(pp) + } +} + func (pp providers) convert() []*terraformsdk.Provider { list := []*terraformsdk.Provider{} for _, p := range pp { diff --git a/terraform/resource.go b/terraform/resource.go index 42b7077..20a40b3 100644 --- a/terraform/resource.go +++ b/terraform/resource.go @@ -82,6 +82,11 @@ func sortResourcesByType(x []*Resource) { type resources []*Resource +func (rr resources) sort(enabled bool, by string) { //nolint:unparam + // always sort by type + sortResourcesByType(rr) +} + func (rr resources) convert() []*terraformsdk.Resource { list := []*terraformsdk.Resource{} for _, r := range rr {