Last active
February 3, 2026 20:20
-
-
Save dacr/32eba591f8fb459dfce43dc2e799548b to your computer and use it in GitHub Desktop.
ZIO learning - playing with streams - find files / published by https://github.com/dacr/code-examples-manager #5d6e5df8-c059-4fe5-a1a2-a9a8233f601a/c4b7c7a0bacddefd1636b0670b06b9f4d0253940
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 streams - find files | |
| // keywords : scala, zio, learning, streams, find, regex, @testable | |
| // publish : gist | |
| // authors : zio | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 5d6e5df8-c059-4fe5-a1a2-a9a8233f601a | |
| // created-on : 2021-11-28T17:58:10+01:00 | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // run-with : scala-cli $file | |
| // --------------------- | |
| //> using scala "3.4.2" | |
| //> using dep "dev.zio::zio:2.0.13" | |
| //> using dep "dev.zio::zio-streams:2.0.13" | |
| // --------------------- | |
| import zio.* | |
| import zio.stream.* | |
| import java.nio.file.attribute.BasicFileAttributes | |
| import java.nio.file.{Files, Path, Paths} | |
| import scala.util.matching.Regex | |
| object App extends ZIOAppDefault { | |
| case class IssueInvalidSearchPath(th: Throwable) | |
| case class IssueInvalidRegexPattern(th: Throwable) | |
| case class IssueJavaFind(th: Throwable) | |
| case class IssueFindCollectResult(th: Throwable) | |
| type FindIssues = IssueInvalidSearchPath | IssueInvalidRegexPattern | IssueJavaFind | IssueFindCollectResult | |
| def searchPredicate(ignoreMaskRegex: Option[Regex])(path: Path, attrs: BasicFileAttributes): Boolean = | |
| attrs.isRegularFile && ( | |
| ignoreMaskRegex.isEmpty || ignoreMaskRegex.get.findFirstIn(path.toString).isDefined | |
| ) | |
| def find(searchRoot: String, findPattern: Option[String]): ZIO[Any, FindIssues, Chunk[Path]] = | |
| for | |
| searchPath <- ZIO.attempt(Path.of(searchRoot)).mapError(th => IssueInvalidSearchPath(th)) | |
| findRegex <- ZIO.attempt(findPattern.map(_.r)).mapError(th => IssueInvalidRegexPattern(th)) | |
| javaStream <- ZIO.attempt(Files.find(searchPath, 10, searchPredicate(findRegex))).mapError(th => IssueJavaFind(th)) | |
| results <- ZStream.fromJavaStream(javaStream).runCollect.mapError(th => IssueFindCollectResult(th)) | |
| yield results | |
| override def run = | |
| for { | |
| results <- find(searchRoot = ".", Some(".*")) | |
| _ <- ZIO.foreach(results)(path => Console.printLine(path)) | |
| } yield () | |
| } | |
| App.main(Array.empty) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment