mirror of
https://github.com/terraform-docs/terraform-docs.git
synced 2026-03-27 12:58:35 +07:00
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>
This commit is contained in:
@@ -11,8 +11,13 @@ the root directory of this source tree.
|
||||
package print
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// Config represents all the available config options that can be accessed and
|
||||
@@ -135,15 +140,15 @@ func defaultSections() sections {
|
||||
Show: []string{},
|
||||
Hide: []string{},
|
||||
|
||||
DataSources: false,
|
||||
Header: false,
|
||||
DataSources: true,
|
||||
Header: true,
|
||||
Footer: false,
|
||||
Inputs: false,
|
||||
ModuleCalls: false,
|
||||
Outputs: false,
|
||||
Providers: false,
|
||||
Requirements: false,
|
||||
Resources: false,
|
||||
Inputs: true,
|
||||
ModuleCalls: true,
|
||||
Outputs: true,
|
||||
Providers: true,
|
||||
Requirements: true,
|
||||
Resources: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,3 +471,40 @@ func (c *Config) Validate() error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadConfig reads config file in `rootDir` with given `filename` and returns
|
||||
// instance of Config. It returns error if config file not found or there is a
|
||||
// problem with unmarshalling.
|
||||
func ReadConfig(rootDir string, filename string) (*Config, error) {
|
||||
cfg := NewConfig()
|
||||
|
||||
v := viper.New()
|
||||
v.SetConfigFile(path.Join(rootDir, filename))
|
||||
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
var perr *os.PathError
|
||||
if errors.As(err, &perr) {
|
||||
return nil, fmt.Errorf("config file %s not found", filename)
|
||||
}
|
||||
|
||||
var cerr viper.ConfigFileNotFoundError
|
||||
if !errors.As(err, &cerr) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := v.Unmarshal(cfg); err != nil {
|
||||
return nil, fmt.Errorf("unable to decode config, %w", err)
|
||||
}
|
||||
|
||||
cfg.ModuleRoot = rootDir
|
||||
|
||||
// process and validate configuration
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg.Parse()
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user