Source

ocaml-pkgbuild / bashparam.ml

Full commit
juster a4622fb 
















juster e2937f6 
juster b6e9383 
juster e2937f6 
juster b6e9383 


juster e2937f6 








juster b6e9383 























type bash_param = Param of string | ParamArray of string list

(** This is equivalent to expanding ${FOO[0]} in bash. *)
let string_of_param_elem param idx =
  match param with
    Param(str) -> if idx > 0 then "" else str
  | ParamArray (strlist) -> try List.nth strlist idx with Failure(_) -> ""

(** This is equivalent to expanding ${FOO[@]} in bash. *)
let string_of_array_param param =
  match param with
    Param(str) -> str | ParamArray (strlist) -> String.concat " " strlist

(** This is equivalent to expanding $FOO in bash. *)
let string_of_param param =
  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("")
  in expander param

(** Lookup the value of a parameter in string context.
    This is like $FOO in bash. *)
let assoc_str = make_lookup string_of_param

(** 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)