Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return error if the config file is invalid. #2048

Merged
merged 4 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 21 additions & 24 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,36 +27,34 @@ import (

var (
cfgFile string
cfgErr 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

// NewRootCmd accepts the mountFn that it executes with the parsed configuration
func NewRootCmd(mountFn func(config cfg.Config) error) (*cobra.Command, error) {
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 cfgErr != nil {
return cfgErr
}
return mountFn(configObj)
},
}
}

func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config-file", "", "The path to the config file where all gcsfuse related config needs to be specified."+
"Refer to 'https://cloud.google.com/storage/docs/gcsfuse-cli#config-file' for possible configurations.")
rootCmd.PersistentFlags().StringVar(&cfgFile, "config-file", "", "Refer to 'https://cloud.google.com/storage/docs/gcsfuse-cli#config-file' for possible configurations.")
kislaykishore marked this conversation as resolved.
Show resolved Hide resolved

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

func initConfig() {
Expand All @@ -72,12 +70,11 @@ func initConfig() {
}
}

err := viper.Unmarshal(&configObj, viper.DecodeHook(cfg.DecodeHook()), func(decoderConfig *mapstructure.DecoderConfig) {
cfgErr = 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 {
kislaykishore marked this conversation as resolved.
Show resolved Hide resolved
logger.Fatal("error while unmarshalling the config: %v", err)
}
}
47 changes: 47 additions & 0 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// 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/googlecloudplatform/gcsfuse/v2/cfg"
"github.com/mitchellh/mapstructure"
"github.com/stretchr/testify/assert"
)

func TestInvalidConfig(t *testing.T) {
cmd, err := NewRootCmd(func(config cfg.Config) error { return nil })
if err != nil {
t.Fatalf("Error while creating the root command: %v", err)
}
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{})
}
}

func TestValidConfig(t *testing.T) {
cmd, err := NewRootCmd(func(config cfg.Config) error { return nil })
if err != nil {
t.Fatalf("Error while creating the root command: %v", err)
}
cmd.SetArgs([]string{"--config-file=testdata/valid_config.yml", "abc", "pqr"})

assert.Nil(t, cmd.Execute())
}
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
18 changes: 16 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@
package main

import (
"fmt"
"log"
"os"
"strings"

"github.com/googlecloudplatform/gcsfuse/v2/cfg"
"github.com/googlecloudplatform/gcsfuse/v2/cmd"
"github.com/googlecloudplatform/gcsfuse/v2/internal/logger"
)
Expand Down Expand Up @@ -63,9 +65,21 @@ func main() {
// Make logging output better.
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()
// TODO: implement the mount logic instead of simply returning nil.
rootCmd, err := cmd.NewRootCmd(func(config cfg.Config) error { return nil })
if err != nil {
exitOnError(err)
kislaykishore marked this conversation as resolved.
Show resolved Hide resolved
}
rootCmd.SetArgs(convertToPosixArgs(os.Args))
if err := rootCmd.Execute(); err != nil {
exitOnError(err)
}
return
}
cmd.ExecuteLegacyMain()
}

func exitOnError(err error) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
Loading