(* Copyright (c) 2024-2026 Thomas Gazagnaire Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. *) type t = { re : Re.re; (* compiled glob, anchored to the whole candidate string *) anchored : bool; (* match the path relative to [base], else its basename *) any_depth : bool; (* leading "**/": match [re] against the path at any depth *) } let drop_first s = String.sub s 1 (String.length s - 1) let compile raw = let leading_slash = raw <> "" && raw.[0] = '/' in let line = if leading_slash then drop_first raw else raw in (* A leading "**/" means "at any depth"; the remainder is then matched against the path and each of its sub-path suffixes (Re's "**" alone does not match zero directories, so the root case needs this). *) let any_depth = String.length line >= 3 && String.sub line 0 3 = "**/" in let line = if any_depth then String.sub line 3 (String.length line - 3) else line in if line = "" then None else (* A pattern is anchored when it has a leading slash, a leading "**/", or any internal slash; otherwise it matches a basename at any depth. *) let anchored = leading_slash || any_depth || String.contains line '/' in match Re.Glob.glob_result ~anchored:true ~pathname:true ~period:false ~double_asterisk:true line with | Error `Parse_error -> None | Ok re -> Some { re = Re.compile re; anchored; any_depth } (* [path] is [base] itself or lies under it. *) let under_base ~base path = base = "" || path = base || String.starts_with ~prefix:(base ^ "/") path let relative_to ~base path = if base = "" then path else String.sub path (String.length base + 1) (String.length path - String.length base - 1) let basename path = match String.rindex_opt path '/' with | None -> path | Some i -> String.sub path (i + 1) (String.length path - i - 1) (* [s] matches [re], or some suffix of [s] starting just after a '/' does. *) let rec matches_any_suffix re s = Re.execp re s || match String.index_opt s '/' with | Some i -> matches_any_suffix re (String.sub s (i + 1) (String.length s - i - 1)) | None -> false let matches t ~base ~path = if not (under_base ~base path) then false else let rel = if t.anchored then relative_to ~base path else basename path in if t.any_depth then matches_any_suffix t.re rel else Re.execp t.re rel