Last active
May 25, 2024 10:20
-
-
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/9b0f61b7ccd88de60e8566f5646086d3a4191ebb
This file contains hidden or 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
// 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.4.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