Skip to content

Commit

Permalink
Return error if the config file is invalid.
Browse files Browse the repository at this point in the history
Refactor the root command to make it testable.
  • Loading branch information
kislaykishore committed Jun 21, 2024
1 parent c81eddf commit b316939
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 24 deletions.
44 changes: 21 additions & 23 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,35 +26,34 @@ import (

var (
cfgFile string
err error
configObj cfg.Config
)
var rootCmd = &cobra.Command{
Use: "gcsfuse [flags] bucket mount_point",
Short: "Mount a specified GCS bucket or all accessible buckets locally",
Long: `Cloud Storage FUSE is an open source FUSE adapter that lets you mount

func NewRootCmd() *cobra.Command {
rootCmd := &cobra.Command{
Use: "gcsfuse [flags] bucket mount_point",
Short: "Mount a specified GCS bucket or all accessible buckets locally",
Long: `Cloud Storage FUSE is an open source FUSE adapter that lets you mount
and access Cloud Storage buckets as local file systems. For a technical overview
of Cloud Storage FUSE, see https://cloud.google.com/storage/docs/gcs-fuse.`,
Version: getVersion(),
RunE: func(cmd *cobra.Command, args []string) error {
// TODO: the following error will be removed once the command is implemented.
return fmt.Errorf("unsupported operation")
},
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
panic(err)
Version: getVersion(),
RunE: func(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
// TODO: the following error will be removed once the command is implemented.
return fmt.Errorf("unsupported operation")
},
}
}

func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config-file", "", "Absolute path to the config file.")

// Add all the other flags.
if err := cfg.BindFlags(rootCmd.PersistentFlags()); err != nil {
logger.Fatal("error while declaring/binding flags: %v", err)
}
return rootCmd
}

func initConfig() {
Expand All @@ -63,15 +62,14 @@ func initConfig() {
}
viper.SetConfigFile(cfgFile)
viper.SetConfigType("yaml")
if err := viper.ReadInConfig(); err != nil {
logger.Fatal("error while reading the config: %v", err)
if err = viper.ReadInConfig(); err != nil {
return
}
err := viper.Unmarshal(&configObj, viper.DecodeHook(cfg.DecodeHook()), func(decoderConfig *mapstructure.DecoderConfig) {
err = viper.Unmarshal(&configObj, viper.DecodeHook(cfg.DecodeHook()), func(decoderConfig *mapstructure.DecoderConfig) {
// By default, viper supports mapstructure tags for unmarshalling. Override that to support yaml tag.
decoderConfig.TagName = "yaml"
// Reject the config file if any of the fields in the YAML don't map to the struct.
decoderConfig.ErrorUnused = true
},
)
if err != nil {
logger.Fatal("error while unmarshalling the config: %v", err)
}
}
33 changes: 33 additions & 0 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2024 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"testing"

"github.com/mitchellh/mapstructure"
"github.com/stretchr/testify/assert"
)

func TestInvalidConfig(t *testing.T) {
cmd := NewRootCmd()
cmd.SetArgs([]string{"--config-file=testdata/invalid_config.yml", "abc", "pqr"})

err := cmd.Execute()

if assert.NotNil(t, err) {
assert.IsType(t, err, &mapstructure.Error{})
}
}
1 change: 1 addition & 0 deletions cmd/testdata/invalid_config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a: abc
1 change: 1 addition & 0 deletions cmd/testdata/valid_config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
app-name: hello
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
if strings.ToLower(os.Getenv("ENABLE_GCSFUSE_VIPER_CONFIG")) == "true" {
os.Args = convertToPosixArgs(os.Args)
cmd.Execute()
cmd.NewRootCmd().Execute()

Check failure on line 67 in main.go

View workflow job for this annotation

GitHub Actions / Lint

Error return value of `(*github.com/spf13/cobra.Command).Execute` is not checked (errcheck)
return
}
cmd.ExecuteLegacyMain()
Expand Down

0 comments on commit b316939

Please sign in to comment.