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
|
package main
// Session log: pressing Enter keeps the sentence that is on screen, turns it green,
// and appends it to a Markdown file so the talk can be edited into a script later.
//
// The file is written lazily — a run where nothing was kept leaves no file behind.
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
type sessionLog struct {
mu sync.Mutex
path string
f *os.File
lastZh string
lastEn string
lastAt time.Time
}
func newSessionLog(path string) (*sessionLog, error) {
if path == "" {
path = "sessions"
}
if strings.HasSuffix(path, string(os.PathSeparator)) || strings.HasSuffix(path, "/") {
path += "session-" + time.Now().Format("20060102-150405") + ".md"
} else if st, err := os.Stat(path); err == nil && st.IsDir() {
path = filepath.Join(path, "session-"+time.Now().Format("20060102-150405")+".md")
}
if dir := filepath.Dir(path); dir != "." {
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
}
return &sessionLog{path: path}, nil
}
// add appends one sentence and returns whether anything was written.
func (l *sessionLog) add(zh, en string) (bool, error) {
zh = strings.TrimSpace(zh)
en = strings.TrimSpace(en)
if zh == "" {
return false, nil
}
l.mu.Lock()
defer l.mu.Unlock()
// A double Enter should not duplicate the same sentence.
if zh == l.lastZh && en == l.lastEn && time.Since(l.lastAt) < 2*time.Second {
return false, nil
}
if l.f == nil {
f, err := os.OpenFile(l.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return false, err
}
l.f = f
if st, err := f.Stat(); err == nil && st.Size() == 0 {
fmt.Fprintf(f, "# lilchinese session %s\n\n", time.Now().Format("2006-01-02 15:04"))
}
}
line := fmt.Sprintf("- %s %s", time.Now().Format("15:04:05"), zh)
if en != "" {
line += " — " + en
}
if _, err := fmt.Fprintln(l.f, line); err != nil {
return false, err
}
l.lastZh, l.lastEn, l.lastAt = zh, en, time.Now()
return true, nil
}
func (l *sessionLog) close() {
l.mu.Lock()
defer l.mu.Unlock()
if l.f != nil {
l.f.Close()
l.f = nil
}
}
|