From fd7b70cf38ac67c8c9ff79f2e7fde5e2ec45a1de Mon Sep 17 00:00:00 2001 From: Henrique Dias Date: Tue, 18 Nov 2025 11:29:28 +0100 Subject: [PATCH] refactor: rename python for clarification --- cmd/cmds_add.go | 8 +++--- cmd/cmds_ls.go | 6 ++--- cmd/cmds_rm.go | 8 +++--- cmd/config_cat.go | 10 +++---- cmd/config_export.go | 10 +++---- cmd/config_import.go | 14 +++++----- cmd/config_init.go | 10 +++---- cmd/config_set.go | 16 ++++++------ cmd/root.go | 62 ++++++++++++++++++++++---------------------- cmd/rule_rm.go | 10 +++---- cmd/rules_add.go | 10 +++---- cmd/rules_ls.go | 6 ++--- cmd/users_add.go | 12 ++++----- cmd/users_export.go | 6 ++--- cmd/users_find.go | 10 +++---- cmd/users_import.go | 14 +++++----- cmd/users_rm.go | 8 +++--- cmd/users_update.go | 12 ++++----- cmd/utils.go | 62 +++++++++++++++++++++++--------------------- 19 files changed, 148 insertions(+), 146 deletions(-) diff --git a/cmd/cmds_add.go b/cmd/cmds_add.go index a4d17061..a209b83f 100644 --- a/cmd/cmds_add.go +++ b/cmd/cmds_add.go @@ -15,18 +15,18 @@ var cmdsAddCmd = &cobra.Command{ Short: "Add a command to run on a specific event", Long: `Add a command to run on a specific event.`, Args: cobra.MinimumNArgs(2), - RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { - s, err := d.store.Settings.Get() + RunE: withStore(func(_ *cobra.Command, args []string, st *store) error { + s, err := st.Settings.Get() if err != nil { return err } command := strings.Join(args[1:], " ") s.Commands[args[0]] = append(s.Commands[args[0]], command) - err = d.store.Settings.Save(s) + err = st.Settings.Save(s) if err != nil { return err } printEvents(s.Commands) return nil - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/cmds_ls.go b/cmd/cmds_ls.go index ad700eb7..694be178 100644 --- a/cmd/cmds_ls.go +++ b/cmd/cmds_ls.go @@ -14,8 +14,8 @@ var cmdsLsCmd = &cobra.Command{ Short: "List all commands for each event", Long: `List all commands for each event.`, Args: cobra.NoArgs, - RunE: python(func(cmd *cobra.Command, _ []string, d *pythonData) error { - s, err := d.store.Settings.Get() + RunE: withStore(func(cmd *cobra.Command, _ []string, st *store) error { + s, err := st.Settings.Get() if err != nil { return err } @@ -35,5 +35,5 @@ var cmdsLsCmd = &cobra.Command{ } return nil - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/cmds_rm.go b/cmd/cmds_rm.go index 34089388..861f495f 100644 --- a/cmd/cmds_rm.go +++ b/cmd/cmds_rm.go @@ -35,8 +35,8 @@ including 'index_end'.`, return nil }, - RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { - s, err := d.store.Settings.Get() + RunE: withStore(func(_ *cobra.Command, args []string, st *store) error { + s, err := st.Settings.Get() if err != nil { return err } @@ -55,11 +55,11 @@ including 'index_end'.`, } s.Commands[evt] = append(s.Commands[evt][:i], s.Commands[evt][f+1:]...) - err = d.store.Settings.Save(s) + err = st.Settings.Save(s) if err != nil { return err } printEvents(s.Commands) return nil - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/config_cat.go b/cmd/config_cat.go index 39b1f664..b8d2f48f 100644 --- a/cmd/config_cat.go +++ b/cmd/config_cat.go @@ -13,19 +13,19 @@ var configCatCmd = &cobra.Command{ Short: "Prints the configuration", Long: `Prints the configuration.`, Args: cobra.NoArgs, - RunE: python(func(_ *cobra.Command, _ []string, d *pythonData) error { - set, err := d.store.Settings.Get() + RunE: withStore(func(_ *cobra.Command, _ []string, st *store) error { + set, err := st.Settings.Get() if err != nil { return err } - ser, err := d.store.Settings.GetServer() + ser, err := st.Settings.GetServer() if err != nil { return err } - auther, err := d.store.Auth.Get(set.AuthMethod) + auther, err := st.Auth.Get(set.AuthMethod) if err != nil { return err } return printSettings(ser, set, auther) - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/config_export.go b/cmd/config_export.go index 9877fb63..b19c10b6 100644 --- a/cmd/config_export.go +++ b/cmd/config_export.go @@ -15,18 +15,18 @@ var configExportCmd = &cobra.Command{ json or yaml file. This exported configuration can be changed, and imported again with 'config import' command.`, Args: jsonYamlArg, - RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { - settings, err := d.store.Settings.Get() + RunE: withStore(func(_ *cobra.Command, args []string, st *store) error { + settings, err := st.Settings.Get() if err != nil { return err } - server, err := d.store.Settings.GetServer() + server, err := st.Settings.GetServer() if err != nil { return err } - auther, err := d.store.Auth.Get(settings.AuthMethod) + auther, err := st.Auth.Get(settings.AuthMethod) if err != nil { return err } @@ -42,5 +42,5 @@ and imported again with 'config import' command.`, return err } return nil - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/config_import.go b/cmd/config_import.go index 63d394d7..4de34c9b 100644 --- a/cmd/config_import.go +++ b/cmd/config_import.go @@ -34,11 +34,11 @@ database. The path must be for a json or yaml file.`, Args: jsonYamlArg, - RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { + RunE: withStore(func(_ *cobra.Command, args []string, st *store) error { var key []byte var err error - if d.databaseExisted { - settings, settingErr := d.store.Settings.Get() + if st.databaseExisted { + settings, settingErr := st.Settings.Get() if settingErr != nil { return settingErr } @@ -54,12 +54,12 @@ The path must be for a json or yaml file.`, } file.Settings.Key = key - err = d.store.Settings.Save(file.Settings) + err = st.Settings.Save(file.Settings) if err != nil { return err } - err = d.store.Settings.SaveServer(file.Server) + err = st.Settings.SaveServer(file.Server) if err != nil { return err } @@ -98,13 +98,13 @@ The path must be for a json or yaml file.`, return autherErr } - err = d.store.Auth.Save(auther) + err = st.Auth.Save(auther) if err != nil { return err } return printSettings(file.Server, file.Settings, auther) - }, pythonConfig{allowsNoDatabase: true}), + }, storeOptions{allowsNoDatabase: true}), } func getAuther(sample auth.Auther, data interface{}) (interface{}, error) { diff --git a/cmd/config_init.go b/cmd/config_init.go index 2787f080..359d02a3 100644 --- a/cmd/config_init.go +++ b/cmd/config_init.go @@ -22,7 +22,7 @@ this options can be changed in the future with the command to the defaults when creating new users and you don't override the options.`, Args: cobra.NoArgs, - RunE: python(func(cmd *cobra.Command, _ []string, d *pythonData) error { + RunE: withStore(func(cmd *cobra.Command, _ []string, st *store) error { flags := cmd.Flags() // Initialize config @@ -36,17 +36,17 @@ override the options.`, } // Save updated config - err = d.store.Settings.Save(s) + err = st.Settings.Save(s) if err != nil { return err } - err = d.store.Settings.SaveServer(ser) + err = st.Settings.SaveServer(ser) if err != nil { return err } - err = d.store.Auth.Save(auther) + err = st.Auth.Save(auther) if err != nil { return err } @@ -57,5 +57,5 @@ Now add your first user via 'filebrowser users add' and then you just need to call the main command to boot up the server. `) return printSettings(ser, s, auther) - }, pythonConfig{expectsNoDatabase: true}), + }, storeOptions{expectsNoDatabase: true}), } diff --git a/cmd/config_set.go b/cmd/config_set.go index d25b6596..df357a02 100644 --- a/cmd/config_set.go +++ b/cmd/config_set.go @@ -15,21 +15,21 @@ var configSetCmd = &cobra.Command{ Long: `Updates the configuration. Set the flags for the options you want to change. Other options will remain unchanged.`, Args: cobra.NoArgs, - RunE: python(func(cmd *cobra.Command, _ []string, d *pythonData) error { + RunE: withStore(func(cmd *cobra.Command, _ []string, st *store) error { flags := cmd.Flags() // Read existing config - set, err := d.store.Settings.Get() + set, err := st.Settings.Get() if err != nil { return err } - ser, err := d.store.Settings.GetServer() + ser, err := st.Settings.GetServer() if err != nil { return err } - auther, err := d.store.Auth.Get(set.AuthMethod) + auther, err := st.Auth.Get(set.AuthMethod) if err != nil { return err } @@ -41,21 +41,21 @@ you want to change. Other options will remain unchanged.`, } // Save updated config - err = d.store.Auth.Save(auther) + err = st.Auth.Save(auther) if err != nil { return err } - err = d.store.Settings.Save(set) + err = st.Settings.Save(set) if err != nil { return err } - err = d.store.Settings.SaveServer(ser) + err = st.Settings.SaveServer(ser) if err != nil { return err } return printSettings(ser, set, auther) - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/root.go b/cmd/root.go index 6a44e2f3..30b70f19 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -146,23 +146,23 @@ The precedence of the configuration values are as follows: Also, if the database path doesn't exist, File Browser will enter into the quick setup mode and a new database will be bootstrapped and a new user created with the credentials from options "username" and "password".`, - RunE: python(func(cmd *cobra.Command, _ []string, d *pythonData) error { - if !d.databaseExisted { - err := quickSetup(*d) + RunE: withViperAndStore(func(cmd *cobra.Command, _ []string, v *viper.Viper, st *store) error { + if !st.databaseExisted { + err := quickSetup(v, st.Storage) if err != nil { return err } } // build img service - imgWorkersCount := d.viper.GetInt("imageProcessors") + imgWorkersCount := v.GetInt("imageProcessors") if imgWorkersCount < 1 { return errors.New("image resize workers count could not be < 1") } imageService := img.New(imgWorkersCount) var fileCache diskcache.Interface = diskcache.NewNoOp() - cacheDir := d.viper.GetString("cacheDir") + cacheDir := v.GetString("cacheDir") if cacheDir != "" { if err := os.MkdirAll(cacheDir, 0700); err != nil { return fmt.Errorf("can't make directory %s: %w", cacheDir, err) @@ -170,7 +170,7 @@ user created with the credentials from options "username" and "password".`, fileCache = diskcache.New(afero.NewOsFs(), cacheDir) } - server, err := getServerSettings(d.viper, d.store) + server, err := getServerSettings(v, st.Storage) if err != nil { return err } @@ -192,7 +192,7 @@ user created with the credentials from options "username" and "password".`, if err != nil { return err } - socketPerm := d.viper.GetUint32("socketPerm") + socketPerm := v.GetUint32("socketPerm") err = os.Chmod(server.Socket, os.FileMode(socketPerm)) if err != nil { return err @@ -221,7 +221,7 @@ user created with the credentials from options "username" and "password".`, panic(err) } - handler, err := fbhttp.NewHandler(imageService, fileCache, d.store, server, assetsFs) + handler, err := fbhttp.NewHandler(imageService, fileCache, st.Storage, server, assetsFs) if err != nil { return err } @@ -262,7 +262,7 @@ user created with the credentials from options "username" and "password".`, log.Println("Graceful shutdown complete.") return nil - }, pythonConfig{allowsNoDatabase: true}), + }, storeOptions{allowsNoDatabase: true}), } func getServerSettings(v *viper.Viper, st *storage.Storage) (*settings.Server, error) { @@ -368,7 +368,7 @@ func setupLog(logMethod string) { } } -func quickSetup(d pythonData) error { +func quickSetup(v *viper.Viper, s *storage.Storage) error { log.Println("Performing quick setup") set := &settings.Settings{ @@ -382,7 +382,7 @@ func quickSetup(d pythonData) error { Scope: ".", Locale: "en", SingleClick: false, - AceEditorTheme: d.viper.GetString("defaults.aceEditorTheme"), + AceEditorTheme: v.GetString("defaults.aceEditorTheme"), Perm: users.Permissions{ Admin: false, Execute: true, @@ -406,44 +406,44 @@ func quickSetup(d pythonData) error { } var err error - if d.viper.GetBool("noauth") { + if v.GetBool("noauth") { set.AuthMethod = auth.MethodNoAuth - err = d.store.Auth.Save(&auth.NoAuth{}) + err = s.Auth.Save(&auth.NoAuth{}) } else { set.AuthMethod = auth.MethodJSONAuth - err = d.store.Auth.Save(&auth.JSONAuth{}) + err = s.Auth.Save(&auth.JSONAuth{}) } if err != nil { return err } - err = d.store.Settings.Save(set) + err = s.Settings.Save(set) if err != nil { return err } ser := &settings.Server{ - BaseURL: d.viper.GetString("baseURL"), - Port: d.viper.GetString("port"), - Log: d.viper.GetString("log"), - TLSKey: d.viper.GetString("key"), - TLSCert: d.viper.GetString("cert"), - Address: d.viper.GetString("address"), - Root: d.viper.GetString("root"), - TokenExpirationTime: d.viper.GetString("tokenExpirationTime"), - EnableThumbnails: !d.viper.GetBool("disableThumbnails"), - ResizePreview: !d.viper.GetBool("disablePreviewResize"), - EnableExec: !d.viper.GetBool("disableExec"), - TypeDetectionByHeader: !d.viper.GetBool("disableTypeDetectionByHeader"), + BaseURL: v.GetString("baseURL"), + Port: v.GetString("port"), + Log: v.GetString("log"), + TLSKey: v.GetString("key"), + TLSCert: v.GetString("cert"), + Address: v.GetString("address"), + Root: v.GetString("root"), + TokenExpirationTime: v.GetString("tokenExpirationTime"), + EnableThumbnails: !v.GetBool("disableThumbnails"), + ResizePreview: !v.GetBool("disablePreviewResize"), + EnableExec: !v.GetBool("disableExec"), + TypeDetectionByHeader: !v.GetBool("disableTypeDetectionByHeader"), } - err = d.store.Settings.SaveServer(ser) + err = s.Settings.SaveServer(ser) if err != nil { return err } - username := d.viper.GetString("username") - password := d.viper.GetString("password") + username := v.GetString("username") + password := v.GetString("password") if password == "" { var pwd string @@ -474,5 +474,5 @@ func quickSetup(d pythonData) error { set.Defaults.Apply(user) user.Perm.Admin = true - return d.store.Users.Save(user) + return s.Users.Save(user) } diff --git a/cmd/rule_rm.go b/cmd/rule_rm.go index 26e801ae..8ed8f151 100644 --- a/cmd/rule_rm.go +++ b/cmd/rule_rm.go @@ -40,7 +40,7 @@ including 'index_end'.`, return nil }, - RunE: python(func(cmd *cobra.Command, args []string, d *pythonData) error { + RunE: withStore(func(cmd *cobra.Command, args []string, st *store) error { i, err := strconv.Atoi(args[0]) if err != nil { return err @@ -55,14 +55,14 @@ including 'index_end'.`, user := func(u *users.User) error { u.Rules = append(u.Rules[:i], u.Rules[f+1:]...) - return d.store.Users.Save(u) + return st.Users.Save(u) } global := func(s *settings.Settings) error { s.Rules = append(s.Rules[:i], s.Rules[f+1:]...) - return d.store.Settings.Save(s) + return st.Settings.Save(s) } - return runRules(d.store, cmd, user, global) - }, pythonConfig{}), + return runRules(st.Storage, cmd, user, global) + }, storeOptions{}), } diff --git a/cmd/rules_add.go b/cmd/rules_add.go index d58a6987..3b34d940 100644 --- a/cmd/rules_add.go +++ b/cmd/rules_add.go @@ -21,7 +21,7 @@ var rulesAddCmd = &cobra.Command{ Short: "Add a global rule or user rule", Long: `Add a global rule or user rule.`, Args: cobra.ExactArgs(1), - RunE: python(func(cmd *cobra.Command, args []string, d *pythonData) error { + RunE: withStore(func(cmd *cobra.Command, args []string, st *store) error { flags := cmd.Flags() allow, err := flags.GetBool("allow") @@ -53,14 +53,14 @@ var rulesAddCmd = &cobra.Command{ user := func(u *users.User) error { u.Rules = append(u.Rules, rule) - return d.store.Users.Save(u) + return st.Users.Save(u) } global := func(s *settings.Settings) error { s.Rules = append(s.Rules, rule) - return d.store.Settings.Save(s) + return st.Settings.Save(s) } - return runRules(d.store, cmd, user, global) - }, pythonConfig{}), + return runRules(st.Storage, cmd, user, global) + }, storeOptions{}), } diff --git a/cmd/rules_ls.go b/cmd/rules_ls.go index 67a279dc..9aa073d0 100644 --- a/cmd/rules_ls.go +++ b/cmd/rules_ls.go @@ -13,7 +13,7 @@ var rulesLsCommand = &cobra.Command{ Short: "List global rules or user specific rules", Long: `List global rules or user specific rules.`, Args: cobra.NoArgs, - RunE: python(func(cmd *cobra.Command, _ []string, d *pythonData) error { - return runRules(d.store, cmd, nil, nil) - }, pythonConfig{}), + RunE: withStore(func(cmd *cobra.Command, _ []string, st *store) error { + return runRules(st.Storage, cmd, nil, nil) + }, storeOptions{}), } diff --git a/cmd/users_add.go b/cmd/users_add.go index bfc70069..daf59aa3 100644 --- a/cmd/users_add.go +++ b/cmd/users_add.go @@ -16,9 +16,9 @@ var usersAddCmd = &cobra.Command{ Short: "Create a new user", Long: `Create a new user and add it to the database.`, Args: cobra.ExactArgs(2), - RunE: python(func(cmd *cobra.Command, args []string, d *pythonData) error { + RunE: withStore(func(cmd *cobra.Command, args []string, st *store) error { flags := cmd.Flags() - s, err := d.store.Settings.Get() + s, err := st.Settings.Get() if err != nil { return err } @@ -54,14 +54,14 @@ var usersAddCmd = &cobra.Command{ s.Defaults.Apply(user) - servSettings, err := d.store.Settings.GetServer() + servSettings, err := st.Settings.GetServer() if err != nil { return err } // since getUserDefaults() polluted s.Defaults.Scope // which makes the Scope not the one saved in the db // we need the right s.Defaults.Scope here - s2, err := d.store.Settings.Get() + s2, err := st.Settings.Get() if err != nil { return err } @@ -72,11 +72,11 @@ var usersAddCmd = &cobra.Command{ } user.Scope = userHome - err = d.store.Users.Save(user) + err = st.Users.Save(user) if err != nil { return err } printUsers([]*users.User{user}) return nil - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/users_export.go b/cmd/users_export.go index d6009a37..9bbec6d8 100644 --- a/cmd/users_export.go +++ b/cmd/users_export.go @@ -14,8 +14,8 @@ var usersExportCmd = &cobra.Command{ Long: `Export all users to a json or yaml file. Please indicate the path to the file where you want to write the users.`, Args: jsonYamlArg, - RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { - list, err := d.store.Users.Gets("") + RunE: withStore(func(_ *cobra.Command, args []string, st *store) error { + list, err := st.Users.Gets("") if err != nil { return err } @@ -25,5 +25,5 @@ path to the file where you want to write the users.`, return err } return nil - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/users_find.go b/cmd/users_find.go index 0dea071a..09bc8d47 100644 --- a/cmd/users_find.go +++ b/cmd/users_find.go @@ -26,7 +26,7 @@ var usersLsCmd = &cobra.Command{ RunE: findUsers, } -var findUsers = python(func(_ *cobra.Command, args []string, d *pythonData) error { +var findUsers = withStore(func(_ *cobra.Command, args []string, st *store) error { var ( list []*users.User user *users.User @@ -36,14 +36,14 @@ var findUsers = python(func(_ *cobra.Command, args []string, d *pythonData) erro if len(args) == 1 { username, id := parseUsernameOrID(args[0]) if username != "" { - user, err = d.store.Users.Get("", username) + user, err = st.Users.Get("", username) } else { - user, err = d.store.Users.Get("", id) + user, err = st.Users.Get("", id) } list = []*users.User{user} } else { - list, err = d.store.Users.Gets("") + list, err = st.Users.Gets("") } if err != nil { @@ -51,4 +51,4 @@ var findUsers = python(func(_ *cobra.Command, args []string, d *pythonData) erro } printUsers(list) return nil -}, pythonConfig{}) +}, storeOptions{}) diff --git a/cmd/users_import.go b/cmd/users_import.go index d08889df..73effca6 100644 --- a/cmd/users_import.go +++ b/cmd/users_import.go @@ -25,7 +25,7 @@ file. You can use this command to import new users to your installation. For that, just don't place their ID on the files list or set it to 0.`, Args: jsonYamlArg, - RunE: python(func(cmd *cobra.Command, args []string, d *pythonData) error { + RunE: withStore(func(cmd *cobra.Command, args []string, st *store) error { flags := cmd.Flags() fd, err := os.Open(args[0]) if err != nil { @@ -52,7 +52,7 @@ list or set it to 0.`, } if replace { - oldUsers, userImportErr := d.store.Users.Gets("") + oldUsers, userImportErr := st.Users.Gets("") if userImportErr != nil { return userImportErr } @@ -63,7 +63,7 @@ list or set it to 0.`, } for _, user := range oldUsers { - err = d.store.Users.Delete(user.ID) + err = st.Users.Delete(user.ID) if err != nil { return err } @@ -76,7 +76,7 @@ list or set it to 0.`, } for _, user := range list { - onDB, err := d.store.Users.Get("", user.ID) + onDB, err := st.Users.Get("", user.ID) // User exists in DB. if err == nil { @@ -88,7 +88,7 @@ list or set it to 0.`, // with the new username. If there is, print an error and cancel the // operation if user.Username != onDB.Username { - if conflictuous, err := d.store.Users.Get("", user.Username); err == nil { + if conflictuous, err := st.Users.Get("", user.Username); err == nil { return usernameConflictError(user.Username, conflictuous.ID, user.ID) } } @@ -98,13 +98,13 @@ list or set it to 0.`, user.ID = 0 } - err = d.store.Users.Save(user) + err = st.Users.Save(user) if err != nil { return err } } return nil - }, pythonConfig{}), + }, storeOptions{}), } func usernameConflictError(username string, originalID, newID uint) error { diff --git a/cmd/users_rm.go b/cmd/users_rm.go index 55b973f4..492a55c3 100644 --- a/cmd/users_rm.go +++ b/cmd/users_rm.go @@ -15,14 +15,14 @@ var usersRmCmd = &cobra.Command{ Short: "Delete a user by username or id", Long: `Delete a user by username or id`, Args: cobra.ExactArgs(1), - RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { + RunE: withStore(func(_ *cobra.Command, args []string, st *store) error { username, id := parseUsernameOrID(args[0]) var err error if username != "" { - err = d.store.Users.Delete(username) + err = st.Users.Delete(username) } else { - err = d.store.Users.Delete(id) + err = st.Users.Delete(id) } if err != nil { @@ -30,5 +30,5 @@ var usersRmCmd = &cobra.Command{ } fmt.Println("user deleted successfully") return nil - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/users_update.go b/cmd/users_update.go index 59854a81..96f1e2d3 100644 --- a/cmd/users_update.go +++ b/cmd/users_update.go @@ -21,7 +21,7 @@ var usersUpdateCmd = &cobra.Command{ Long: `Updates an existing user. Set the flags for the options you want to change.`, Args: cobra.ExactArgs(1), - RunE: python(func(cmd *cobra.Command, args []string, d *pythonData) error { + RunE: withStore(func(cmd *cobra.Command, args []string, st *store) error { flags := cmd.Flags() username, id := parseUsernameOrID(args[0]) password, err := flags.GetString("password") @@ -34,7 +34,7 @@ options you want to change.`, return err } - s, err := d.store.Settings.Get() + s, err := st.Settings.Get() if err != nil { return err } @@ -43,9 +43,9 @@ options you want to change.`, user *users.User ) if id != 0 { - user, err = d.store.Users.Get("", id) + user, err = st.Users.Get("", id) } else { - user, err = d.store.Users.Get("", username) + user, err = st.Users.Get("", username) } if err != nil { return err @@ -99,11 +99,11 @@ options you want to change.`, } } - err = d.store.Users.Update(user) + err = st.Users.Update(user) if err != nil { return err } printUsers([]*users.User{user}) return nil - }, pythonConfig{}), + }, storeOptions{}), } diff --git a/cmd/utils.go b/cmd/utils.go index a136db10..eb953d32 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -36,6 +36,7 @@ func getAndParseFileMode(flags *pflag.FlagSet, name string) (fs.FileMode, error) if err != nil { return 0, err } + return fs.FileMode(b), nil } @@ -131,38 +132,29 @@ func initViper(cmd *cobra.Command) (*viper.Viper, error) { return v, nil } -type cobraFunc func(cmd *cobra.Command, args []string) error -type pythonFunc func(cmd *cobra.Command, args []string, data *pythonData) error +type store struct { + *storage.Storage + databaseExisted bool +} -type pythonConfig struct { +type storeOptions struct { expectsNoDatabase bool allowsNoDatabase bool } -type pythonData struct { - databaseExisted bool - viper *viper.Viper - store *storage.Storage -} +type cobraFunc func(cmd *cobra.Command, args []string) error -func python(fn pythonFunc, cfg pythonConfig) cobraFunc { +// withViperAndStore initializes Viper and the storage.Store and passes them to the callback function. +// This function should only be used by [withStore] and the root command. No other command should call +// this function directly. +func withViperAndStore(fn func(cmd *cobra.Command, args []string, v *viper.Viper, store *store) error, options storeOptions) cobraFunc { return func(cmd *cobra.Command, args []string) error { v, err := initViper(cmd) if err != nil { return err } - data := &pythonData{databaseExisted: true} - path := v.GetString("database") - - // Only make the viper instance available to the root command (filebrowser). - // This is to make sure that we don't make the mistake of using it somewhere - // else. - if cmd.Name() == "filebrowser" { - data.viper = v - } - - absPath, err := filepath.Abs(path) + path, err := filepath.Abs(v.GetString("database")) if err != nil { return err } @@ -170,16 +162,15 @@ func python(fn pythonFunc, cfg pythonConfig) cobraFunc { exists, err := dbExists(path) if err != nil { return err - } else if exists && cfg.expectsNoDatabase { - log.Fatal(absPath + " already exists") - } else if !exists && !cfg.expectsNoDatabase && !cfg.allowsNoDatabase { - log.Fatal(absPath + " does not exist. Please run 'filebrowser config init' first.") - } else if !exists && !cfg.expectsNoDatabase { - log.Println("Warning: filebrowser.db can't be found. Initialing in " + strings.TrimSuffix(absPath, "filebrowser.db")) + } else if exists && options.expectsNoDatabase { + log.Fatal(path + " already exists") + } else if !exists && !options.expectsNoDatabase && !options.allowsNoDatabase { + log.Fatal(path + " does not exist. Please run 'filebrowser config init' first.") + } else if !exists && !options.expectsNoDatabase { + log.Println("WARNING: filebrowser.db can't be found. Initialing in " + strings.TrimSuffix(path, "filebrowser.db")) } - log.Println("Using database: " + absPath) - data.databaseExisted = exists + log.Println("Using database: " + path) db, err := storm.Open(path, storm.BoltOptions(databasePermissions, nil)) if err != nil { @@ -187,15 +178,26 @@ func python(fn pythonFunc, cfg pythonConfig) cobraFunc { } defer db.Close() - data.store, err = bolt.NewStorage(db) + storage, err := bolt.NewStorage(db) if err != nil { return err } - return fn(cmd, args, data) + store := &store{ + Storage: storage, + databaseExisted: exists, + } + + return fn(cmd, args, v, store) } } +func withStore(fn func(cmd *cobra.Command, args []string, store *store) error, options storeOptions) cobraFunc { + return withViperAndStore(func(cmd *cobra.Command, args []string, v *viper.Viper, store *store) error { + return fn(cmd, args, store) + }, options) +} + func marshal(filename string, data interface{}) error { fd, err := os.Create(filename) if err != nil {