Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples/fs: show how to read files while scanning #745

Merged
merged 1 commit into from
Jun 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 22 additions & 11 deletions examples/fs/main.ml
Original file line number Diff line number Diff line change
@@ -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
Loading