summaryrefslogtreecommitdiff
path: root/order/order.go
blob: 41bbccdb73a833d76448298cdd5056ad65fc533b (plain)
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
package order

import (
	"bufio"
	"github.com/ewy1/pik/describe"
	"github.com/ewy1/pik/identity"
	"io"
	"io/fs"
	"os"
	"strings"
)

type Element struct {
	Identifier  identity.Identity
	Description string
}

type Order struct {
	Elements []Element
}

var Empty = Order{}

func FromFile(f fs.FS, path string) (Order, error) {
	fd, err := os.Open(path)
	if err != nil {
		return Empty, err
	}
	defer fd.Close()
	return FromReader(fd)
}

func FromReader(r io.Reader) (Order, error) {
	o := &Order{}
	scanner := bufio.NewScanner(r)
	scanner.Split(bufio.ScanLines)
	for scanner.Scan() {
		line := scanner.Text()
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}

		for _, p := range describe.DescriptionPrefixes {
			if strings.HasPrefix(line, p) {
				continue
			}
		}

		spl := strings.SplitN(line, "#", 2)

		e := &Element{
			Identifier: identity.New(spl[0]),
		}
		if len(spl) > 1 {
			e.Description = spl[1]
		}

		o.Elements = append(o.Elements, *e)
	}

	return *o, nil
}