~aleteoryx/webjrnl

webjrnl/parse.go -rw-r--r-- 743 bytes
821b974aAleteoryx more compat testing 18 days ago
                                                                                
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
package main

import "strings"
import "time"

const HeadFormat = "> 2006-01-02"

func NextLine(s string) (line, rest string) {
	line, rest, _ = strings.Cut(s, "\n")
	if len(line) > 0 && line[len(line) - 1] == '\r' {
		line = line[:len(line) - 1]
	}
	return
}

func NextEntry(s *string) (ts time.Time, body string, ok bool) {
	var err error

	for {
		if *s == "" {
			return ts, body, false
		}

		line, rest := NextLine(*s)
			*s = rest
		if ts, err = time.Parse(HeadFormat, line); err == nil {
			break
		}
	}

	for {
		if *s == "" {
			break
		}

		line, rest := NextLine(*s)
		if _, err = time.Parse(HeadFormat, line); err != nil {
			body += line + "\n"
			*s = rest
		} else {
			break
		}
	}

	return ts, strings.TrimSpace(body), true
}