Repository navigation
Expand file tree
/
Copy pathfold.go
More file actions
260 lines (240 loc) · 7.22 KB
/
Copy pathfold.go
File metadata and controls
260 lines (240 loc) · 7.22 KB
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package main
// Working out what the words actually say.
//
// A script almost never writes the interesting string in one piece. It puts
// the host in one variable at the top, the version in another, joins them
// three lines later and pipes the result into a shell. Reading that as
// "curl $URL" and stopping there is what makes most tools in this area
// useless: they can tell you a download happened and not what was
// downloaded, which is the only part anybody wants.
//
// So this keeps a small table of what each variable is known to hold and
// fills the words in as it goes. It is deliberately timid. A value that
// came out of a command substitution is unknown and stays unknown; a
// variable assigned twice on two branches is unknown from then on; a
// variable the script reads from the user is unknown forever. Being wrong
// here would put a made up URL in a report, and a report with one invented
// line in it is worth nothing.
//
// The one liberty taken is with the handful of variables whose meaning is
// the same on every machine. HOME is a home directory whatever it holds, so
// $HOME/.bashrc is shown as ~/.bashrc rather than given up on. That is a
// substitution a reader would make themselves.
import (
"strings"
)
// Facts is what is known about the variables at one point in the script.
type Facts struct {
value map[string]string
// lost are the names that were set to something unknowable, kept apart
// from names never seen at all so that a word using one can say which.
lost map[string]bool
}
func newFacts() *Facts {
return &Facts{value: map[string]string{}, lost: map[string]bool{}}
}
// clone is used when a branch is walked, so that what the then branch
// assigns does not leak into the else branch.
func (f *Facts) clone() *Facts {
out := newFacts()
for k, v := range f.value {
out.value[k] = v
}
for k := range f.lost {
out.lost[k] = true
}
return out
}
// merge takes the facts back from two branches. A name only survives if
// both sides agree on it, which is the only honest answer: after an if,
// the value is whichever branch ran.
func (f *Facts) merge(other *Facts) {
for name, value := range f.value {
if theirs, found := other.value[name]; !found || theirs != value {
delete(f.value, name)
f.lost[name] = true
}
}
for name := range other.lost {
if _, found := f.value[name]; found {
delete(f.value, name)
}
f.lost[name] = true
}
}
func (f *Facts) set(name, value string) {
f.value[name] = value
delete(f.lost, name)
}
func (f *Facts) forget(name string) {
delete(f.value, name)
f.lost[name] = true
}
// standing are the variables whose meaning is fixed even when their value
// is not, written the way a person reads them.
var standing = map[string]string{
"HOME": "~",
"USER": "$USER",
"USERNAME": "$USER",
"LOGNAME": "$USER",
"TMPDIR": "/tmp",
"TMP": "/tmp",
"PWD": ".",
}
// Show fills in a word as far as it can be filled in, and says whether
// anything in it is still unknown. The string it gives back is meant to be
// read by a person: what is known is filled in and what is not is left
// standing as $NAME, because "$TOKEN" tells a reader more than a blank
// does.
func (f *Facts) Show(t Token) (string, bool) {
var out strings.Builder
certain := true
for _, piece := range t.Pieces {
switch piece.Kind {
case Literal:
out.WriteString(piece.Text)
case Variable:
name := piece.Text
if strings.HasPrefix(name, "!") {
// ${!name} looks up a variable whose name is in another
// variable, so the name being used is not written here.
out.WriteString("${" + name + "}")
certain = false
continue
}
if value, found := f.value[name]; found {
out.WriteString(value)
continue
}
// Nothing known about it, so the value the script itself puts
// there when it is unset is the best answer there is, and on
// most machines it is the right one.
if piece.Or != "" {
text, sure := f.expand(piece.Or)
out.WriteString(text)
certain = certain && sure
continue
}
if fixed, found := standing[name]; found {
out.WriteString(fixed)
if fixed == "~" || fixed == "/tmp" || fixed == "." {
continue
}
} else {
out.WriteString("$" + name)
}
certain = false
case Command:
out.WriteString("$(" + firstWords(piece.Inside) + ")")
certain = false
case Arithmetic:
out.WriteString("$((...))")
certain = false
}
}
return out.String(), certain
}
// Sure gives the value only when the whole word is known, for the places
// where a guess would be worse than nothing.
func (f *Facts) Sure(t Token) (string, bool) {
text, certain := f.Show(t)
return text, certain
}
// firstWords keeps a command substitution short enough to print inside a
// path without the line running off the side.
func firstWords(inside string) string {
inside = strings.TrimSpace(strings.ReplaceAll(inside, "\n", " "))
fields := strings.Fields(inside)
if len(fields) == 0 {
return ""
}
if len(fields) > 2 {
fields = append(fields[:2], "...")
}
return strings.Join(fields, " ")
}
// Learn takes in what a command tells us about the variables, and forgets
// what it makes unknowable. Called for every command as the walk goes past
// it, in the order the shell would reach them.
func (f *Facts) Learn(cmd *Cmd) {
for _, a := range cmd.Assigns {
f.learnOne(a)
}
if len(cmd.Words) == 0 {
return
}
switch base(firstWord(cmd)) {
case "export", "local", "readonly", "declare", "typeset":
// The same assignment with a word in front of it.
for _, word := range cmd.Words[1:] {
if name, value, ok := assignment(word); ok {
f.learnOne(Assign{Name: name, Value: value, Line: word.Line})
continue
}
if isName(word.Text) {
// export NAME on its own says nothing new about it.
continue
}
}
case "unset":
for _, word := range cmd.Words[1:] {
delete(f.value, word.Text)
delete(f.lost, word.Text)
}
case "read":
// Whatever the user types is not knowable here.
for _, word := range cmd.Words[1:] {
if isName(word.Text) {
f.forget(word.Text)
}
}
case "eval", "source", ".":
// After this anything could have changed, and pretending otherwise
// is how a report ends up confident about a value some other file
// replaced.
f.value = map[string]string{}
}
}
func (f *Facts) learnOne(a Assign) {
value, certain := f.Show(a.Value)
if !certain {
f.forget(a.Name)
return
}
f.set(a.Name, value)
}
func isName(s string) bool {
if s == "" || !isNameStart(s[0]) {
return false
}
for i := 0; i < len(s); i++ {
if !isNameByte(s[i]) {
return false
}
}
return true
}
func firstWord(cmd *Cmd) string {
if len(cmd.Words) == 0 {
return ""
}
return cmd.Words[0].Text
}
// base is the command name without the path it was called through, so that
// /usr/bin/curl and curl are the same command, which they are.
func base(name string) string {
name = strings.TrimSpace(name)
if at := strings.LastIndexAny(name, "/\\"); at >= 0 {
name = name[at+1:]
}
return name
}
// expand resolves the default half of a ${NAME:-something}, which is
// itself a word and often has a variable of its own in it.
func (f *Facts) expand(text string) (string, bool) {
tokens, _ := lex(text)
if len(tokens) == 0 || tokens[0].Kind != Word {
return text, false
}
return f.Show(tokens[0])
}