-
Notifications
You must be signed in to change notification settings - Fork 0
/
voc.go
485 lines (433 loc) · 11.6 KB
/
voc.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
package main
import (
"bufio"
"database/sql"
"flag"
"fmt"
"github.com/eiannone/keyboard"
. "github.com/logrusorgru/aurora"
_ "github.com/mattn/go-sqlite3"
"log"
"math/rand"
"os"
"strings"
"time"
)
const (
SPLITLINE string = "----split----"
)
var dbFullPath string //sqlite database
var fib = [14]int{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233} //review statergy
var voc string //vocabulary.txt file
type Word struct {
name string
trans string
}
type WordTableRow struct {
word string
trans string
createDate string
nextReviewDate string
reviewStatus int
}
type WordTableRows []WordTableRow
func initDB(filePath string) *sql.DB {
db, err := sql.Open("sqlite3", filePath)
if err != nil {
fmt.Printf("Oops! Database %s already exist", filePath)
return db
}
if db == nil {
panic("db nil")
}
fmt.Printf("Database %s created!\n", filePath)
return db
}
func createTable(db *sql.DB) {
// create table if not exists
sql_table := `
CREATE TABLE words (
word text NOT NULL,
translation text NOT NULL,
createdate text DEFAULT (STRFTIME('%Y-%m-%d', 'NOW')),
nextreviewdate text DEFAULT (STRFTIME('%Y-%m-%d', 'NOW')),
reviewstatus INT DEFAULT 0,
PRIMARY KEY(word, nextreviewdate)
);`
_, err := db.Exec(sql_table)
if err != nil {
fmt.Println("Table already exist.")
return
} else {
fmt.Println("Table words created!")
return
}
}
func readVoc(voc string) []Word {
/*read voc file parse every word and transation
then save it to a Word array and return it.*/
file, err := os.Open(voc)
if err != nil {
fmt.Printf("Vocabulary file %s was not created by now, user %s or %s to create it.\n", Cyan(voc), Red("translate"), Red("newtrans"))
os.Exit(1)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var txtlines []string
for scanner.Scan() {
txtlines = append(txtlines, scanner.Text())
}
file.Close()
var words []Word
var word Word
var tag = false
var lines []string
for n := 0; n < len(txtlines); n++ { //Purge multiple continued ----split----
if n+1 < len(txtlines) {
if txtlines[n] == SPLITLINE && txtlines[n+1] == SPLITLINE {
continue
} else {
lines = append(lines, txtlines[n])
}
}
}
for n := 0; n < len(lines); n++ { //Parse
if lines[n] == SPLITLINE {
if tag {
words = append(words, word)
word.trans = ""
tag = false
}
n++
word.name = lines[n]
tag = true
continue
}
word.trans += lines[n]
word.trans += "\n"
}
words = append(words, word)
return words
}
func creatVoc(voc string) {
emptyFile, err := os.Create(voc)
if err != nil {
fmt.Printf("Oops, can not creat %s", voc)
panic(err)
}
emptyFile.Close()
fmt.Printf("%s created!\n", voc)
}
func removeVoc(voc string) {
err := os.Remove(voc)
if err != nil {
fmt.Printf("Opps!!! Cannot delete file: %s\n", voc)
} else {
fmt.Printf("File: %s removed.\n", voc)
}
}
func checkRecord(word string) bool {
/* check if a word.name exist in dbFullPath */
db, err := sql.Open("sqlite3", dbFullPath)
if err != nil {
panic(err)
}
stmt := `SELECT word FROM words WHERE word = ?`
err = db.QueryRow(stmt, word).Scan(&word)
if err != nil {
if err != sql.ErrNoRows {
log.Print(err)
}
return false
}
return true
}
func storeDB(db *sql.DB, words []Word) {
/* store words list to word.db */
for _, word := range words {
if checkRecord(word.name) {
fmt.Printf("Word: %s already exist\n", word.name)
resetWord(db, word.name)
fmt.Printf("Word: %s is %s as today's new word.\n", Cyan(word.name), Red("Reset"))
continue
}
stmt, err := db.Prepare("INSERT INTO words(word, translation, createdate, nextreviewdate, reviewstatus) values(?,?,?,?,?)")
if err != nil {
panic(err)
}
date := time.Now().Format("2006-01-02")
res, err := stmt.Exec(word.name, word.trans, date, date, 0)
if err != nil {
panic(err)
}
rowId, err := res.LastInsertId()
if err != nil {
panic(err)
}
fmt.Printf("Inserted Word: %s with RowID: %d\n", word.name, rowId)
}
removeVoc(voc)
return
}
func openDB(dfFullPath string) *sql.DB {
db, err := sql.Open("sqlite3", dbFullPath)
if err != nil {
panic(err)
}
return db
}
func readDB(db *sql.DB) WordTableRows {
/* read words from table word of current date */
date := time.Now().Format("2006-01-02")
rows, err := db.Query("select * from words where nextreviewdate <= ?", date)
if err != nil {
panic(err)
}
var wordRecords WordTableRows
for rows.Next() {
var record WordTableRow
err = rows.Scan(&record.word, &record.trans, &record.createDate, &record.nextReviewDate, &record.reviewStatus)
if err != nil {
panic(err)
}
wordRecords = append(wordRecords, record)
}
return wordRecords
}
func totalWordsDB(db *sql.DB) int {
/* total words from table word of current date */
rows, err := db.Query("select * from words")
if err != nil {
panic(err)
}
var wordRecords WordTableRows
for rows.Next() {
var record WordTableRow
err = rows.Scan(&record.word, &record.trans, &record.createDate, &record.nextReviewDate, &record.reviewStatus)
if err != nil {
panic(err)
}
wordRecords = append(wordRecords, record)
}
return len(wordRecords)
}
func updateNextReviewDate(db *sql.DB, rec WordTableRow) {
rec.reviewStatus += 1 //enter next reivew series
nextDay := time.Now().AddDate(0, 0, fib[rec.reviewStatus])
fmt.Printf("Will review on %s\n", nextDay.Format("2006-01-02"))
stmt, err := db.Prepare(`UPDATE words SET nextreviewdate = ?, reviewstatus = ? WHERE word = ?`)
if err != nil {
fmt.Println("Update Prepare Error")
panic(err)
}
_, err = stmt.Exec(nextDay.Format("2006-01-02"), rec.reviewStatus, rec.word)
if err != nil {
fmt.Printf("Can not update %s's nextreview and reviewstatus", rec.word)
}
return
}
func resetWord(db *sql.DB, word string) {
reviewStatus := 0 //reset to the first review status
date := time.Now().Format("2006-01-02") // reset the nextreviewdate to today
stmt, err := db.Prepare(`UPDATE words SET nextreviewdate = ?, reviewstatus = ? WHERE word = ?`)
if err != nil {
fmt.Println("Update Prepare Error")
panic(err)
}
_, err = stmt.Exec(date, reviewStatus, word)
if err != nil {
fmt.Printf("Can not update %s's nextreview and reviewstatus.\n", word)
return
}
fmt.Printf("Word %s was reset as a NEW %s.\n", Red(word), Cyan("word"))
}
func modifyWordRecord(db *sql.DB, rec WordTableRow) {
/* Only change a word in DB, for example change pl gaffes to gaffe */
stmt, err := db.Prepare(`UPDATE words SET word = ? WHERE word = ?`)
if err != nil {
fmt.Printf("Can not prepare modify the word %s\n", Cyan(rec.word))
panic(err)
}
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Please input the new word for %s: ", rec.word)
newWord, _ := reader.ReadString('\n')
newWord = strings.TrimSuffix(newWord, "\n")
newWord = strings.Trim(newWord, " ")
if newWord == "" {
fmt.Println("You did not input anything.")
return
}
_, err = stmt.Exec(newWord, rec.word)
if err != nil {
fmt.Printf("Can not modify the word %s \n", Cyan(rec.word))
panic(err)
}
fmt.Printf("The word %s replaced by %s \n", Cyan(rec.word), Red(newWord))
return
}
func deleteRecord(db *sql.DB, rec WordTableRow) {
stmt, err := db.Prepare(`DELETE FROM words WHERE word == ?`)
if err != nil {
panic(err)
}
_, err = stmt.Exec(rec.word)
if err != nil {
fmt.Printf("Can not delete record: %s", rec.word)
panic(err)
}
fmt.Printf("Word: %s removed from remember database\n", Cyan(rec.word))
return
}
func review(db *sql.DB, wordList WordTableRows) {
wordsLength := len(wordList)
if wordsLength == 0 {
return
}
index := 0
for {
fmt.Printf("\n(%d/%d): %s | %s\n\n", Cyan(index+1), Cyan(wordsLength), Red(wordList[index].word), Red(strings.ToUpper(wordList[index].word)))
char, _, err := keyboard.GetSingleKey()
if err != nil {
panic(err)
}
if char == '\x00' {
fmt.Printf("%s\n-----------------\n\n", Green(wordList[index].trans))
for {
char, _, err = keyboard.GetSingleKey()
if err != nil {
panic(err)
}
if char == 'p' { // pass after trans displayed
updateNextReviewDate(db, wordList[index]) //change nextReviewDate
if index >= wordsLength-1 {
return
} else {
index += 1
break
}
} else if char == 'd' { //delete the word from db
deleteRecord(db, wordList[index])
if index >= wordsLength-1 {
return
} else {
index += 1
}
} else if char == 'r' { //reset the old word to new word
resetWord(db, wordList[index].word)
if index >= wordsLength-1 {
return
} else {
index += 1
}
} else if char == 'm' { //modify word's spell.
modifyWordRecord(db, wordList[index])
if index >= wordsLength-1 {
return
} else {
index += 1
}
} else if char == '\x00' {
if index >= wordsLength-1 {
return
} else {
index += 1
break
}
} else if char == 'q' { // exit at any time
return
}
break
}
} else if char == 'p' { // pass before trans displayed
updateNextReviewDate(db, wordList[index]) //change nextReviewDate
if index >= wordsLength-1 {
return
} else {
index += 1
}
} else if char == 'm' { // modified the current word after a the word displayed
modifyWordRecord(db, wordList[index])
if index >= wordsLength-1 {
return
} else {
index += 1
}
} else if char == 'd' { // delete the current word (after the word displayed)
deleteRecord(db, wordList[index])
if index >= wordsLength-1 {
return
} else {
index += 1
}
} else if char == 'r' { //reset the old word to new word
resetWord(db, wordList[index].word)
if index >= wordsLength-1 {
return
} else {
index += 1
}
} else if char == 'q' { // exit
return
}
}
}
func shuffle(vals []int) []int {
/* shuffle an array */
r := rand.New(rand.NewSource(time.Now().Unix()))
ret := make([]int, len(vals))
perm := r.Perm(len(vals))
for i, randIndex := range perm {
ret[i] = vals[randIndex]
}
return ret
}
func (words WordTableRows) disorder() WordTableRows {
length := len(words)
var array []int
for i := 0; i <= length-1; i++ {
array = append(array, i)
}
array = shuffle(array)
var newWords WordTableRows
for _, order := range array {
newWords = append(newWords, words[order])
}
return newWords
}
func main() {
storePtr := flag.Bool("store", false, "Store new words to Database")
listPtr := flag.Bool("list", false, "List words in ~/.words/vocabulary.txt ")
initPtr := flag.Bool("init", false, "Init Local database in ~/.word/words.db")
totalPtr := flag.Bool("total", false, "Return the total number of words in database in ~/.word/words.db")
flag.Parse()
homeFullPath := os.Getenv("HOME") + "/.word"
dbFullPath = homeFullPath + "/words.db"
voc = homeFullPath + "/vocabulary.txt"
if *initPtr { // Fist time use, build a new words.db in ~/.word
err := os.MkdirAll(homeFullPath, os.ModePerm)
if err != nil {
fmt.Printf("Can not create directory: %s ", homeFullPath)
}
db := initDB(dbFullPath)
createTable(db)
creatVoc(voc)
} else if *storePtr { // store all the vocabulary from voc.txt to database
words := readVoc(voc)
db := openDB(dbFullPath)
storeDB(db, words)
} else if *listPtr {
words := readVoc(voc)
for index, word := range words {
fmt.Printf("Index: %2d, Word: %s\n", index, word.name)
}
} else if *totalPtr {
db := openDB(dbFullPath)
totalNumber := totalWordsDB(db)
fmt.Printf("Total numbers of words in DB is %d\n", Red(totalNumber))
} else {
db := openDB(dbFullPath)
words := readDB(db)
words = words.disorder()
review(db, words)
}
}