Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 18:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dacr/0f96462811e4499edf46f3b27617f34b to your computer and use it in GitHub Desktop.
ZIO learning - playing with nio - find files using glob / published by https://github.com/dacr/code-examples-manager #f3f5d44a-0e43-4e54-bdc0-82b1bd6f7d20/67076284fcc78fedef841046dc8e6d6792f344a6
// summary : ZIO learning - playing with nio - find files using glob
// keywords : scala, zio, learning, nio, glob, file, find, search, pure-functional, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : f3f5d44a-0e43-4e54-bdc0-82b1bd6f7d20
// created-on : 2021-06-05T19:53:50Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
//> using dep "dev.zio::zio-nio:2.0.1"
// ---------------------
import zio.*
import zio.nio.file.*
import zio.nio.charset.Charset
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.{FileVisitOption, OpenOption, StandardOpenOption}
object App extends ZIOAppDefault {
def createFile(path: Path, content: String = "hello") = {
for {
encoded <- Charset.Standard.utf16.encodeString(content)
dir <- ZIO.from(path.parent)
_ <- Files.createDirectories(dir)
_ <- Files.writeBytes(path, encoded, StandardOpenOption.CREATE)
} yield path
}
def fileFilter(path: Path, fileAttrs: BasicFileAttributes): Boolean = {
FileSystem.default
.getPathMatcher("glob:**/*.{md,sc}")
.matches(path.toFile.toPath)
}
val from = Path("/tmp") / "tests-zio-nio"
val files = List(
"a/b/c/d/f1.txt",
"a/b/f2.txt",
"a/b/c/e/f3.txt",
"a/b/c/README.md",
"a/truc.sc",
"README.md",
"blah.sc",
"bouh.txt"
)
val prepareLogic = for {
created <- ZIO.foreach(files)(f => createFile(from / f))
} yield created
val filesStream = for {
foundFile <- Files.find(from)(fileFilter)
} yield foundFile
val findLogic = filesStream.foreach(f => Console.printLine(f.toString()))
override def run = prepareLogic.zip(findLogic)
}
// -------------------------------------------------------------
App.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment