Debian Codegraph @

tools/antithesis-go-instrumentor/common/files.go

raw
1 package common
2
3 import (
4 "crypto/sha256"
5 "encoding/hex"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 )
14
15 const (
16 HashBitsUsed = 48
17 HashBytesUsed = HashBitsUsed / 8
18 EncodedHashByteLength = HashBytesUsed * 2
19 NotifierMinimumGoVersion = "1.24.0"
20 )
21
22 // HashFileContent reads the binary content of
23 // every file in paths (assumed to be in lexical order)
24 // and returns the SHA-256 digest.
25 func HashFileContent(paths []string) string {
26 hasher := sha256.New()
27 for _, path := range paths {
28 bytes, err := os.ReadFile(path)
29 if err != nil {
30 Logger.Fatalf("Error reading file %s: %v", path, err)
31 }
32 hasher.Write(bytes)
33 }
34
35 return hex.EncodeToString(hasher.Sum(nil))[0:EncodedHashByteLength]
36 }
37
38 func WriteTextFile(text, file_name string) (err error) {
39 var f *os.File
40 if f, err = os.Create(file_name); err != nil {
41 Logger.Printf(Normal, "Error: could not create %s", file_name)
42 quietClose(f)
43 return
44 }
45
46 if _, err = f.WriteString(text); err != nil {
47 quietClose(f)
48 Logger.Printf(Normal, "Error: Could not write text to %s", file_name)
49 } else {
50 err = f.Close()
51 if err != nil {
52 Logger.Printf(Normal, "Error: Could not sync text to %s", file_name)
53 }
54 }
55
56 return
57 }
58
59 func EnsureDirExists(dirName string) (err error) {
60 var dirInfo os.FileInfo
61 if dirInfo, err = os.Stat(dirName); err != nil {
62 err = os.MkdirAll(dirName, 0777)
63 return
64 }
65
66 // We stat-ed an existing directory or something else
67 if !dirInfo.IsDir() {
68 err = fmt.Errorf("%q is not a directory", dirName)
69 }
70 return
71 }
72
73 func OpenExistingDir(dirName string) (dir *os.File, err error) {
74 var dirInfo os.FileInfo
75
76 if dir, err = os.Open(dirName); err != nil {
77 dir = nil
78 return
79 }
80
81 if dirInfo, err = dir.Stat(); err != nil {
82 quietClose(dir)
83 dir = nil
84 return
85 }
86
87 if !dirInfo.IsDir() {
88 quietClose(dir)
89 dir = nil
90 err = fmt.Errorf("%q is not a directory", dirName)
91 }
92 return
93 }
94
95 // Use quietClose when there are files that should be closed, and
96 // the caller has already decided to return `err`. Do not use
97 // quietClose where the return value from Close(), on a writable file
98 // is important to isolate and preserve.
99 //
100 // Ref: https://www.joeshaw.org/dont-defer-close-on-writable-files/
101 func quietClose(fps ...*os.File) {
102 for _, fp := range fps {
103 if fp != nil {
104 fp.Close()
105 }
106 }
107 }
108
109 func CopyFile(from, to string) (err error) {
110 var fromFile *os.File
111 var toFile *os.File
112 var fileInfo os.FileInfo
113
114 if fromFile, err = os.Open(from); err != nil {
115 quietClose(fromFile)
116 return
117 }
118
119 if toFile, err = os.Create(to); err != nil {
120 quietClose(fromFile, toFile)
121 return
122 }
123
124 if _, err = io.Copy(toFile, fromFile); err != nil {
125 quietClose(fromFile, toFile)
126 return
127 }
128
129 if err = toFile.Sync(); err != nil {
130 quietClose(fromFile, toFile)
131 return
132 }
133
134 // Dont use quietClose so that Close() errors can be properly reported
135 if fromFile != nil {
136 if err = fromFile.Close(); err != nil {
137 quietClose(toFile)
138 return
139 }
140 }
141 if toFile != nil {
142 if err = toFile.Close(); err != nil {
143 return
144 }
145 }
146
147 if fileInfo, err = os.Stat(from); err != nil {
148 return
149 }
150 err = os.Chmod(to, fileInfo.Mode())
151 return
152 }
153
154 func CopyRecursiveDir(from, to string) (err error) {
155
156 var fromDir *os.File
157
158 var fromDirEntries []os.DirEntry
159 var fileInfo os.FileInfo
160
161 if fromDir, err = OpenExistingDir(from); err != nil {
162 return
163 }
164
165 // Make sure the 'to' path is a directory that exists
166 if err = EnsureDirExists(to); err != nil {
167 return
168 }
169
170 // Read the 'from' directory (and close its *File)
171 if fromDirEntries, err = fromDir.ReadDir(0); err != nil {
172 quietClose(fromDir)
173 return
174 }
175 if err = fromDir.Close(); err != nil {
176 return
177 }
178
179 for _, dirEntry := range fromDirEntries {
180 if fileInfo, err = dirEntry.Info(); err != nil {
181 return
182 }
183 filename := fileInfo.Name()
184 fromPath := filepath.Join(from, filename)
185 toPath := filepath.Join(to, filename)
186 fileMode := fileInfo.Mode()
187
188 if fileMode.IsDir() {
189 if err = CopyRecursiveDir(fromPath, toPath); err != nil {
190 return
191 }
192 continue
193 }
194 if (fileMode & os.ModeSymlink) == os.ModeSymlink {
195 if _, err = os.Stat(toPath); errors.Is(err, os.ErrNotExist) {
196 var target string
197 if target, err = os.Readlink(fromPath); err != nil {
198 return
199 }
200 if err = os.Symlink(target, toPath); err != nil {
201 return
202 }
203 }
204 }
205
206 if fileMode.IsRegular() {
207 if _, err = os.Stat(toPath); errors.Is(err, os.ErrNotExist) {
208 if err = CopyFile(fromPath, toPath); err != nil {
209 return
210 }
211 }
212 }
213 }
214
215 return
216 }
217
218 func ShowDirRecursive(dir, desc string) {
219 commandLine := fmt.Sprintf("ls -lR %s", dir)
220 cmd := exec.Command("bash", "-c", commandLine)
221 Logger.Printf(Normal, "")
222 Logger.Printf(Normal, "Directory Listing (%s)", desc)
223 Logger.Printf(Normal, "Executing %s", commandLine)
224 allOutput, err := cmd.CombinedOutput()
225 allText := strings.TrimSpace(string(allOutput))
226 lines := strings.Split(allText, "\n")
227 for _, line := range lines {
228 if len(line) > 0 {
229 Logger.Printf(Normal, "ls: %s", line)
230 }
231 }
232 if err != nil {
233 Logger.Printf(Normal, "ls completed with %+v", err)
234 }
235 }
236
237 func AddDependencies(customerInputDirectory, customerOutputDirectory, instrumentorVersion, notifierModule, localNotifier string) {
238 destGoModFile := fmt.Sprintf("%s/go.mod", customerOutputDirectory)
239
240 cmd1 := fmt.Sprintf("cd %s", customerInputDirectory)
241 cmd2 := fmt.Sprintf("go mod edit -require=%[email protected] -replace=%s=%s -print > %s",
242 notifierModule, notifierModule, localNotifier, destGoModFile)
243 commandLine := fmt.Sprintf("(%s; %s)", cmd1, cmd2)
244
245 cmd := exec.Command("bash", "-c", commandLine)
246 Logger.Printf(Normal, "Adding Antithesis module as a dependency to %s", customerOutputDirectory)
247 Logger.Printf(Normal, "Executing %s", commandLine)
248 allOutput, err := cmd.CombinedOutput()
249 allText := strings.TrimSpace(string(allOutput))
250 if len(allText) > 0 {
251 lines := strings.Split(allText, "\n")
252 for _, line := range lines {
253 Logger.Printf(Normal, "go mod edit: %s", line)
254 }
255 }
256 if err != nil {
257 // Errors here are pretty mysterious.
258 Logger.Fatalf("%v", err)
259 }
260 }
261
262 func FetchDependencies(customerOutputDirectory string) {
263 commandLine := fmt.Sprintf("(cd %s; go mod tidy)", customerOutputDirectory)
264
265 cmd := exec.Command("bash", "-c", commandLine)
266 Logger.Printf(Normal, "")
267 Logger.Printf(Normal, "Fetching Dependencies (go mod tidy)")
268 Logger.Printf(Normal, "Executing %s", commandLine)
269 allOutput, err := cmd.CombinedOutput()
270 allText := strings.TrimSpace(string(allOutput))
271 if len(allText) > 0 {
272 lines := strings.Split(allText, "\n")
273 for _, line := range lines {
274 Logger.Printf(Normal, "go mod tidy: %s", line)
275 }
276 }
277 if err != nil {
278 // Errors here are pretty mysterious.
279 Logger.Fatalf("%v", err)
280 }
281 }
282
283 func NotifierDependencies(notifierOutputDirectory, notifierModuleName, instrumentorVersion, localSDKPath string) {
284 dependencyRef := fmt.Sprintf("go get %s@%s",
285 ANTITHESIS_SDK_MODULE,
286 instrumentorVersion)
287
288 if localSDKPath != "" {
289 dependencyRef = fmt.Sprintf("go mod edit -require=%[email protected] -replace=%s=%s",
290 ANTITHESIS_SDK_MODULE, ANTITHESIS_SDK_MODULE, localSDKPath)
291 }
292
293 commandLine := fmt.Sprintf("(cd %s; go mod init %s; go mod edit -go=%s; go mod edit -toolchain=none; %s; go mod tidy; go mod edit -toolchain=none)",
294 notifierOutputDirectory,
295 notifierModuleName,
296 NotifierMinimumGoVersion,
297 dependencyRef)
298
299 cmd := exec.Command("bash", "-c", commandLine)
300 Logger.Printf(Normal, "")
301 Logger.Printf(Normal, "Creating Notifier Module")
302 Logger.Printf(Normal, "Executing %s", commandLine)
303 allOutput, err := cmd.CombinedOutput()
304 allText := strings.TrimSpace(string(allOutput))
305 if len(allText) > 0 {
306 lines := strings.Split(allText, "\n")
307 for _, line := range lines {
308 Logger.Printf(Normal, "go mod (notifier): %s", line)
309 }
310 }
311 if err != nil {
312 // Errors here are pretty mysterious.
313 Logger.Fatalf("%v", err)
314 }
315 }
316
317 // GetAbsoluteDirectory converts a path, whether a symlink or
318 // a relative path, into an absolute path.
319 func GetAbsoluteDirectory(path string) string {
320 if absolute, e := filepath.Abs(path); e != nil {
321 Logger.Fatalf("Could not evaluate %s as an absolute path: %v", path, e)
322 } else {
323 if s, err := os.Stat(absolute); err != nil {
324 Logger.Fatalf("%v", err)
325 } else {
326 if !s.IsDir() {
327 Logger.Fatalf("%s is not a directory", absolute)
328 }
329 return absolute
330 }
331 }
332 // This code will never be executed.
333 return ""
334 }
335
336 func CanonicalizeDirectory(d string) string {
337 target, e := filepath.EvalSymlinks(d)
338 if e != nil {
339 Logger.Fatalf("filepath.EvalSymlinks(%s) failed: %v", d, e)
340 }
341
342 a, e := filepath.Abs(target)
343 if e != nil {
344 Logger.Fatalf("filepath.Abs(%s) failed: %v", target, e)
345 }
346 return a
347 }
348
349 func confirmEmptyOutputDirectory(output string) {
350 d, e := os.Open(output)
351 if e != nil {
352 Logger.Fatalf("Could not open %s: %v", output, e)
353 }
354 defer d.Close()
355 // See the documentation on File.Readdirnames().
356 if names, _ := d.Readdirnames(1); len(names) > 0 {
357 Logger.Fatalf("Output directory %s must be empty.", output)
358 }
359 }
360
361 // ValidateDirectories checks that neither directory is a child of the other,
362 // and of course that they're not the same.
363 func ValidateDirectories(input, output string) (err error) {
364 // Go does not have a type for filepaths, and will not do this for me: https://golang.org/src/path/filepath/path_unix.go?s=717:754#L16
365 // The UNIX kernel absolutely forbids slashes in filenames. So, quick and dirty:
366 input = CanonicalizeDirectory(input) + "/"
367 output = CanonicalizeDirectory(output) + "/"
368 if strings.HasPrefix(output, input) {
369 err = fmt.Errorf("input directory %s is a prefix of the output directory %s", input, output)
370 return
371 }
372 if strings.HasPrefix(input, output) {
373 err = fmt.Errorf("output directory %s is a prefix of the input directory %s", output, input)
374 }
375 return
376 }
377
378 // PathFromBaseDirectory returns the path of someDir relative to baseDir.
379 // Returns "" when baseDir == someDir, or when someDir is not under baseDir
380 // (the caller in scanners/coverage/config uses an empty result to skip a
381 // dependent module — see ENG-3940 for the history).
382 //
383 // Example:
384 //
385 // PathFromBaseDirectory("/home/ricky/etcd", "/home/ricky/etcd/server/test")
386 // ==> "server/test"
387 func PathFromBaseDirectory(baseDir, someDir string) string {
388 baseNorm := CanonicalizeDirectory(baseDir)
389 someNorm := CanonicalizeDirectory(someDir)
390 if baseNorm == someNorm {
391 return ""
392 }
393 rel, err := filepath.Rel(baseNorm, someNorm)
394 if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
395 return ""
396 }
397 return rel
398 }