underbbs/cli/cli.go

117 lines
2.4 KiB
Go
Raw Permalink Normal View History

2024-10-02 01:49:13 +00:00
package cli
import (
"encoding/json"
2024-10-03 00:54:14 +00:00
"errors"
2024-10-02 01:49:13 +00:00
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"strings"
2024-10-02 01:49:13 +00:00
"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!")
}
}
2024-10-02 01:49:13 +00:00
func Process(args ...string) error {
// allocate storage for the settings array
var settings []models.Settings
2024-10-03 00:54:14 +00:00
var s *models.Settings
if len(args) < 3 {
return errors.New("CLI requires at least 3 args: ADAPTER ACTION DATA...")
}
2024-10-02 01:49:13 +00:00
EnsureConfigLocationExists()
cfgdir := GetConfigLocation()
2024-10-02 01:49:13 +00:00
// 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"))
2024-10-02 01:49:13 +00:00
if err != nil {
return err
}
err = json.Unmarshal(content, &settings)
2024-10-02 01:49:13 +00:00
if err != nil {
return err
}
for _, x := range settings {
if x.Nickname == adapterName {
2024-10-03 00:54:14 +00:00
s = &x
2024-10-02 01:49:13 +00:00
break
}
}
2024-10-03 00:54:14 +00:00
if s == nil {
return errors.New("given adapter " + adapterName + " is not in the config file")
}
2024-10-02 01:49:13 +00:00
// 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{}
2024-10-02 01:49:13 +00:00
default:
break
}
2024-10-03 00:54:14 +00:00
a.Init(*s, nil)
2024-10-02 01:49:13 +00:00
// process remaining args and execute
switch args[0] {
2024-10-03 00:54:14 +00:00
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)
2024-10-02 01:49:13 +00:00
default:
log.Print(args)
}
return nil
}