github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/cnbutils/copy_project.go (about) 1 package cnbutils 2 3 import ( 4 "os" 5 "path" 6 "path/filepath" 7 "strings" 8 9 "github.com/SAP/jenkins-library/pkg/log" 10 "github.com/pkg/errors" 11 ignore "github.com/sabhiram/go-gitignore" 12 ) 13 14 func CopyProject(source, target string, include, exclude *ignore.GitIgnore, utils BuildUtils) error { 15 sourceFiles, _ := utils.Glob(path.Join(source, "**")) 16 for _, sourceFile := range sourceFiles { 17 relPath, err := filepath.Rel(source, sourceFile) 18 if err != nil { 19 log.SetErrorCategory(log.ErrorBuild) 20 return errors.Wrapf(err, "Calculating relative path for '%s' failed", sourceFile) 21 } 22 if !isIgnored(relPath, include, exclude) { 23 target := path.Join(target, strings.ReplaceAll(sourceFile, source, "")) 24 dir, err := utils.DirExists(sourceFile) 25 if err != nil { 26 log.SetErrorCategory(log.ErrorBuild) 27 return errors.Wrapf(err, "Checking file info '%s' failed", target) 28 } 29 30 if dir { 31 err = utils.MkdirAll(target, os.ModePerm) 32 if err != nil { 33 log.SetErrorCategory(log.ErrorBuild) 34 return errors.Wrapf(err, "Creating directory '%s' failed", target) 35 } 36 } else { 37 log.Entry().Debugf("Copying '%s' to '%s'", sourceFile, target) 38 err = copyFile(sourceFile, target, utils) 39 if err != nil { 40 log.SetErrorCategory(log.ErrorBuild) 41 return errors.Wrapf(err, "Copying '%s' to '%s' failed", sourceFile, target) 42 } 43 } 44 45 } 46 } 47 return nil 48 } 49 50 func copyFile(source, target string, utils BuildUtils) error { 51 targetDir := filepath.Dir(target) 52 53 exists, err := utils.DirExists(targetDir) 54 if err != nil { 55 return err 56 } 57 58 if !exists { 59 log.Entry().Debugf("Creating directory %s", targetDir) 60 err = utils.MkdirAll(targetDir, os.ModePerm) 61 if err != nil { 62 return err 63 } 64 } 65 66 _, err = utils.Copy(source, target) 67 return err 68 } 69 70 func isIgnored(find string, include, exclude *ignore.GitIgnore) bool { 71 if exclude != nil { 72 filtered := exclude.MatchesPath(find) 73 74 if filtered { 75 log.Entry().Debugf("%s matches exclude pattern, ignoring", find) 76 return true 77 } 78 } 79 80 if include != nil { 81 filtered := !include.MatchesPath(find) 82 83 if filtered { 84 log.Entry().Debugf("%s doesn't match include pattern, ignoring", find) 85 return true 86 } else { 87 log.Entry().Debugf("%s matches include pattern", find) 88 return false 89 } 90 } 91 92 return false 93 }