-
Notifications
You must be signed in to change notification settings - Fork 0
/
deck.go
97 lines (83 loc) · 1.96 KB
/
deck.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package storage
import (
"os"
"path/filepath"
"strings"
"github.com/sirupsen/logrus"
)
type SRS interface {
UpdateSRSData(deck *Deck, cardID string, outcome int)
GetReviewCards(numCards int) []Flashcard
SaveSRSToFile() error
LoadSRSFromFile() error
LoadCardsFromMarkdown(deckDir string) error
}
type Deck struct {
Name string `json:"name"`
Cards []Flashcard `json:"cards"`
DirPath string `json:"-"`
SRS `json:"-"`
}
func NewDeck(name string, srsData SRS) *Deck {
dir := DeckDIR + "/" + name
return &Deck{Name: name, DirPath: dir, SRS: srsData}
}
func EnsureDecksDir() error {
dirPath := DeckDIR
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
err := os.MkdirAll(dirPath, 0755)
if err != nil {
return err
}
}
return nil
}
func LoadDeck(deckName string) (*Deck, error) {
deckPath := filepath.Join(DeckDIR, deckName)
if _, err := os.Stat(deckPath); os.IsNotExist(err) {
return nil, err
}
deck := &Deck{Name: deckName, Cards: []Flashcard{}}
err := filepath.Walk(deckPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && filepath.Ext(path) == fileEXT {
content, err := os.ReadFile(path)
if err != nil {
return err
}
card := Flashcard{
DeckID: deckName,
ID: strings.TrimSuffix(info.Name(), fileEXT),
Title: strings.Replace(strings.TrimSuffix(info.Name(), fileEXT), "_", " ", -1),
Content: string(content),
}
deck.Cards = append(deck.Cards, card)
}
return nil
})
if err != nil {
return nil, err
}
return deck, nil
}
func LoadAllDecks() ([]*Deck, error) {
var decks []*Deck
entries, err := os.ReadDir(DeckDIR)
if err != nil {
return nil, err
}
for _, entry := range entries {
if entry.IsDir() {
deckName := entry.Name()
deck, err := LoadDeck(deckName)
if err != nil {
logrus.Errorf("Failed to load deck %s: %v", deckName, err)
continue
}
decks = append(decks, deck)
}
}
return decks, nil
}