Ensure file handles are always closed (#122)

* [core] Ensure files are closed even when interrupted

* [changelog] updated
This commit is contained in:
Paul Campbell 2019-07-24 18:38:19 +01:00 committed by GitHub
parent cad152379e
commit ad0f848bed
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 12 deletions

View file

@ -12,6 +12,7 @@ The format is based on [[https://keepachangelog.com/en/1.0.0/][Keep a Changelog]
- Log copy and delete operations (#119)
- Log errors with red label (#119)
- Ensure file handles are always closed (#122)
** Changed

View file

@ -5,7 +5,7 @@ import java.nio.file.Path
import java.security.MessageDigest
import net.kemitix.thorp.domain.MD5Hash
import zio.Task
import zio.{Task, UIO, ZManaged}
import scala.collection.immutable.NumericRange
@ -47,22 +47,22 @@ object MD5HashGenerator {
offset: Long,
endOffset: Long
) =
for {
fis <- openFile(file, offset)
digest <- digestFile(fis, offset, endOffset)
_ <- closeFile(fis)
} yield digest
openFile(file, offset)
.use(digestFile(_, offset, endOffset))
private def openFile(
file: File,
offset: Long
) = Task {
) =
ZManaged.make {
Task {
val stream = new FileInputStream(file)
stream skip offset
stream
}
}(closeFile)
private def closeFile(fis: FileInputStream) = Task(fis.close())
private def closeFile(fis: FileInputStream) = UIO(fis.close())
private def digestFile(
fis: FileInputStream,