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.
(fn func(cmd *cobra.Command, args []string, v *viper.Viper, store *store) error, options storeOptions)
| 148 | // This function should only be used by [withStore] and the root command. No other command should call |
| 149 | // this function directly. |
| 150 | func withViperAndStore(fn func(cmd *cobra.Command, args []string, v *viper.Viper, store *store) error, options storeOptions) cobraFunc { |
| 151 | return func(cmd *cobra.Command, args []string) error { |
| 152 | v, err := initViper(cmd) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | |
| 157 | path, err := filepath.Abs(v.GetString("database")) |
| 158 | if err != nil { |
| 159 | return err |
| 160 | } |
| 161 | |
| 162 | exists, err := dbExists(path) |
| 163 | switch { |
| 164 | case err != nil: |
| 165 | return err |
| 166 | case exists && options.expectsNoDatabase: |
| 167 | log.Fatal(path + " already exists") |
| 168 | case !exists && !options.expectsNoDatabase && !options.allowsNoDatabase: |
| 169 | log.Fatal(path + " does not exist. Please run 'filebrowser config init' first.") |
| 170 | case !exists && !options.expectsNoDatabase: |
| 171 | log.Println("WARNING: filebrowser.db can't be found. Initialing in " + strings.TrimSuffix(path, "filebrowser.db")) |
| 172 | } |
| 173 | |
| 174 | log.Println("Using database: " + path) |
| 175 | |
| 176 | db, err := storm.Open(path, storm.BoltOptions(databasePermissions, nil)) |
| 177 | if err != nil { |
| 178 | return err |
| 179 | } |
| 180 | defer db.Close() |
| 181 | |
| 182 | storage, err := bolt.NewStorage(db) |
| 183 | if err != nil { |
| 184 | return err |
| 185 | } |
| 186 | |
| 187 | store := &store{ |
| 188 | Storage: storage, |
| 189 | databaseExisted: exists, |
| 190 | } |
| 191 | |
| 192 | return fn(cmd, args, v, store) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | func withStore(fn func(cmd *cobra.Command, args []string, store *store) error, options storeOptions) cobraFunc { |
| 197 | return withViperAndStore(func(cmd *cobra.Command, args []string, _ *viper.Viper, store *store) error { |