From 80172d77f4f0a2a2c5d0cea09d390e60752d4062 Mon Sep 17 00:00:00 2001 From: Khosrow Moossavi Date: Thu, 2 Apr 2020 16:17:30 -0400 Subject: [PATCH] fix: Don't crash when reading header if 'main.tf' not found (#235) Signed-off-by: Khosrow Moossavi --- cmd/root.go | 17 +++++++++++------ internal/module/module.go | 5 ++++- internal/module/module_test.go | 7 +++++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 226650c..1054337 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -13,11 +13,13 @@ var settings = print.NewSettings() var options = module.NewOptions() var rootCmd = &cobra.Command{ - Args: cobra.NoArgs, - Use: "terraform-docs", - Short: "A utility to generate documentation from Terraform modules in various output formats", - Long: "A utility to generate documentation from Terraform modules in various output formats", - Version: version.Version(), + Args: cobra.NoArgs, + Use: "terraform-docs", + Short: "A utility to generate documentation from Terraform modules in various output formats", + Long: "A utility to generate documentation from Terraform modules in various output formats", + Version: version.Version(), + SilenceUsage: true, + SilenceErrors: true, PersistentPreRun: func(cmd *cobra.Command, args []string) { oppositeBool := func(name string) bool { val, _ := cmd.Flags().GetBool(name) @@ -67,7 +69,10 @@ func init() { // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() error { - return rootCmd.Execute() + if err := rootCmd.Execute(); err != nil { + fmt.Printf("Error: %s\n", err.Error()) + } + return nil } // RootCmd represents the base command when called without any subcommands diff --git a/internal/module/module.go b/internal/module/module.go index 791d2a1..5bb7a48 100644 --- a/internal/module/module.go +++ b/internal/module/module.go @@ -72,7 +72,10 @@ func loadHeader(options *Options) (string, error) { filename := filepath.Join(options.Path, options.HeaderFromFile) _, err := ioutil.ReadFile(filename) if err != nil { - return "", err + if options.HeaderFromFile != "main.tf" { + return "", err // user explicitly asked for a file which doesn't exist + } + return "", nil // absorb the error to not break workflow of users who don't have 'main.tf at all } lines := reader.Lines{ FileName: filename, diff --git a/internal/module/module_test.go b/internal/module/module_test.go index 22e5821..7361bf2 100644 --- a/internal/module/module_test.go +++ b/internal/module/module_test.go @@ -75,6 +75,13 @@ func TestLoadHeader(t *testing.T) { expected: "Custom Header:\n\nExample of 'foo_bar' module in `foo_bar.tf`.\n\n- list item 1\n- list item 2", wantErr: false, }, + { + name: "load module header from path", + path: "no-inputs", + header: "main.tf", + expected: "", + wantErr: false, + }, { name: "load module header from path", path: "full-example",