moonmath/moonmath.go

85 lines
1.7 KiB
Go

package main
import (
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"strings"
"code.humancabbage.net/sam/moonmath/coindesk"
"code.humancabbage.net/sam/moonmath/config"
"code.humancabbage.net/sam/moonmath/tui"
"github.com/alecthomas/kong"
tea "github.com/charmbracelet/bubbletea"
)
var CLI struct {
Asset []string `short:"a" default:"BTC" help:"Asset(s) to project."`
ConfigFile string `short:"c" help:"Path to YAML configuration file."`
Perf bool `help:"Display internal performance stats."`
}
func main() {
logFile := setupLogging()
defer func() {
_ = logFile.Close()
}()
ctx := kong.Parse(&CLI)
if ctx.Error != nil {
fail(ctx.Error)
}
allCfg, err := config.Load(CLI.ConfigFile)
if err != nil {
fail(err)
}
var assets []coindesk.Asset
for i := range CLI.Asset {
asset := coindesk.Asset(strings.ToUpper(CLI.Asset[i]))
assets = append(assets, asset)
}
m := tui.New(assets, allCfg, CLI.Perf)
p := tea.NewProgram(m,
tea.WithAltScreen(),
tea.WithFPS(30),
)
if _, err := p.Run(); err != nil {
fail(err)
}
}
func setupLogging() io.Closer {
homePath, err := os.UserHomeDir()
if err != nil {
panic(err)
}
programConfigPath := filepath.Join(homePath, ".moonmath")
err = os.MkdirAll(programConfigPath, 0755)
if err != nil {
panic(err)
}
errLogPath := filepath.Join(programConfigPath, "errors.log")
errLogFile, err := os.OpenFile(
errLogPath,
os.O_CREATE|os.O_APPEND|os.O_WRONLY,
0600,
)
if err != nil {
panic(err)
}
slog.SetDefault(slog.New(
slog.NewTextHandler(errLogFile, &slog.HandlerOptions{
Level: slog.LevelError,
})))
return errLogFile
}
func fail(err error) {
fmt.Printf("program error: %v\n", err)
os.Exit(1)
}