underbbs/cli/cli.go

116 lines
2.4 KiB
Go

package cli
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"forge.lightcrystal.systems/lightcrystal/underbbs/adapter"
"forge.lightcrystal.systems/lightcrystal/underbbs/models"
)
func GetConfigLocation() string {
home := os.Getenv("HOME")
appdata := os.Getenv("APPDATA")
switch runtime.GOOS {
case "windows":
return filepath.Join(appdata, "underbbs")
case "darwin":
return filepath.Join(home, "Library", "Application Support", "underbbs")
case "plan9":
return filepath.Join(home, "lib", "underbbs")
default:
return filepath.Join(home, ".config", "underbbs")
}
}
func EnsureConfigLocationExists() {
fileInfo, err := os.Stat(GetConfigLocation())
if os.IsNotExist(err) {
os.MkdirAll(GetConfigLocation(), os.ModePerm)
} else if !fileInfo.IsDir() {
panic("Config location is not a directory!")
}
}
func Process(args ...string) error {
// allocate storage for the settings array
var settings []models.Settings
var s *models.Settings
if len(args) < 3 {
return errors.New("CLI requires at least 3 args: ADAPTER ACTION DATA...")
}
EnsureConfigLocationExists()
cfgdir := GetConfigLocation()
// get adapter from first arg
adapterName := args[0]
args = args[1:]
// get config from config fle based on adapter
content, err := ioutil.ReadFile(filepath.Join(cfgdir, "config.json"))
if err != nil {
return err
}
err = json.Unmarshal(content, &settings)
if err != nil {
return err
}
for _, x := range settings {
if x.Nickname == adapterName {
s = &x
break
}
}
if s == nil {
return errors.New("given adapter " + adapterName + " is not in the config file")
}
// instantiate adapter with config
var a adapter.Adapter
switch s.Protocol {
case "nostr":
a = &adapter.NostrAdapter{}
case "mastodon":
a = &adapter.MastoAdapter{}
case "misskey":
a = &adapter.MisskeyAdapter{}
case "honk":
a = &adapter.HonkAdapter{}
default:
break
}
a.Init(*s, nil)
// process remaining args and execute
switch args[0] {
case "fetch":
a.Fetch(args[1], args[2:])
case "do":
data := map[string]string{}
for _, a := range args[2:] {
if !strings.Contains(a, "=") {
return errors.New("args are in the form KEY=VALUE")
} else {
aa := strings.Split(a, "=")
k := aa[0]
v := strings.Join(aa[1:], "=")
data[k] = v
}
}
a.Do(args[1], data)
default:
log.Print(args)
}
return nil
}