| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package tools |
| 5 |
|
| 6 |
import ( |
| 7 |
"io" |
| 8 |
"os" |
| 9 |
"strconv" |
| 10 |
"strings" |
| 11 |
|
| 12 |
"github.com/git-lfs/git-lfs/v3/errors" |
| 13 |
"github.com/git-lfs/git-lfs/v3/tr" |
| 14 |
"golang.org/x/sys/unix" |
| 15 |
) |
| 16 |
|
| 17 |
var cloneFileSupported bool |
| 18 |
|
| 19 |
func init() { |
| 20 |
cloneFileSupported = checkCloneFileSupported() |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
func checkCloneFileSupported() bool { |
| 33 |
bytes, err := unix.Sysctl("kern.osrelease") |
| 34 |
if err != nil { |
| 35 |
return false |
| 36 |
} |
| 37 |
|
| 38 |
versionString := strings.Split(string(bytes), ".") |
| 39 |
if len(versionString) < 2 { |
| 40 |
return false |
| 41 |
} |
| 42 |
|
| 43 |
major, err := strconv.Atoi(versionString[0]) |
| 44 |
if err != nil { |
| 45 |
return false |
| 46 |
} |
| 47 |
|
| 48 |
return major >= 16 |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
func CheckCloneFileSupported(dir string) (supported bool, err error) { |
| 56 |
if !cloneFileSupported { |
| 57 |
return false, errors.New(tr.Tr.Get("Unsupported OS version. 10.12.x Sierra or higher required.")) |
| 58 |
} |
| 59 |
|
| 60 |
src, err := os.CreateTemp(dir, "src") |
| 61 |
if err != nil { |
| 62 |
return false, err |
| 63 |
} |
| 64 |
defer os.Remove(src.Name()) |
| 65 |
src.Close() |
| 66 |
|
| 67 |
dst, err := os.CreateTemp(dir, "dst") |
| 68 |
if err != nil { |
| 69 |
return false, err |
| 70 |
} |
| 71 |
defer os.Remove(dst.Name()) |
| 72 |
dst.Close() |
| 73 |
|
| 74 |
return CloneFileByPath(dst.Name(), src.Name()) |
| 75 |
} |
| 76 |
|
| 77 |
type CloneFileError struct { |
| 78 |
Unsupported bool |
| 79 |
errorString string |
| 80 |
} |
| 81 |
|
| 82 |
func (c *CloneFileError) Error() string { |
| 83 |
return c.errorString |
| 84 |
} |
| 85 |
|
| 86 |
func CloneFile(_ io.Writer, _ io.Reader) (bool, error) { |
| 87 |
return false, nil |
| 88 |
} |
| 89 |
|
| 90 |
func CloneFileByPath(dst, src string) (bool, error) { |
| 91 |
if !cloneFileSupported { |
| 92 |
return false, &CloneFileError{Unsupported: true, errorString: tr.Tr.Get("clonefile is not supported")} |
| 93 |
} |
| 94 |
|
| 95 |
if FileExists(dst) { |
| 96 |
if err := os.Remove(dst); err != nil { |
| 97 |
return false, err |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
if err := cloneFileSyscall(dst, src); err != nil { |
| 102 |
return false, err |
| 103 |
} |
| 104 |
|
| 105 |
return true, nil |
| 106 |
} |
| 107 |
|
| 108 |
func cloneFileSyscall(dst, src string) *CloneFileError { |
| 109 |
err := unix.Clonefileat(unix.AT_FDCWD, src, unix.AT_FDCWD, dst, unix.CLONE_NOFOLLOW) |
| 110 |
if err != nil { |
| 111 |
return &CloneFileError{ |
| 112 |
Unsupported: err == unix.ENOTSUP, |
| 113 |
errorString: tr.Tr.Get("error cloning from %v to %v: %s", src, dst, err), |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
return nil |
| 118 |
} |