Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/32eba591f8fb459dfce43dc2e799548b to your computer and use it in GitHub Desktop.
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/9f5325770b93b74735955d8cb261a5e8e09ef563
// summary : ZIO learning - playing with streams - find files
// keywords : scala, zio, learning, streams, find, regex, @testable
// publish : gist
// authors : zio
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// 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.2.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