filebrowser/cmd/utils.go
Henrique Dias e5c150e83f merge with master
License: MIT
Signed-off-by: Henrique Dias <hacdias@gmail.com>

Former-commit-id: dfac33db9ca3454cd3af02a732a64a02a8268b01 [formerly 38be015f7b3376a3bc992725c1cb1a019c1843cb] [formerly 5a4e310b96ebc5895e64f8eeb2f592890d4b63b0 [formerly 2b8bd28158]]
Former-commit-id: a30bfcebe6bbc115990b8f8398171b32942a8767 [formerly 553fafa22b46b2689ece093f3b0cf85b3cff1c87]
Former-commit-id: 5ce047d4e3f5217a179685f8b2850d4eb157376e
2019-01-06 13:20:17 +00:00

92 lines
1.7 KiB
Go

package cmd
import (
"crypto/rand"
"errors"
"os"
"github.com/asdine/storm"
"github.com/filebrowser/filebrowser/v2/storage"
"github.com/filebrowser/filebrowser/v2/storage/bolt"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
v "github.com/spf13/viper"
)
func vaddP(f *pflag.FlagSet, k, p string, i interface{}, u string) {
switch y := i.(type) {
case bool:
f.BoolP(k, p, y, u)
case int:
f.IntP(k, p, y, u)
case string:
f.StringP(k, p, y, u)
}
v.SetDefault(k, i)
}
func vadd(f *pflag.FlagSet, k string, i interface{}, u string) {
switch y := i.(type) {
case bool:
f.Bool(k, y, u)
case int:
f.Int(k, y, u)
case string:
f.String(k, y, u)
}
v.SetDefault(k, i)
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func mustGetString(cmd *cobra.Command, flag string) string {
s, err := cmd.Flags().GetString(flag)
checkErr(err)
return s
}
func mustGetBool(cmd *cobra.Command, flag string) bool {
b, err := cmd.Flags().GetBool(flag)
checkErr(err)
return b
}
func mustGetInt(cmd *cobra.Command, flag string) int {
b, err := cmd.Flags().GetInt(flag)
checkErr(err)
return b
}
func mustGetUint(cmd *cobra.Command, flag string) uint {
b, err := cmd.Flags().GetUint(flag)
checkErr(err)
return b
}
func getDB() *storm.DB {
databasePath := v.GetString("database")
if _, err := os.Stat(databasePath); err != nil {
panic(errors.New(databasePath + " does not exist. Please run 'filebrowser init' first."))
}
db, err := storm.Open(databasePath)
checkErr(err)
return db
}
func getStorage(db *storm.DB) *storage.Storage {
return bolt.NewStorage(db)
}
func generateRandomBytes(n int) []byte {
b := make([]byte, n)
_, err := rand.Read(b)
checkErr(err)
// Note that err == nil only if we read len(b) bytes.
return b
}