You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
diary/cmd/util.go

138 lines
2.8 KiB

package cmd
import (
"errors"
"fmt"
"git.nagee.dev/isthisnagee/diary/model"
markdown "github.com/MichaelMure/go-term-markdown"
"github.com/fatih/color"
3 years ago
"github.com/spf13/cobra"
"github.com/spf13/viper"
"log"
"os"
"os/exec"
"path"
"strconv"
"time"
)
3 years ago
type Cfg struct {
DbPath string
}
3 years ago
type TApp struct {
Db *model.App
Cfg *Cfg
}
var App *TApp
3 years ago
// var App *model.App
// initConfig reads in config file and ENV variables if set.
func initConfig() Cfg {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Search config in home directory with name ".diary" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("toml")
viper.SetConfigName(".diary")
}
3 years ago
var db_path = path.Join(home, ".diary.sql")
viper.SetDefault("db_path", db_path)
viper.AutomaticEnv() // read in environment variables that match
3 years ago
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
}
return Cfg{db_path}
}
func InitApp() {
var cfg = initConfig()
if _, err := os.Stat(cfg.DbPath); errors.Is(err, os.ErrNotExist) {
_, err := os.Create(cfg.DbPath)
if err != nil {
log.Fatal(err.Error())
}
}
3 years ago
var app = model.NewApp(cfg.DbPath)
App = &TApp{&app, &cfg}
}
var fmt_str = "%-10s %-20s %s\n"
var time_fmt_str = "2006/01/02 03:04pm"
func PrintEntryHeader() {
fmt.Printf(
fmt_str+"\n", "Id", "Created time", "Title",
)
}
func PrintEntry(entry *model.DiaryEntry) {
created_time := time.Unix(entry.CreatedAt, 0).Format(time_fmt_str)
titleColor := color.New(color.FgCyan).Add(color.Underline).SprintFunc()
fmt.Printf(
fmt_str, strconv.FormatInt(entry.Id, 10), created_time, titleColor(entry.Title),
)
}
func PrintEntries(entries []*model.DiaryEntry) {
PrintEntryHeader()
for _, entry := range entries {
PrintEntry(entry)
}
}
func PrintNote(note *model.DiaryEntryNote, add_tail bool) {
created_time := time.Unix(note.CreatedAt, 0).Format(time_fmt_str)
fmt.Println("---note ( id:", note.Id, ")", created_time)
fmt.Println()
body := markdown.Render(note.Body, 80, 3)
fmt.Println(string(body))
if add_tail {
fmt.Println("---")
}
}
func PrintNotes(notes []*model.DiaryEntryNote) {
for idx, entry := range notes {
var is_last = idx == len(notes)-1
PrintNote(entry, is_last)
}
}
func OpenEditor(fpath string) error {
var editor = os.Getenv("EDITOR")
if editor == "" {
editor = "nano"
}
editor_cmd := exec.Command(editor, fpath)
editor_cmd.Stdin = os.Stdin
editor_cmd.Stdout = os.Stdout
editor_cmd.Stderr = os.Stderr
err := editor_cmd.Start()
if err != nil {
return err
}
err = editor_cmd.Wait()
if err != nil {
return err
}
return nil
}