Debian Codegraph @

tools/antithesis-go-instrumentor/scanners/coverage/config/config.go

raw
1 package config
2
3 import (
4 "fmt"
5 "io/fs"
6 "os"
7 "path/filepath"
8 "strings"
9
10 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/args"
11 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/common"
12 commonconfig "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/config"
13 )
14
15 // CoverageConfig holds fields specific to coverage instrumentation.
16 type CoverageConfig struct {
17 // The modules inferred from scanning source files and
18 // looking for files named go.mod
19 // Each of these go.mod files may need the antithesis
20 // module added as a dependency.
21 dependentModules map[string]bool
22
23 // The name of the symbol table file, which incorporates
24 // the overall 'filesHash' and 'symbtablePrefix'
25 SymbolTableFilename string
26
27 // created and written during instrumentation.
28 // Will contain the corresponding .tsv file expected
29 // by the antithesis fuzzer
30 SymbolsDirectory string
31
32 // The instrumentation (only) base output directory
33 // Is required to exist, and to be empty prior to instrumentation
34 //
35 // After instrumentation, will contain the subdirectories for
36 // 'symbols' and 'customer'
37 outputDirectory string
38
39 // A prefix used to distinguish symbol table filenames
40 // that will be used by the antithesis fuzzer.
41 SymtablePrefix string
42
43 // The version of SDK to use at runtime for CoverageInstrumentation
44 instrumentorVersion string
45
46 // The path to the SDK to use to create the notifier
47 localSDKPath string
48
49 // created and written to during instrumentation.
50 // Will contain the antithesis notifier module (go.mod) and source (notifier.go)
51 notifierDirectory string
52
53 // UseSourceEditing selects the source-editing (edit-buffer) instrumentor
54 // instead of the default AST-rewriting one. Opt-in for now; the default is
55 // expected to flip once the source-editing path has proven itself, after
56 // which the AST-rewriting implementation will be removed.
57 UseSourceEditing bool
58 }
59
60 func NewCoverageConfig(args *args.Args) (*CoverageConfig, error) {
61 symtablePrefix := ""
62 if args.SymPrefix != "" {
63 symtablePrefix = args.SymPrefix + "-"
64 }
65
66 customerInputDirectory := common.GetAbsoluteDirectory(args.InputDir)
67 outputDirectory := common.GetAbsoluteDirectory(args.OutputDir)
68 if err := common.ValidateDirectories(customerInputDirectory, outputDirectory); err != nil {
69 return nil, err
70 }
71
72 customerDirectory := filepath.Join(outputDirectory, common.INSTRUMENTED_SOURCE_FOLDER)
73 notifierDirectory := filepath.Join(outputDirectory, common.NOTIFIER_FOLDER)
74 symbolsDirectory := filepath.Join(outputDirectory, common.SYMBOLS_FOLDER)
75 if err := createOutputDirectories(customerDirectory, notifierDirectory, symbolsDirectory); err != nil {
76 return nil, err
77 }
78
79 return &CoverageConfig{
80 outputDirectory: outputDirectory,
81 SymbolsDirectory: symbolsDirectory,
82 SymtablePrefix: symtablePrefix,
83 instrumentorVersion: args.InstrumentorVersion,
84 localSDKPath: args.LocalSDKPath,
85 notifierDirectory: notifierDirectory,
86 UseSourceEditing: args.SourceEditing,
87 }, nil
88 }
89
90 func (cov *CoverageConfig) GetSourceFiles(cc *commonconfig.CommonConfig) (sourceFiles []string, err error) {
91 sourceFiles = []string{}
92 cc.FilesSkipped = 0
93 if err = cc.ParseExclusionsFile(); err != nil {
94 return
95 }
96
97 numSkipped := 0
98 if sourceFiles, numSkipped, err = cov.FindSourceCode(cc); err != nil {
99 return
100 }
101 cc.FilesSkipped = numSkipped
102 cc.FilesHash = common.HashFileContent(sourceFiles)
103 return
104 }
105
106 // FindSourceCode scans an input directory recursively for .go files,
107 // skipping any files or directories specified in exclusions.
108 func (cov *CoverageConfig) FindSourceCode(cc *commonconfig.CommonConfig) (paths []string, numSkipped int, err error) {
109 paths = []string{}
110 numSkipped = 0
111
112 cov.dependentModules = map[string]bool{}
113
114 logger := common.Logger
115 logger.Printf(common.Normal, "Scanning %s recursively for .go source", cc.InputDirectory)
116 // Files are read in lexical order, i.e. we can later deterministically
117 // hash their content: https://pkg.go.dev/path/filepath#WalkDir
118 err = filepath.WalkDir(cc.InputDirectory,
119 func(path string, info fs.DirEntry, erx error) error {
120 if erx != nil {
121 logger.Printf(common.Normal, "Error %v in directory %s; skipping", erx, path)
122 return erx
123 }
124
125 if b := filepath.Base(path); strings.HasPrefix(b, ".") {
126 logger.Printf(common.Debug, "Ignoring 'dot' directory: %s", path)
127 if info.IsDir() {
128 return fs.SkipDir
129 }
130 return nil
131 }
132
133 if b := filepath.Base(path); b == "testdata" {
134 logger.Printf(common.Debug, "Ignoring 'testdata' directory: %s", path)
135 if info.IsDir() {
136 return fs.SkipDir
137 }
138 return nil
139 }
140
141 if cc.Exclusions[path] {
142 if info.IsDir() {
143 logger.Printf(common.Normal, "Ignoring excluded directory %s and its children", path)
144 return fs.SkipDir
145 }
146 logger.Printf(common.Normal, "Skipping excluded file %s", path)
147 numSkipped++
148 return nil
149 }
150 if info.IsDir() {
151 return nil
152 }
153 dir, baseFile := filepath.Split(path)
154 ext := filepath.Ext(path)
155 if ext != ".go" {
156 if baseFile == "go.mod" {
157 cov.dependentModules[filepath.Clean(dir)] = false
158 }
159 numSkipped++
160 return nil
161 }
162 // This is the mandatory format of unit test file names.
163 if cc.SkipTestFiles && strings.HasSuffix(baseFile, "_test.go") {
164 logger.Printf(common.Info, "Skipping test file %s", path)
165 numSkipped++
166 return nil
167 }
168
169 if cc.SkipProtoBufFiles && strings.HasSuffix(baseFile, ".pb.go") {
170 logger.Printf(common.Info, "Skipping generated file %s", path)
171 numSkipped++
172 return nil
173 }
174
175 paths = append(paths, path)
176
177 return nil
178 })
179 if err != nil {
180 err = fmt.Errorf("error walking input directory %s: %v", cc.InputDirectory, err)
181 }
182
183 return
184 }
185
186 func (cov *CoverageConfig) GetNotifierDirectory() string {
187 return cov.notifierDirectory
188 }
189
190 func (cov *CoverageConfig) CreateNotifierModule(cc *commonconfig.CommonConfig) {
191 notifierModuleName := common.NOTIFIER_MODULE_NAME
192 common.NotifierDependencies(cov.notifierDirectory, notifierModuleName, cov.instrumentorVersion, cov.localSDKPath)
193 }
194
195 func (cov *CoverageConfig) ShowDependentModules() {
196 isText := ""
197 common.Logger.Printf(common.Normal, "")
198 common.Logger.Printf(common.Normal, "Module Usage Summary")
199 for modName, used := range cov.dependentModules {
200 isText = "is"
201 if !used {
202 isText = "is not"
203 }
204 common.Logger.Printf(common.Normal, "%s %s used", modName, isText)
205 }
206 common.Logger.Printf(common.Normal, "")
207 }
208
209 func (cov *CoverageConfig) UpdateDependentModules(file_name string) {
210 ok := false
211 isUsed := false
212 this_dir := filepath.Clean(filepath.Dir(file_name))
213 for !ok {
214 common.Logger.Printf(common.Debug, "Checking if %q is a dependentModule", this_dir)
215 if this_dir == "." {
216 break
217 }
218 isUsed, ok = cov.dependentModules[this_dir]
219 if ok {
220 if !isUsed {
221 cov.dependentModules[this_dir] = true
222 }
223 return
224 } else {
225 old_dir := this_dir
226 this_dir = filepath.Clean(filepath.Dir(this_dir))
227 ok = (old_dir == this_dir)
228 }
229 }
230 common.Logger.Printf(common.Normal, "%q does not belong to a scanned module", file_name)
231 }
232
233 func (cov *CoverageConfig) WrapUp(cc *commonconfig.CommonConfig) {
234 notifierModule := common.FullNotifierName(cc.FilesHash)
235 notifierRelPath := ".."
236 localNotifier := filepath.Join(notifierRelPath, common.NOTIFIER_FOLDER)
237 common.AddDependencies(cc.InputDirectory, cc.CustomerDirectory, cov.instrumentorVersion, notifierModule, localNotifier)
238
239 someOffset := ""
240 for modFolder, used := range cov.dependentModules {
241 if used {
242 someOffset = common.PathFromBaseDirectory(cc.InputDirectory, modFolder)
243 if someOffset != "" {
244 destModuleFolder := filepath.Join(cc.CustomerDirectory, someOffset)
245 os.MkdirAll(destModuleFolder, 0777)
246
247 basePath := filepath.Join(cc.CustomerDirectory, someOffset)
248 targPath := cov.notifierDirectory
249 if altDestModuleFolder, erx := filepath.Rel(basePath, targPath); erx == nil {
250 common.AddDependencies(modFolder, destModuleFolder, cov.instrumentorVersion, notifierModule, altDestModuleFolder)
251 }
252 }
253 }
254 }
255
256 if err := common.CopyRecursiveDir(cc.InputDirectory, cc.CustomerDirectory); err == nil {
257 common.Logger.Printf(common.Normal, "All other files copied unmodified from %s to %s", cc.InputDirectory, cc.CustomerDirectory)
258 } else {
259 common.Logger.Printf(common.Normal, "CopyRecursiveDir err: %s", err.Error())
260 }
261
262 if common.Logger.VerboseLevel(common.Info) {
263 common.ShowDirRecursive(cc.CustomerDirectory, "instrumented files")
264 }
265
266 if cov.localSDKPath == "" {
267 common.FetchDependencies(cc.CustomerDirectory)
268 common.Logger.Printf(common.Normal, "Downloaded Antithesis dependencies")
269 }
270 }
271
272 // Private helpers
273
274 func createOutputDirectories(customerDirectory, notifierDirectory, symbolsDirectory string) (err error) {
275 if err = os.Mkdir(customerDirectory, 0755); err != nil {
276 return
277 }
278 if err = os.Mkdir(notifierDirectory, 0755); err != nil {
279 return
280 }
281 err = os.Mkdir(symbolsDirectory, 0755)
282 return
283 }