(****************************************************************************)
(*  Copyright © 2012-2015 Mehdi Dogguy <mehdi@debian.org>                   *)
(*                                                                          *)
(*  This file is part of Dochelp.                                           *)
(*                                                                          *)
(*  Dochelp is free software: you can redistribute it and/or modify it      *)
(*  under the terms of the GNU General Public License as published by the   *)
(*  Free Software Foundation, either version 3 of the License, or (at your  *)
(*  option) any later version.                                              *)
(*                                                                          *)
(*  Dochelp is distributed in the hope that it will be useful, but WITHOUT  *)
(*  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or   *)
(*  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License   *)
(*  for more details.                                                       *)
(*                                                                          *)
(*  You should have received a copy of the GNU General Public License       *)
(*  along with Dochelp.  If not, see <http://www.gnu.org/licenses/>.        *)
(****************************************************************************)

let (//) = Filename.concat
let ($) f g = f g

let regexp_match rex =
  fun string ->
    try
      ignore (Pcre.exec ~rex string);
      true
    with Not_found ->
      false

external glob : string -> string array = "ocaml_glob"

let glob_l s =
  Array.to_list $ glob s

let with_in_file file f =
  let chan = open_in_bin file in
  try
    let res = f chan in
    close_in chan; res
  with e -> close_in chan; raise e

let print_files files =
  let files = glob files in
  if Array.length files > 0 then begin
    print_endline "Files:";
    Array.iter begin fun file ->
      Printf.printf " %s\n" file
    end files
  end

let print_s f s = Printf.printf f s
let print_o f = function
| None -> Printf.ifprintf f ""
| Some s -> print_s f s

let is_valid_doc_base_file =
  let rex = Pcre.regexp "^[-a-z0-9\\+\\.]+$" in
  regexp_match rex

let iter_files directory f =
  let open Unix in
      Array.iter begin fun filename ->
        let file = directory // filename in
        if (stat file).st_kind = S_REG then
          f file filename
      end (Sys.readdir directory)

let fold_files directory f accu =
  let open Unix in
      Array.fold_left begin fun accu filename ->
        let file = directory // filename in
        if (stat file).st_kind = S_REG then
          f accu file filename
        else accu
      end accu (Sys.readdir directory)
