filebrowser/backend/cmd/utils.go

89 lines
2.0 KiB
Go
Raw Normal View History

package cmd
import (
"encoding/json"
"errors"
"os"
"path/filepath"
2023-09-03 22:03:00 +00:00
"github.com/goccy/go-yaml"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
2020-05-31 23:12:36 +00:00
2023-06-15 01:08:09 +00:00
"github.com/gtsteffaniak/filebrowser/storage"
2024-10-07 22:44:53 +00:00
"github.com/gtsteffaniak/filebrowser/utils"
)
func mustGetString(flags *pflag.FlagSet, flag string) string {
s, err := flags.GetString(flag)
2024-10-07 22:44:53 +00:00
utils.CheckErr("mustGetString", err)
return s
}
func mustGetBool(flags *pflag.FlagSet, flag string) bool {
b, err := flags.GetBool(flag)
2024-10-07 22:44:53 +00:00
utils.CheckErr("mustGetBool", err)
return b
}
func mustGetUint(flags *pflag.FlagSet, flag string) uint {
b, err := flags.GetUint(flag)
2024-10-07 22:44:53 +00:00
utils.CheckErr("mustGetUint", err)
return b
}
type cobraFunc func(cmd *cobra.Command, args []string)
2024-10-07 22:44:53 +00:00
type pythonFunc func(cmd *cobra.Command, args []string, store *storage.Storage)
func marshal(filename string, data interface{}) error {
fd, err := os.Create(filename)
2024-07-30 17:45:27 +00:00
2024-10-07 22:44:53 +00:00
utils.CheckErr("os.Create", err)
defer fd.Close()
switch ext := filepath.Ext(filename); ext {
case ".json":
encoder := json.NewEncoder(fd)
encoder.SetIndent("", " ")
return encoder.Encode(data)
2020-05-31 23:12:36 +00:00
case ".yml", ".yaml": //nolint:goconst
2023-09-03 22:03:00 +00:00
_, err := yaml.Marshal(fd)
return err
default:
return errors.New("invalid format: " + ext)
}
}
func unmarshal(filename string, data interface{}) error {
fd, err := os.Open(filename)
2024-10-07 22:44:53 +00:00
utils.CheckErr("os.Open", err)
defer fd.Close()
switch ext := filepath.Ext(filename); ext {
case ".json":
return json.NewDecoder(fd).Decode(data)
case ".yml", ".yaml":
return yaml.NewDecoder(fd).Decode(data)
default:
return errors.New("invalid format: " + ext)
}
}
func jsonYamlArg(cmd *cobra.Command, args []string) error {
if err := cobra.ExactArgs(1)(cmd, args); err != nil {
return err
}
switch ext := filepath.Ext(args[0]); ext {
case ".json", ".yml", ".yaml":
return nil
default:
return errors.New("invalid format: " + ext)
}
}
2024-10-07 22:44:53 +00:00
func cobraCmd(fn pythonFunc) cobraFunc {
return func(cmd *cobra.Command, args []string) {
}
}