TUN-3715: Only read config file once, right before invoking the command

This commit is contained in:
Igor Postelnik
2021-02-04 19:44:03 -06:00
parent 2c746b3361
commit 8c5498fad1
18 changed files with 125 additions and 114 deletions

View File

@@ -9,12 +9,12 @@ import (
func RemovedCommand(name string) *cli.Command {
return &cli.Command{
Name: name,
Action: ErrorHandler(func(context *cli.Context) error {
Action: func(context *cli.Context) error {
return cli.Exit(
fmt.Sprintf("%s command is no longer supported by cloudflared. Consult Argo Tunnel documentation for possible alternative solutions.", name),
-1,
)
}),
},
Description: fmt.Sprintf("%s is deprecated", name),
Hidden: true,
}

View File

@@ -2,6 +2,7 @@ package cliutil
import (
"fmt"
"github.com/urfave/cli/v2"
)
@@ -21,7 +22,7 @@ func UsageError(format string, args ...interface{}) error {
}
// Ensures exit with error code if actionFunc returns an error
func ErrorHandler(actionFunc cli.ActionFunc) cli.ActionFunc {
func WithErrorHandler(actionFunc cli.ActionFunc) cli.ActionFunc {
return func(ctx *cli.Context) error {
err := actionFunc(ctx)
if err != nil {

View File

@@ -0,0 +1,53 @@
package cliutil
import (
"github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc"
"github.com/cloudflare/cloudflared/config"
"github.com/cloudflare/cloudflared/logger"
)
func Action(actionFunc cli.ActionFunc) cli.ActionFunc {
return WithErrorHandler(func(c *cli.Context) error {
if err := setFlagsFromConfigFile(c); err != nil {
return err
}
return actionFunc(c)
})
}
func setFlagsFromConfigFile(c *cli.Context) error {
const errorExitCode = 1
log := logger.CreateLoggerFromContext(c, logger.EnableTerminalLog)
inputSource, err := config.ReadConfigFile(c, log)
if err != nil {
if err == config.ErrNoConfigFile {
return nil
}
return cli.Exit(err, errorExitCode)
}
if err := applyConfig(c, inputSource); err != nil {
return cli.Exit(err, errorExitCode)
}
return nil
}
func applyConfig(c *cli.Context, inputSource altsrc.InputSourceContext) error {
for _, context := range c.Lineage() {
if context.Command == nil {
// we've reached the placeholder root context not associated with the app
break
}
targetFlags := context.Command.Flags
if context.Command.Name == "" {
// commands that define child subcommands are executed as if they were an app
targetFlags = c.App.Flags
}
if err := altsrc.ApplyInputSourceValues(context, inputSource, targetFlags); err != nil {
return err
}
}
return nil
}