Basic file locking

Needs tests
This commit is contained in:
Alexandre Archambault 2015-07-06 01:48:26 +01:00
parent d7696cc445
commit d84fcf6608
1 changed files with 32 additions and 15 deletions

View File

@ -1,6 +1,7 @@
package coursier
import java.net.URL
import java.nio.channels.{ OverlappingFileLockException, FileLock }
import java.security.MessageDigest
import java.util.concurrent.{ Executors, ExecutorService }
@ -92,27 +93,43 @@ case class Files(
logger.foreach(_.downloadingArtifact(url))
val url0 = new URL(url)
val b = Array.fill[Byte](Files.bufferSize)(0)
val in = new BufferedInputStream(url0.openStream(), Files.bufferSize)
try {
val out = new FileOutputStream(file)
val result =
try {
@tailrec
def helper(): Unit = {
val read = in.read(b)
if (read >= 0) {
out.write(b, 0, read)
helper()
}
}
val out = new FileOutputStream(file)
try {
var lock: FileLock = null
try {
lock = out.getChannel.tryLock()
if (lock == null)
-\/(FileError.Locked(file.toString))
else {
val b = Array.fill[Byte](Files.bufferSize)(0)
helper()
} finally out.close()
} finally in.close()
@tailrec
def helper(): Unit = {
val read = in.read(b)
if (read >= 0) {
out.write(b, 0, read)
helper()
}
}
helper()
\/-(file)
}
}
catch {
case e: OverlappingFileLockException =>
-\/(FileError.Locked(file.toString))
}
finally if (lock != null) lock.release()
} finally out.close()
} finally in.close()
logger.foreach(_.downloadedArtifact(url, success = true))
\/-(file)
result
}
catch { case e: Exception =>
logger.foreach(_.downloadedArtifact(url, success = false))