-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_handling.go
More file actions
115 lines (100 loc) · 3.21 KB
/
Copy pathfile_handling.go
File metadata and controls
115 lines (100 loc) · 3.21 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"golang.org/x/tools/godoc/util"
)
type File struct {
Path string
info os.FileInfo
}
// NewFile resolves path to an absolute path and wraps it in a *File. It
// returns an error if the working directory cannot be determined (the only
// failure mode of filepath.Abs).
func NewFile(path string) (*File, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return nil, fmt.Errorf("resolve absolute path of %v: %w", path, err)
}
return &File{Path: absPath}, nil
}
func (f *File) Base() string {
return filepath.Base(f.Path)
}
func (f *File) Dir() string {
return filepath.Dir(f.Path)
}
// Info lazily stats the file and caches the result. It returns an error if
// the underlying os.Stat fails.
func (f *File) Info() (os.FileInfo, error) {
if f.info == nil {
stat, err := os.Stat(f.Path)
if err != nil {
return nil, fmt.Errorf("stat %v: %w", f.Path, err)
}
f.info = stat
}
return f.info, nil
}
// Mode returns the cached mode bits. It is only safe to call after Info() has
// succeeded; callers that have a *File handed to them by the walker can rely
// on that precondition because the walker calls Info() before dispatching.
func (f *File) Mode() (os.FileMode, error) {
info, err := f.Info()
if err != nil {
return 0, err
}
return info.Mode(), nil
}
// Read reads the file into a string, or returns the empty string for binary
// files. An error indicates the file could not be opened or fully read; the
// caller should log-and-skip rather than abort.
func (f *File) Read() (string, error) {
handle, err := os.Open(f.Path)
if err != nil {
return "", fmt.Errorf("open %v: %w", f.Path, err)
}
defer handle.Close()
// Check if the file looks like text before reading the entire file.
var buf [1024]byte
n, err := handle.Read(buf[0:])
if err != nil || !util.IsText(buf[0:n]) {
return "", nil
}
// Reset file handle so we can read the entire file.
if _, err := handle.Seek(0, io.SeekStart); err != nil {
return "", fmt.Errorf("seek to start of %v: %w", f.Path, err)
}
builder := new(strings.Builder)
if _, err := io.Copy(builder, handle); err != nil {
return "", fmt.Errorf("read %v: %w", f.Path, err)
}
return builder.String(), nil
}
// Write atomically replaces the file with content, via a temp file + rename.
// A deferred os.Remove(tempName) ensures the temp file is cleaned up if any
// step after its creation fails (including the rename); on success the remove
// is a no-op because the file has already been renamed away.
func (f *File) Write(content string) error {
mode, err := f.Mode()
if err != nil {
return err
}
tempName := filepath.Join(f.Dir(), RandomString(20))
if err := os.WriteFile(tempName, []byte(content), mode); err != nil {
return fmt.Errorf("create tempfile in %v: %w", f.Dir(), err)
}
// Make sure the temp file is removed if the rename below fails. On
// success, the rename has already moved the file to f.Path so this is
// a no-op (we deliberately ignore the not-exist error).
defer os.Remove(tempName)
log.Printf("Rewriting %v", f.Path)
if err := os.Rename(tempName, f.Path); err != nil {
return fmt.Errorf("atomically move temp file %v to %v: %w", tempName, f.Path, err)
}
return nil
}