github.com/balzaczyy/golucene@v0.0.0-20151210033525-d0be9ee89713/core/util/io.go (about) 1 package util 2 3 import ( 4 _ "errors" 5 _ "fmt" 6 "io" 7 ) 8 9 type CompoundError struct { 10 errs []error 11 } 12 13 func (e *CompoundError) Error() string { 14 return e.errs[0].Error() 15 } 16 17 func CloseWhileHandlingError(priorErr error, objects ...io.Closer) error { 18 var th error = nil 19 20 for _, object := range objects { 21 if object == nil { 22 continue 23 } 24 t := safeClose(object) 25 if t == nil { 26 continue 27 } 28 if priorErr == nil { 29 addSuppressed(th, t) 30 } else { 31 addSuppressed(priorErr, t) 32 } 33 if th == nil { 34 th = t 35 } 36 } 37 38 if priorErr != nil { 39 return priorErr 40 } 41 return th 42 } 43 44 func CloseWhileSuppressingError(objects ...io.Closer) { 45 for _, object := range objects { 46 if object == nil { 47 continue 48 } 49 safeClose(object) 50 } 51 } 52 53 func Close(objects ...io.Closer) error { 54 var th error = nil 55 56 for _, object := range objects { 57 if object == nil { 58 continue 59 } 60 t := safeClose(object) 61 if t != nil { 62 addSuppressed(th, t) 63 if th == nil { 64 th = t 65 } 66 } 67 } 68 69 return th 70 } 71 72 func safeClose(obj io.Closer) (err error) { 73 // defer func() { 74 // if p := recover(); p != nil { 75 // err = errors.New(fmt.Sprintf("%v", p)) 76 // } 77 // }() 78 return obj.Close() 79 } 80 81 func addSuppressed(err error, suppressed error) error { 82 assert2(err != suppressed, "Self-suppression not permitted") 83 if suppressed == nil { 84 return err 85 } 86 if ce, ok := err.(*CompoundError); ok { 87 ce.errs = append(ce.errs, suppressed) 88 return ce 89 } 90 return &CompoundError{[]error{suppressed}} 91 } 92 93 type FileDeleter interface { 94 DeleteFile(name string) error 95 } 96 97 /* 98 Deletes all given files, suppressing all throw errors. 99 100 Note that the files should not be nil. 101 */ 102 func DeleteFilesIgnoringErrors(dir FileDeleter, files ...string) { 103 for _, name := range files { 104 dir.DeleteFile(name) // ignore error 105 } 106 } 107 108 /* 109 Ensure that any writes to the given file is written to the storage 110 device that contains it. 111 */ 112 func Fsync(fileToSync string, isDir bool) error { 113 // TODO enable fsync, now just ignored 114 return nil 115 }