summaryrefslogtreecommitdiff
path: root/log.go
diff options
context:
space:
mode:
Diffstat (limited to 'log.go')
-rw-r--r--log.go87
1 files changed, 87 insertions, 0 deletions
diff --git a/log.go b/log.go
new file mode 100644
index 0000000..e2cf182
--- /dev/null
+++ b/log.go
@@ -0,0 +1,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
+ }
+}