-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Autodetect config format based on extension
- Loading branch information
1 parent
560c87b
commit 6de748e
Showing
3 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package altsrc | ||
|
||
import ( | ||
"fmt" | ||
"path/filepath" | ||
|
||
"github.com/urfave/cli/v2" | ||
) | ||
|
||
var detectableSources = map[string]func(string) func(cCtx *cli.Context) (InputSourceContext, error){ | ||
".conf": NewTomlSourceFromFlagFunc, | ||
".json": NewJSONSourceFromFlagFunc, | ||
".toml": NewTomlSourceFromFlagFunc, | ||
".yaml": NewYamlSourceFromFlagFunc, | ||
} | ||
|
||
// RegisterDetectableSource lets developers add support for their own altsrc filetypes to the autodetection list. | ||
func RegisterDetectableSource(extension string, handler func(string) func(cCtx *cli.Context) (InputSourceContext, error)) { | ||
detectableSources[extension] = handler | ||
} | ||
|
||
// DetectNewSourceFromFlagFunc creates a new InputSourceContext from a provided flag name and source context. | ||
func DetectNewSourceFromFlagFunc(flagFileName string) func(cCtx *cli.Context) (InputSourceContext, error) { | ||
return func(cCtx *cli.Context) (InputSourceContext, error) { | ||
if fileFullPath := cCtx.String(flagFileName); fileFullPath != "" { | ||
fileExt := filepath.Ext(fileFullPath) | ||
if handler, ok := detectableSources[fileExt]; ok { | ||
return handler(flagFileName)(cCtx) | ||
} | ||
return nil, fmt.Errorf("Unable to determine config file type from extension.\nMust be one of %v", detectableExtensions()) | ||
} | ||
return defaultInputSource() | ||
} | ||
} | ||
|
||
func detectableExtensions() []string { | ||
extensions := make([]string, 0, len(detectableSources)) | ||
for ext := range detectableSources { | ||
extensions = append(extensions, ext) | ||
} | ||
|
||
return extensions | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters