Skip to content

Commit

Permalink
Add some string matching utils (#263)
Browse files Browse the repository at this point in the history
Splitting this out from #262 for ease of review; please suggest more
maintainable / idomatic ways of implementing these functions if there
are such
  • Loading branch information
JasonGross authored Jan 24, 2023
2 parents 795be0b + 8d81a74 commit fb0e357
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
16 changes: 14 additions & 2 deletions src/helpers.ml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,24 @@ open Base

let f = Printf.sprintf

let string_match ~regexp string =
let string_match ~regexp ?(pos = 0) string =
try
let _ = Str.search_forward (Str.regexp regexp) string 0 in
let (_ : int) = Str.search_forward (Str.regexp regexp) string pos in
true
with Stdlib.Not_found -> false

let rec fold_string_matches ~regexp ~f ~init ?(pos = 0) string =
if string_match ~regexp ~pos string then
let pos = Str.match_end () in
f (fun () -> fold_string_matches ~regexp ~f ~init ~pos string)
else init

let map_string_matches ~regexp ~f string =
fold_string_matches ~regexp ~f:(fun rest -> let v = f () in v :: rest ()) ~init:[] string

let iter_string_matches ~regexp ~f string =
fold_string_matches ~regexp ~f:(fun rest -> f () ; rest ()) ~init:() string

let pr_from_branch branch =
if string_match ~regexp:"^pr-\\([0-9]*\\)$" branch then
(Some (Str.matched_group 1 branch |> Int.of_string), "pull request")
Expand Down
9 changes: 8 additions & 1 deletion src/helpers.mli
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
val f : ('a, unit, string) format -> 'a

val string_match : regexp:string -> string -> bool
val string_match : regexp:string -> ?pos:int -> string -> bool

val fold_string_matches :
regexp:string -> f:((unit -> 'a) -> 'a) -> init:'a -> ?pos:int -> string -> 'a

val map_string_matches : regexp:string -> f:(unit -> 'a) -> string -> 'a list

val iter_string_matches : regexp:string -> f:(unit -> unit) -> string -> unit

val pr_from_branch : string -> int option * string

Expand Down

0 comments on commit fb0e357

Please sign in to comment.