-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrename.go
More file actions
99 lines (89 loc) · 1.97 KB
/
Copy pathrename.go
File metadata and controls
99 lines (89 loc) · 1.97 KB
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
package fs
import (
"context"
"errors"
"io"
)
// A RenameFS is a file system with the Rename method.
type RenameFS interface {
FS
// Rename renames (moves) oldname to newname.
// If newname already exists and is not a directory, Rename replaces it.
Rename(ctx context.Context, oldname, newname string) error
}
// Rename renames (moves) oldname to newname.
// Analogous to: [os.Rename], mv, 9P2000.u Trename.
// If newname already exists and is not a directory, Rename replaces it.
//
// Requires: [RenameFS] || ([FS] && [CreateFS] && [RemoveFS])
func Rename(ctx context.Context, fsys FS, oldname, newname string) error {
var err error
if oldname, err = localizePath(ctx, fsys, oldname); err != nil {
return err
}
if newname, err = localizePath(ctx, fsys, newname); err != nil {
return err
}
if rfs, ok := fsys.(RenameFS); ok {
err := rfs.Rename(ctx, oldname, newname)
if err == nil || !errors.Is(err, ErrUnsupported) {
return err
}
// Fall through to fallback if ErrUnsupported
}
// Fallback: copy file and delete original
cfs, createOK := fsys.(CreateFS)
rfs, removeOK := fsys.(RemoveFS)
if !createOK || !removeOK {
return &PathError{
Op: "rename",
Path: oldname,
Err: ErrUnsupported,
}
}
// Open source file
src, err := fsys.Open(ctx, oldname)
if err != nil {
return &PathError{
Op: "rename",
Path: oldname,
Err: err,
}
}
defer src.Close()
// Create destination file
dst, err := cfs.Create(ctx, newname)
if err != nil {
return &PathError{
Op: "rename",
Path: newname,
Err: err,
}
}
// Copy data
_, err = io.Copy(dst, src)
closeErr := dst.Close()
if err != nil {
return &PathError{
Op: "rename",
Path: newname,
Err: err,
}
}
if closeErr != nil {
return &PathError{
Op: "rename",
Path: newname,
Err: closeErr,
}
}
// Remove original file
if err := rfs.Remove(ctx, oldname); err != nil {
return &PathError{
Op: "rename",
Path: oldname,
Err: err,
}
}
return nil
}