-
Notifications
You must be signed in to change notification settings - Fork 50
/
move.go
72 lines (59 loc) · 1.78 KB
/
move.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
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
package fetch
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
func MoveDir(path, dstPath string) error {
err := os.RemoveAll(dstPath)
if err != nil {
return fmt.Errorf("Deleting dir %s: %s", dstPath, err)
}
err = os.Rename(path, dstPath)
if err != nil {
return fmt.Errorf("Moving directory '%s' to staging dir: %s", path, err)
}
return nil
}
// MoveFile moves a file to the destination, before that it removes all the contents of the destination folder
// If folder already existed it will keep the permissions if not it will use 0700
func MoveFile(path, dstPath string) error {
folderPermission := os.FileMode(0700)
_, err := os.Stat(dstPath)
if !errors.Is(err, &os.PathError{}) {
err := os.RemoveAll(dstPath)
if err != nil {
return fmt.Errorf("Deleting dir %s: %s", dstPath, err)
}
}
err = os.Mkdir(dstPath, folderPermission)
if err != nil {
return fmt.Errorf("Creating dir %s: %s", dstPath, err)
}
err = os.Rename(path, filepath.Join(dstPath, filepath.Base(path)))
if err != nil {
return fmt.Errorf("Moving file '%s' to staging dir: %s", path, err)
}
return nil
}
func ScopedPath(path, subPath string) (string, error) {
path, err := filepath.Abs(path)
if err != nil {
return "", fmt.Errorf("Abs path: %s", err)
}
newPath, err := filepath.Abs(filepath.Join(path, subPath))
if err != nil {
return "", fmt.Errorf("Abs path: %s", err)
}
// Check that subPath is contained within path (disallow this scenario):
// ScopedPath("/root", "../root-trick/file1")
// "/root-trick/file1" == "/root" + "../root-trick/file1"
if newPath != path && !strings.HasPrefix(newPath, path+string(filepath.Separator)) {
return "", fmt.Errorf("Invalid path: %s", subPath)
}
return newPath, nil
}