Skip to content

Commit de684ce

Browse files
committed
Add public ReadConfig function
If terraform-docs is being used as a library, `print.ReadConfig()` can be used to dynamically read and load .terraform-docs.yml config file. Example: ```go config, err := print.ReadConfig(".", ".terraform-docs.yml") if err != nil { ... } ``` Signed-off-by: Khosrow Moossavi <khos2ow@gmail.com>
1 parent ba42be1 commit de684ce

File tree

1 file changed

+50
-8
lines changed

1 file changed

+50
-8
lines changed

print/config.go

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,13 @@ the root directory of this source tree.
1111
package print
1212

1313
import (
14+
"errors"
1415
"fmt"
16+
"os"
17+
"path"
1518
"strings"
19+
20+
"github.com/spf13/viper"
1621
)
1722

1823
// Config represents all the available config options that can be accessed and
@@ -135,15 +140,15 @@ func defaultSections() sections {
135140
Show: []string{},
136141
Hide: []string{},
137142

138-
DataSources: false,
139-
Header: false,
143+
DataSources: true,
144+
Header: true,
140145
Footer: false,
141-
Inputs: false,
142-
ModuleCalls: false,
143-
Outputs: false,
144-
Providers: false,
145-
Requirements: false,
146-
Resources: false,
146+
Inputs: true,
147+
ModuleCalls: true,
148+
Outputs: true,
149+
Providers: true,
150+
Requirements: true,
151+
Resources: true,
147152
}
148153
}
149154

@@ -466,3 +471,40 @@ func (c *Config) Validate() error {
466471

467472
return nil
468473
}
474+
475+
// ReadConfig reads config file in `rootDir` with given `filename` and returns
476+
// instance of Config. It returns error if config file not found or there is a
477+
// problem with unmarshalling.
478+
func ReadConfig(rootDir string, filename string) (*Config, error) {
479+
cfg := NewConfig()
480+
481+
v := viper.New()
482+
v.SetConfigFile(path.Join(rootDir, filename))
483+
484+
if err := v.ReadInConfig(); err != nil {
485+
var perr *os.PathError
486+
if errors.As(err, &perr) {
487+
return nil, fmt.Errorf("config file %s not found", filename)
488+
}
489+
490+
var cerr viper.ConfigFileNotFoundError
491+
if !errors.As(err, &cerr) {
492+
return nil, err
493+
}
494+
}
495+
496+
if err := v.Unmarshal(cfg); err != nil {
497+
return nil, fmt.Errorf("unable to decode config, %w", err)
498+
}
499+
500+
cfg.ModuleRoot = rootDir
501+
502+
// process and validate configuration
503+
if err := cfg.Validate(); err != nil {
504+
return nil, err
505+
}
506+
507+
cfg.Parse()
508+
509+
return cfg, nil
510+
}

0 commit comments

Comments
 (0)