Debian Codegraph @

tools/iotools.go

raw symbols SCIP
1 package tools
2
3 import (
4 "bytes"
5 "crypto/sha256"
6 "encoding/hex"
7 "hash"
8 "io"
9 "os"
10
11 "github.com/git-lfs/git-lfs/v3/errors"
12 "github.com/git-lfs/git-lfs/v3/tr"
13 )
14
15 const (
16 // MemoryBufferLimit is the number of bytes to buffer in memory before
17 // spooling the contents of an `io.Reader` in `Spool()` to a temporary
18 // file on disk.
19 MemoryBufferLimit = 1024
20 )
21
22 // CopyWithCallback copies reader to writer while performing a progress callback
23 func CopyWithCallback(writer io.Writer, reader io.Reader, totalSize int64, cb CopyCallback) (int64, error) {
24 if success, _ := CloneFile(writer, reader); success {
25 if cb != nil {
26 cb(totalSize, totalSize, 0)
27 }
28 return totalSize, nil
29 }
30 if cb == nil {
31 return io.Copy(writer, reader)
32 }
33
34 cbReader := NewCallbackReader(reader, totalSize, cb)
35
36 return io.Copy(writer, cbReader)
37 }
38
39 type ClosingByteReader struct {
40 *bytes.Reader
41 }
42
43 // Close() is simply a no-op to complete the io.ReadSeekCloser interface.
44 func (r *ClosingByteReader) Close() error {
45 return nil
46 }
47
48 func NewClosingByteReader(b []byte) *ClosingByteReader {
49 return &ClosingByteReader{bytes.NewReader(b)}
50 }
51
52 // Get a new Hash instance of the type used to hash LFS content
53 func NewLfsContentHash() hash.Hash {
54 return sha256.New()
55 }
56
57 // HashingReader wraps a reader and calculates the hash of the data as it is read
58 type HashingReader struct {
59 reader io.Reader
60 hasher hash.Hash
61 }
62
63 func NewHashingReader(r io.Reader) *HashingReader {
64 return &HashingReader{r, NewLfsContentHash()}
65 }
66
67 func NewHashingReaderPreloadHash(r io.Reader, hash hash.Hash) *HashingReader {
68 return &HashingReader{r, hash}
69 }
70
71 func (r *HashingReader) Hash() string {
72 return hex.EncodeToString(r.hasher.Sum(nil))
73 }
74
75 func (r *HashingReader) Read(b []byte) (int, error) {
76 w, err := r.reader.Read(b)
77 if err == nil || err == io.EOF {
78 _, e := r.hasher.Write(b[0:w])
79 if e != nil && err == nil {
80 return w, e
81 }
82 }
83
84 return w, err
85 }
86
87 // RetriableReader wraps a error response of reader as RetriableError()
88 type RetriableReader struct {
89 reader io.Reader
90 }
91
92 func NewRetriableReader(r io.Reader) io.Reader {
93 return &RetriableReader{r}
94 }
95
96 func (r *RetriableReader) Read(b []byte) (int, error) {
97 n, err := r.reader.Read(b)
98
99 // EOF is a successful response as it is used to signal a graceful end
100 // of input c.f. https://git.io/v6riQ
101 //
102 // Otherwise, if the error is non-nil and already retriable (in the
103 // case that the underlying reader `r.reader` is itself a
104 // `*RetriableReader`, return the error wholesale:
105 if err == nil || err == io.EOF || errors.IsRetriableError(err) {
106 return n, err
107 }
108
109 return n, errors.NewRetriableError(err)
110 }
111
112 // Spool spools the contents from 'from' to 'to' by buffering the entire
113 // contents of 'from' into a temporary file created in the directory "dir".
114 // That buffer is held in memory until the file grows to larger than
115 // `MemoryBufferLimit`, then the remaining contents are spooled to disk.
116 //
117 // The temporary file is cleaned up after the copy is complete.
118 //
119 // The number of bytes written to "to", as well as any error encountered are
120 // returned.
121 func Spool(to io.Writer, from io.Reader, dir string) (n int64, err error) {
122 // First, buffer up to `MemoryBufferLimit` in memory.
123 buf := make([]byte, MemoryBufferLimit)
124 if bn, err := from.Read(buf); err != nil && err != io.EOF {
125 return int64(bn), err
126 } else {
127 buf = buf[:bn]
128 }
129
130 var spool io.Reader = bytes.NewReader(buf)
131 if err != io.EOF {
132 // If we weren't at the end of the stream, create a temporary
133 // file, and spool the remaining contents there.
134 tmp, err := os.CreateTemp(dir, "")
135 if err != nil {
136 return 0, errors.Wrap(err, tr.Tr.Get("Unable to create temporary file for spooling"))
137 }
138 defer func() {
139 tmp.Close()
140 os.Remove(tmp.Name())
141 }()
142
143 if n, err = io.Copy(tmp, from); err != nil {
144 return n, errors.Wrap(err, tr.Tr.Get("unable to spool"))
145 }
146
147 if _, err = tmp.Seek(0, io.SeekStart); err != nil {
148 return 0, errors.Wrap(err, tr.Tr.Get("unable to seek"))
149 }
150
151 // The spooled contents will now be the concatenation of the
152 // contents we stored in memory, then the remainder of the
153 // contents on disk.
154 spool = io.MultiReader(spool, tmp)
155 }
156
157 return io.Copy(to, spool)
158 }
159
160 // Split the input on the NUL character. Usable with bufio.Scanner.
161 func SplitOnNul(data []byte, atEOF bool) (advance int, token []byte, err error) {
162 for i := 0; i < len(data); i++ {
163 if data[i] == '\x00' {
164 return i + 1, data[:i], nil
165 }
166 }
167 return 0, nil, nil
168 }