From c45978252a95f862f3c7da8a453c081fc4f99ba2 Mon Sep 17 00:00:00 2001 From: Thomas Leonard Date: Sat, 22 Jun 2024 16:27:53 +0100 Subject: [PATCH] examples/fs: show how to read files while scanning --- examples/fs/main.ml | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/examples/fs/main.ml b/examples/fs/main.ml index d91e29d89..ef5b4ab0a 100644 --- a/examples/fs/main.ml +++ b/examples/fs/main.ml @@ -1,21 +1,32 @@ -(* Walks the directory tree rooted at the current directory, - displaying all directory names (skipping hidden directories and `_build`). *) - -open Eio.Std +(* Walk the directory tree rooted at the current directory, + showing a summary for any .mli files. *) let ( / ) = Eio.Path.( / ) -let rec scan t = +let is_doc_comment = String.starts_with ~prefix:"(** " + +(* Print the first line of [t]'s doc-comment, if any *) +let scan_mli t f = + Eio.Path.with_lines t (fun lines -> + Seq.find is_doc_comment lines + |> Option.iter (fun line -> + let stop = String.index_from_opt line 4 '*' |> Option.value ~default:(String.length line) in + Format.fprintf f "%a: %s@." Eio.Path.pp t (String.sub line 4 (stop - 4)) + ) + ) + +(* Walk the tree rooted at [t] and scan any .mli files found. *) +let rec scan t f = match Eio.Path.kind ~follow:false t with | `Directory -> - traceln "Visiting %a" Eio.Path.pp t; Eio.Path.read_dir t |> List.iter (function - | "_build" -> () - | item when String.starts_with ~prefix:"." item -> () - | item -> scan (t / item) - ) + | "_build" | "_opam" -> () (* Don't examine these directories *) + | item when String.starts_with ~prefix:"." item -> () (* Skip hidden items *) + | item -> scan (t / item) f + ) + | `Regular_file when Filename.check_suffix (snd t) ".mli" -> scan_mli t f | _ -> () let () = Eio_main.run @@ fun env -> - scan (Eio.Stdenv.cwd env) + scan (Eio.Stdenv.cwd env) Format.std_formatter