-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.go
57 lines (47 loc) · 1010 Bytes
/
tokenizer.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
package goenvloader
import (
"bufio"
"io"
"strings"
)
type tokens map[string]string
const (
EQUALS = "="
HASH = "#"
EMPTY = ""
)
func createNewLineScanner(reader io.ReadCloser) *bufio.Scanner {
scanner := bufio.NewScanner(reader)
return scanner
}
func parseVars(v string) (string, string, error) {
if !strings.Contains(v, EQUALS) {
return "", "", &illegalVariableDeclared{token: v}
}
if strings.Contains(v, HASH) {
commentIndex := strings.Index(v, "#")
v = v[:commentIndex]
}
if strings.EqualFold(v, EMPTY) {
return "", "", &emptyToken{}
}
envVar := strings.Split(v, EQUALS)
return envVar[0], envVar[1], nil
}
func generateTokens(scanner *bufio.Scanner) (tokens, error) {
var isMore bool = false
generatedTokens := make(tokens)
for {
isMore = scanner.Scan()
if !isMore {
break
}
token := scanner.Text()
key, value, err := parseVars(token)
if err != nil {
return generatedTokens, err
}
generatedTokens[key] = value
}
return generatedTokens, nil
}