Skip to content
Permalink
Browse files

replace "primary" with "broker", allow configuring like git

  • Loading branch information...
justone committed Jun 20, 2019
1 parent e00e85a commit 6d963bd009934e0fd2a99b99be1dad2c8c1c5df6
@@ -0,0 +1,171 @@
package pmb

import (
"fmt"
"os"
"path/filepath"
"strings"

ini "gopkg.in/ini.v1"
)

type ConfigClient interface {
GetAll() (map[string]string, error)
Unset(system bool, key string) error
Set(system bool, key, value string) error
Get(key string) (string, error)
}

type ConfigGetter interface {
Get(key string) (string, error)
}

type RealConfigClient struct {
systemConfig string
userConfig string
}

func (rcc *RealConfigClient) Set(system bool, key, value string) error {
var configPath string

if system {
configPath = rcc.systemConfig
} else {
configPath = rcc.userConfig
}

cfg, err := ini.LooseLoad(configPath)
if err != nil {
return fmt.Errorf("error: %v", err)
}

section, k := splitKey(key)

_, err = cfg.Section(section).NewKey(k, value)
if err != nil {
return fmt.Errorf("unable to set new key: %v", err)
}

err = cfg.SaveToIndent(configPath, " ")
if err != nil {
return fmt.Errorf("unable to save: %v", err)
}

return nil
}

func (rcc *RealConfigClient) Unset(system bool, key string) error {
var configPath string

if system {
configPath = rcc.systemConfig
} else {
configPath = rcc.userConfig
}

cfg, err := ini.LooseLoad(configPath)
if err != nil {
return fmt.Errorf("error: %v", err)
}

section, k := splitKey(key)

cfg.Section(section).DeleteKey(k)
if len(cfg.Section(section).Keys()) == 0 {
cfg.DeleteSection(section)
}

err = cfg.SaveToIndent(configPath, " ")
if err != nil {
return fmt.Errorf("unable to save: %v", err)
}

return nil
}

func (rcc *RealConfigClient) Get(key string) (string, error) {
cfg, err := ini.LooseLoad(rcc.systemConfig, rcc.userConfig)
if err != nil {
return "", fmt.Errorf("failure to load config: %v", err)
}

section, k := splitKey(key)
ck := cfg.Section(section).Key(k)

return ck.Value(), nil
}

func (rcc *RealConfigClient) GetAll() (map[string]string, error) {
all := make(map[string]string)

cfg, err := ini.LooseLoad(rcc.systemConfig, rcc.userConfig)
if err != nil {
return all, fmt.Errorf("failure to load config: %v", err)
}

for _, section := range cfg.Sections() {
if len(section.Keys()) > 0 {
for _, key := range section.Keys() {
all[fmt.Sprintf("%s.%s", section.Name(), key.Name())] = key.Value()
}
}
}

return all, nil
}

func splitKey(key string) (string, string) {
parts := strings.SplitN(key, ".", 2)

return parts[0], parts[1]
}

func fileExists(path string) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
return false
}
return true
}

func NewDefaultConfigClient() (*RealConfigClient, error) {
var baseDir string
if xdgConfigHome := os.Getenv("XDG_CONFIG_HOME"); len(xdgConfigHome) > 0 {
baseDir = filepath.Join(xdgConfigHome, "pmb")
} else {
var home string
if home = os.Getenv("HOME"); len(home) == 0 {
return nil, fmt.Errorf("$HOME environment variable not found")
}
baseDir = filepath.Join(home, ".config", "pmb")
os.MkdirAll(baseDir, 0755)
}

systemHome := "/etc"
if pmbSystemEnv := os.Getenv("PMB_SYSTEM_CONFIG"); len(pmbSystemEnv) > 0 {
systemHome = pmbSystemEnv
}

var err error
systemConfigPath := filepath.Join(systemHome, "pmbconfig")
if fileExists(systemConfigPath) {
systemConfigPath, err = filepath.EvalSymlinks(systemConfigPath)
if err != nil {
return nil, err
}
}

userConfigPath := filepath.Join(baseDir, "config")
if fileExists(userConfigPath) {
userConfigPath, err = filepath.EvalSymlinks(userConfigPath)
if err != nil {
return nil, err
}
}

configClient := RealConfigClient{
systemConfig: systemConfigPath,
userConfig: userConfigPath,
}

return &configClient, nil
}
@@ -42,19 +42,30 @@ type Notification struct {
Level float64
}

func GetPMB(primaryURI string) *PMB {
config := getConfig(primaryURI)
func GetPMB(brokerURI string) *PMB {
config := getConfig(brokerURI)

return &PMB{config: config}
}

func getConfig(primaryURI string) PMBConfig {
func getConfig(brokerURI string) PMBConfig {
config := make(PMBConfig)

if len(primaryURI) > 0 {
config["primary"] = primaryURI
} else if primaryURI := os.Getenv("PMB_PRIMARY_URI"); len(primaryURI) > 0 {
config["primary"] = primaryURI
conf, err := NewDefaultConfigClient()
var confBrokerURI string
if err == nil {
confBrokerURI, _ = conf.Get("broker.uri")
}

if len(brokerURI) > 0 {
logrus.Debugf("Broker URI retrieved from argument")
config["broker"] = brokerURI
} else if brokerURI := os.Getenv("PMB_BROKER_URI"); len(brokerURI) > 0 {
logrus.Debugf("Broker URI retrieved from ENV")
config["broker"] = brokerURI
} else if len(confBrokerURI) > 0 {
logrus.Debugf("Broker URI retrieved from config")
config["broker"] = confBrokerURI
}

if key := os.Getenv("PMB_KEY"); len(key) > 0 {
@@ -71,29 +82,29 @@ func getConfig(primaryURI string) PMBConfig {

func (pmb *PMB) ConnectIntroducer(id string) (*Connection, error) {

if len(pmb.config["primary"]) > 0 {
if len(pmb.config["broker"]) > 0 {
logrus.Debugf("calling connectWithKey")
return connectWithKey(pmb.config["primary"], id, "", pmb.config["key"], true, true)
return connectWithKey(pmb.config["broker"], id, "", pmb.config["key"], true, true)
}

return nil, errors.New("No URI found, use '-p' to specify one")
}

func (pmb *PMB) ConnectClient(id string, checkKey bool) (*Connection, error) {

if len(pmb.config["primary"]) > 0 {
if len(pmb.config["broker"]) > 0 {
logrus.Debugf("calling connectWithKey")
return connectWithKey(pmb.config["primary"], id, "", pmb.config["key"], false, checkKey)
return connectWithKey(pmb.config["broker"], id, "", pmb.config["key"], false, checkKey)
}

return nil, errors.New("No URI found, use '-p' to specify one")
}

func (pmb *PMB) ConnectSubClient(conn *Connection, sub string) (*Connection, error) {

if len(pmb.config["primary"]) > 0 {
if len(pmb.config["broker"]) > 0 {
logrus.Debugf("calling connectWithKey")
return connectWithKey(pmb.config["primary"], conn.Id, sub, strings.Join(conn.Keys, ","), false, false)
return connectWithKey(pmb.config["broker"], conn.Id, sub, strings.Join(conn.Keys, ","), false, false)
}

return nil, errors.New("No URI found, use '-p' to specify one")
@@ -102,18 +113,18 @@ func (pmb *PMB) ConnectSubClient(conn *Connection, sub string) (*Connection, err
// Deprecated
func (pmb *PMB) GetConnection(id string, isIntroducer bool) (*Connection, error) {

if len(pmb.config["primary"]) > 0 {
if len(pmb.config["broker"]) > 0 {
logrus.Debugf("calling connectWithKey")
return connectWithKey(pmb.config["primary"], id, "", pmb.config["key"], isIntroducer, true)
return connectWithKey(pmb.config["broker"], id, "", pmb.config["key"], isIntroducer, true)
}

return nil, errors.New("No URI found, use '-p' to specify one")
}

func (pmb *PMB) CopyKey(id string) (*Connection, error) {

if len(pmb.config["primary"]) > 0 {
return copyKey(pmb.config["primary"], id)
if len(pmb.config["broker"]) > 0 {
return copyKey(pmb.config["broker"], id)
}

return nil, errors.New("No URI found, use '-p' to specify one")
@@ -334,6 +345,6 @@ func requestKey(conn *Connection) (string, error) {
return string(key), nil
}

func (pmb *PMB) PrimaryURI() string {
return pmb.config["primary"]
func (pmb *PMB) BrokerURI() string {
return pmb.config["broker"]
}
@@ -0,0 +1,70 @@
package main

import (
"errors"
"fmt"

"github.com/justone/pmb/api"
)

// ConfigCommand specifies options for the config subcommand.
type ConfigCommand struct {
System bool `short:"s" long:"system" description:"Modify system level configuration."`
Unset bool `short:"u" long:"unset" description:"Unset key."`
List bool `short:"l" long:"list" description:"List current config values."`
Args struct {
Key string `description:"Configuration key." positional-arg-name:"key"`
Value string `description:"Configuration value. (optional)" positional-arg-name:"value"`
} `positional-args:"yes"`
}

var configCommand ConfigCommand

// Execute handles setting, getting, and listing configuration values.
func (x *ConfigCommand) Execute(args []string) error {
conf, err := pmb.NewDefaultConfigClient()
if err != nil {
return err
}

if configCommand.List {
all, err := conf.GetAll()
if err != nil {
return err
}

for k, v := range all {
fmt.Printf("%s = %s\n", k, v)
}
} else if configCommand.Unset {
err := conf.Unset(configCommand.System, configCommand.Args.Key)
if err != nil {
return err
}
} else {
if len(configCommand.Args.Value) > 0 {
return conf.Set(configCommand.System, configCommand.Args.Key, configCommand.Args.Value)
} else if len(configCommand.Args.Key) > 0 {
val, err := conf.Get(configCommand.Args.Key)
if err != nil {
return err
}
fmt.Println(val)
} else {
return errors.New("Specify a key and optional value to set or pass --help for more information")
}
}

return nil
}

func init() {
_, err := parser.AddCommand("config",
"Set and get configuration.",
"",
&configCommand)

if err != nil {
fmt.Println(err)
}
}
@@ -17,7 +17,7 @@ type DumpRawCommand struct {
var dumpRawCommand DumpRawCommand

func (x *DumpRawCommand) Execute(args []string) error {
bus := pmb.GetPMB(globalOptions.Primary)
bus := pmb.GetPMB(globalOptions.Broker)

id := pmb.GenerateRandomID("dumpRaw")

@@ -52,7 +52,7 @@ func (x *IntroducerCommand) Execute(args []string) error {
}

logrus.Debugf("calling GetPMB")
bus := pmb.GetPMB(globalOptions.Primary)
bus := pmb.GetPMB(globalOptions.Broker)

var name string
if len(introducerCommand.Name) > 0 {
@@ -170,7 +170,6 @@ func runIntroducer(bus *pmb.PMB, conn *pmb.Connection, level float64) error {
}
conn.Out <- pmb.Message{Contents: data}
} else if message.Contents["type"].(string) == "RequestAuth" {
// copy primary uri to clipboard
copyToClipboard(strings.Join(conn.Keys, ","))
displayNotice("Copied key.", false)
} else if message.Contents["type"].(string) == "Notification" {

0 comments on commit 6d963bd

Please sign in to comment.
You can’t perform that action at this time.