Commits

juster  committed b6e9383

Add assoc_arr_indices and match_names functions to Bashparam module.

  • Participants
  • Parent commits edb0293

Comments (0)

Files changed (2)

File bashparam.ml

   match param with
     Param(str) -> str | ParamArray (_) -> string_of_param_elem param 0
 
+(** Create a lookup closure that returns the empty string as default. *)
 let make_lookup expander name plist =
-  let param = try List.assoc name plist
-  with Not_found -> Param("")
+  let param =
+    try  List.assoc name plist
+    with Not_found -> Param("")
   in expander param
 
 (** Lookup the value of a parameter in string context.
 (** Lookup the value of a parameter in array context.
     This is like ${FOO[@]} in bash. *)
 let assoc_arr = make_lookup string_of_array_param
+
+(** Return a string of all the array indices or 0 if not an array.
+    This is used for an expansion like: ${!FOO[*]} *)
+let assoc_arr_indices = make_lookup begin
+  function
+    | Param(_) -> "0"
+    | ParamArray(arr) ->
+      (* Creates a string list of indices. *)
+        let rec indices_list i length =
+          if i >= length then []
+          else string_of_int i :: indices_list (i + 1) length
+        in String.concat " " (indices_list 0 (List.length arr))
+end
+
+(** Return a string of all parameter names that are prefixed with prefix. *)
+let match_names prefix plist =
+  let prelen = String.length prefix in
+  let match_prefix name =
+    if String.length name < prelen then false
+    else
+      let strstart = String.sub name 0 prelen in
+      strstart == prefix
+  in
+  let found = List.filter (function (name, _) -> match_prefix name) plist in
+  String.concat " " (List.map (fun x -> fst x) found)

File bashparam.mli

 
 val assoc_str : string -> (string * bash_param) list -> string
 val assoc_arr : string -> (string * bash_param) list -> string
+val assoc_arr_indices : string -> (string * bash_param) list -> string
+
+val match_names : string -> (string * bash_param) list -> string