Debian Codegraph @

util/util.go

raw symbols SCIP
1 package util
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "io/fs"
8 "os"
9 "path/filepath"
10 "strconv"
11 "sync"
12 "time"
13
14 "github.com/go-git/go-billy/v6"
15 )
16
17 const (
18 tempDirectoryMode = 0o700
19 tempFileMode = 0o600
20 )
21
22 // RemoveAll removes path and any children it contains. It removes everything it
23 // can but returns the first error it encounters. If the path does not exist,
24 // RemoveAll returns nil (no error).
25 func RemoveAll(fs billy.Basic, path string) error {
26 if r, ok := fs.(removerAll); ok {
27 return r.RemoveAll(path)
28 }
29
30 return removeAll(fs, path)
31 }
32
33 type removerAll interface {
34 RemoveAll(string) error
35 }
36
37 func removeAll(fs billy.Basic, path string) error {
38 // This implementation is adapted from os.RemoveAll.
39
40 // Simple case: if Remove works, we're done.
41 err := fs.Remove(path)
42 if err == nil || errors.Is(err, os.ErrNotExist) {
43 return nil
44 }
45
46 // Otherwise, is this a directory we need to recurse into?
47 dir, serr := lstat(fs, path)
48 if serr != nil {
49 if errors.Is(serr, os.ErrNotExist) {
50 return nil
51 }
52
53 return serr
54 }
55
56 if dir.Mode()&os.ModeSymlink != 0 || !dir.IsDir() {
57 // Not a directory we should recurse into; return the error from Remove.
58 return err
59 }
60
61 dirfs, ok := fs.(billy.Dir)
62 if !ok {
63 return billy.ErrNotSupported
64 }
65
66 // Directory.
67 fis, err := dirfs.ReadDir(path)
68 if err != nil {
69 if errors.Is(err, os.ErrNotExist) {
70 // Race. It was deleted between the Lstat and ReadDir.
71 // Return nil per RemoveAll's docs.
72 return nil
73 }
74
75 return err
76 }
77
78 // Remove contents & return first error.
79 err = nil
80 for _, fi := range fis {
81 cpath := fs.Join(path, fi.Name())
82 err1 := removeAll(fs, cpath)
83 if err == nil {
84 err = err1
85 }
86 }
87
88 // Remove directory.
89 err1 := fs.Remove(path)
90 if err1 == nil || errors.Is(err1, os.ErrNotExist) {
91 return nil
92 }
93
94 if err == nil {
95 err = err1
96 }
97
98 return err
99 }
100
101 func lstat(filesystem billy.Basic, path string) (fs.FileInfo, error) {
102 if sl, ok := filesystem.(billy.Symlink); ok {
103 // Avoid following a symlink substituted after the initial Remove fails.
104 fi, err := sl.Lstat(path)
105 if err == nil || !errors.Is(err, billy.ErrNotSupported) {
106 return fi, err
107 }
108 }
109
110 return filesystem.Stat(path)
111 }
112
113 // WriteFile writes data to a file named by filename in the given filesystem.
114 // If the file does not exist, WriteFile creates it with permissions perm;
115 // otherwise WriteFile truncates it before writing.
116 func WriteFile(fs billy.Basic, filename string, data []byte, perm fs.FileMode) (err error) {
117 f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
118 if err != nil {
119 return err
120 }
121 defer func() {
122 if f != nil {
123 err1 := f.Close()
124 if err == nil {
125 err = err1
126 }
127 }
128 }()
129
130 n, err := f.Write(data)
131 if err == nil && n < len(data) {
132 err = io.ErrShortWrite
133 }
134 if err != nil {
135 return err
136 }
137 if sf, ok := f.(billy.Syncer); ok {
138 return sf.Sync()
139 }
140
141 return nil
142 }
143
144 // Random number state.
145 // We generate random temporary file names so that there's a good
146 // chance the file doesn't exist yet - keeps the number of tries in
147 // TempFile to a minimum.
148 var (
149 rand uint32
150 randmu sync.Mutex
151 )
152
153 func reseed() uint32 {
154 return uint32(time.Now().UnixNano() + int64(os.Getpid()))
155 }
156
157 func nextSuffix() string {
158 randmu.Lock()
159 r := rand
160 if r == 0 {
161 r = reseed()
162 }
163 r = r*1664525 + 1013904223 // constants from Numerical Recipes
164 rand = r
165 randmu.Unlock()
166 return strconv.Itoa(int(1e9 + r%1e9))[1:]
167 }
168
169 // TempFile creates a new temporary file in the directory dir with a name
170 // beginning with prefix, opens the file for reading and writing, and returns
171 // the resulting *os.File. If dir is the empty string, TempFile uses the default
172 // directory for temporary files (see os.TempDir). Multiple programs calling
173 // TempFile simultaneously will not choose the same file. The caller can use
174 // f.Name() to find the pathname of the file. It is the caller's responsibility
175 // to remove the file when no longer needed.
176 func TempFile(fs billy.Basic, dir, prefix string) (f billy.File, err error) {
177 // This implementation is based on stdlib ioutil.TempFile.
178 if dir == "" {
179 dir = getTempDir(fs)
180 }
181
182 nconflict := 0
183 for range 10000 {
184 name := filepath.Join(dir, prefix+nextSuffix())
185 f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, tempFileMode)
186 if errors.Is(err, os.ErrExist) {
187 if nconflict++; nconflict > 10 {
188 randmu.Lock()
189 rand = reseed()
190 randmu.Unlock()
191 }
192 continue
193 }
194 break
195 }
196 return
197 }
198
199 // TempDir creates a new temporary directory in the directory dir
200 // with a name beginning with prefix and returns the path of the
201 // new directory. If dir is the empty string, TempDir uses the
202 // default directory for temporary files (see os.TempDir).
203 // Multiple programs calling TempDir simultaneously
204 // will not choose the same directory. It is the caller's responsibility
205 // to remove the directory when no longer needed.
206 func TempDir(fs billy.Dir, dir, prefix string) (name string, err error) {
207 // This implementation is based on stdlib ioutil.TempDir
208 if dir == "" {
209 base, ok := fs.(billy.Basic)
210 if !ok {
211 return "", fmt.Errorf("fs does not implement billy.Basic")
212 }
213 dir = getTempDir(base)
214 }
215
216 nconflict := 0
217 for range 10000 {
218 try := filepath.Join(dir, prefix+nextSuffix())
219 err = fs.MkdirAll(try, tempDirectoryMode)
220 if errors.Is(err, os.ErrExist) {
221 if nconflict++; nconflict > 10 {
222 randmu.Lock()
223 rand = reseed()
224 randmu.Unlock()
225 }
226 continue
227 }
228 if errors.Is(err, os.ErrNotExist) {
229 if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
230 return "", err
231 }
232 }
233 if err == nil {
234 name = try
235 }
236 break
237 }
238 return
239 }
240
241 func getTempDir(fs billy.Basic) string {
242 ch, ok := fs.(billy.Chroot)
243 if !ok || ch.Root() == "" || ch.Root() == "/" || ch.Root() == string(filepath.Separator) {
244 return os.TempDir()
245 }
246
247 return ".tmp"
248 }
249
250 // ReadFile reads the named file and returns the contents from the given filesystem.
251 // A successful call returns err == nil, not err == EOF.
252 // Because ReadFile reads the whole file, it does not treat an EOF from Read
253 // as an error to be reported.
254 func ReadFile(fs billy.Basic, name string) ([]byte, error) {
255 f, err := fs.Open(name)
256 if err != nil {
257 return nil, err
258 }
259
260 defer f.Close()
261
262 return io.ReadAll(f)
263 }