summaryrefslogtreecommitdiff
path: root/pkgtools/pkglint/files/expecter.go
blob: 5e188d8a077e487574b32451662bd72d54765bfc (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main

// Expecter records the state when checking a list of lines from top to bottom.
type Expecter struct {
	lines []*Line
	index int
	m     []string
}

func NewExpecter(lines []*Line) *Expecter {
	return &Expecter{lines, 0, nil}
}

func (exp *Expecter) CurrentLine() *Line {
	if exp.index < len(exp.lines) {
		return exp.lines[exp.index]
	}

	return NewLineEOF(exp.lines[0].Fname)
}

func (exp *Expecter) PreviousLine() *Line {
	return exp.lines[exp.index-1]
}

func (exp *Expecter) EOF() bool {
	return !(exp.index < len(exp.lines))
}

func (exp *Expecter) Advance() bool {
	exp.index++
	exp.m = nil
	return true
}

func (exp *Expecter) StepBack() {
	exp.index--
}

func (exp *Expecter) AdvanceIfMatches(re RegexPattern) bool {
	if G.opts.Debug {
		defer tracecall(exp.CurrentLine().Text, re)()
	}

	if !exp.EOF() {
		if m := match(exp.lines[exp.index].Text, re); m != nil {
			exp.index++
			exp.m = m
			return true
		}
	}
	return false
}

func (exp *Expecter) AdvanceIfPrefix(prefix string) bool {
	if G.opts.Debug {
		defer tracecall2(exp.CurrentLine().Text, prefix)()
	}

	return !exp.EOF() && hasPrefix(exp.lines[exp.index].Text, prefix) && exp.Advance()
}

func (exp *Expecter) AdvanceIfEquals(text string) bool {
	if G.opts.Debug {
		defer tracecall2(exp.CurrentLine().Text, text)()
	}

	return !exp.EOF() && exp.lines[exp.index].Text == text && exp.Advance()
}

func (exp *Expecter) ExpectEmptyLine() bool {
	if exp.AdvanceIfEquals("") {
		return true
	}

	if G.opts.WarnSpace {
		if !exp.CurrentLine().AutofixInsertBefore("") {
			exp.CurrentLine().Notef("Empty line expected.")
		}
	}
	return false
}

func (exp *Expecter) ExpectText(text string) bool {
	if !exp.EOF() && exp.lines[exp.index].Text == text {
		exp.index++
		exp.m = nil
		return true
	}

	exp.CurrentLine().Warnf("This line should contain the following text: %s", text)
	return false
}