Created
November 7, 2020 13:02
-
-
Save afsalthaj/cf6cf155457d27db11e7d0b6e57d5240 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileInputStream | |
import java.nio.file.{ Files, Path } | |
import cats.Applicative | |
import cats.implicits._ | |
import cats.effect.{ IO, Resource } | |
import com.amazonaws.services.s3.model.S3Object | |
import org.apache.commons.codec.digest.DigestUtils | |
import org.apache.commons.io.FileUtils | |
abstract sealed case class TemporaryLocalFile(path: Path) { | |
def writeFrom[A](s3Object: S3Object): IO[Unit] = | |
IO(FileUtils.copyInputStreamToFile(s3Object.getObjectContent, path.toFile)) | |
} | |
object TemporaryLocalFile { | |
def createResource( | |
tempDirectory: String, | |
prefix: Option[Prefix], | |
suffix: Option[Suffix] | |
): Resource[IO, TemporaryLocalFile] = | |
Resource.make(mk(tempDirectory, prefix, suffix))(_.delete.void) | |
def mk(tempDirectory: String, prefix: Option[Prefix], suffix: Option[Suffix]): IO[TemporaryLocalFile] = { | |
val getOrEmpty: Option[Either[Prefix, Suffix]] => String = | |
s => s.map(_.bimap(_.value, _.value).merge).foldMap(identity) | |
for { | |
tempDir <- IO(Files.createTempDirectory(tempDirectory)) flatTap (path => IO(path.toFile.deleteOnExit()) as path) | |
tempPath <- IO( | |
Files.createTempFile(tempDir, getOrEmpty(prefix.map(_.asLeft)), getOrEmpty(suffix.map(_.asRight))) | |
) flatTap ( | |
path => IO(path.toFile.deleteOnExit()) | |
) | |
} yield new TemporaryLocalFile(tempPath) {} | |
} | |
// Prefix or suffix that always makes sure its appended or prepended with dots | |
abstract sealed case class Prefix(value: String) | |
object Prefix { | |
def mk(s: String): Prefix = | |
if (s.endsWith(".")) { | |
new Prefix(s) {} | |
} else | |
new Prefix(s"${s}.") {} | |
} | |
abstract sealed case class Suffix(value: String) | |
object Suffix { | |
def mk(s: String): Suffix = | |
if (s.startsWith(".")) { | |
new Suffix(s) {} | |
} else new Suffix(s".${s}") {} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment