github.com/google/osv-scalibr@v0.4.1/common/linux/dpkg/testing/dpkgutil/dpkgutil.go (about) 1 // Copyright 2025 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package dpkgutil provides test utilities for DPKG annotators. 16 package dpkgutil 17 18 import ( 19 "os" 20 "path/filepath" 21 "strings" 22 "testing" 23 ) 24 25 // SetupDPKGInfo sets up the DPKG info directory based on the supplied filename->content map. 26 // if createFiles is true it also creates the provided files (files with no extension are marked as executable) 27 func SetupDPKGInfo(t *testing.T, contents map[string]string, createFiles bool) string { 28 t.Helper() 29 30 dir := t.TempDir() 31 32 infoDir := filepath.Join(dir, "var/lib/dpkg/info") 33 if err := os.MkdirAll(infoDir, 0777); err != nil { 34 t.Fatalf("error creating directory %q: %v", infoDir, err) 35 } 36 37 for name, content := range contents { 38 listPath := filepath.Join(infoDir, name) 39 40 listFile, err := os.Create(listPath) 41 if err != nil { 42 t.Fatalf("Error while creating file %q: %v", listPath, err) 43 } 44 defer listFile.Close() 45 46 for path := range strings.SplitSeq(content, "\n") { 47 path, isFolder := strings.CutSuffix(path, "/") 48 49 if _, err := listFile.WriteString(path + "\n"); err != nil { 50 t.Fatalf("Error writing creating file %q: %v", listPath, err) 51 } 52 53 // create Files only if the provided argument is true 54 if !createFiles { 55 continue 56 } 57 58 fullPath := filepath.Join(dir, path) 59 60 if isFolder { 61 if err := os.Mkdir(fullPath, 0777); err != nil { 62 t.Fatalf("Error creating directory %q: %v", infoDir, err) 63 } 64 continue 65 } 66 perm := os.FileMode(0666) 67 if !strings.Contains(fullPath, ".") { 68 perm = 0755 69 } 70 if err := os.WriteFile(fullPath, []byte{}, perm); err != nil { 71 t.Fatalf("Error creating file %q: %v", fullPath, err) 72 } 73 } 74 } 75 return dir 76 }