summaryrefslogtreecommitdiff
path: root/pkgtools/pkglint/files/files.go
blob: d4eb93d6114ad0caae1c35befa156e0eecb5784f (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package pkglint

import (
	"netbsd.org/pkglint/textproc"
	"strings"
)

type LoadOptions uint8

const (
	MustSucceed LoadOptions = 1 << iota // It's a fatal error if loading fails.
	NotEmpty                            // It is an error if the file is empty.
	Makefile                            // Lines ending in a backslash are continued in the next line.
	LogErrors                           //
)

func LoadMk(filename Path, options LoadOptions) *MkLines {
	lines := Load(filename, options|Makefile)
	if lines == nil {
		return nil
	}
	return NewMkLines(lines)
}

func Load(filename Path, options LoadOptions) *Lines {
	if fromCache := G.fileCache.Get(filename, options); fromCache != nil {
		return fromCache
	}

	rawText, err := filename.ReadString()
	if err != nil {
		switch {
		case options&MustSucceed != 0:
			NewLineWhole(filename).Fatalf("Cannot be read.")
		case options&LogErrors != 0:
			NewLineWhole(filename).Errorf("Cannot be read.")
		}
		return nil
	}

	if rawText == "" && options&NotEmpty != 0 {
		switch {
		case options&MustSucceed != 0:
			NewLineWhole(filename).Fatalf("Must not be empty.")
		case options&LogErrors != 0:
			NewLineWhole(filename).Errorf("Must not be empty.")
		}
		return nil
	}

	if G.Opts.Profiling {
		G.loaded.Add(filename.Clean().String(), 1)
	}

	result := convertToLogicalLines(filename, rawText, options&Makefile != 0)
	if filename.HasSuffixText(".mk") {
		G.fileCache.Put(filename, options, result)
	}
	return result
}

func convertToLogicalLines(filename Path, rawText string, joinBackslashLines bool) *Lines {
	var rawLines []*RawLine
	for lineno, rawLine := range strings.SplitAfter(rawText, "\n") {
		if rawLine != "" {
			rawLines = append(rawLines, &RawLine{1 + lineno, rawLine, rawLine})
		}
	}

	var loglines []*Line
	if joinBackslashLines {
		for lineno := 0; lineno < len(rawLines); {
			line, nextLineno := nextLogicalLine(filename, rawLines, lineno)
			loglines = append(loglines, line)
			lineno = nextLineno
		}
	} else {
		for _, rawLine := range rawLines {
			text := strings.TrimSuffix(rawLine.textnl, "\n")
			logline := NewLine(filename, rawLine.Lineno, text, rawLine)
			loglines = append(loglines, logline)
		}
	}

	if rawText != "" && !hasSuffix(rawText, "\n") {
		loglines[len(loglines)-1].Errorf("File must end with a newline.")
	}

	return NewLines(filename, loglines)
}

func nextLogicalLine(filename Path, rawLines []*RawLine, index int) (*Line, int) {
	{ // Handle the common case efficiently
		rawLine := rawLines[index]
		textnl := rawLine.textnl
		if hasSuffix(textnl, "\n") && !hasSuffix(textnl, "\\\n") {
			return NewLine(filename, rawLine.Lineno, textnl[:len(textnl)-1], rawLines[index]), index + 1
		}
	}

	var text strings.Builder
	firstlineno := rawLines[index].Lineno
	var lineRawLines []*RawLine
	interestingRawLines := rawLines[index:]
	trim := ""

	for i, rawLine := range interestingRawLines {
		indent, rawText, outdent, cont := matchContinuationLine(rawLine.textnl)

		if text.Len() == 0 {
			text.WriteString(indent)
		}
		text.WriteString(strings.TrimPrefix(rawText, trim))

		lineRawLines = append(lineRawLines, rawLine)

		if cont != "" && i != len(interestingRawLines)-1 {
			text.WriteString(" ")
			index++
			trim = textproc.NewLexer(rawText).NextString("#")
		} else {
			text.WriteString(outdent)
			text.WriteString(cont)
			break
		}
	}

	lastlineno := rawLines[index].Lineno

	return NewLineMulti(filename, firstlineno, lastlineno, text.String(), lineRawLines), index + 1
}

func matchContinuationLine(textnl string) (leadingWhitespace, text, trailingWhitespace, cont string) {
	j := len(textnl)

	if textnl[j-1] == '\n' {
		j--
	}

	backslashes := 0
	for j > 0 && textnl[j-1] == '\\' {
		j--
		backslashes++
	}
	cont = textnl[j : j+backslashes%2]
	j += backslashes / 2

	trailingEnd := j
	for j > 0 && isHspace(textnl[j-1]) {
		j--
	}
	trailingStart := j
	trailingWhitespace = textnl[trailingStart:trailingEnd]

	i := 0
	leadingStart := i
	for i < j && isHspace(textnl[i]) {
		i++
	}
	leadingEnd := i
	leadingWhitespace = textnl[leadingStart:leadingEnd]

	text = textnl[leadingEnd:trailingStart]
	return
}