forked from cloudfoundry-attic/bosh-init
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_copier.go
75 lines (61 loc) · 1.92 KB
/
cp_copier.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
package commands
import (
"os"
"path/filepath"
"github.com/cloudfoundry/gofileutils/glob"
bosherr "github.com/cloudfoundry/bosh-agent/errors"
boshlog "github.com/cloudfoundry/bosh-agent/logger"
boshsys "github.com/cloudfoundry/bosh-agent/system"
)
const cpCopierLogTag = "cpCopier"
type cpCopier struct {
fs boshsys.FileSystem
cmdRunner boshsys.CmdRunner
logger boshlog.Logger
}
func NewCpCopier(
cmdRunner boshsys.CmdRunner,
fs boshsys.FileSystem,
logger boshlog.Logger,
) Copier {
return cpCopier{fs: fs, cmdRunner: cmdRunner, logger: logger}
}
func (c cpCopier) FilteredCopyToTemp(dir string, filters []string) (string, error) {
tempDir, err := c.fs.TempDir("bosh-platform-commands-cpCopier-FilteredCopyToTemp")
if err != nil {
return "", bosherr.WrapError(err, "Creating temporary directory")
}
dirGlob := glob.NewDir(dir)
filesToCopy, err := dirGlob.Glob(filters...)
if err != nil {
c.CleanUp(tempDir)
return "", bosherr.WrapError(err, "Finding files matching filters")
}
for _, relativePath := range filesToCopy {
src := filepath.Join(dir, relativePath)
dst := filepath.Join(tempDir, relativePath)
err = c.fs.MkdirAll(filepath.Dir(dst), os.ModePerm)
if err != nil {
c.CleanUp(tempDir)
return "", bosherr.WrapErrorf(err, "Making destination directory for %s", relativePath)
}
// Golang does not have a way of copying files and preserving file info...
_, _, _, err = c.cmdRunner.RunCommand("cp", "-Rp", src, dst)
if err != nil {
c.CleanUp(tempDir)
return "", bosherr.WrapError(err, "Shelling out to cp")
}
}
err = c.fs.Chmod(tempDir, os.FileMode(0755))
if err != nil {
c.CleanUp(tempDir)
return "", bosherr.WrapError(err, "Fixing permissions on temp dir")
}
return tempDir, nil
}
func (c cpCopier) CleanUp(tempDir string) {
err := c.fs.RemoveAll(tempDir)
if err != nil {
c.logger.Error(cpCopierLogTag, "Failed to clean up temporary directory %s: %#v", tempDir, err)
}
}