github.com/catandhorse/git-lfs@v2.5.2+incompatible/tools/sync_writer.go (about) 1 package tools 2 3 import "io" 4 5 // closeFn is the type of func Close() in the io.Closer interface. 6 type closeFn func() error 7 8 // syncFn is the type of func Sync() in the *os.File implementation. 9 type syncFn func() error 10 11 // SyncWriter provides a wrapper around an io.Writer that synchronizes all 12 // write after they occur, if the underlying writer supports synchronization. 13 type SyncWriter struct { 14 w io.Writer 15 16 closeFn closeFn 17 syncFn syncFn 18 } 19 20 // NewSyncWriter returns a new instance of the *SyncWriter that sends all writes 21 // to the given io.Writer. 22 func NewSyncWriter(w io.Writer) *SyncWriter { 23 sw := &SyncWriter{ 24 w: w, 25 } 26 27 if sync, ok := w.(interface { 28 Sync() error 29 }); ok { 30 sw.syncFn = sync.Sync 31 } else { 32 sw.syncFn = func() error { return nil } 33 } 34 35 if close, ok := w.(io.Closer); ok { 36 sw.closeFn = close.Close 37 } else { 38 sw.closeFn = func() error { return nil } 39 } 40 41 return sw 42 } 43 44 // Write will write to the file and perform a Sync() if writing succeeds. 45 func (w *SyncWriter) Write(b []byte) error { 46 if _, err := w.w.Write(b); err != nil { 47 return err 48 } 49 return w.syncFn() 50 } 51 52 // Close will call Close() on the underlying file 53 func (w *SyncWriter) Close() error { 54 return w.closeFn() 55 }