This repository has been archived on 2023-12-27. You can view files and clone it, but cannot push or open issues or pull requests.
Files
ledger-tui/cmd/ledger-tui/ledger-tui.go

88 lines
2.0 KiB
Go

package main
import (
"errors"
"fmt"
"io"
"log"
"os"
tea "github.com/charmbracelet/bubbletea"
"github.com/spf13/cobra"
"github.com/tgrosinger/ledger-tui/pkg/tui/commands/add"
"github.com/tgrosinger/ledger-tui/pkg/tui/commands/license"
)
var rootCmd = &cobra.Command{
Use: "ledger-tui",
Short: "An interactive terminal UI for ledger",
PersistentPreRun: configureLogging,
PersistentPostRun: loggingCleanup,
}
var debugLogging bool
var debugLoggingFile *os.File
var ledgerFilePath string
func configureLogging(_ *cobra.Command, _ []string) {
if debugLogging {
var err error
debugLoggingFile, err = tea.LogToFile("debug.log", "debug")
if err != nil {
fmt.Println("fatal:", err)
os.Exit(1)
}
} else {
log.SetOutput(io.Discard)
}
}
func loggingCleanup(_ *cobra.Command, _ []string) {
if debugLoggingFile != nil {
debugLoggingFile.Close()
debugLoggingFile = nil
}
}
func verifyLedgerFile() {
f, err := rootCmd.Flags().GetString("file")
if err != nil {
fmt.Fprintln(os.Stderr, "Error loading value of the file argument: "+err.Error())
os.Exit(1)
}
if f == "" {
var ok bool
f, ok = os.LookupEnv("LEDGER_FILE")
if !ok {
fmt.Fprintln(os.Stderr,
"You must specify the -f option or set the LEDGER_FILE environment variable")
fmt.Fprintln(os.Stderr, "Try 'ledger-tui --help' for more information.")
os.Exit(1)
}
rootCmd.Flags().Set("file", f)
}
if _, err := os.Stat(f); errors.Is(err, os.ErrNotExist) {
fmt.Fprintln(os.Stderr, "Ledger file specified does not exist.")
os.Exit(1)
}
}
func main() {
rootCmd.PersistentFlags().BoolVar(&debugLogging, "debug", false,
"Output debug logs to debug.log file")
rootCmd.PersistentFlags().StringVarP(&ledgerFilePath, "file", "f", "",
"Path to the ledger file that should be loaded. If empty, the value "+
"from the LEDGER_FILE environment variable is used.")
cobra.OnInitialize(verifyLedgerFile)
rootCmd.AddCommand(add.AddCmd)
rootCmd.AddCommand(license.LicenseCmd)
rootCmd.Execute()
}