Remove LogMessage and replace with charmbraclet/log

This commit is contained in:
Florian Baumann 2023-09-14 16:53:08 +02:00
parent 71259001d3
commit 135f4a93a5
15 changed files with 110 additions and 91 deletions

1
go.mod
View File

@ -4,6 +4,7 @@ go 1.14
require ( require (
github.com/bytedance/sonic v1.10.0 // indirect github.com/bytedance/sonic v1.10.0 // indirect
github.com/charmbracelet/log v0.2.4 // indirect
github.com/chzyer/readline v1.5.1 github.com/chzyer/readline v1.5.1
github.com/gin-gonic/gin v1.9.1 github.com/gin-gonic/gin v1.9.1
github.com/go-playground/validator/v10 v10.15.3 // indirect github.com/go-playground/validator/v10 v10.15.3 // indirect

18
go.sum
View File

@ -1,8 +1,14 @@
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
github.com/bytedance/sonic v1.10.0 h1:qtNZduETEIWJVIyDl01BeNxur2rW9OwTQ/yBqFRkKEk= github.com/bytedance/sonic v1.10.0 h1:qtNZduETEIWJVIyDl01BeNxur2rW9OwTQ/yBqFRkKEk=
github.com/bytedance/sonic v1.10.0/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= github.com/bytedance/sonic v1.10.0/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
github.com/charmbracelet/lipgloss v0.8.0 h1:IS00fk4XAHcf8uZKc3eHeMUTCxUH6NkaTrdyCQk84RU=
github.com/charmbracelet/lipgloss v0.8.0/go.mod h1:p4eYUZZJ/0oXTuCQKFF8mqyKCz0ja6y+7DniDDw5KKU=
github.com/charmbracelet/log v0.2.4 h1:3pKtq5/Y5QMKtcZt7kDqD1p9w7lICzHYQACBFY4ocHA=
github.com/charmbracelet/log v0.2.4/go.mod h1:nQGK8tvc4pS9cvVEH/pWJiZ50eUq1aoXUOjGpXvdD0k=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=
@ -26,6 +32,8 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@ -69,9 +77,13 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
@ -87,12 +99,17 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=
github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
@ -175,6 +192,7 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

View File

@ -2,7 +2,6 @@ package serra
import ( import (
"fmt" "fmt"
"os"
"strconv" "strconv"
"strings" "strings"
@ -37,9 +36,9 @@ var addCmd = &cobra.Command{
} }
func addCardsInteractive(unique bool, set string) { func addCardsInteractive(unique bool, set string) {
l := Logger()
if len(set) == 0 { if len(set) == 0 {
LogMessage("Error: --set must be given in interactive mode", "red") l.Fatal("Option --set <set> must be given in interactive mode")
os.Exit(1)
} }
rl, err := readline.New(fmt.Sprintf("%s> ", set)) rl, err := readline.New(fmt.Sprintf("%s> ", set))
@ -84,6 +83,7 @@ func addCardsInteractive(unique bool, set string) {
func addCards(cards []string, unique bool, count int64) error { func addCards(cards []string, unique bool, count int64) error {
client := storageConnect() client := storageConnect()
coll := &Collection{client.Database("serra").Collection("cards")} coll := &Collection{client.Database("serra").Collection("cards")}
l := Logger()
defer storageDisconnect(client) defer storageDisconnect(client)
// Loop over different cards // Loop over different cards
@ -91,7 +91,7 @@ func addCards(cards []string, unique bool, count int64) error {
// Extract collector number and set name from card input & trim any leading 0 from collector number // Extract collector number and set name from card input & trim any leading 0 from collector number
if !strings.Contains(card, "/") { if !strings.Contains(card, "/") {
LogMessage(fmt.Sprintf("Invalid card format %s. Needs to be set/collector number i.e. \"usg/13\"", card), "red") l.Errorf("Invalid card format %s. Needs to be set/collector number i.e. \"usg/13\"", card)
continue continue
} }
@ -99,14 +99,14 @@ func addCards(cards []string, unique bool, count int64) error {
collectorNumber := strings.TrimLeft(strings.Split(card, "/")[1], "0") collectorNumber := strings.TrimLeft(strings.Split(card, "/")[1], "0")
if collectorNumber == "" { if collectorNumber == "" {
LogMessage(fmt.Sprintf("Invalid card format %s. Needs to be set/collector number i.e. \"usg/13\"", card), "red") l.Errorf("Invalid card format %s. Needs to be set/collector number i.e. \"usg/13\"", card)
continue continue
} }
// Check if card is already in collection // Check if card is already in collection
co, err := coll.storageFind(bson.D{{"set", setName}, {"collectornumber", collectorNumber}}, bson.D{}, 0, 0) co, err := coll.storageFind(bson.D{{"set", setName}, {"collectornumber", collectorNumber}}, bson.D{}, 0, 0)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("%v", err), "red") l.Error(err)
continue continue
} }
@ -114,7 +114,7 @@ func addCards(cards []string, unique bool, count int64) error {
c := co[0] c := co[0]
if unique { if unique {
LogMessage(fmt.Sprintf("Not adding \"%s\" (%s, %.2f%s) to Collection because it already exists.", c.Name, c.Rarity, c.getValue(foil), getCurrency()), "red") l.Warnf("Not adding \"%s\" (%s, %.2f%s) because it already exists.", c.Name, c.Rarity, c.getValue(foil), getCurrency())
continue continue
} }
@ -127,14 +127,14 @@ func addCards(cards []string, unique bool, count int64) error {
total = c.SerraCount + count total = c.SerraCount + count
} }
// Give feedback of successfully added card // Give feedback of successfully added card
LogMessage(fmt.Sprintf("%dx \"%s\" (%s, %.2f%s) added to Collection.", total, c.Name, c.Rarity, c.getValue(foil), getCurrency()), "green") l.Infof("%dx \"%s\" (%s, %.2f%s) added.", total, c.Name, c.Rarity, c.getValue(foil), getCurrency())
// If card is not already in collection, fetching from scyfall // If card is not already in collection, fetching from scyfall
} else { } else {
// Fetch card from scryfall // Fetch card from scryfall
c, err := fetchCard(setName, collectorNumber) c, err := fetchCard(setName, collectorNumber)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("%v", err), "red") l.Warn(err)
continue continue
} }
@ -149,12 +149,12 @@ func addCards(cards []string, unique bool, count int64) error {
} }
err = coll.storageAdd(c) err = coll.storageAdd(c)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("%v", err), "red") l.Warn(err)
continue continue
} }
// Give feedback of successfully added card // Give feedback of successfully added card
LogMessage(fmt.Sprintf("%dx \"%s\" (%s, %.2f%s) added to Collection.", total, c.Name, c.Rarity, c.getValue(foil), getCurrency()), "green") l.Infof("%dx \"%s\" (%s, %.2f%s) added to Collection.", total, c.Name, c.Rarity, c.getValue(foil), getCurrency())
} }
} }
storageDisconnect(client) storageDisconnect(client)

View File

@ -45,11 +45,12 @@ otherwise you'll get a list of cards as a search result.`,
func ShowCard(cardids []string) { func ShowCard(cardids []string) {
client := storageConnect() client := storageConnect()
coll := &Collection{client.Database("serra").Collection("cards")} coll := &Collection{client.Database("serra").Collection("cards")}
l := Logger()
defer storageDisconnect(client) defer storageDisconnect(client)
for _, v := range cardids { for _, v := range cardids {
if len(strings.Split(v, "/")) < 2 || strings.Split(v, "/")[1] == "" { if len(strings.Split(v, "/")) < 2 || strings.Split(v, "/")[1] == "" {
LogMessage(fmt.Sprintf("Invalid card %s", v), "red") l.Warnf("Invalid card %s", v)
continue continue
} }

View File

@ -30,6 +30,7 @@ func checkCards(cards []string, detail bool) error {
client := storageConnect() client := storageConnect()
coll := &Collection{client.Database("serra").Collection("cards")} coll := &Collection{client.Database("serra").Collection("cards")}
defer storageDisconnect(client) defer storageDisconnect(client)
l := Logger()
// Loop over different cards // Loop over different cards
for _, card := range cards { for _, card := range cards {
@ -41,23 +42,23 @@ func checkCards(cards []string, detail bool) error {
// Check if card is already in collection // Check if card is already in collection
co, err := coll.storageFind(bson.D{{"set", setName}, {"collectornumber", collectorNumber}}, bson.D{}, 0, 0) co, err := coll.storageFind(bson.D{{"set", setName}, {"collectornumber", collectorNumber}}, bson.D{}, 0, 0)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("%v", err), "red") l.Warn(err)
continue continue
} }
// If Card is in collection, print yes. // If Card is in collection, print yes.
if len(co) >= 1 { if len(co) >= 1 {
c := co[0] c := co[0]
LogMessage(fmt.Sprintf("PRESENT %s \"%s\" (%s, %.2f%s)", card, c.Name, c.Rarity, c.getValue(foil), getCurrency()), "green") fmt.Sprintf("PRESENT %s \"%s\" (%s, %.2f%s)", card, c.Name, c.Rarity, c.getValue(foil), getCurrency())
continue continue
} else { } else {
if detail { if detail {
// fetch card from scyrfall if --detail was given // fetch card from scyrfall if --detail was given
c, _ := fetchCard(setName, collectorNumber) c, _ := fetchCard(setName, collectorNumber)
LogMessage(fmt.Sprintf("MISSING %s \"%s\" (%s, %.2f%s)", card, c.Name, c.Rarity, c.getValue(foil), getCurrency()), "red") fmt.Sprintf("MISSING %s \"%s\" (%s, %.2f%s)", card, c.Name, c.Rarity, c.getValue(foil), getCurrency())
} else { } else {
// Just print, the card name was not found // Just print, the card name was not found
LogMessage(fmt.Sprintf("MISSING \"%s\"", card), "red") fmt.Sprintf("MISSING \"%s\"", card)
} }
} }
} }

View File

@ -1,7 +1,6 @@
package serra package serra
import ( import (
"log"
"os" "os"
) )
@ -9,9 +8,10 @@ const EUR = "€"
const USD = "$" const USD = "$"
func getMongoDBURI() string { func getMongoDBURI() string {
l := Logger()
uri := os.Getenv("MONGODB_URI") uri := os.Getenv("MONGODB_URI")
if uri == "" { if uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/#environment-variable") l.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/#environment-variable")
} }
return uri return uri
@ -20,13 +20,14 @@ func getMongoDBURI() string {
// Returns configured human readable name for // Returns configured human readable name for
// the configured currency of the user // the configured currency of the user
func getCurrency() string { func getCurrency() string {
l := Logger()
switch os.Getenv("SERRA_CURRENCY") { switch os.Getenv("SERRA_CURRENCY") {
case "EUR": case "EUR":
return EUR return EUR
case "USD": case "USD":
return USD return USD
default: default:
LogMessage("Warning: You did not configure SERRA_CURRENCY. Assuming \"USD\"", "yellow") l.Warn("Warning: You did not configure SERRA_CURRENCY. Assuming \"USD\"")
return "$" return "$"
} }
} }

View File

@ -4,10 +4,12 @@ import (
"errors" "errors"
"fmt" "fmt"
"math" "math"
"os"
"strconv" "strconv"
"time" "time"
"unicode" "unicode"
"github.com/charmbracelet/log"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/bson/primitive"
) )
@ -16,6 +18,29 @@ type Rarities struct {
Rares, Uncommons, Commons, Mythics float64 Rares, Uncommons, Commons, Mythics float64
} }
var (
Icon = "\U0001F9D9\U0001F3FC"
Reset = "\033[0m"
Background = "\033[38;5;59m"
CurrentLine = "\033[38;5;60m"
Foreground = "\033[38;5;231m"
Comment = "\033[38;5;103m"
Cyan = "\033[38;5;159m"
Green = "\033[38;5;120m"
Orange = "\033[38;5;222m"
Pink = "\033[38;5;212m"
Purple = "\033[38;5;183m"
Red = "\033[38;5;210m"
Yellow = "\033[38;5;229m"
)
func Logger() *log.Logger {
l := log.New(os.Stderr)
l.SetReportTimestamp(false)
return l
}
func modifyCardCount(coll *Collection, c *Card, amount int64, foil bool) error { func modifyCardCount(coll *Collection, c *Card, amount int64, foil bool) error {
// find already existing card // find already existing card
@ -47,7 +72,7 @@ func modifyCardCount(coll *Collection, c *Card, amount int64, foil bool) error {
} else { } else {
total = storedCard.SerraCount + amount total = storedCard.SerraCount + amount
} }
LogMessage(fmt.Sprintf("Updating Card \"%s\" amount to %d", storedCard.Name, total), "purple") fmt.Sprintf("Updating Card \"%s\" amount to %d", storedCard.Name, total)
return nil return nil
} }

View File

@ -23,12 +23,13 @@ cards you dont own (yet) :)`,
RunE: func(cmd *cobra.Command, setName []string) error { RunE: func(cmd *cobra.Command, setName []string) error {
client := storageConnect() client := storageConnect()
coll := &Collection{client.Database("serra").Collection("cards")} coll := &Collection{client.Database("serra").Collection("cards")}
l := Logger()
defer storageDisconnect(client) defer storageDisconnect(client)
// fetch all cards in set // fetch all cards in set
cards, err := coll.storageFind(bson.D{{"set", setName[0]}}, bson.D{{"collectornumber", 1}}, 0, 0) cards, err := coll.storageFind(bson.D{{"set", setName[0]}}, bson.D{{"collectornumber", 1}}, 0, 0)
if (err != nil) || len(cards) == 0 { if (err != nil) || len(cards) == 0 {
LogMessage(fmt.Sprintf("Error: Set %s not found or no card in your collection.", setName[0]), "red") l.Errorf("Set %s not found or no card in your collection.", setName[0])
return err return err
} }
@ -37,7 +38,7 @@ cards you dont own (yet) :)`,
sets, _ := setcoll.storageFindSet(bson.D{{"code", setName[0]}}, bson.D{{"_id", 1}}) sets, _ := setcoll.storageFindSet(bson.D{{"code", setName[0]}}, bson.D{{"_id", 1}})
set := sets[0] set := sets[0]
LogMessage(fmt.Sprintf("Missing cards in %s", sets[0].Name), "green") fmt.Printf("Missing cards in %s", sets[0].Name)
// generate set with all setnumbers // generate set with all setnumbers
var ( var (

View File

@ -2,7 +2,6 @@ package serra
import ( import (
"fmt" "fmt"
"os"
"strings" "strings"
"github.com/chzyer/readline" "github.com/chzyer/readline"
@ -36,9 +35,10 @@ var removeCmd = &cobra.Command{
} }
func removeCardsInteractive(unique bool, set string) { func removeCardsInteractive(unique bool, set string) {
l := Logger()
if len(set) == 0 { if len(set) == 0 {
LogMessage("Error: --set must be given in interactive mode", "red") l.Fatal("Option --set must be given in interactive mode")
os.Exit(1)
} }
rl, err := readline.New(fmt.Sprintf("%s> ", set)) rl, err := readline.New(fmt.Sprintf("%s> ", set))
@ -66,6 +66,7 @@ func removeCards(cards []string, count int64) error {
// Connect to the DB & load the collection // Connect to the DB & load the collection
client := storageConnect() client := storageConnect()
coll := &Collection{client.Database("serra").Collection("cards")} coll := &Collection{client.Database("serra").Collection("cards")}
l := Logger()
defer storageDisconnect(client) defer storageDisconnect(client)
// Loop over different cards // Loop over different cards
@ -77,23 +78,23 @@ func removeCards(cards []string, count int64) error {
// Fetch card from scryfall // Fetch card from scryfall
c, err := findCardByCollectorNumber(coll, setName, collectorNumber) c, err := findCardByCollectorNumber(coll, setName, collectorNumber)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("%v", err), "red") l.Error(err)
continue continue
} }
if foil && c.SerraCountFoil < 1 { if foil && c.SerraCountFoil < 1 {
LogMessage(fmt.Sprintf("Error: No Foil \"%s\" in the Collection.", c.Name), "red") l.Errorf("No foil \"%s\" in the collection", c.Name)
continue continue
} }
if !foil && c.SerraCount < 1 { if !foil && c.SerraCount < 1 {
LogMessage(fmt.Sprintf("Error: No normal \"%s\" in the Collection.", c.Name), "red") l.Errorf("No normal \"%s\" in the collection", c.Name)
continue continue
} }
if foil && c.SerraCountFoil == 1 && c.SerraCount == 0 || !foil && c.SerraCount == 1 && c.SerraCountFoil == 0 { if foil && c.SerraCountFoil == 1 && c.SerraCount == 0 || !foil && c.SerraCount == 1 && c.SerraCountFoil == 0 {
coll.storageRemove(bson.M{"_id": c.ID}) coll.storageRemove(bson.M{"_id": c.ID})
LogMessage(fmt.Sprintf("\"%s\" (%.2f%s) removed from the Collection.", c.Name, c.getValue(foil), getCurrency()), "green") l.Infof("\"%s\" (%.2f%s) removed", c.Name, c.getValue(foil), getCurrency())
} else { } else {
modifyCardCount(coll, c, -count, foil) modifyCardCount(coll, c, -count, foil)
} }

View File

@ -1,9 +1,6 @@
package serra package serra
import ( import (
"fmt"
"os"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -37,8 +34,9 @@ var rootCmd = &cobra.Command{
} }
func Execute() { func Execute() {
l := Logger()
if err := rootCmd.Execute(); err != nil { if err := rootCmd.Execute(); err != nil {
fmt.Println(err) l.Fatal(err)
os.Exit(1)
} }
} }

View File

@ -88,6 +88,7 @@ func ShowSet(setname string) error {
client := storageConnect() client := storageConnect()
coll := &Collection{client.Database("serra").Collection("cards")} coll := &Collection{client.Database("serra").Collection("cards")}
l := Logger()
defer storageDisconnect(client) defer storageDisconnect(client)
// fetch all cards in set ordered by currently used currency // fetch all cards in set ordered by currently used currency
@ -97,7 +98,7 @@ func ShowSet(setname string) error {
} }
cards, err := coll.storageFind(bson.D{{"set", setname}}, cardSortCurrency, 0, 0) cards, err := coll.storageFind(bson.D{{"set", setname}}, cardSortCurrency, 0, 0)
if (err != nil) || len(cards) == 0 { if (err != nil) || len(cards) == 0 {
LogMessage(fmt.Sprintf("Error: Set %s not found or no card in your collection.", setname), "red") l.Errorf("Set %s not found or no card in your collection.", setname)
return err return err
} }
@ -142,7 +143,7 @@ func ShowSet(setname string) error {
ri := convertRarities(rar) ri := convertRarities(rar)
LogMessage(sets[0].Name, "green") fmt.Printf(sets[0].Name)
fmt.Printf("Released: %s\n", sets[0].ReleasedAt) fmt.Printf("Released: %s\n", sets[0].ReleasedAt)
fmt.Printf("Set Cards: %d/%d\n", len(cards), sets[0].CardCount) fmt.Printf("Set Cards: %d/%d\n", len(cards), sets[0].CardCount)
fmt.Printf("Total Cards: %.0f\n", stats[0]["count"]) fmt.Printf("Total Cards: %.0f\n", stats[0]["count"])
@ -150,12 +151,12 @@ func ShowSet(setname string) error {
normalValue, err := getFloat64(stats[0]["value"]) normalValue, err := getFloat64(stats[0]["value"])
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Error: %v", err), "red") l.Error(err)
normalValue = 0 normalValue = 0
} }
foilValue, err := getFloat64(stats[0]["value_foil"]) foilValue, err := getFloat64(stats[0]["value_foil"])
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Error: %v", err), "red") l.Error(err)
foilValue = 0 foilValue = 0
} }
totalValue := normalValue + foilValue totalValue := normalValue + foilValue

View File

@ -23,6 +23,7 @@ var statsCmd = &cobra.Command{
client := storageConnect() client := storageConnect()
coll := &Collection{client.Database("serra").Collection("cards")} coll := &Collection{client.Database("serra").Collection("cards")}
totalcoll := &Collection{client.Database("serra").Collection("total")} totalcoll := &Collection{client.Database("serra").Collection("total")}
l := Logger()
defer storageDisconnect(client) defer storageDisconnect(client)
// Colors // Colors
@ -149,12 +150,12 @@ var statsCmd = &cobra.Command{
fmt.Printf("\n%sTotal Value%s\n", Green, Reset) fmt.Printf("\n%sTotal Value%s\n", Green, Reset)
normalValue, err := getFloat64(stats[0]["value"]) normalValue, err := getFloat64(stats[0]["value"])
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Error: %v", err), "red") l.Error(err)
normalValue = 0 normalValue = 0
} }
foilValue, err := getFloat64(stats[0]["value_foil"]) foilValue, err := getFloat64(stats[0]["value_foil"])
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Error: %v", err), "red") l.Error(err)
foilValue = 0 foilValue = 0
} }
totalValue := normalValue + foilValue totalValue := normalValue + foilValue

View File

@ -3,7 +3,6 @@ package serra
import ( import (
"context" "context"
"fmt" "fmt"
"log"
"os" "os"
"time" "time"
@ -46,12 +45,12 @@ func getCurrencyField(foil bool) string {
} }
func storageConnect() *mongo.Client { func storageConnect() *mongo.Client {
l := Logger()
uri := getMongoDBURI() uri := getMongoDBURI()
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri)) client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Could not connect to mongodb at %s", uri), "red") l.Fatalf("Could not connect to mongodb at %s", uri)
os.Exit(1)
} }
return client return client
@ -104,14 +103,15 @@ func (coll Collection) storageAddTotal(p PriceEntry) error {
func (coll Collection) storageFind(filter, sort bson.D, skip, limit int64) ([]Card, error) { func (coll Collection) storageFind(filter, sort bson.D, skip, limit int64) ([]Card, error) {
opts := options.Find().SetSort(sort).SetSkip(skip).SetLimit(limit) opts := options.Find().SetSort(sort).SetSkip(skip).SetLimit(limit)
cursor, err := coll.Find(context.TODO(), filter, opts) cursor, err := coll.Find(context.TODO(), filter, opts)
l := Logger()
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Could not query data due to connection errors to database: %s", err.Error()), "red") l.Fatalf("Could not query data due to connection errors to database: %s", err.Error())
os.Exit(1)
} }
var results []Card var results []Card
if err = cursor.All(context.TODO(), &results); err != nil { if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatal(err) l.Fatal(err)
return []Card{}, err return []Card{}, err
} }
return results, nil return results, nil
@ -119,17 +119,17 @@ func (coll Collection) storageFind(filter, sort bson.D, skip, limit int64) ([]Ca
} }
func (coll Collection) storageFindSet(filter, sort bson.D) ([]Set, error) { func (coll Collection) storageFindSet(filter, sort bson.D) ([]Set, error) {
l := Logger()
opts := options.Find().SetSort(sort) opts := options.Find().SetSort(sort)
cursor, err := coll.Find(context.TODO(), filter, opts) cursor, err := coll.Find(context.TODO(), filter, opts)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Could not query set data due to connection errors to database: %s", err.Error()), "red") l.Fatalf("Could not query set data due to connection errors to database: %s", err.Error())
os.Exit(1)
} }
var results []Set var results []Set
if err = cursor.All(context.TODO(), &results); err != nil { if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatal(err) l.Fatal(err)
return []Set{}, err return []Set{}, err
} }
@ -138,27 +138,29 @@ func (coll Collection) storageFindSet(filter, sort bson.D) ([]Set, error) {
func (coll Collection) storageFindTotal() (Total, error) { func (coll Collection) storageFindTotal() (Total, error) {
var total Total var total Total
l := Logger()
err := coll.FindOne(context.TODO(), bson.D{{"_id", "1"}}).Decode(&total) err := coll.FindOne(context.TODO(), bson.D{{"_id", "1"}}).Decode(&total)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Could not query total data due to connection errors to database: %s", err.Error()), "red") l.Fatalf("Could not query total data due to connection errors to database: %s", err.Error())
os.Exit(1)
} }
return total, nil return total, nil
} }
func (coll Collection) storageRemove(filter bson.M) error { func (coll Collection) storageRemove(filter bson.M) error {
l := Logger()
_, err := coll.DeleteOne(context.TODO(), filter) _, err := coll.DeleteOne(context.TODO(), filter)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Could remove card data due to connection errors to database: %s", err.Error()), "red") l.Fatalf("Could remove card data due to connection errors to database: %s", err.Error())
os.Exit(1)
} }
return nil return nil
} }
func (coll Collection) storageAggregate(pipeline mongo.Pipeline) ([]primitive.M, error) { func (coll Collection) storageAggregate(pipeline mongo.Pipeline) ([]primitive.M, error) {
l := Logger()
opts := options.Aggregate() opts := options.Aggregate()
cursor, err := coll.Aggregate( cursor, err := coll.Aggregate(
@ -166,21 +168,21 @@ func (coll Collection) storageAggregate(pipeline mongo.Pipeline) ([]primitive.M,
pipeline, pipeline,
opts) opts)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Could not aggregate data due to connection errors to database: %s", err.Error()), "red") l.Fatalf("Could not aggregate data due to connection errors to database: %s", err.Error())
os.Exit(1)
} }
// Get a list of all returned documents and print them out. // Get a list of all returned documents and print them out.
// See the mongo.Cursor documentation for more examples of using cursors. // See the mongo.Cursor documentation for more examples of using cursors.
var results []bson.M var results []bson.M
if err = cursor.All(context.TODO(), &results); err != nil { if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatal(err) l.Fatal(err)
} }
return results, nil return results, nil
} }
func (coll Collection) storageUpdate(filter, update bson.M) error { func (coll Collection) storageUpdate(filter, update bson.M) error {
l := Logger()
// Call the driver's UpdateOne() method and pass filter and update to it // Call the driver's UpdateOne() method and pass filter and update to it
_, err := coll.UpdateOne( _, err := coll.UpdateOne(
context.Background(), context.Background(),
@ -188,8 +190,7 @@ func (coll Collection) storageUpdate(filter, update bson.M) error {
update, update,
) )
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("Could not update data due to connection errors to database: %s", err.Error()), "red") l.Fatalf("Could not update data due to connection errors to database: %s", err.Error())
os.Exit(1)
} }
return nil return nil

View File

@ -25,6 +25,7 @@ var updateCmd = &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
client := storageConnect() client := storageConnect()
l := Logger()
defer storageDisconnect(client) defer storageDisconnect(client)
// update sets // update sets
@ -81,7 +82,7 @@ var updateCmd = &cobra.Command{
bar.Add(1) bar.Add(1)
updatedCard, err := fetchCard(card.Set, card.CollectorNumber) updatedCard, err := fetchCard(card.Set, card.CollectorNumber)
if err != nil { if err != nil {
LogMessage(fmt.Sprintf("%v", err), "red") l.Error(err)
continue continue
} }

View File

@ -1,32 +0,0 @@
package serra
import "fmt"
var (
Icon = "\U0001F9D9\U0001F3FC"
Reset = "\033[0m"
Background = "\033[38;5;59m"
CurrentLine = "\033[38;5;60m"
Foreground = "\033[38;5;231m"
Comment = "\033[38;5;103m"
Cyan = "\033[38;5;159m"
Green = "\033[38;5;120m"
Orange = "\033[38;5;222m"
Pink = "\033[38;5;212m"
Purple = "\033[38;5;183m"
Red = "\033[38;5;210m"
Yellow = "\033[38;5;229m"
)
// Colored output on commandline
func LogMessage(message string, color string) {
if color == "red" {
fmt.Printf("%s%s%s\n", Red, message, Reset)
} else if color == "green" {
fmt.Printf("%s%s%s\n", Green, message, Reset)
} else if color == "purple" {
fmt.Printf("%s%s%s\n", Purple, message, Reset)
} else {
fmt.Printf("%s\n", message)
}
}