Skip to content

Commit

Permalink
refactor: Validate flag at first
Browse files Browse the repository at this point in the history
  • Loading branch information
haijima committed Mar 27, 2024
1 parent c1cbe11 commit e42d52d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
13 changes: 9 additions & 4 deletions cmd/trend.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ func runTrend(cmd *cobra.Command, v *viper.Viper, fs afero.Fs, p *internal.Trend
if interval <= 0 {
return fmt.Errorf("interval flag should be positive. but: %d", interval)
}
if format != "table" && format != "md" && format != "csv" {
return errors.Newf("unknown format: %s", format)
}

f, err := cobrax.OpenOrStdIn(v.GetString("file"), fs, cobrax.WithStdin(cmd.InOrStdin()))
if err != nil {
Expand All @@ -73,14 +76,16 @@ func runTrend(cmd *cobra.Command, v *viper.Viper, fs afero.Fs, p *internal.Trend
return err
}

if format == "table" {
switch format {
case "table":
return printTrendTable(cmd, result, false)
} else if format == "md" {
case "md":
return printTrendTable(cmd, result, true)
} else if format == "csv" {
case "csv":
return printTrendCsv(cmd, result)
default:
return nil // unreachable
}
return errors.Newf("unknown format: %s", format)
}

func printTrendTable(cmd *cobra.Command, result *internal.Trend, markdown bool) error {
Expand Down
2 changes: 2 additions & 0 deletions cmd/trend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ func Test_TrendCmd_RunE_file_not_exists(t *testing.T) {

fileName := "./not_exists.log"
v.Set("file", fileName)
v.Set("format", "table")
v.Set("interval", "5")

err := cmd.RunE(cmd, []string{})
Expand All @@ -103,6 +104,7 @@ func Test_TrendCmd_RunE_file_profiler_error(t *testing.T) {

fileName := "./access.log"
v.Set("file", fileName)
v.Set("format", "table")
v.Set("time_format", "invalid")
v.Set("interval", "5")
_, _ = fs.Create(fileName)
Expand Down

0 comments on commit e42d52d

Please sign in to comment.