-
Notifications
You must be signed in to change notification settings - Fork 594
/
copy_project.go
93 lines (79 loc) · 2.23 KB
/
copy_project.go
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
package cnbutils
import (
"os"
"path"
"path/filepath"
"strings"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/pkg/errors"
ignore "github.com/sabhiram/go-gitignore"
)
func CopyProject(source, target string, include, exclude *ignore.GitIgnore, utils BuildUtils) error {
sourceFiles, _ := utils.Glob(path.Join(source, "**"))
for _, sourceFile := range sourceFiles {
relPath, err := filepath.Rel(source, sourceFile)
if err != nil {
log.SetErrorCategory(log.ErrorBuild)
return errors.Wrapf(err, "Calculating relative path for '%s' failed", sourceFile)
}
if !isIgnored(relPath, include, exclude) {
target := path.Join(target, strings.ReplaceAll(sourceFile, source, ""))
dir, err := utils.DirExists(sourceFile)
if err != nil {
log.SetErrorCategory(log.ErrorBuild)
return errors.Wrapf(err, "Checking file info '%s' failed", target)
}
if dir {
err = utils.MkdirAll(target, os.ModePerm)
if err != nil {
log.SetErrorCategory(log.ErrorBuild)
return errors.Wrapf(err, "Creating directory '%s' failed", target)
}
} else {
log.Entry().Debugf("Copying '%s' to '%s'", sourceFile, target)
err = copyFile(sourceFile, target, utils)
if err != nil {
log.SetErrorCategory(log.ErrorBuild)
return errors.Wrapf(err, "Copying '%s' to '%s' failed", sourceFile, target)
}
}
}
}
return nil
}
func copyFile(source, target string, utils BuildUtils) error {
targetDir := filepath.Dir(target)
exists, err := utils.DirExists(targetDir)
if err != nil {
return err
}
if !exists {
log.Entry().Debugf("Creating directory %s", targetDir)
err = utils.MkdirAll(targetDir, os.ModePerm)
if err != nil {
return err
}
}
_, err = utils.Copy(source, target)
return err
}
func isIgnored(find string, include, exclude *ignore.GitIgnore) bool {
if exclude != nil {
filtered := exclude.MatchesPath(find)
if filtered {
log.Entry().Debugf("%s matches exclude pattern, ignoring", find)
return true
}
}
if include != nil {
filtered := !include.MatchesPath(find)
if filtered {
log.Entry().Debugf("%s doesn't match include pattern, ignoring", find)
return true
} else {
log.Entry().Debugf("%s matches include pattern", find)
return false
}
}
return false
}