refactor: rename python for clarification

pull/5173/head^2
Henrique Dias 2025-11-18 11:29:28 +01:00
parent 13e3b46718
commit fd7b70cf38
No known key found for this signature in database
19 changed files with 148 additions and 146 deletions

View File

@ -15,18 +15,18 @@ var cmdsAddCmd = &cobra.Command{
Short: "Add a command to run on a specific event", Short: "Add a command to run on a specific event",
Long: `Add a command to run on a specific event.`, Long: `Add a command to run on a specific event.`,
Args: cobra.MinimumNArgs(2), Args: cobra.MinimumNArgs(2),
RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { RunE: withStore(func(_ *cobra.Command, args []string, st *store) error {
s, err := d.store.Settings.Get() s, err := st.Settings.Get()
if err != nil { if err != nil {
return err return err
} }
command := strings.Join(args[1:], " ") command := strings.Join(args[1:], " ")
s.Commands[args[0]] = append(s.Commands[args[0]], command) s.Commands[args[0]] = append(s.Commands[args[0]], command)
err = d.store.Settings.Save(s) err = st.Settings.Save(s)
if err != nil { if err != nil {
return err return err
} }
printEvents(s.Commands) printEvents(s.Commands)
return nil return nil
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -14,8 +14,8 @@ var cmdsLsCmd = &cobra.Command{
Short: "List all commands for each event", Short: "List all commands for each event",
Long: `List all commands for each event.`, Long: `List all commands for each event.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: python(func(cmd *cobra.Command, _ []string, d *pythonData) error { RunE: withStore(func(cmd *cobra.Command, _ []string, st *store) error {
s, err := d.store.Settings.Get() s, err := st.Settings.Get()
if err != nil { if err != nil {
return err return err
} }
@ -35,5 +35,5 @@ var cmdsLsCmd = &cobra.Command{
} }
return nil return nil
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -35,8 +35,8 @@ including 'index_end'.`,
return nil return nil
}, },
RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { RunE: withStore(func(_ *cobra.Command, args []string, st *store) error {
s, err := d.store.Settings.Get() s, err := st.Settings.Get()
if err != nil { if err != nil {
return err return err
} }
@ -55,11 +55,11 @@ including 'index_end'.`,
} }
s.Commands[evt] = append(s.Commands[evt][:i], s.Commands[evt][f+1:]...) 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 { if err != nil {
return err return err
} }
printEvents(s.Commands) printEvents(s.Commands)
return nil return nil
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -13,19 +13,19 @@ var configCatCmd = &cobra.Command{
Short: "Prints the configuration", Short: "Prints the configuration",
Long: `Prints the configuration.`, Long: `Prints the configuration.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: python(func(_ *cobra.Command, _ []string, d *pythonData) error { RunE: withStore(func(_ *cobra.Command, _ []string, st *store) error {
set, err := d.store.Settings.Get() set, err := st.Settings.Get()
if err != nil { if err != nil {
return err return err
} }
ser, err := d.store.Settings.GetServer() ser, err := st.Settings.GetServer()
if err != nil { if err != nil {
return err return err
} }
auther, err := d.store.Auth.Get(set.AuthMethod) auther, err := st.Auth.Get(set.AuthMethod)
if err != nil { if err != nil {
return err return err
} }
return printSettings(ser, set, auther) return printSettings(ser, set, auther)
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -15,18 +15,18 @@ var configExportCmd = &cobra.Command{
json or yaml file. This exported configuration can be changed, json or yaml file. This exported configuration can be changed,
and imported again with 'config import' command.`, and imported again with 'config import' command.`,
Args: jsonYamlArg, Args: jsonYamlArg,
RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { RunE: withStore(func(_ *cobra.Command, args []string, st *store) error {
settings, err := d.store.Settings.Get() settings, err := st.Settings.Get()
if err != nil { if err != nil {
return err return err
} }
server, err := d.store.Settings.GetServer() server, err := st.Settings.GetServer()
if err != nil { if err != nil {
return err return err
} }
auther, err := d.store.Auth.Get(settings.AuthMethod) auther, err := st.Auth.Get(settings.AuthMethod)
if err != nil { if err != nil {
return err return err
} }
@ -42,5 +42,5 @@ and imported again with 'config import' command.`,
return err return err
} }
return nil return nil
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -34,11 +34,11 @@ database.
The path must be for a json or yaml file.`, The path must be for a json or yaml file.`,
Args: jsonYamlArg, 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 key []byte
var err error var err error
if d.databaseExisted { if st.databaseExisted {
settings, settingErr := d.store.Settings.Get() settings, settingErr := st.Settings.Get()
if settingErr != nil { if settingErr != nil {
return settingErr return settingErr
} }
@ -54,12 +54,12 @@ The path must be for a json or yaml file.`,
} }
file.Settings.Key = key file.Settings.Key = key
err = d.store.Settings.Save(file.Settings) err = st.Settings.Save(file.Settings)
if err != nil { if err != nil {
return err return err
} }
err = d.store.Settings.SaveServer(file.Server) err = st.Settings.SaveServer(file.Server)
if err != nil { if err != nil {
return err return err
} }
@ -98,13 +98,13 @@ The path must be for a json or yaml file.`,
return autherErr return autherErr
} }
err = d.store.Auth.Save(auther) err = st.Auth.Save(auther)
if err != nil { if err != nil {
return err return err
} }
return printSettings(file.Server, file.Settings, auther) return printSettings(file.Server, file.Settings, auther)
}, pythonConfig{allowsNoDatabase: true}), }, storeOptions{allowsNoDatabase: true}),
} }
func getAuther(sample auth.Auther, data interface{}) (interface{}, error) { func getAuther(sample auth.Auther, data interface{}) (interface{}, error) {

View File

@ -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 to the defaults when creating new users and you don't
override the options.`, override the options.`,
Args: cobra.NoArgs, 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() flags := cmd.Flags()
// Initialize config // Initialize config
@ -36,17 +36,17 @@ override the options.`,
} }
// Save updated config // Save updated config
err = d.store.Settings.Save(s) err = st.Settings.Save(s)
if err != nil { if err != nil {
return err return err
} }
err = d.store.Settings.SaveServer(ser) err = st.Settings.SaveServer(ser)
if err != nil { if err != nil {
return err return err
} }
err = d.store.Auth.Save(auther) err = st.Auth.Save(auther)
if err != nil { if err != nil {
return err 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. need to call the main command to boot up the server.
`) `)
return printSettings(ser, s, auther) return printSettings(ser, s, auther)
}, pythonConfig{expectsNoDatabase: true}), }, storeOptions{expectsNoDatabase: true}),
} }

View File

@ -15,21 +15,21 @@ var configSetCmd = &cobra.Command{
Long: `Updates the configuration. Set the flags for the options Long: `Updates the configuration. Set the flags for the options
you want to change. Other options will remain unchanged.`, you want to change. Other options will remain unchanged.`,
Args: cobra.NoArgs, 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() flags := cmd.Flags()
// Read existing config // Read existing config
set, err := d.store.Settings.Get() set, err := st.Settings.Get()
if err != nil { if err != nil {
return err return err
} }
ser, err := d.store.Settings.GetServer() ser, err := st.Settings.GetServer()
if err != nil { if err != nil {
return err return err
} }
auther, err := d.store.Auth.Get(set.AuthMethod) auther, err := st.Auth.Get(set.AuthMethod)
if err != nil { if err != nil {
return err return err
} }
@ -41,21 +41,21 @@ you want to change. Other options will remain unchanged.`,
} }
// Save updated config // Save updated config
err = d.store.Auth.Save(auther) err = st.Auth.Save(auther)
if err != nil { if err != nil {
return err return err
} }
err = d.store.Settings.Save(set) err = st.Settings.Save(set)
if err != nil { if err != nil {
return err return err
} }
err = d.store.Settings.SaveServer(ser) err = st.Settings.SaveServer(ser)
if err != nil { if err != nil {
return err return err
} }
return printSettings(ser, set, auther) return printSettings(ser, set, auther)
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -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 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 the quick setup mode and a new database will be bootstrapped and a new
user created with the credentials from options "username" and "password".`, user created with the credentials from options "username" and "password".`,
RunE: python(func(cmd *cobra.Command, _ []string, d *pythonData) error { RunE: withViperAndStore(func(cmd *cobra.Command, _ []string, v *viper.Viper, st *store) error {
if !d.databaseExisted { if !st.databaseExisted {
err := quickSetup(*d) err := quickSetup(v, st.Storage)
if err != nil { if err != nil {
return err return err
} }
} }
// build img service // build img service
imgWorkersCount := d.viper.GetInt("imageProcessors") imgWorkersCount := v.GetInt("imageProcessors")
if imgWorkersCount < 1 { if imgWorkersCount < 1 {
return errors.New("image resize workers count could not be < 1") return errors.New("image resize workers count could not be < 1")
} }
imageService := img.New(imgWorkersCount) imageService := img.New(imgWorkersCount)
var fileCache diskcache.Interface = diskcache.NewNoOp() var fileCache diskcache.Interface = diskcache.NewNoOp()
cacheDir := d.viper.GetString("cacheDir") cacheDir := v.GetString("cacheDir")
if cacheDir != "" { if cacheDir != "" {
if err := os.MkdirAll(cacheDir, 0700); err != nil { if err := os.MkdirAll(cacheDir, 0700); err != nil {
return fmt.Errorf("can't make directory %s: %w", cacheDir, err) 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) fileCache = diskcache.New(afero.NewOsFs(), cacheDir)
} }
server, err := getServerSettings(d.viper, d.store) server, err := getServerSettings(v, st.Storage)
if err != nil { if err != nil {
return err return err
} }
@ -192,7 +192,7 @@ user created with the credentials from options "username" and "password".`,
if err != nil { if err != nil {
return err return err
} }
socketPerm := d.viper.GetUint32("socketPerm") socketPerm := v.GetUint32("socketPerm")
err = os.Chmod(server.Socket, os.FileMode(socketPerm)) err = os.Chmod(server.Socket, os.FileMode(socketPerm))
if err != nil { if err != nil {
return err return err
@ -221,7 +221,7 @@ user created with the credentials from options "username" and "password".`,
panic(err) 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 { if err != nil {
return err return err
} }
@ -262,7 +262,7 @@ user created with the credentials from options "username" and "password".`,
log.Println("Graceful shutdown complete.") log.Println("Graceful shutdown complete.")
return nil return nil
}, pythonConfig{allowsNoDatabase: true}), }, storeOptions{allowsNoDatabase: true}),
} }
func getServerSettings(v *viper.Viper, st *storage.Storage) (*settings.Server, error) { 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") log.Println("Performing quick setup")
set := &settings.Settings{ set := &settings.Settings{
@ -382,7 +382,7 @@ func quickSetup(d pythonData) error {
Scope: ".", Scope: ".",
Locale: "en", Locale: "en",
SingleClick: false, SingleClick: false,
AceEditorTheme: d.viper.GetString("defaults.aceEditorTheme"), AceEditorTheme: v.GetString("defaults.aceEditorTheme"),
Perm: users.Permissions{ Perm: users.Permissions{
Admin: false, Admin: false,
Execute: true, Execute: true,
@ -406,44 +406,44 @@ func quickSetup(d pythonData) error {
} }
var err error var err error
if d.viper.GetBool("noauth") { if v.GetBool("noauth") {
set.AuthMethod = auth.MethodNoAuth set.AuthMethod = auth.MethodNoAuth
err = d.store.Auth.Save(&auth.NoAuth{}) err = s.Auth.Save(&auth.NoAuth{})
} else { } else {
set.AuthMethod = auth.MethodJSONAuth set.AuthMethod = auth.MethodJSONAuth
err = d.store.Auth.Save(&auth.JSONAuth{}) err = s.Auth.Save(&auth.JSONAuth{})
} }
if err != nil { if err != nil {
return err return err
} }
err = d.store.Settings.Save(set) err = s.Settings.Save(set)
if err != nil { if err != nil {
return err return err
} }
ser := &settings.Server{ ser := &settings.Server{
BaseURL: d.viper.GetString("baseURL"), BaseURL: v.GetString("baseURL"),
Port: d.viper.GetString("port"), Port: v.GetString("port"),
Log: d.viper.GetString("log"), Log: v.GetString("log"),
TLSKey: d.viper.GetString("key"), TLSKey: v.GetString("key"),
TLSCert: d.viper.GetString("cert"), TLSCert: v.GetString("cert"),
Address: d.viper.GetString("address"), Address: v.GetString("address"),
Root: d.viper.GetString("root"), Root: v.GetString("root"),
TokenExpirationTime: d.viper.GetString("tokenExpirationTime"), TokenExpirationTime: v.GetString("tokenExpirationTime"),
EnableThumbnails: !d.viper.GetBool("disableThumbnails"), EnableThumbnails: !v.GetBool("disableThumbnails"),
ResizePreview: !d.viper.GetBool("disablePreviewResize"), ResizePreview: !v.GetBool("disablePreviewResize"),
EnableExec: !d.viper.GetBool("disableExec"), EnableExec: !v.GetBool("disableExec"),
TypeDetectionByHeader: !d.viper.GetBool("disableTypeDetectionByHeader"), TypeDetectionByHeader: !v.GetBool("disableTypeDetectionByHeader"),
} }
err = d.store.Settings.SaveServer(ser) err = s.Settings.SaveServer(ser)
if err != nil { if err != nil {
return err return err
} }
username := d.viper.GetString("username") username := v.GetString("username")
password := d.viper.GetString("password") password := v.GetString("password")
if password == "" { if password == "" {
var pwd string var pwd string
@ -474,5 +474,5 @@ func quickSetup(d pythonData) error {
set.Defaults.Apply(user) set.Defaults.Apply(user)
user.Perm.Admin = true user.Perm.Admin = true
return d.store.Users.Save(user) return s.Users.Save(user)
} }

View File

@ -40,7 +40,7 @@ including 'index_end'.`,
return nil 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]) i, err := strconv.Atoi(args[0])
if err != nil { if err != nil {
return err return err
@ -55,14 +55,14 @@ including 'index_end'.`,
user := func(u *users.User) error { user := func(u *users.User) error {
u.Rules = append(u.Rules[:i], u.Rules[f+1:]...) 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 { global := func(s *settings.Settings) error {
s.Rules = append(s.Rules[:i], s.Rules[f+1:]...) 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) return runRules(st.Storage, cmd, user, global)
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -21,7 +21,7 @@ var rulesAddCmd = &cobra.Command{
Short: "Add a global rule or user rule", Short: "Add a global rule or user rule",
Long: `Add a global rule or user rule.`, Long: `Add a global rule or user rule.`,
Args: cobra.ExactArgs(1), 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() flags := cmd.Flags()
allow, err := flags.GetBool("allow") allow, err := flags.GetBool("allow")
@ -53,14 +53,14 @@ var rulesAddCmd = &cobra.Command{
user := func(u *users.User) error { user := func(u *users.User) error {
u.Rules = append(u.Rules, rule) u.Rules = append(u.Rules, rule)
return d.store.Users.Save(u) return st.Users.Save(u)
} }
global := func(s *settings.Settings) error { global := func(s *settings.Settings) error {
s.Rules = append(s.Rules, rule) s.Rules = append(s.Rules, rule)
return d.store.Settings.Save(s) return st.Settings.Save(s)
} }
return runRules(d.store, cmd, user, global) return runRules(st.Storage, cmd, user, global)
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -13,7 +13,7 @@ var rulesLsCommand = &cobra.Command{
Short: "List global rules or user specific rules", Short: "List global rules or user specific rules",
Long: `List global rules or user specific rules.`, Long: `List global rules or user specific rules.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: python(func(cmd *cobra.Command, _ []string, d *pythonData) error { RunE: withStore(func(cmd *cobra.Command, _ []string, st *store) error {
return runRules(d.store, cmd, nil, nil) return runRules(st.Storage, cmd, nil, nil)
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -16,9 +16,9 @@ var usersAddCmd = &cobra.Command{
Short: "Create a new user", Short: "Create a new user",
Long: `Create a new user and add it to the database.`, Long: `Create a new user and add it to the database.`,
Args: cobra.ExactArgs(2), 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() flags := cmd.Flags()
s, err := d.store.Settings.Get() s, err := st.Settings.Get()
if err != nil { if err != nil {
return err return err
} }
@ -54,14 +54,14 @@ var usersAddCmd = &cobra.Command{
s.Defaults.Apply(user) s.Defaults.Apply(user)
servSettings, err := d.store.Settings.GetServer() servSettings, err := st.Settings.GetServer()
if err != nil { if err != nil {
return err return err
} }
// since getUserDefaults() polluted s.Defaults.Scope // since getUserDefaults() polluted s.Defaults.Scope
// which makes the Scope not the one saved in the db // which makes the Scope not the one saved in the db
// we need the right s.Defaults.Scope here // we need the right s.Defaults.Scope here
s2, err := d.store.Settings.Get() s2, err := st.Settings.Get()
if err != nil { if err != nil {
return err return err
} }
@ -72,11 +72,11 @@ var usersAddCmd = &cobra.Command{
} }
user.Scope = userHome user.Scope = userHome
err = d.store.Users.Save(user) err = st.Users.Save(user)
if err != nil { if err != nil {
return err return err
} }
printUsers([]*users.User{user}) printUsers([]*users.User{user})
return nil return nil
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -14,8 +14,8 @@ var usersExportCmd = &cobra.Command{
Long: `Export all users to a json or yaml file. Please indicate the Long: `Export all users to a json or yaml file. Please indicate the
path to the file where you want to write the users.`, path to the file where you want to write the users.`,
Args: jsonYamlArg, Args: jsonYamlArg,
RunE: python(func(_ *cobra.Command, args []string, d *pythonData) error { RunE: withStore(func(_ *cobra.Command, args []string, st *store) error {
list, err := d.store.Users.Gets("") list, err := st.Users.Gets("")
if err != nil { if err != nil {
return err return err
} }
@ -25,5 +25,5 @@ path to the file where you want to write the users.`,
return err return err
} }
return nil return nil
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -26,7 +26,7 @@ var usersLsCmd = &cobra.Command{
RunE: findUsers, 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 ( var (
list []*users.User list []*users.User
user *users.User user *users.User
@ -36,14 +36,14 @@ var findUsers = python(func(_ *cobra.Command, args []string, d *pythonData) erro
if len(args) == 1 { if len(args) == 1 {
username, id := parseUsernameOrID(args[0]) username, id := parseUsernameOrID(args[0])
if username != "" { if username != "" {
user, err = d.store.Users.Get("", username) user, err = st.Users.Get("", username)
} else { } else {
user, err = d.store.Users.Get("", id) user, err = st.Users.Get("", id)
} }
list = []*users.User{user} list = []*users.User{user}
} else { } else {
list, err = d.store.Users.Gets("") list, err = st.Users.Gets("")
} }
if err != nil { if err != nil {
@ -51,4 +51,4 @@ var findUsers = python(func(_ *cobra.Command, args []string, d *pythonData) erro
} }
printUsers(list) printUsers(list)
return nil return nil
}, pythonConfig{}) }, storeOptions{})

View File

@ -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 installation. For that, just don't place their ID on the files
list or set it to 0.`, list or set it to 0.`,
Args: jsonYamlArg, 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() flags := cmd.Flags()
fd, err := os.Open(args[0]) fd, err := os.Open(args[0])
if err != nil { if err != nil {
@ -52,7 +52,7 @@ list or set it to 0.`,
} }
if replace { if replace {
oldUsers, userImportErr := d.store.Users.Gets("") oldUsers, userImportErr := st.Users.Gets("")
if userImportErr != nil { if userImportErr != nil {
return userImportErr return userImportErr
} }
@ -63,7 +63,7 @@ list or set it to 0.`,
} }
for _, user := range oldUsers { for _, user := range oldUsers {
err = d.store.Users.Delete(user.ID) err = st.Users.Delete(user.ID)
if err != nil { if err != nil {
return err return err
} }
@ -76,7 +76,7 @@ list or set it to 0.`,
} }
for _, user := range list { for _, user := range list {
onDB, err := d.store.Users.Get("", user.ID) onDB, err := st.Users.Get("", user.ID)
// User exists in DB. // User exists in DB.
if err == nil { 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 // with the new username. If there is, print an error and cancel the
// operation // operation
if user.Username != onDB.Username { 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) return usernameConflictError(user.Username, conflictuous.ID, user.ID)
} }
} }
@ -98,13 +98,13 @@ list or set it to 0.`,
user.ID = 0 user.ID = 0
} }
err = d.store.Users.Save(user) err = st.Users.Save(user)
if err != nil { if err != nil {
return err return err
} }
} }
return nil return nil
}, pythonConfig{}), }, storeOptions{}),
} }
func usernameConflictError(username string, originalID, newID uint) error { func usernameConflictError(username string, originalID, newID uint) error {

View File

@ -15,14 +15,14 @@ var usersRmCmd = &cobra.Command{
Short: "Delete a user by username or id", Short: "Delete a user by username or id",
Long: `Delete a user by username or id`, Long: `Delete a user by username or id`,
Args: cobra.ExactArgs(1), 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]) username, id := parseUsernameOrID(args[0])
var err error var err error
if username != "" { if username != "" {
err = d.store.Users.Delete(username) err = st.Users.Delete(username)
} else { } else {
err = d.store.Users.Delete(id) err = st.Users.Delete(id)
} }
if err != nil { if err != nil {
@ -30,5 +30,5 @@ var usersRmCmd = &cobra.Command{
} }
fmt.Println("user deleted successfully") fmt.Println("user deleted successfully")
return nil return nil
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -21,7 +21,7 @@ var usersUpdateCmd = &cobra.Command{
Long: `Updates an existing user. Set the flags for the Long: `Updates an existing user. Set the flags for the
options you want to change.`, options you want to change.`,
Args: cobra.ExactArgs(1), 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() flags := cmd.Flags()
username, id := parseUsernameOrID(args[0]) username, id := parseUsernameOrID(args[0])
password, err := flags.GetString("password") password, err := flags.GetString("password")
@ -34,7 +34,7 @@ options you want to change.`,
return err return err
} }
s, err := d.store.Settings.Get() s, err := st.Settings.Get()
if err != nil { if err != nil {
return err return err
} }
@ -43,9 +43,9 @@ options you want to change.`,
user *users.User user *users.User
) )
if id != 0 { if id != 0 {
user, err = d.store.Users.Get("", id) user, err = st.Users.Get("", id)
} else { } else {
user, err = d.store.Users.Get("", username) user, err = st.Users.Get("", username)
} }
if err != nil { if err != nil {
return err 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 { if err != nil {
return err return err
} }
printUsers([]*users.User{user}) printUsers([]*users.User{user})
return nil return nil
}, pythonConfig{}), }, storeOptions{}),
} }

View File

@ -36,6 +36,7 @@ func getAndParseFileMode(flags *pflag.FlagSet, name string) (fs.FileMode, error)
if err != nil { if err != nil {
return 0, err return 0, err
} }
return fs.FileMode(b), nil return fs.FileMode(b), nil
} }
@ -131,38 +132,29 @@ func initViper(cmd *cobra.Command) (*viper.Viper, error) {
return v, nil return v, nil
} }
type cobraFunc func(cmd *cobra.Command, args []string) error type store struct {
type pythonFunc func(cmd *cobra.Command, args []string, data *pythonData) error *storage.Storage
databaseExisted bool
}
type pythonConfig struct { type storeOptions struct {
expectsNoDatabase bool expectsNoDatabase bool
allowsNoDatabase bool allowsNoDatabase bool
} }
type pythonData struct { type cobraFunc func(cmd *cobra.Command, args []string) error
databaseExisted bool
viper *viper.Viper
store *storage.Storage
}
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 { return func(cmd *cobra.Command, args []string) error {
v, err := initViper(cmd) v, err := initViper(cmd)
if err != nil { if err != nil {
return err return err
} }
data := &pythonData{databaseExisted: true} path, err := filepath.Abs(v.GetString("database"))
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)
if err != nil { if err != nil {
return err return err
} }
@ -170,16 +162,15 @@ func python(fn pythonFunc, cfg pythonConfig) cobraFunc {
exists, err := dbExists(path) exists, err := dbExists(path)
if err != nil { if err != nil {
return err return err
} else if exists && cfg.expectsNoDatabase { } else if exists && options.expectsNoDatabase {
log.Fatal(absPath + " already exists") log.Fatal(path + " already exists")
} else if !exists && !cfg.expectsNoDatabase && !cfg.allowsNoDatabase { } else if !exists && !options.expectsNoDatabase && !options.allowsNoDatabase {
log.Fatal(absPath + " does not exist. Please run 'filebrowser config init' first.") log.Fatal(path + " does not exist. Please run 'filebrowser config init' first.")
} else if !exists && !cfg.expectsNoDatabase { } else if !exists && !options.expectsNoDatabase {
log.Println("Warning: filebrowser.db can't be found. Initialing in " + strings.TrimSuffix(absPath, "filebrowser.db")) log.Println("WARNING: filebrowser.db can't be found. Initialing in " + strings.TrimSuffix(path, "filebrowser.db"))
} }
log.Println("Using database: " + absPath) log.Println("Using database: " + path)
data.databaseExisted = exists
db, err := storm.Open(path, storm.BoltOptions(databasePermissions, nil)) db, err := storm.Open(path, storm.BoltOptions(databasePermissions, nil))
if err != nil { if err != nil {
@ -187,15 +178,26 @@ func python(fn pythonFunc, cfg pythonConfig) cobraFunc {
} }
defer db.Close() defer db.Close()
data.store, err = bolt.NewStorage(db) storage, err := bolt.NewStorage(db)
if err != nil { if err != nil {
return err 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 { func marshal(filename string, data interface{}) error {
fd, err := os.Create(filename) fd, err := os.Create(filename)
if err != nil { if err != nil {