databricks-cli/cmd/root/progress_logger.go

65 lines
1.8 KiB
Go
Raw Normal View History

2023-03-29 12:58:09 +00:00
package root
import (
"context"
"fmt"
"os"
"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/env"
"github.com/databricks/cli/libs/flags"
"github.com/spf13/cobra"
2023-03-29 12:58:09 +00:00
"golang.org/x/term"
)
const envProgressFormat = "DATABRICKS_CLI_PROGRESS_FORMAT"
2023-03-29 12:58:09 +00:00
type progressLoggerFlag struct {
flags.ProgressLogFormat
log *logFlags
}
func (f *progressLoggerFlag) resolveModeDefault(format flags.ProgressLogFormat) flags.ProgressLogFormat {
if (f.log.level.String() == "disabled" || f.log.file.String() != "stderr") &&
2023-03-29 12:58:09 +00:00
term.IsTerminal(int(os.Stderr.Fd())) {
return flags.ModeInplace
}
return flags.ModeAppend
}
func (f *progressLoggerFlag) initializeContext(ctx context.Context) (context.Context, error) {
if f.log.level.String() != "disabled" && f.log.file.String() == "stderr" &&
f.ProgressLogFormat == flags.ModeInplace {
2023-03-29 12:58:09 +00:00
return nil, fmt.Errorf("inplace progress logging cannot be used when log-file is stderr")
}
format := f.ProgressLogFormat
2023-03-29 12:58:09 +00:00
if format == flags.ModeDefault {
format = f.resolveModeDefault(format)
2023-03-29 12:58:09 +00:00
}
progressLogger := cmdio.NewLogger(format)
return cmdio.NewContext(ctx, progressLogger), nil
2023-03-29 12:58:09 +00:00
}
func initProgressLoggerFlag(cmd *cobra.Command, logFlags *logFlags) *progressLoggerFlag {
f := progressLoggerFlag{
ProgressLogFormat: flags.NewProgressLogFormat(),
log: logFlags,
}
2023-03-29 12:58:09 +00:00
// Configure defaults from environment, if applicable.
// If the provided value is invalid it is ignored.
if v, ok := env.Lookup(cmd.Context(), envProgressFormat); ok {
f.Set(v)
2023-03-29 12:58:09 +00:00
}
flags := cmd.PersistentFlags()
flags.Var(&f.ProgressLogFormat, "progress-format", "format for progress logs (append, inplace, json)")
flags.MarkHidden("progress-format")
cmd.RegisterFlagCompletionFunc("progress-format", f.ProgressLogFormat.Complete)
return &f
2023-03-29 12:58:09 +00:00
}