Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions description.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package cleanenv

import (
"os"
"strconv"
"text/tabwriter"
"text/template"
)

const (
DefaultTableFormat = `The following environment variables can be used for configuration:

KEY TYPE DEFAULT REQUIRED DESCRIPTION
{{range .}}{{usage_key .}} {{usage_type .}} {{usage_default .}} {{usage_required .}} {{usage_description .}}
{{end}}`
)

func PrintDescription(cfg interface{}) error {
meta, err := readStructMetadata(cfg)
if err != nil {
return err
}

// Specify the default usage template functions
functions := template.FuncMap{
"usage_key": func(v structMeta) string { return v.envList[0] },
"usage_description": func(v structMeta) string { return v.description },
"usage_type": func(v structMeta) string { return v.fieldValue.Kind().String() },
"usage_default": func(v structMeta) string { return derefString(v.defValue) },
"usage_required": func(v structMeta) string { return formatBool(v.required) },
}

tmpl, err := template.New("cleanenv").Funcs(functions).Parse(DefaultTableFormat)
if err != nil {
return err
}
tabs := tabwriter.NewWriter(os.Stdout, 1, 0, 4, ' ', 0)
err = tmpl.Execute(tabs, meta)
if err != nil {
return err
}
tabs.Flush()
return nil
}

func derefString(s *string) string {
if s != nil {
return *s
}

return ""
}

func formatBool(b bool) string {
if b {
return strconv.FormatBool(b)
}
return ""
}
20 changes: 20 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,26 @@ import (
"github.com/ilyakaznacheev/cleanenv"
)

// ExamplePrintDescription prints a description text from structure tags
func ExamplePrintDescription() {
type config struct {
One int64 `env:"ONE" env-description:"first parameter" env-required:"true"`
Two float64 `env:"TWO" env-description:"second parameter"`
Three string `env:"THREE" env-description:"third parameter"`
}

var cfg config

cleanenv.PrintDescription(&cfg)
//Output: The following environment variables can be used for configuration:
//
// KEY TYPE DEFAULT REQUIRED DESCRIPTION
// ONE int64 true first parameter
// TWO float64 second parameter
// THREE string third parameter

}

// ExampleGetDescription builds a description text from structure tags
func ExampleGetDescription() {
type config struct {
Expand Down