Skip to content

Commit

Permalink
feat: wrap commands to send info (#612)
Browse files Browse the repository at this point in the history
Wrap commands in a better way to pass storage
  • Loading branch information
hacdias committed Jan 7, 2019
1 parent f396602 commit 01ff03e
Show file tree
Hide file tree
Showing 16 changed files with 163 additions and 205 deletions.
13 changes: 4 additions & 9 deletions cmd/cmds_add.go
Expand Up @@ -15,18 +15,13 @@ 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),
Run: func(cmd *cobra.Command, args []string) {
db := getDB()
defer db.Close()
st := getStorage(db)
s, err := st.Settings.Get()
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
s, err := d.store.Settings.Get()
checkErr(err)

command := strings.Join(args[1:], " ")

s.Commands[args[0]] = append(s.Commands[args[0]], command)
err = st.Settings.Save(s)
err = d.store.Settings.Save(s)
checkErr(err)
printEvents(s.Commands)
},
}, pythonConfig{}),
}
9 changes: 3 additions & 6 deletions cmd/cmds_ls.go
Expand Up @@ -14,11 +14,8 @@ var cmdsLsCmd = &cobra.Command{
Short: "List all commands for each event",
Long: `List all commands for each event.`,
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
db := getDB()
defer db.Close()
st := getStorage(db)
s, err := st.Settings.Get()
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
s, err := d.store.Settings.Get()
checkErr(err)
evt := mustGetString(cmd, "event")

Expand All @@ -30,5 +27,5 @@ var cmdsLsCmd = &cobra.Command{
show["after_"+evt] = s.Commands["after_"+evt]
printEvents(show)
}
},
}, pythonConfig{}),
}
11 changes: 4 additions & 7 deletions cmd/cmds_rm.go
Expand Up @@ -27,11 +27,8 @@ var cmdsRmCmd = &cobra.Command{

return nil
},
Run: func(cmd *cobra.Command, args []string) {
db := getDB()
defer db.Close()
st := getStorage(db)
s, err := st.Settings.Get()
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
s, err := d.store.Settings.Get()
checkErr(err)
evt := args[0]

Expand All @@ -44,8 +41,8 @@ var cmdsRmCmd = &cobra.Command{
}

s.Commands[evt] = append(s.Commands[evt][:i], s.Commands[evt][f+1:]...)
err = st.Settings.Save(s)
err = d.store.Settings.Save(s)
checkErr(err)
printEvents(s.Commands)
},
}, pythonConfig{}),
}
11 changes: 4 additions & 7 deletions cmd/config_cat.go
Expand Up @@ -13,14 +13,11 @@ var configCatCmd = &cobra.Command{
Short: "Prints the configuration",
Long: `Prints the configuration.`,
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
db := getDB()
defer db.Close()
st := getStorage(db)
s, err := st.Settings.Get()
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
s, err := d.store.Settings.Get()
checkErr(err)
auther, err := st.Auth.Get(s.AuthMethod)
auther, err := d.store.Auth.Get(s.AuthMethod)
checkErr(err)
printSettings(s, auther)
},
}, pythonConfig{}),
}
21 changes: 4 additions & 17 deletions cmd/config_init.go
@@ -1,15 +1,11 @@
package cmd

import (
"errors"
"fmt"
"os"
"strings"

"github.com/asdine/storm"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/spf13/cobra"
v "github.com/spf13/viper"
)

func init() {
Expand All @@ -26,20 +22,11 @@ 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,
Run: func(cmd *cobra.Command, args []string) {
databasePath := v.GetString("database")
if _, err := os.Stat(databasePath); err == nil {
panic(errors.New(databasePath + " already exists"))
}

Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
defaults := settings.UserDefaults{}
getUserDefaults(cmd, &defaults, true)
authMethod, auther := getAuthentication(cmd)

db, err := storm.Open(databasePath)
checkErr(err)
defer db.Close()
st := getStorage(db)
s := &settings.Settings{
Key: generateRandomBytes(64), // 256 bit
Signup: mustGetBool(cmd, "signup"),
Expand All @@ -53,9 +40,9 @@ override the options.`,
},
}

err = st.Settings.Save(s)
err := d.store.Settings.Save(s)
checkErr(err)
err = st.Auth.Save(auther)
err = d.store.Auth.Save(auther)
checkErr(err)

fmt.Printf(`
Expand All @@ -64,5 +51,5 @@ Now add your first user via 'filebrowser users new' and then you just
need to call the main command to boot up the server.
`)
printSettings(s, auther)
},
}, pythonConfig{noDB: true}),
}
16 changes: 6 additions & 10 deletions cmd/config_set.go
Expand Up @@ -19,12 +19,8 @@ var configSetCmd = &cobra.Command{
Long: `Updates the configuration. Set the flags for the options
you want to change.`,
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
db := getDB()
defer db.Close()

st := getStorage(db)
s, err := st.Settings.Get()
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
s, err := d.store.Settings.Get()
checkErr(err)

hasAuth := false
Expand All @@ -50,15 +46,15 @@ you want to change.`,
var auther auth.Auther
if hasAuth {
s.AuthMethod, auther = getAuthentication(cmd)
err = st.Auth.Save(auther)
err = d.store.Auth.Save(auther)
checkErr(err)
} else {
auther, err = st.Auth.Get(s.AuthMethod)
auther, err = d.store.Auth.Get(s.AuthMethod)
checkErr(err)
}

err = st.Settings.Save(s)
err = d.store.Settings.Save(s)
checkErr(err)
printSettings(s, auther)
},
}, pythonConfig{}),
}
131 changes: 59 additions & 72 deletions cmd/root.go
Expand Up @@ -12,7 +12,6 @@ import (
"strconv"
"strings"

"github.com/asdine/storm"
"github.com/filebrowser/filebrowser/v2/auth"
fbhttp "github.com/filebrowser/filebrowser/v2/http"
"github.com/filebrowser/filebrowser/v2/settings"
Expand Down Expand Up @@ -91,81 +90,71 @@ set FB_DATABASE equals to the path.
Also, if the database path doesn't exist, File Browser will enter into
the quick setup mode and a new database will be bootstraped and a new
user created with the credentials from options "username" and "password".`,
Run: serveAndListen,
}

func serveAndListen(cmd *cobra.Command, args []string) {
switch logMethod := v.GetString("log"); logMethod {
case "stdout":
log.SetOutput(os.Stdout)
case "stderr":
log.SetOutput(os.Stderr)
case "":
log.SetOutput(ioutil.Discard)
default:
log.SetOutput(&lumberjack.Logger{
Filename: logMethod,
MaxSize: 100,
MaxAge: 14,
MaxBackups: 10,
})
}

if _, err := os.Stat(v.GetString("database")); os.IsNotExist(err) {
quickSetup(cmd)
}

db := getDB()
defer db.Close()
st := getStorage(db)

port := v.GetInt("port")
address := v.GetString("address")
cert := v.GetString("cert")
key := v.GetString("key")
scope := v.GetString("scope")

scope, err := filepath.Abs(scope)
checkErr(err)
settings, err := st.Settings.Get()
checkErr(err)

// Despite Base URL and Scope being "server" type of
// variables, we persist them to the database because
// they are needed during the execution and not only
// to start up the server.
settings.BaseURL = v.GetString("baseurl")
settings.Scope = scope
err = st.Settings.Save(settings)
checkErr(err)
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
switch logMethod := v.GetString("log"); logMethod {
case "stdout":
log.SetOutput(os.Stdout)
case "stderr":
log.SetOutput(os.Stderr)
case "":
log.SetOutput(ioutil.Discard)
default:
log.SetOutput(&lumberjack.Logger{
Filename: logMethod,
MaxSize: 100,
MaxAge: 14,
MaxBackups: 10,
})
}

handler, err := fbhttp.NewHandler(st)
checkErr(err)
if !d.hadDB {
quickSetup(d)
}

var listener net.Listener
port := v.GetInt("port")
address := v.GetString("address")
cert := v.GetString("cert")
key := v.GetString("key")
scope := v.GetString("scope")

if key != "" && cert != "" {
cer, err := tls.LoadX509KeyPair(cert, key)
scope, err := filepath.Abs(scope)
checkErr(err)
config := &tls.Config{Certificates: []tls.Certificate{cer}}
listener, err = tls.Listen("tcp", address+":"+strconv.Itoa(port), config)
settings, err := d.store.Settings.Get()
checkErr(err)
} else {
listener, err = net.Listen("tcp", address+":"+strconv.Itoa(port))

// Despite Base URL and Scope being "server" type of
// variables, we persist them to the database because
// they are needed during the execution and not only
// to start up the server.
settings.BaseURL = v.GetString("baseurl")
settings.Scope = scope
err = d.store.Settings.Save(settings)
checkErr(err)
}

log.Println("Listening on", listener.Addr().String())
if err := http.Serve(listener, handler); err != nil {
log.Fatal(err)
}
}
handler, err := fbhttp.NewHandler(d.store)
checkErr(err)

func quickSetup(cmd *cobra.Command) {
db, err := storm.Open(v.GetString("database"))
checkErr(err)
defer db.Close()
var listener net.Listener

if key != "" && cert != "" {
cer, err := tls.LoadX509KeyPair(cert, key)
checkErr(err)
config := &tls.Config{Certificates: []tls.Certificate{cer}}
listener, err = tls.Listen("tcp", address+":"+strconv.Itoa(port), config)
checkErr(err)
} else {
listener, err = net.Listen("tcp", address+":"+strconv.Itoa(port))
checkErr(err)
}

log.Println("Listening on", listener.Addr().String())
if err := http.Serve(listener, handler); err != nil {
log.Fatal(err)
}
}, pythonConfig{noDB: true}),
}

func quickSetup(d pythonData) {
set := &settings.Settings{
Key: generateRandomBytes(64), // 256 bit
BaseURL: v.GetString("baseurl"),
Expand All @@ -187,12 +176,10 @@ func quickSetup(cmd *cobra.Command) {
},
}

st := getStorage(db)

err = st.Settings.Save(set)
err := d.store.Settings.Save(set)
checkErr(err)

err = st.Auth.Save(&auth.JSONAuth{})
err = d.store.Auth.Save(&auth.JSONAuth{})
checkErr(err)

username := v.GetString("username")
Expand All @@ -216,7 +203,7 @@ func quickSetup(cmd *cobra.Command) {
set.Defaults.Apply(user)
user.Perm.Admin = true

err = st.Users.Save(user)
err = d.store.Users.Save(user)
checkErr(err)
}

Expand Down
15 changes: 7 additions & 8 deletions cmd/rule_rm.go
Expand Up @@ -4,7 +4,6 @@ import (
"strconv"

"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage"
"github.com/filebrowser/filebrowser/v2/users"
"github.com/spf13/cobra"
)
Expand Down Expand Up @@ -32,7 +31,7 @@ var rulesRmCommand = &cobra.Command{

return nil
},
Run: func(cmd *cobra.Command, args []string) {
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
i, err := strconv.Atoi(args[0])
checkErr(err)
f := i
Expand All @@ -41,18 +40,18 @@ var rulesRmCommand = &cobra.Command{
checkErr(err)
}

user := func(u *users.User, st *storage.Storage) {
user := func(u *users.User) {
u.Rules = append(u.Rules[:i], u.Rules[f+1:]...)
err := st.Users.Save(u)
err := d.store.Users.Save(u)
checkErr(err)
}

global := func(s *settings.Settings, st *storage.Storage) {
global := func(s *settings.Settings) {
s.Rules = append(s.Rules[:i], s.Rules[f+1:]...)
err := st.Settings.Save(s)
err := d.store.Settings.Save(s)
checkErr(err)
}

runRules(cmd, user, global)
},
runRules(d.store, cmd, user, global)
}, pythonConfig{}),
}

0 comments on commit 01ff03e

Please sign in to comment.