initClient uses bookmark if it exists

if options.Bookmark is set, initClient will now use
it to create a client from the bookmarked settings.

initClientUsingBookmark uses methods introduced in
previous commits. It constructs connection string
to db from Bookmark.Url if it exists. If not, it
uses other fields in Bookmark to construct the
connection string. An implication of this is that
the Url field of Bookmark takes precedence.
This commit is contained in:
akarki15 2016-11-10 01:22:21 -05:00
parent 61dfe67ca8
commit 1b4902f196
2 changed files with 41 additions and 4 deletions

44
main.go
View File

@ -10,9 +10,11 @@ import (
"github.com/jessevdk/go-flags"
"github.com/sosedoff/pgweb/pkg/api"
"github.com/sosedoff/pgweb/pkg/bookmarks"
"github.com/sosedoff/pgweb/pkg/client"
"github.com/sosedoff/pgweb/pkg/command"
"github.com/sosedoff/pgweb/pkg/connection"
"github.com/sosedoff/pgweb/pkg/shared"
"github.com/sosedoff/pgweb/pkg/util"
)
@ -23,14 +25,48 @@ func exitWithMessage(message string) {
os.Exit(1)
}
func initClientUsingBookmark(bookmarkPath, bookmarkName string) (*client.Client, error) {
bookmark, err := bookmarks.GetBookmark(bookmarkPath, bookmarkName)
if err != nil {
return nil, err
}
opt, err := bookmark.ConvertToOptions()
if err != nil {
return nil, err
}
var connStr string
if opt.Url != "" { // if the bookmark has url set, use it
connStr = opt.Url
} else {
connStr, err = connection.BuildString(opt)
if err != nil {
return nil, fmt.Errorf("error building connection string: %v", err)
}
}
var ssh *shared.SSHInfo
if !bookmark.SSHInfoIsEmpty() {
ssh = &bookmark.Ssh
}
return client.NewFromUrl(connStr, ssh)
}
func initClient() {
if connection.IsBlank(command.Opts) {
if connection.IsBlank(command.Opts) && options.Bookmark == "" {
return
}
cl, err := client.New()
if err != nil {
exitWithMessage(err.Error())
var cl *client.Client
var err error
if options.Bookmark != "" {
cl, err = initClientUsingBookmark(bookmarks.Path(), options.Bookmark)
if err != nil {
exitWithMessage(err.Error())
}
} else {
cl, err = client.New()
if err != nil {
exitWithMessage(err.Error())
}
}
if command.Opts.Debug {

View File

@ -27,6 +27,7 @@ type Options struct {
Prefix string `long:"prefix" description:"Add a url prefix"`
ReadOnly bool `long:"readonly" description:"Run database connection in readonly mode"`
LockSession bool `long:"lock-session" description:"Lock session to a single database connection" default:"false"`
Bookmark string `short:"b" long:"bookmark" description:"Bookmark to use for connection. Bookmark files are stored under $HOME/.pgweb/bookmarks/*.toml" default:""`
}
var Opts Options