-
Notifications
You must be signed in to change notification settings - Fork 46
/
filesystem.go
209 lines (177 loc) · 4.86 KB
/
filesystem.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package filesystem
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/hashicorp/nomad-pack/internal/pkg/logging"
)
// CopyFile copies a file from one path to another
func CopyFile(sourcePath, destinationPath string, logger logging.Logger) (err error) {
// Open the source file
sourceFile, err := os.Open(sourcePath)
if err != nil {
logger.Debug(fmt.Sprintf("error opening source file: %s", err))
return
}
// Set up a deferred close handler
defer func() {
if err = sourceFile.Close(); err != nil {
logger.Debug(fmt.Sprintf("error closing source file: %s", err))
}
}()
// Open the destination file
destinationFile, err := os.Create(destinationPath)
if err != nil {
logger.Debug(fmt.Sprintf("error opening destination file: %s", err))
return
}
// Set up a deferred close handler
defer func() {
if err = destinationFile.Close(); err != nil {
logger.Debug(fmt.Sprintf("error closing destination file: %s", err))
}
}()
// Copy the file
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
logger.Debug(fmt.Sprintf("error copying file: %s", err))
return
}
// Sync the file contents
err = destinationFile.Sync()
if err != nil {
logger.Debug(fmt.Sprintf("error syncing destination file: %s", err))
return
}
// Get the source file info so we can copy the permissions
sourceFileInfo, err := os.Stat(sourcePath)
if err != nil {
logger.Debug(fmt.Sprintf("error getting source file info: %s", err))
return
}
// Set the destination file permissions from the source file mode
err = os.Chmod(destinationPath, sourceFileInfo.Mode())
if err != nil {
logger.Debug(fmt.Sprintf("error getting setting destination file permissions: %s", err))
return
}
// Give the defer functions a chance to set this variable
return
}
// CopyDir recursively copies a directory.
func CopyDir(sourceDir string, destinationDir string, overwrite bool, logger logging.Logger) (err error) {
// Clean the directory paths
sourceDir = filepath.Clean(sourceDir)
destinationDir = filepath.Clean(destinationDir)
// Get the source directory info to validate that it is a directory
sourceDirInfo, err := os.Stat(sourceDir)
if err != nil {
logger.Debug(fmt.Sprintf("error getting source directory info: %s", err))
return
}
// Throw error if not a directory
// TODO: Might need to handle symlinks.
if !sourceDirInfo.IsDir() {
err = errors.New("source is not a directory")
logger.Debug(err.Error())
return
}
// Make sure the destination directory doesn't already exist
_, err = os.Stat(destinationDir)
if err != nil && !os.IsNotExist(err) {
logger.Debug(fmt.Sprintf("error getting destination file info: %s", err))
return
}
if !overwrite {
// throw error if it does exist
if err == nil {
err = errors.New("destination already exists")
logger.Debug(err.Error())
return
}
// Make the destination direction and copy the file permissions
err = MaybeCreateDestinationDir(
destinationDir,
WithFileMode(sourceDirInfo.Mode()),
ErrOnExists(),
)
if err != nil {
logger.Debug(fmt.Sprintf("error creating destination directory: %s", err))
return
}
}
// Read the contents of the source directory
sourceEntries, err := os.ReadDir(sourceDir)
if err != nil {
logger.Debug(fmt.Sprintf("error reading source directory entries: %s", err))
return
}
// Iterate over all the directory entries and copy them
for _, sourceEntry := range sourceEntries {
// Build the source and destination paths
sourcePath := filepath.Join(sourceDir, sourceEntry.Name())
destinationPath := filepath.Join(destinationDir, sourceEntry.Name())
// If a directory, then recurse, else copy all files
if sourceEntry.IsDir() {
err = CopyDir(sourcePath, destinationPath, overwrite, logger)
if err != nil {
return
}
} else {
// Skip symlinks.
if sourceEntry.Type()&os.ModeSymlink != 0 {
continue
}
// Copy file from source directory to destination directory
err = CopyFile(sourcePath, destinationPath, logger)
if err != nil {
return
}
}
}
return nil
}
func MaybeCreateDestinationDir(path string, opts ...CreateOption) error {
co := &createOpts{
perms: 0755,
}
for _, opt := range opts {
opt(co)
}
_, err := os.Stat(path)
if err == nil && co.errOnExists {
return &fs.PathError{
Op: "MaybeCreateDestinationDir",
Path: path,
Err: fs.ErrExist,
}
}
// If the directory doesn't exist, create it.
if errors.Is(err, fs.ErrNotExist) {
err := os.MkdirAll(path, co.perms)
if err != nil {
return err
}
}
return nil
}
func WithFileMode(m fs.FileMode) CreateOption {
return func(c *createOpts) {
c.perms = m
}
}
func ErrOnExists() CreateOption {
return func(c *createOpts) {
c.errOnExists = true
}
}
type CreateOption func(c *createOpts)
type createOpts struct {
errOnExists bool
perms fs.FileMode
}