fortlit/main.go

90 lines
1.5 KiB
Go
Raw Normal View History

2020-01-07 11:45:10 +01:00
package main
import (
"encoding/json"
2020-02-12 11:14:56 +01:00
"flag"
2020-01-07 11:45:10 +01:00
"fmt"
"math/rand"
2020-02-12 11:14:56 +01:00
"os"
"regexp"
2020-01-07 11:45:10 +01:00
"time"
2020-02-12 11:14:56 +01:00
"github.com/xsteadfastx/fortlit-go/data"
2020-01-07 11:45:10 +01:00
)
2020-02-12 11:14:56 +01:00
//go:generate go-bindata -pkg data -o ./data/bindata.go litdata.json
//go:generate go fmt ./data/bindata.go
var version = "development"
2020-01-07 11:45:10 +01:00
const (
Purple = "\033[1;34m%s\033[0m"
Teal = "\033[1;36m%s\033[0m"
)
type Quote struct {
Author string `json:"author"`
Book string `json:"book"`
Text string `json:"text"`
Time string `json:"time"`
}
func get(qs map[string][]Quote, t string) Quote {
quote := Quote{}
if _, exists := qs[t]; exists {
2020-02-12 11:14:56 +01:00
//nolint: gomnd
2020-01-07 11:45:10 +01:00
if len(qs[t]) != 1 {
rand.Seed(time.Now().Unix())
quote = qs[t][rand.Intn(len(qs[t]))]
} else {
quote = qs[t][0]
2020-01-07 11:45:10 +01:00
}
}
return quote
}
func open(as string) []byte {
2020-02-12 11:14:56 +01:00
data, err := data.Asset(as)
2020-01-07 11:45:10 +01:00
if err != nil {
panic(err)
}
return data
}
func (q *Quote) decorate() string {
2020-02-12 11:14:56 +01:00
m := regexp.MustCompile(fmt.Sprintf("(?i)(%s)", q.Time))
text := m.ReplaceAllString(q.Text, fmt.Sprintf(Purple, "$1"))
2020-01-07 11:45:10 +01:00
return fmt.Sprintf("\n%s\n\n - %s, %s\n", text, q.Book, fmt.Sprintf(Teal, q.Author))
}
func main() {
2020-02-12 11:14:56 +01:00
fversion := flag.Bool("version", false, "Shows version.")
flag.Parse()
if *fversion {
fmt.Printf("Version: %s", version)
os.Exit(0)
}
2020-01-07 11:45:10 +01:00
data := open("litdata.json")
qs := make(map[string][]Quote)
2020-02-12 11:14:56 +01:00
2020-01-07 11:45:10 +01:00
if err := json.Unmarshal(data, &qs); err != nil {
panic(err)
}
2020-02-12 11:14:56 +01:00
2020-01-07 11:45:10 +01:00
now := time.Now()
t := fmt.Sprintf("%02d:%02d", now.Hour(), now.Minute())
quote := get(qs, t)
2020-02-12 11:14:56 +01:00
2020-01-07 11:45:10 +01:00
if quote != (Quote{}) {
fmt.Println(quote.decorate())
}
}