ounit-1.1.2/0000755000175000017500000000000011765510533012201 5ustar gildorgildorounit-1.1.2/_oasis0000644000175000017500000000246111765510533013404 0ustar gildorgildorOASISFormat: 0.2 Name: ounit Version: 1.1.2 Synopsis: Unit testing framework Authors: Maas-Maarten Zeeman, Sylvain Le Gall Copyrights: (C) 2002-2008 Maas-Maarten Zeeman, (C) 2010 OCamlCore SARL License: MIT LicenseFile: LICENSE.txt Homepage: http://ounit.forge.ocamlcore.org Plugins: META (0.2), StdFiles (0.2), DevFiles (0.2) BuildTools: ocamlbuild, camlp4 Description: OUnit is a unit testing framework for OCaml, inspired by the JUnit tool for Java, and the HUnit tool for Haskell. . More information on [HUnit](http://hunit.sourceforge.net) Flag backtrace Description: Enable backtrace display in exception Library "oUnit" Path: src Modules: OUnit, OUnitDiff BuildDepends: unix if flag(backtrace) ByteOpt: -ppopt -DBACKTRACE NativeOpt: -ppopt -DBACKTRACE Executable test Path: test MainIs: test.ml BuildDepends: oUnit Install: false Test main Command: $test Document "api-ounit" Title: API reference for OUnit Type: ocamlbuild (0.2) BuildTools+: ocamldoc XOCamlbuildLibraries: oUnit XOCamlbuildPath: src/ SourceRepository head Type: darcs Location: http://darcs.ocamlcore.org/repos/ounit Browser: http://darcs.ocamlcore.org/cgi-bin/darcsweb.cgi?r=ounit;a=summary ounit-1.1.2/README.txt0000644000175000017500000000107611765510533013703 0ustar gildorgildor(* OASIS_START *) (* DO NOT EDIT (digest: ac260da3dc5dbc8b63343daec02e41ac) *) This is the README file for the ounit distribution. (C) 2002-2008 Maas-Maarten Zeeman (C) 2010 OCamlCore SARL Unit testing framework OUnit is a unit testing framework for OCaml, inspired by the JUnit tool for Java, and the HUnit tool for Haskell. More information on [HUnit](http://hunit.sourceforge.net) See the files INSTALL.txt for building and installation instructions. See the file LICENSE.txt for copying conditions. Home page: http://ounit.forge.ocamlcore.org (* OASIS_STOP *) ounit-1.1.2/examples/0000755000175000017500000000000011765510533014017 5ustar gildorgildorounit-1.1.2/examples/test_list.ml0000644000175000017500000000070011765510533016360 0ustar gildorgildoropen OUnit let empty_list = [] let list_a = [1;2;3] let test_list_length _ = assert_equal 1 (List.length empty_list); assert_equal 3 (List.length list_a) (* etc, etc *) let test_list_append _ = let list_b = List.append empty_list [1;2;3] in assert_equal list_b list_a let suite = "OUnit Example" >::: ["test_list_length" >:: test_list_length; "test_list_append" >:: test_list_append] (* let _ = run_test_tt_main suite *) ounit-1.1.2/examples/Makefile0000644000175000017500000000061311765510533015457 0ustar gildorgildor# # TESTS = test_list.ml test_list2.ml test_stack.ml test: test_suite example -./test_suite -./example test_suite: $(TESTS) test_suite.ml ocamlfind ocamlc -o test_suite -package oUnit -linkpkg \ test_list.ml test_list2.ml test_stack.ml test_suite.ml example: example.ml ocamlfind ocamlc -o example -package oUnit -linkpkg \ example.ml clean: -$(RM) *.cmi *.cmo test_suite example ounit-1.1.2/examples/test_stack.ml0000644000175000017500000000152111765510533016514 0ustar gildorgildoropen OUnit (* * This test shows how brackets can be used. They are handy to create * a so called fixture, which can be used for multiple tests *) (* prepare a stack for test *) let setup _ = let s = Stack.create () in Stack.push 1 s; Stack.push 2 s; Stack.push 3 s; s let teardown _ = () let test_top stack = assert_equal 3 (Stack.top stack) let test_clear stack = Stack.clear stack; assert_raises Stack.Empty (fun _ -> Stack.top stack) let test_pop stack = assert_equal 3 (Stack.pop stack); assert_equal 2 (Stack.pop stack); assert_equal 1 (Stack.pop stack); assert_raises Stack.Empty (fun _ -> Stack.pop stack) let suite = "Test Stack" >::: ["test_top" >:: (bracket setup test_top teardown); "test_clear" >:: (bracket setup test_clear teardown); "test_pop" >:: (bracket setup test_pop teardown)] ounit-1.1.2/examples/test_suite.ml0000644000175000017500000000032011765510533016534 0ustar gildorgildoropen OUnit (* Collect the tests of different modules into one test suite *) let suite = "OUnit Example" >::: [Test_list.suite; Test_list2.suite; Test_stack.suite] let _ = run_test_tt_main suite ounit-1.1.2/examples/example.ml0000644000175000017500000000066711765510533016015 0ustar gildorgildoropen OUnit let empty_list = [] let list_a = [1;2;3] let test_list_length _ = assert_equal 1 (List.length empty_list); assert_equal 3 (List.length list_a) (* etc, etc *) let test_list_append _ = let list_b = List.append empty_list [1;2;3] in assert_equal list_b list_a let suite = "OUnit Example" >::: ["test_list_length" >:: test_list_length; "test_list_append" >:: test_list_append] let _ = run_test_tt_main suite ounit-1.1.2/examples/test_list2.ml0000644000175000017500000000063211765510533016446 0ustar gildorgildoropen OUnit let empty_list = [] let list_a = [1;2;3] let test_list_length _ = assert_equal 1 (List.length empty_list); assert_equal 3 (List.length list_a) (* etc, etc *) let test_list_append _ = let list_b = List.append empty_list [1;2;3] in assert_equal list_b list_a let suite = "Test_list2" >::: ["test_list_length2" >:: test_list_length; "test_list_append2" >:: test_list_append] ounit-1.1.2/Makefile0000644000175000017500000000167011765510533013645 0ustar gildorgildor#TESTFLAGS=-only-test "OUnit:1" default: test # OASIS_START # DO NOT EDIT (digest: bc1e05bfc8b39b664f29dae8dbd3ebbb) SETUP = ocaml setup.ml build: setup.data $(SETUP) -build $(BUILDFLAGS) doc: setup.data build $(SETUP) -doc $(DOCFLAGS) test: setup.data build $(SETUP) -test $(TESTFLAGS) all: $(SETUP) -all $(ALLFLAGS) install: setup.data $(SETUP) -install $(INSTALLFLAGS) uninstall: setup.data $(SETUP) -uninstall $(UNINSTALLFLAGS) reinstall: setup.data $(SETUP) -reinstall $(REINSTALLFLAGS) clean: $(SETUP) -clean $(CLEANFLAGS) distclean: $(SETUP) -distclean $(DISTCLEANFLAGS) setup.data: $(SETUP) -configure $(CONFIGUREFLAGS) .PHONY: build doc test all install uninstall reinstall clean distclean configure # OASIS_STOP doc-test: doc ocamldoc -g ../ocaml-tmp/odoc-extract-code/odoc_extract_code.cmo \ -load _build/src/oUnit.odoc -intro doc/manual.txt > _build/src/tmp.ml; ocamlc -c -I _build/src/ _build/src/tmp.ml ounit-1.1.2/myocamlbuild.ml0000644000175000017500000004530411765510533015222 0ustar gildorgildor(* OASIS_START *) (* DO NOT EDIT (digest: 6734ccf68190fa1cf092623f29f63fbd) *) module OASISGettext = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISGettext.ml" let ns_ str = str let s_ str = str let f_ (str : ('a, 'b, 'c, 'd) format4) = str let fn_ fmt1 fmt2 n = if n = 1 then fmt1^^"" else fmt2^^"" let init = [] end module OASISExpr = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISExpr.ml" open OASISGettext type test = string type flag = string type t = | EBool of bool | ENot of t | EAnd of t * t | EOr of t * t | EFlag of flag | ETest of test * string type 'a choices = (t * 'a) list let eval var_get t = let rec eval' = function | EBool b -> b | ENot e -> not (eval' e) | EAnd (e1, e2) -> (eval' e1) && (eval' e2) | EOr (e1, e2) -> (eval' e1) || (eval' e2) | EFlag nm -> let v = var_get nm in assert(v = "true" || v = "false"); (v = "true") | ETest (nm, vl) -> let v = var_get nm in (v = vl) in eval' t let choose ?printer ?name var_get lst = let rec choose_aux = function | (cond, vl) :: tl -> if eval var_get cond then vl else choose_aux tl | [] -> let str_lst = if lst = [] then s_ "" else String.concat (s_ ", ") (List.map (fun (cond, vl) -> match printer with | Some p -> p vl | None -> s_ "") lst) in match name with | Some nm -> failwith (Printf.sprintf (f_ "No result for the choice list '%s': %s") nm str_lst) | None -> failwith (Printf.sprintf (f_ "No result for a choice list: %s") str_lst) in choose_aux (List.rev lst) end # 117 "myocamlbuild.ml" module BaseEnvLight = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseEnvLight.ml" module MapString = Map.Make(String) type t = string MapString.t let default_filename = Filename.concat (Sys.getcwd ()) "setup.data" let load ?(allow_empty=false) ?(filename=default_filename) () = if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in let line = ref 1 in let st_line = Stream.from (fun _ -> try match Stream.next st with | '\n' -> incr line; Some '\n' | c -> Some c with Stream.Failure -> None) in let lexer = Genlex.make_lexer ["="] st_line in let rec read_file mp = match Stream.npeek 3 lexer with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lexer; Stream.junk lexer; Stream.junk lexer; read_file (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in let mp = read_file MapString.empty in close_in chn; mp end else if allow_empty then begin MapString.empty end else begin failwith (Printf.sprintf "Unable to load environment, the file '%s' doesn't exist." filename) end let var_get name env = let rec var_expand str = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff in var_expand (MapString.find name env) let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 215 "myocamlbuild.ml" module MyOCamlbuildFindlib = struct # 21 "/home/gildor/programmation/oasis/src/plugins/ocamlbuild/MyOCamlbuildFindlib.ml" (** OCamlbuild extension, copied from * http://brion.inria.fr/gallium/index.php/Using_ocamlfind_with_ocamlbuild * by N. Pouillard and others * * Updated on 2009/02/28 * * Modified by Sylvain Le Gall *) open Ocamlbuild_plugin (* these functions are not really officially exported *) let run_and_read = Ocamlbuild_pack.My_unix.run_and_read let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings let split s ch = let x = ref [] in let rec go s = let pos = String.index s ch in x := (String.before s pos)::!x; go (String.after s (pos + 1)) in try go s with Not_found -> !x let split_nl s = split s '\n' let before_space s = try String.before s (String.index s ' ') with Not_found -> s (* this lists all supported packages *) let find_packages () = List.map before_space (split_nl & run_and_read "ocamlfind list") (* this is supposed to list available syntaxes, but I don't know how to do it. *) let find_syntaxes () = ["camlp4o"; "camlp4r"] (* ocamlfind command *) let ocamlfind x = S[A"ocamlfind"; x] let dispatch = function | Before_options -> (* by using Before_options one let command line options have an higher priority *) (* on the contrary using After_options will guarantee to have the higher priority *) (* override default commands by ocamlfind ones *) Options.ocamlc := ocamlfind & A"ocamlc"; Options.ocamlopt := ocamlfind & A"ocamlopt"; Options.ocamldep := ocamlfind & A"ocamldep"; Options.ocamldoc := ocamlfind & A"ocamldoc"; Options.ocamlmktop := ocamlfind & A"ocamlmktop" | After_rules -> (* When one link an OCaml library/binary/package, one should use -linkpkg *) flag ["ocaml"; "link"; "program"] & A"-linkpkg"; (* For each ocamlfind package one inject the -package option when * compiling, computing dependencies, generating documentation and * linking. *) List.iter begin fun pkg -> flag ["ocaml"; "compile"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "doc"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "link"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S[A"-package"; A pkg]; end (find_packages ()); (* Like -package but for extensions syntax. Morover -syntax is useless * when linking. *) List.iter begin fun syntax -> flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "infer_interface"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; end (find_syntaxes ()); (* The default "thread" tag is not compatible with ocamlfind. * Indeed, the default rules add the "threads.cma" or "threads.cmxa" * options when using this tag. When using the "-linkpkg" option with * ocamlfind, this module will then be added twice on the command line. * * To solve this, one approach is to add the "-thread" option when using * the "threads" package using the previous plugin. *) flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "doc"] (S[A "-I"; A "+threads"]); flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "infer_interface"] (S[A "-thread"]) | _ -> () end module MyOCamlbuildBase = struct # 21 "/home/gildor/programmation/oasis/src/plugins/ocamlbuild/MyOCamlbuildBase.ml" (** Base functions for writing myocamlbuild.ml @author Sylvain Le Gall *) open Ocamlbuild_plugin module OC = Ocamlbuild_pack.Ocaml_compiler type dir = string type file = string type name = string type tag = string # 56 "/home/gildor/programmation/oasis/src/plugins/ocamlbuild/MyOCamlbuildBase.ml" type t = { lib_ocaml: (name * dir list) list; lib_c: (name * dir * file list) list; flags: (tag list * (spec OASISExpr.choices)) list; (* Replace the 'dir: include' from _tags by a precise interdepends in * directory. *) includes: (dir * dir list) list; } let env_filename = Pathname.basename BaseEnvLight.default_filename let dispatch_combine lst = fun e -> List.iter (fun dispatch -> dispatch e) lst let tag_libstubs nm = "use_lib"^nm^"_stubs" let nm_libstubs nm = nm^"_stubs" let dispatch t e = let env = BaseEnvLight.load ~filename:env_filename ~allow_empty:true () in match e with | Before_options -> let no_trailing_dot s = if String.length s >= 1 && s.[0] = '.' then String.sub s 1 ((String.length s) - 1) else s in List.iter (fun (opt, var) -> try opt := no_trailing_dot (BaseEnvLight.var_get var env) with Not_found -> Printf.eprintf "W: Cannot get variable %s" var) [ Options.ext_obj, "ext_obj"; Options.ext_lib, "ext_lib"; Options.ext_dll, "ext_dll"; ] | Before_rules -> (* TODO: move this into its own file and conditionnaly include it, if * needed. *) (* OCaml cmxs rules: cmxs available in ocamlopt but not ocamlbuild. Copied from ocaml_specific.ml in ocamlbuild sources. *) let has_native_dynlink = try bool_of_string (BaseEnvLight.var_get "native_dynlink" env) with Not_found -> false in if has_native_dynlink && String.sub Sys.ocaml_version 0 4 = "3.11" then begin let ext_lib = !Options.ext_lib in let ext_obj = !Options.ext_obj in let ext_dll = !Options.ext_dll in let x_o = "%"-.-ext_obj in let x_a = "%"-.-ext_lib in let x_dll = "%"-.-ext_dll in let x_p_o = "%.p"-.-ext_obj in let x_p_a = "%.p"-.-ext_lib in let x_p_dll = "%.p"-.-ext_dll in rule "ocaml: mldylib & p.cmx* & p.o* -> p.cmxs & p.so" ~tags:["ocaml"; "native"; "profile"; "shared"; "library"] ~prods:["%.p.cmxs"; x_p_dll] ~dep:"%.mldylib" (OC.native_profile_shared_library_link_mldylib "%.mldylib" "%.p.cmxs"); rule "ocaml: mldylib & cmx* & o* -> cmxs & so" ~tags:["ocaml"; "native"; "shared"; "library"] ~prods:["%.cmxs"; x_dll] ~dep:"%.mldylib" (OC.native_shared_library_link_mldylib "%.mldylib" "%.cmxs"); rule "ocaml: p.cmx & p.o -> p.cmxs & p.so" ~tags:["ocaml"; "native"; "profile"; "shared"; "library"] ~prods:["%.p.cmxs"; x_p_dll] ~deps:["%.p.cmx"; x_p_o] (OC.native_shared_library_link ~tags:["profile"] "%.p.cmx" "%.p.cmxs"); rule "ocaml: p.cmxa & p.a -> p.cmxs & p.so" ~tags:["ocaml"; "native"; "profile"; "shared"; "library"] ~prods:["%.p.cmxs"; x_p_dll] ~deps:["%.p.cmxa"; x_p_a] (OC.native_shared_library_link ~tags:["profile"; "linkall"] "%.p.cmxa" "%.p.cmxs"); rule "ocaml: cmx & o -> cmxs" ~tags:["ocaml"; "native"; "shared"; "library"] ~prods:["%.cmxs"] ~deps:["%.cmx"; x_o] (OC.native_shared_library_link "%.cmx" "%.cmxs"); rule "ocaml: cmx & o -> cmxs & so" ~tags:["ocaml"; "native"; "shared"; "library"] ~prods:["%.cmxs"; x_dll] ~deps:["%.cmx"; x_o] (OC.native_shared_library_link "%.cmx" "%.cmxs"); rule "ocaml: cmxa & a -> cmxs & so" ~tags:["ocaml"; "native"; "shared"; "library"] ~prods:["%.cmxs"; x_dll] ~deps:["%.cmxa"; x_a] (OC.native_shared_library_link ~tags:["linkall"] "%.cmxa" "%.cmxs"); end | After_rules -> (* Declare OCaml libraries *) List.iter (function | nm, [] -> ocaml_lib nm | nm, dir :: tl -> ocaml_lib ~dir:dir (dir^"/"^nm); List.iter (fun dir -> List.iter (fun str -> flag ["ocaml"; "use_"^nm; str] (S[A"-I"; P dir])) ["compile"; "infer_interface"; "doc"]) tl) t.lib_ocaml; (* Declare directories dependencies, replace "include" in _tags. *) List.iter (fun (dir, include_dirs) -> Pathname.define_context dir include_dirs) t.includes; (* Declare C libraries *) List.iter (fun (lib, dir, headers) -> (* Handle C part of library *) flag ["link"; "library"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("-l"^(nm_libstubs lib)); A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "library"; "ocaml"; "native"; tag_libstubs lib] (S[A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "program"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("dll"^(nm_libstubs lib))]); (* When ocaml link something that use the C library, then one need that file to be up to date. *) dep ["link"; "ocaml"; "program"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; dep ["compile"; "ocaml"; "program"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; (* TODO: be more specific about what depends on headers *) (* Depends on .h files *) dep ["compile"; "c"] headers; (* Setup search path for lib *) flag ["link"; "ocaml"; "use_"^lib] (S[A"-I"; P(dir)]); ) t.lib_c; (* Add flags *) List.iter (fun (tags, cond_specs) -> let spec = BaseEnvLight.var_choose cond_specs env in flag tags & spec) t.flags | _ -> () let dispatch_default t = dispatch_combine [ dispatch t; MyOCamlbuildFindlib.dispatch; ] end # 548 "myocamlbuild.ml" open Ocamlbuild_plugin;; let package_default = { MyOCamlbuildBase.lib_ocaml = [("oUnit", ["src"])]; lib_c = []; flags = [ (["oasis_library_ounit_byte"; "ocaml"; "link"; "byte"], [ (OASISExpr.EBool true, S []); (OASISExpr.EFlag "backtrace", S [A "-ppopt"; A "-DBACKTRACE"]) ]); (["oasis_library_ounit_native"; "ocaml"; "link"; "native"], [ (OASISExpr.EBool true, S []); (OASISExpr.EFlag "backtrace", S [A "-ppopt"; A "-DBACKTRACE"]) ]); (["oasis_library_ounit_byte"; "ocaml"; "ocamldep"; "byte"], [ (OASISExpr.EBool true, S []); (OASISExpr.EFlag "backtrace", S [A "-ppopt"; A "-DBACKTRACE"]) ]); (["oasis_library_ounit_native"; "ocaml"; "ocamldep"; "native"], [ (OASISExpr.EBool true, S []); (OASISExpr.EFlag "backtrace", S [A "-ppopt"; A "-DBACKTRACE"]) ]); (["oasis_library_ounit_byte"; "ocaml"; "compile"; "byte"], [ (OASISExpr.EBool true, S []); (OASISExpr.EFlag "backtrace", S [A "-ppopt"; A "-DBACKTRACE"]) ]); (["oasis_library_ounit_native"; "ocaml"; "compile"; "native"], [ (OASISExpr.EBool true, S []); (OASISExpr.EFlag "backtrace", S [A "-ppopt"; A "-DBACKTRACE"]) ]) ]; includes = [("test", ["src"])]; } ;; let dispatch_default = MyOCamlbuildBase.dispatch_default package_default;; # 594 "myocamlbuild.ml" (* OASIS_STOP *) Ocamlbuild_plugin.dispatch (function | After_rules as e -> dep ["doc"; "docdir"; "extension:html"; "ocaml"; "oasis_document_api_ounit"] & ["doc/manual.txt"]; flag ["doc"; "docdir"; "extension:html"; "ocaml"; "oasis_document_api_ounit"] & (S[A"-t"; A"OUnit user guide"; A"-intro"; P"doc/manual.txt"; A"-colorize-code"]); dispatch_default e | e -> dispatch_default e) ;; ounit-1.1.2/setup.ml0000644000175000017500000046103511765510533013704 0ustar gildorgildor(* setup.ml generated for the first time by OASIS v0.2.0~alpha1 *) (* OASIS_START *) (* DO NOT EDIT (digest: 3898e020bbe0544be241273d25b44d1b) *) (* Regenerated by OASIS v0.3.0~rc6 Visit http://oasis.forge.ocamlcore.org for more information and documentation about functions used in this file. *) module OASISGettext = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISGettext.ml" let ns_ str = str let s_ str = str let f_ (str : ('a, 'b, 'c, 'd) format4) = str let fn_ fmt1 fmt2 n = if n = 1 then fmt1^^"" else fmt2^^"" let init = [] end module OASISContext = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISContext.ml" open OASISGettext type level = [ `Debug | `Info | `Warning | `Error] type t = { quiet: bool; info: bool; debug: bool; ignore_plugins: bool; ignore_unknown_fields: bool; printf: level -> string -> unit; } let printf lvl str = let beg = match lvl with | `Error -> s_ "E: " | `Warning -> s_ "W: " | `Info -> s_ "I: " | `Debug -> s_ "D: " in prerr_endline (beg^str) let default = ref { quiet = false; info = false; debug = false; ignore_plugins = false; ignore_unknown_fields = false; printf = printf; } let quiet = {!default with quiet = true} let args () = ["-quiet", Arg.Unit (fun () -> default := {!default with quiet = true}), (s_ " Run quietly"); "-info", Arg.Unit (fun () -> default := {!default with info = true}), (s_ " Display information message"); "-debug", Arg.Unit (fun () -> default := {!default with debug = true}), (s_ " Output debug message")] end module OASISString = struct # 1 "/home/gildor/programmation/oasis/src/oasis/OASISString.ml" (** Various string utilities. Mostly inspired by extlib and batteries ExtString and BatString libraries. @author Sylvain Le Gall *) let nsplitf str f = if str = "" then [] else let buf = Buffer.create 13 in let lst = ref [] in let push () = lst := Buffer.contents buf :: !lst; Buffer.clear buf in let str_len = String.length str in for i = 0 to str_len - 1 do if f str.[i] then push () else Buffer.add_char buf str.[i] done; push (); List.rev !lst (** [nsplit c s] Split the string [s] at char [c]. It doesn't include the separator. *) let nsplit str c = nsplitf str ((=) c) let find ~what ?(offset=0) str = let what_idx = ref 0 in let str_idx = ref offset in while !str_idx < String.length str && !what_idx < String.length what do if str.[!str_idx] = what.[!what_idx] then incr what_idx else what_idx := 0; incr str_idx done; if !what_idx <> String.length what then raise Not_found else !str_idx - !what_idx let sub_start str len = let str_len = String.length str in if len >= str_len then "" else String.sub str len (str_len - len) let sub_end ?(offset=0) str len = let str_len = String.length str in if len >= str_len then "" else String.sub str 0 (str_len - len) let starts_with ~what ?(offset=0) str = let what_idx = ref 0 in let str_idx = ref offset in let ok = ref true in while !ok && !str_idx < String.length str && !what_idx < String.length what do if str.[!str_idx] = what.[!what_idx] then incr what_idx else ok := false; incr str_idx done; if !what_idx = String.length what then true else false let strip_starts_with ~what str = if starts_with ~what str then sub_start str (String.length what) else raise Not_found let ends_with ~what ?(offset=0) str = let what_idx = ref ((String.length what) - 1) in let str_idx = ref ((String.length str) - 1) in let ok = ref true in while !ok && offset <= !str_idx && 0 <= !what_idx do if str.[!str_idx] = what.[!what_idx] then decr what_idx else ok := false; decr str_idx done; if !what_idx = -1 then true else false let strip_ends_with ~what str = if ends_with ~what str then sub_end str (String.length what) else raise Not_found let replace_chars f s = let buf = String.make (String.length s) 'X' in for i = 0 to String.length s - 1 do buf.[i] <- f s.[i] done; buf end module OASISUtils = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISUtils.ml" open OASISGettext module MapString = Map.Make(String) let map_string_of_assoc assoc = List.fold_left (fun acc (k, v) -> MapString.add k v acc) MapString.empty assoc module SetString = Set.Make(String) let set_string_add_list st lst = List.fold_left (fun acc e -> SetString.add e acc) st lst let set_string_of_list = set_string_add_list SetString.empty let compare_csl s1 s2 = String.compare (String.lowercase s1) (String.lowercase s2) module HashStringCsl = Hashtbl.Make (struct type t = string let equal s1 s2 = (String.lowercase s1) = (String.lowercase s2) let hash s = Hashtbl.hash (String.lowercase s) end) let varname_of_string ?(hyphen='_') s = if String.length s = 0 then begin invalid_arg "varname_of_string" end else begin let buf = OASISString.replace_chars (fun c -> if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') then c else hyphen) s; in let buf = (* Start with a _ if digit *) if '0' <= s.[0] && s.[0] <= '9' then "_"^buf else buf in String.lowercase buf end let varname_concat ?(hyphen='_') p s = let what = String.make 1 hyphen in let p = try OASISString.strip_ends_with ~what p with Not_found -> p in let s = try OASISString.strip_starts_with ~what s with Not_found -> s in p^what^s let is_varname str = str = varname_of_string str let failwithf fmt = Printf.ksprintf failwith fmt end module PropList = struct # 21 "/home/gildor/programmation/oasis/src/oasis/PropList.ml" open OASISGettext type name = string exception Not_set of name * string option exception No_printer of name exception Unknown_field of name * name let () = Printexc.register_printer (function | Not_set (nm, Some rsn) -> Some (Printf.sprintf (f_ "Field '%s' is not set: %s") nm rsn) | Not_set (nm, None) -> Some (Printf.sprintf (f_ "Field '%s' is not set") nm) | No_printer nm -> Some (Printf.sprintf (f_ "No default printer for value %s") nm) | Unknown_field (nm, schm) -> Some (Printf.sprintf (f_ "Field %s is not defined in schema %s") nm schm) | _ -> None) module Data = struct type t = (name, unit -> unit) Hashtbl.t let create () = Hashtbl.create 13 let clear t = Hashtbl.clear t # 71 "/home/gildor/programmation/oasis/src/oasis/PropList.ml" end module Schema = struct type ('ctxt, 'extra) value = { get: Data.t -> string; set: Data.t -> ?context:'ctxt -> string -> unit; help: (unit -> string) option; extra: 'extra; } type ('ctxt, 'extra) t = { name: name; fields: (name, ('ctxt, 'extra) value) Hashtbl.t; order: name Queue.t; name_norm: string -> string; } let create ?(case_insensitive=false) nm = { name = nm; fields = Hashtbl.create 13; order = Queue.create (); name_norm = (if case_insensitive then String.lowercase else fun s -> s); } let add t nm set get extra help = let key = t.name_norm nm in if Hashtbl.mem t.fields key then failwith (Printf.sprintf (f_ "Field '%s' is already defined in schema '%s'") nm t.name); Hashtbl.add t.fields key { set = set; get = get; help = help; extra = extra; }; Queue.add nm t.order let mem t nm = Hashtbl.mem t.fields nm let find t nm = try Hashtbl.find t.fields (t.name_norm nm) with Not_found -> raise (Unknown_field (nm, t.name)) let get t data nm = (find t nm).get data let set t data nm ?context x = (find t nm).set data ?context x let fold f acc t = Queue.fold (fun acc k -> let v = find t k in f acc k v.extra v.help) acc t.order let iter f t = fold (fun () -> f) () t let name t = t.name end module Field = struct type ('ctxt, 'value, 'extra) t = { set: Data.t -> ?context:'ctxt -> 'value -> unit; get: Data.t -> 'value; sets: Data.t -> ?context:'ctxt -> string -> unit; gets: Data.t -> string; help: (unit -> string) option; extra: 'extra; } let new_id = let last_id = ref 0 in fun () -> incr last_id; !last_id let create ?schema ?name ?parse ?print ?default ?update ?help extra = (* Default value container *) let v = ref None in (* If name is not given, create unique one *) let nm = match name with | Some s -> s | None -> Printf.sprintf "_anon_%d" (new_id ()) in (* Last chance to get a value: the default *) let default () = match default with | Some d -> d | None -> raise (Not_set (nm, Some (s_ "no default value"))) in (* Get data *) let get data = (* Get value *) try (Hashtbl.find data nm) (); match !v with | Some x -> x | None -> default () with Not_found -> default () in (* Set data *) let set data ?context x = let x = match update with | Some f -> begin try f ?context (get data) x with Not_set _ -> x end | None -> x in Hashtbl.replace data nm (fun () -> v := Some x) in (* Parse string value, if possible *) let parse = match parse with | Some f -> f | None -> fun ?context s -> failwith (Printf.sprintf (f_ "Cannot parse field '%s' when setting value %S") nm s) in (* Set data, from string *) let sets data ?context s = set ?context data (parse ?context s) in (* Output value as string, if possible *) let print = match print with | Some f -> f | None -> fun _ -> raise (No_printer nm) in (* Get data, as a string *) let gets data = print (get data) in begin match schema with | Some t -> Schema.add t nm sets gets extra help | None -> () end; { set = set; get = get; sets = sets; gets = gets; help = help; extra = extra; } let fset data t ?context x = t.set data ?context x let fget data t = t.get data let fsets data t ?context s = t.sets data ?context s let fgets data t = t.gets data end module FieldRO = struct let create ?schema ?name ?parse ?print ?default ?update ?help extra = let fld = Field.create ?schema ?name ?parse ?print ?default ?update ?help extra in fun data -> Field.fget data fld end end module OASISMessage = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISMessage.ml" open OASISGettext open OASISContext let generic_message ~ctxt lvl fmt = let cond = if ctxt.quiet then false else match lvl with | `Debug -> ctxt.debug | `Info -> ctxt.info | _ -> true in Printf.ksprintf (fun str -> if cond then begin ctxt.printf lvl str end) fmt let debug ~ctxt fmt = generic_message ~ctxt `Debug fmt let info ~ctxt fmt = generic_message ~ctxt `Info fmt let warning ~ctxt fmt = generic_message ~ctxt `Warning fmt let error ~ctxt fmt = generic_message ~ctxt `Error fmt end module OASISVersion = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISVersion.ml" open OASISGettext type s = string type t = string type comparator = | VGreater of t | VGreaterEqual of t | VEqual of t | VLesser of t | VLesserEqual of t | VOr of comparator * comparator | VAnd of comparator * comparator (* Range of allowed characters *) let is_digit c = '0' <= c && c <= '9' let is_alpha c = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') let is_special = function | '.' | '+' | '-' | '~' -> true | _ -> false let rec version_compare v1 v2 = if v1 <> "" || v2 <> "" then begin (* Compare ascii string, using special meaning for version * related char *) let val_ascii c = if c = '~' then -1 else if is_digit c then 0 else if c = '\000' then 0 else if is_alpha c then Char.code c else (Char.code c) + 256 in let len1 = String.length v1 in let len2 = String.length v2 in let p = ref 0 in (** Compare ascii part *) let compare_vascii () = let cmp = ref 0 in while !cmp = 0 && !p < len1 && !p < len2 && not (is_digit v1.[!p] && is_digit v2.[!p]) do cmp := (val_ascii v1.[!p]) - (val_ascii v2.[!p]); incr p done; if !cmp = 0 && !p < len1 && !p = len2 then val_ascii v1.[!p] else if !cmp = 0 && !p = len1 && !p < len2 then - (val_ascii v2.[!p]) else !cmp in (** Compare digit part *) let compare_digit () = let extract_int v p = let start_p = !p in while !p < String.length v && is_digit v.[!p] do incr p done; let substr = String.sub v !p ((String.length v) - !p) in let res = match String.sub v start_p (!p - start_p) with | "" -> 0 | s -> int_of_string s in res, substr in let i1, tl1 = extract_int v1 (ref !p) in let i2, tl2 = extract_int v2 (ref !p) in i1 - i2, tl1, tl2 in match compare_vascii () with | 0 -> begin match compare_digit () with | 0, tl1, tl2 -> if tl1 <> "" && is_digit tl1.[0] then 1 else if tl2 <> "" && is_digit tl2.[0] then -1 else version_compare tl1 tl2 | n, _, _ -> n end | n -> n end else begin 0 end let version_of_string str = str let string_of_version t = t let chop t = try let pos = String.rindex t '.' in String.sub t 0 pos with Not_found -> t let rec comparator_apply v op = match op with | VGreater cv -> (version_compare v cv) > 0 | VGreaterEqual cv -> (version_compare v cv) >= 0 | VLesser cv -> (version_compare v cv) < 0 | VLesserEqual cv -> (version_compare v cv) <= 0 | VEqual cv -> (version_compare v cv) = 0 | VOr (op1, op2) -> (comparator_apply v op1) || (comparator_apply v op2) | VAnd (op1, op2) -> (comparator_apply v op1) && (comparator_apply v op2) let rec string_of_comparator = function | VGreater v -> "> "^(string_of_version v) | VEqual v -> "= "^(string_of_version v) | VLesser v -> "< "^(string_of_version v) | VGreaterEqual v -> ">= "^(string_of_version v) | VLesserEqual v -> "<= "^(string_of_version v) | VOr (c1, c2) -> (string_of_comparator c1)^" || "^(string_of_comparator c2) | VAnd (c1, c2) -> (string_of_comparator c1)^" && "^(string_of_comparator c2) let rec varname_of_comparator = let concat p v = OASISUtils.varname_concat p (OASISUtils.varname_of_string (string_of_version v)) in function | VGreater v -> concat "gt" v | VLesser v -> concat "lt" v | VEqual v -> concat "eq" v | VGreaterEqual v -> concat "ge" v | VLesserEqual v -> concat "le" v | VOr (c1, c2) -> (varname_of_comparator c1)^"_or_"^(varname_of_comparator c2) | VAnd (c1, c2) -> (varname_of_comparator c1)^"_and_"^(varname_of_comparator c2) let version_0_3_or_after t = comparator_apply t (VGreaterEqual (string_of_version "0.3")) end module OASISLicense = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISLicense.ml" (** License for _oasis fields @author Sylvain Le Gall *) type license = string type license_exception = string type license_version = | Version of OASISVersion.t | VersionOrLater of OASISVersion.t | NoVersion type license_dep_5_unit = { license: license; excption: license_exception option; version: license_version; } type license_dep_5 = | DEP5Unit of license_dep_5_unit | DEP5Or of license_dep_5 list | DEP5And of license_dep_5 list type t = | DEP5License of license_dep_5 | OtherLicense of string (* URL *) end module OASISExpr = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISExpr.ml" open OASISGettext type test = string type flag = string type t = | EBool of bool | ENot of t | EAnd of t * t | EOr of t * t | EFlag of flag | ETest of test * string type 'a choices = (t * 'a) list let eval var_get t = let rec eval' = function | EBool b -> b | ENot e -> not (eval' e) | EAnd (e1, e2) -> (eval' e1) && (eval' e2) | EOr (e1, e2) -> (eval' e1) || (eval' e2) | EFlag nm -> let v = var_get nm in assert(v = "true" || v = "false"); (v = "true") | ETest (nm, vl) -> let v = var_get nm in (v = vl) in eval' t let choose ?printer ?name var_get lst = let rec choose_aux = function | (cond, vl) :: tl -> if eval var_get cond then vl else choose_aux tl | [] -> let str_lst = if lst = [] then s_ "" else String.concat (s_ ", ") (List.map (fun (cond, vl) -> match printer with | Some p -> p vl | None -> s_ "") lst) in match name with | Some nm -> failwith (Printf.sprintf (f_ "No result for the choice list '%s': %s") nm str_lst) | None -> failwith (Printf.sprintf (f_ "No result for a choice list: %s") str_lst) in choose_aux (List.rev lst) end module OASISTypes = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISTypes.ml" type name = string type package_name = string type url = string type unix_dirname = string type unix_filename = string type host_dirname = string type host_filename = string type prog = string type arg = string type args = string list type command_line = (prog * arg list) type findlib_name = string type findlib_full = string type compiled_object = | Byte | Native | Best type dependency = | FindlibPackage of findlib_full * OASISVersion.comparator option | InternalLibrary of name type tool = | ExternalTool of name | InternalExecutable of name type vcs = | Darcs | Git | Svn | Cvs | Hg | Bzr | Arch | Monotone | OtherVCS of url type plugin_kind = [ `Configure | `Build | `Doc | `Test | `Install | `Extra ] type plugin_data_purpose = [ `Configure | `Build | `Install | `Clean | `Distclean | `Install | `Uninstall | `Test | `Doc | `Extra | `Other of string ] type 'a plugin = 'a * name * OASISVersion.t option type all_plugin = plugin_kind plugin type plugin_data = (all_plugin * plugin_data_purpose * (unit -> unit)) list # 102 "/home/gildor/programmation/oasis/src/oasis/OASISTypes.ml" type 'a conditional = 'a OASISExpr.choices type custom = { pre_command: (command_line option) conditional; post_command: (command_line option) conditional; } type common_section = { cs_name: name; cs_data: PropList.Data.t; cs_plugin_data: plugin_data; } type build_section = { bs_build: bool conditional; bs_install: bool conditional; bs_path: unix_dirname; bs_compiled_object: compiled_object; bs_build_depends: dependency list; bs_build_tools: tool list; bs_c_sources: unix_filename list; bs_data_files: (unix_filename * unix_filename option) list; bs_ccopt: args conditional; bs_cclib: args conditional; bs_dlllib: args conditional; bs_dllpath: args conditional; bs_byteopt: args conditional; bs_nativeopt: args conditional; } type library = { lib_modules: string list; lib_pack: bool; lib_internal_modules: string list; lib_findlib_parent: findlib_name option; lib_findlib_name: findlib_name option; lib_findlib_containers: findlib_name list; } type executable = { exec_custom: bool; exec_main_is: unix_filename; } type flag = { flag_description: string option; flag_default: bool conditional; } type source_repository = { src_repo_type: vcs; src_repo_location: url; src_repo_browser: url option; src_repo_module: string option; src_repo_branch: string option; src_repo_tag: string option; src_repo_subdir: unix_filename option; } type test = { test_type: [`Test] plugin; test_command: command_line conditional; test_custom: custom; test_working_directory: unix_filename option; test_run: bool conditional; test_tools: tool list; } type doc_format = | HTML of unix_filename | DocText | PDF | PostScript | Info of unix_filename | DVI | OtherDoc type doc = { doc_type: [`Doc] plugin; doc_custom: custom; doc_build: bool conditional; doc_install: bool conditional; doc_install_dir: unix_filename; doc_title: string; doc_authors: string list; doc_abstract: string option; doc_format: doc_format; doc_data_files: (unix_filename * unix_filename option) list; doc_build_tools: tool list; } type section = | Library of common_section * build_section * library | Executable of common_section * build_section * executable | Flag of common_section * flag | SrcRepo of common_section * source_repository | Test of common_section * test | Doc of common_section * doc type section_kind = [ `Library | `Executable | `Flag | `SrcRepo | `Test | `Doc ] type package = { oasis_version: OASISVersion.t; ocaml_version: OASISVersion.comparator option; findlib_version: OASISVersion.comparator option; name: package_name; version: OASISVersion.t; license: OASISLicense.t; license_file: unix_filename option; copyrights: string list; maintainers: string list; authors: string list; homepage: url option; synopsis: string; description: string option; categories: url list; conf_type: [`Configure] plugin; conf_custom: custom; build_type: [`Build] plugin; build_custom: custom; install_type: [`Install] plugin; install_custom: custom; uninstall_custom: custom; clean_custom: custom; distclean_custom: custom; files_ab: unix_filename list; sections: section list; plugins: [`Extra] plugin list; schema_data: PropList.Data.t; plugin_data: plugin_data; } end module OASISUnixPath = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISUnixPath.ml" type unix_filename = string type unix_dirname = string type host_filename = string type host_dirname = string let current_dir_name = "." let parent_dir_name = ".." let concat f1 f2 = if f1 = current_dir_name || f1 = "" then f2 else let f1' = try OASISString.strip_ends_with ~what:"/" f1 with Not_found -> f1 in f1'^"/"^f2 let make = function | hd :: tl -> List.fold_left (fun f p -> concat f p) hd tl | [] -> invalid_arg "OASISUnixPath.make" let dirname f = try String.sub f 0 (String.rindex f '/') with Not_found -> current_dir_name let basename f = try let pos_start = (String.rindex f '/') + 1 in String.sub f pos_start ((String.length f) - pos_start) with Not_found -> f let chop_extension f = try let last_dot = String.rindex f '.' in let sub = String.sub f 0 last_dot in try let last_slash = String.rindex f '/' in if last_slash < last_dot then sub else f with Not_found -> sub with Not_found -> f let capitalize_file f = let dir = dirname f in let base = basename f in concat dir (String.capitalize base) let uncapitalize_file f = let dir = dirname f in let base = basename f in concat dir (String.uncapitalize base) end module OASISHostPath = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISHostPath.ml" open Filename module Unix = OASISUnixPath let make = function | [] -> invalid_arg "OASISHostPath.make" | hd :: tl -> List.fold_left Filename.concat hd tl let of_unix ufn = if Sys.os_type = "Unix" then ufn else make (List.map (fun p -> if p = Unix.current_dir_name then current_dir_name else if p = Unix.parent_dir_name then parent_dir_name else p) (OASISString.nsplit ufn '/')) end module OASISSection = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISSection.ml" open OASISTypes let section_kind_common = function | Library (cs, _, _) -> `Library, cs | Executable (cs, _, _) -> `Executable, cs | Flag (cs, _) -> `Flag, cs | SrcRepo (cs, _) -> `SrcRepo, cs | Test (cs, _) -> `Test, cs | Doc (cs, _) -> `Doc, cs let section_common sct = snd (section_kind_common sct) let section_common_set cs = function | Library (_, bs, lib) -> Library (cs, bs, lib) | Executable (_, bs, exec) -> Executable (cs, bs, exec) | Flag (_, flg) -> Flag (cs, flg) | SrcRepo (_, src_repo) -> SrcRepo (cs, src_repo) | Test (_, tst) -> Test (cs, tst) | Doc (_, doc) -> Doc (cs, doc) (** Key used to identify section *) let section_id sct = let k, cs = section_kind_common sct in k, cs.cs_name let string_of_section sct = let k, nm = section_id sct in (match k with | `Library -> "library" | `Executable -> "executable" | `Flag -> "flag" | `SrcRepo -> "src repository" | `Test -> "test" | `Doc -> "doc") ^" "^nm let section_find id scts = List.find (fun sct -> id = section_id sct) scts module CSection = struct type t = section let id = section_id let compare t1 t2 = compare (id t1) (id t2) let equal t1 t2 = (id t1) = (id t2) let hash t = Hashtbl.hash (id t) end module MapSection = Map.Make(CSection) module SetSection = Set.Make(CSection) end module OASISBuildSection = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISBuildSection.ml" end module OASISExecutable = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISExecutable.ml" open OASISTypes let unix_exec_is (cs, bs, exec) is_native ext_dll suffix_program = let dir = OASISUnixPath.concat bs.bs_path (OASISUnixPath.dirname exec.exec_main_is) in let is_native_exec = match bs.bs_compiled_object with | Native -> true | Best -> is_native () | Byte -> false in OASISUnixPath.concat dir (cs.cs_name^(suffix_program ())), if not is_native_exec && not exec.exec_custom && bs.bs_c_sources <> [] then Some (dir^"/dll"^cs.cs_name^"_stubs"^(ext_dll ())) else None end module OASISLibrary = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISLibrary.ml" open OASISTypes open OASISUtils open OASISGettext open OASISSection type library_name = name type findlib_part_name = name type 'a map_of_findlib_part_name = 'a OASISUtils.MapString.t exception InternalLibraryNotFound of library_name exception FindlibPackageNotFound of findlib_name type group_t = | Container of findlib_name * group_t list | Package of (findlib_name * common_section * build_section * library * group_t list) (* Look for a module file, considering capitalization or not. *) let find_module source_file_exists (cs, bs, lib) modul = let possible_base_fn = List.map (OASISUnixPath.concat bs.bs_path) [modul; OASISUnixPath.uncapitalize_file modul; OASISUnixPath.capitalize_file modul] in (* TODO: we should be able to be able to determine the source for every * files. Hence we should introduce a Module(source: fn) for the fields * Modules and InternalModules *) List.fold_left (fun acc base_fn -> match acc with | `No_sources _ -> begin let file_found = List.fold_left (fun acc ext -> if source_file_exists (base_fn^ext) then (base_fn^ext) :: acc else acc) [] [".ml"; ".mli"; ".mll"; ".mly"] in match file_found with | [] -> acc | lst -> `Sources (base_fn, lst) end | `Sources _ -> acc) (`No_sources possible_base_fn) possible_base_fn let source_unix_files ~ctxt (cs, bs, lib) source_file_exists = List.fold_left (fun acc modul -> match find_module source_file_exists (cs, bs, lib) modul with | `Sources (base_fn, lst) -> (base_fn, lst) :: acc | `No_sources _ -> OASISMessage.warning ~ctxt (f_ "Cannot find source file matching \ module '%s' in library %s") modul cs.cs_name; acc) [] (lib.lib_modules @ lib.lib_internal_modules) let generated_unix_files ~ctxt ~is_native ~has_native_dynlink ~ext_lib ~ext_dll ~source_file_exists (cs, bs, lib) = let find_modules lst ext = let find_module modul = match find_module source_file_exists (cs, bs, lib) modul with | `Sources (base_fn, _) -> [base_fn] | `No_sources lst -> OASISMessage.warning ~ctxt (f_ "Cannot find source file matching \ module '%s' in library %s") modul cs.cs_name; lst in List.map (fun nm -> List.map (fun base_fn -> base_fn ^"."^ext) (find_module nm)) lst in (* The headers that should be compiled along *) let headers = if lib.lib_pack then [] else find_modules lib.lib_modules "cmi" in (* The .cmx that be compiled along *) let cmxs = let should_be_built = (not lib.lib_pack) && (* Do not install .cmx packed submodules *) match bs.bs_compiled_object with | Native -> true | Best -> is_native | Byte -> false in if should_be_built then find_modules (lib.lib_modules @ lib.lib_internal_modules) "cmx" else [] in let acc_nopath = [] in (* Compute what libraries should be built *) let acc_nopath = (* Add the packed header file if required *) let add_pack_header acc = if lib.lib_pack then [cs.cs_name^".cmi"] :: acc else acc in let byte acc = add_pack_header ([cs.cs_name^".cma"] :: acc) in let native acc = let acc = [cs.cs_name^".cmxa"] :: [cs.cs_name^ext_lib] :: acc in add_pack_header (if has_native_dynlink then [cs.cs_name^".cmxs"] :: acc else acc) in match bs.bs_compiled_object with | Native -> byte (native acc_nopath) | Best when is_native -> byte (native acc_nopath) | Byte | Best -> byte acc_nopath in (* Add C library to be built *) let acc_nopath = if bs.bs_c_sources <> [] then begin ["lib"^cs.cs_name^"_stubs"^ext_lib] :: ["dll"^cs.cs_name^"_stubs"^ext_dll] :: acc_nopath end else acc_nopath in (* All the files generated *) List.rev_append (List.rev_map (List.rev_map (OASISUnixPath.concat bs.bs_path)) acc_nopath) (headers @ cmxs) type data = common_section * build_section * library type tree = | Node of (data option) * (tree MapString.t) | Leaf of data let findlib_mapping pkg = (* Map from library name to either full findlib name or parts + parent. *) let fndlb_parts_of_lib_name = let fndlb_parts cs lib = let name = match lib.lib_findlib_name with | Some nm -> nm | None -> cs.cs_name in let name = String.concat "." (lib.lib_findlib_containers @ [name]) in name in List.fold_left (fun mp -> function | Library (cs, _, lib) -> begin let lib_name = cs.cs_name in let fndlb_parts = fndlb_parts cs lib in if MapString.mem lib_name mp then failwithf (f_ "The library name '%s' is used more than once.") lib_name; match lib.lib_findlib_parent with | Some lib_name_parent -> MapString.add lib_name (`Unsolved (lib_name_parent, fndlb_parts)) mp | None -> MapString.add lib_name (`Solved fndlb_parts) mp end | Executable _ | Test _ | Flag _ | SrcRepo _ | Doc _ -> mp) MapString.empty pkg.sections in (* Solve the above graph to be only library name to full findlib name. *) let fndlb_name_of_lib_name = let rec solve visited mp lib_name lib_name_child = if SetString.mem lib_name visited then failwithf (f_ "Library '%s' is involved in a cycle \ with regard to findlib naming.") lib_name; let visited = SetString.add lib_name visited in try match MapString.find lib_name mp with | `Solved fndlb_nm -> fndlb_nm, mp | `Unsolved (lib_nm_parent, post_fndlb_nm) -> let pre_fndlb_nm, mp = solve visited mp lib_nm_parent lib_name in let fndlb_nm = pre_fndlb_nm^"."^post_fndlb_nm in fndlb_nm, MapString.add lib_name (`Solved fndlb_nm) mp with Not_found -> failwithf (f_ "Library '%s', which is defined as the findlib parent of \ library '%s', doesn't exist.") lib_name lib_name_child in let mp = MapString.fold (fun lib_name status mp -> match status with | `Solved _ -> (* Solved initialy, no need to go further *) mp | `Unsolved _ -> let _, mp = solve SetString.empty mp lib_name "" in mp) fndlb_parts_of_lib_name fndlb_parts_of_lib_name in MapString.map (function | `Solved fndlb_nm -> fndlb_nm | `Unsolved _ -> assert false) mp in (* Convert an internal library name to a findlib name. *) let findlib_name_of_library_name lib_nm = try MapString.find lib_nm fndlb_name_of_lib_name with Not_found -> raise (InternalLibraryNotFound lib_nm) in (* Add a library to the tree. *) let add sct mp = let fndlb_fullname = let cs, _, _ = sct in let lib_name = cs.cs_name in findlib_name_of_library_name lib_name in let rec add_children nm_lst (children : tree MapString.t) = match nm_lst with | (hd :: tl) -> begin let node = try add_node tl (MapString.find hd children) with Not_found -> (* New node *) new_node tl in MapString.add hd node children end | [] -> (* Should not have a nameless library. *) assert false and add_node tl node = if tl = [] then begin match node with | Node (None, children) -> Node (Some sct, children) | Leaf (cs', _, _) | Node (Some (cs', _, _), _) -> (* TODO: allow to merge Package, i.e. * archive(byte) = "foo.cma foo_init.cmo" *) let cs, _, _ = sct in failwithf (f_ "Library '%s' and '%s' have the same findlib name '%s'") cs.cs_name cs'.cs_name fndlb_fullname end else begin match node with | Leaf data -> Node (Some data, add_children tl MapString.empty) | Node (data_opt, children) -> Node (data_opt, add_children tl children) end and new_node = function | [] -> Leaf sct | hd :: tl -> Node (None, MapString.add hd (new_node tl) MapString.empty) in add_children (OASISString.nsplit fndlb_fullname '.') mp in let rec group_of_tree mp = MapString.fold (fun nm node acc -> let cur = match node with | Node (Some (cs, bs, lib), children) -> Package (nm, cs, bs, lib, group_of_tree children) | Node (None, children) -> Container (nm, group_of_tree children) | Leaf (cs, bs, lib) -> Package (nm, cs, bs, lib, []) in cur :: acc) mp [] in let group_mp = List.fold_left (fun mp -> function | Library (cs, bs, lib) -> add (cs, bs, lib) mp | _ -> mp) MapString.empty pkg.sections in let groups = group_of_tree group_mp in let library_name_of_findlib_name = Lazy.lazy_from_fun (fun () -> (* Revert findlib_name_of_library_name. *) MapString.fold (fun k v mp -> MapString.add v k mp) fndlb_name_of_lib_name MapString.empty) in let library_name_of_findlib_name fndlb_nm = try MapString.find fndlb_nm (Lazy.force library_name_of_findlib_name) with Not_found -> raise (FindlibPackageNotFound fndlb_nm) in groups, findlib_name_of_library_name, library_name_of_findlib_name let findlib_of_group = function | Container (fndlb_nm, _) | Package (fndlb_nm, _, _, _, _) -> fndlb_nm let root_of_group grp = let rec root_lib_aux = (* We do a DFS in the group. *) function | Container (_, children) -> List.fold_left (fun res grp -> if res = None then root_lib_aux grp else res) None children | Package (_, cs, bs, lib, _) -> Some (cs, bs, lib) in match root_lib_aux grp with | Some res -> res | None -> failwithf (f_ "Unable to determine root library of findlib library '%s'") (findlib_of_group grp) end module OASISFlag = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISFlag.ml" end module OASISPackage = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISPackage.ml" end module OASISSourceRepository = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISSourceRepository.ml" end module OASISTest = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISTest.ml" end module OASISDocument = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISDocument.ml" end module OASISExec = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISExec.ml" open OASISGettext open OASISUtils open OASISMessage let run ~ctxt ?f_exit_code cmd args = let cmdline = String.concat " " (cmd :: args) in info ~ctxt (f_ "Running command '%s'") cmdline; match f_exit_code, Sys.command cmdline with | None, 0 -> () | None, i -> failwithf (f_ "Command '%s' terminated with error code %d") cmdline i | Some f, i -> f i let run_read_output ~ctxt ?f_exit_code cmd args = let fn = Filename.temp_file "oasis-" ".txt" in try begin let () = run ~ctxt ?f_exit_code cmd (args @ [">"; Filename.quote fn]) in let chn = open_in fn in let routput = ref [] in begin try while true do routput := (input_line chn) :: !routput done with End_of_file -> () end; close_in chn; Sys.remove fn; List.rev !routput end with e -> (try Sys.remove fn with _ -> ()); raise e let run_read_one_line ~ctxt ?f_exit_code cmd args = match run_read_output ~ctxt ?f_exit_code cmd args with | [fst] -> fst | lst -> failwithf (f_ "Command return unexpected output %S") (String.concat "\n" lst) end module OASISFileUtil = struct # 21 "/home/gildor/programmation/oasis/src/oasis/OASISFileUtil.ml" open OASISGettext let file_exists_case fn = let dirname = Filename.dirname fn in let basename = Filename.basename fn in if Sys.file_exists dirname then if basename = Filename.current_dir_name then true else List.mem basename (Array.to_list (Sys.readdir dirname)) else false let find_file ?(case_sensitive=true) paths exts = (* Cardinal product of two list *) let ( * ) lst1 lst2 = List.flatten (List.map (fun a -> List.map (fun b -> a,b) lst2) lst1) in let rec combined_paths lst = match lst with | p1 :: p2 :: tl -> let acc = (List.map (fun (a,b) -> Filename.concat a b) (p1 * p2)) in combined_paths (acc :: tl) | [e] -> e | [] -> [] in let alternatives = List.map (fun (p,e) -> if String.length e > 0 && e.[0] <> '.' then p ^ "." ^ e else p ^ e) ((combined_paths paths) * exts) in List.find (if case_sensitive then file_exists_case else Sys.file_exists) alternatives let which ~ctxt prg = let path_sep = match Sys.os_type with | "Win32" -> ';' | _ -> ':' in let path_lst = OASISString.nsplit (Sys.getenv "PATH") path_sep in let exec_ext = match Sys.os_type with | "Win32" -> "" :: (OASISString.nsplit (Sys.getenv "PATHEXT") path_sep) | _ -> [""] in find_file ~case_sensitive:false [path_lst; [prg]] exec_ext (**/**) let rec fix_dir dn = (* Windows hack because Sys.file_exists "src\\" = false when * Sys.file_exists "src" = true *) let ln = String.length dn in if Sys.os_type = "Win32" && ln > 0 && dn.[ln - 1] = '\\' then fix_dir (String.sub dn 0 (ln - 1)) else dn let q = Filename.quote (**/**) let cp ~ctxt ?(recurse=false) src tgt = if recurse then match Sys.os_type with | "Win32" -> OASISExec.run ~ctxt "xcopy" [q src; q tgt; "/E"] | _ -> OASISExec.run ~ctxt "cp" ["-r"; q src; q tgt] else OASISExec.run ~ctxt (match Sys.os_type with | "Win32" -> "copy" | _ -> "cp") [q src; q tgt] let mkdir ~ctxt tgt = OASISExec.run ~ctxt (match Sys.os_type with | "Win32" -> "md" | _ -> "mkdir") [q tgt] let rec mkdir_parent ~ctxt f tgt = let tgt = fix_dir tgt in if Sys.file_exists tgt then begin if not (Sys.is_directory tgt) then OASISUtils.failwithf (f_ "Cannot create directory '%s', a file of the same name already \ exists") tgt end else begin mkdir_parent ~ctxt f (Filename.dirname tgt); if not (Sys.file_exists tgt) then begin f tgt; mkdir ~ctxt tgt end end let rmdir ~ctxt tgt = if Sys.readdir tgt = [||] then begin match Sys.os_type with | "Win32" -> OASISExec.run ~ctxt "rd" [q tgt] | _ -> OASISExec.run ~ctxt "rm" ["-r"; q tgt] end let glob ~ctxt fn = let basename = Filename.basename fn in if String.length basename >= 2 && basename.[0] = '*' && basename.[1] = '.' then begin let ext_len = (String.length basename) - 2 in let ext = String.sub basename 2 ext_len in let dirname = Filename.dirname fn in Array.fold_left (fun acc fn -> try let fn_ext = String.sub fn ((String.length fn) - ext_len) ext_len in if fn_ext = ext then (Filename.concat dirname fn) :: acc else acc with Invalid_argument _ -> acc) [] (Sys.readdir dirname) end else begin if file_exists_case fn then [fn] else [] end end # 2121 "setup.ml" module BaseEnvLight = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseEnvLight.ml" module MapString = Map.Make(String) type t = string MapString.t let default_filename = Filename.concat (Sys.getcwd ()) "setup.data" let load ?(allow_empty=false) ?(filename=default_filename) () = if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in let line = ref 1 in let st_line = Stream.from (fun _ -> try match Stream.next st with | '\n' -> incr line; Some '\n' | c -> Some c with Stream.Failure -> None) in let lexer = Genlex.make_lexer ["="] st_line in let rec read_file mp = match Stream.npeek 3 lexer with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lexer; Stream.junk lexer; Stream.junk lexer; read_file (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in let mp = read_file MapString.empty in close_in chn; mp end else if allow_empty then begin MapString.empty end else begin failwith (Printf.sprintf "Unable to load environment, the file '%s' doesn't exist." filename) end let var_get name env = let rec var_expand str = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff in var_expand (MapString.find name env) let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 2219 "setup.ml" module BaseContext = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseContext.ml" open OASISContext let args = args let default = default end module BaseMessage = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseMessage.ml" (** Message to user, overrid for Base @author Sylvain Le Gall *) open OASISMessage open BaseContext let debug fmt = debug ~ctxt:!default fmt let info fmt = info ~ctxt:!default fmt let warning fmt = warning ~ctxt:!default fmt let error fmt = error ~ctxt:!default fmt end module BaseEnv = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseEnv.ml" open OASISGettext open OASISUtils open PropList module MapString = BaseEnvLight.MapString type origin_t = | ODefault | OGetEnv | OFileLoad | OCommandLine type cli_handle_t = | CLINone | CLIAuto | CLIWith | CLIEnable | CLIUser of (Arg.key * Arg.spec * Arg.doc) list type definition_t = { hide: bool; dump: bool; cli: cli_handle_t; arg_help: string option; group: string option; } let schema = Schema.create "environment" (* Environment data *) let env = Data.create () (* Environment data from file *) let env_from_file = ref MapString.empty (* Lexer for var *) let var_lxr = Genlex.make_lexer [] let rec var_expand str = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try (* TODO: this is a quick hack to allow calling Test.Command * without defining executable name really. I.e. if there is * an exec Executable toto, then $(toto) should be replace * by its real name. It is however useful to have this function * for other variable that depend on the host and should be * written better than that. *) let st = var_lxr (Stream.of_string var) in match Stream.npeek 3 st with | [Genlex.Ident "utoh"; Genlex.Ident nm] -> OASISHostPath.of_unix (var_get nm) | [Genlex.Ident "utoh"; Genlex.String s] -> OASISHostPath.of_unix s | [Genlex.Ident "ocaml_escaped"; Genlex.Ident nm] -> String.escaped (var_get nm) | [Genlex.Ident "ocaml_escaped"; Genlex.String s] -> String.escaped s | [Genlex.Ident nm] -> var_get nm | _ -> failwithf (f_ "Unknown expression '%s' in variable expansion of %s.") var str with | Unknown_field (_, _) -> failwithf (f_ "No variable %s defined when trying to expand %S.") var str | Stream.Error e -> failwithf (f_ "Syntax error when parsing '%s' when trying to \ expand %S: %s") var str e) str; Buffer.contents buff and var_get name = let vl = try Schema.get schema env name with Unknown_field _ as e -> begin try MapString.find name !env_from_file with Not_found -> raise e end in var_expand vl let var_choose ?printer ?name lst = OASISExpr.choose ?printer ?name var_get lst let var_protect vl = let buff = Buffer.create (String.length vl) in String.iter (function | '$' -> Buffer.add_string buff "\\$" | c -> Buffer.add_char buff c) vl; Buffer.contents buff let var_define ?(hide=false) ?(dump=true) ?short_desc ?(cli=CLINone) ?arg_help ?group name (* TODO: type constraint on the fact that name must be a valid OCaml id *) dflt = let default = [ OFileLoad, (fun () -> MapString.find name !env_from_file); ODefault, dflt; OGetEnv, (fun () -> Sys.getenv name); ] in let extra = { hide = hide; dump = dump; cli = cli; arg_help = arg_help; group = group; } in (* Try to find a value that can be defined *) let var_get_low lst = let errors, res = List.fold_left (fun (errors, res) (o, v) -> if res = None then begin try errors, Some (v ()) with | Not_found -> errors, res | Failure rsn -> (rsn :: errors), res | e -> (Printexc.to_string e) :: errors, res end else errors, res) ([], None) (List.sort (fun (o1, _) (o2, _) -> Pervasives.compare o2 o1) lst) in match res, errors with | Some v, _ -> v | None, [] -> raise (Not_set (name, None)) | None, lst -> raise (Not_set (name, Some (String.concat (s_ ", ") lst))) in let help = match short_desc with | Some fs -> Some fs | None -> None in let var_get_lst = FieldRO.create ~schema ~name ~parse:(fun ?(context=ODefault) s -> [context, fun () -> s]) ~print:var_get_low ~default ~update:(fun ?context x old_x -> x @ old_x) ?help extra in fun () -> var_expand (var_get_low (var_get_lst env)) let var_redefine ?hide ?dump ?short_desc ?cli ?arg_help ?group name dflt = if Schema.mem schema name then begin (* TODO: look suspsicious, we want to memorize dflt not dflt () *) Schema.set schema env ~context:ODefault name (dflt ()); fun () -> var_get name end else begin var_define ?hide ?dump ?short_desc ?cli ?arg_help ?group name dflt end let var_ignore (e : unit -> string) = () let print_hidden = var_define ~hide:true ~dump:false ~cli:CLIAuto ~arg_help:"Print even non-printable variable. (debug)" "print_hidden" (fun () -> "false") let var_all () = List.rev (Schema.fold (fun acc nm def _ -> if not def.hide || bool_of_string (print_hidden ()) then nm :: acc else acc) [] schema) let default_filename = BaseEnvLight.default_filename let load ?allow_empty ?filename () = env_from_file := BaseEnvLight.load ?allow_empty ?filename () let unload () = env_from_file := MapString.empty; Data.clear env let dump ?(filename=default_filename) () = let chn = open_out_bin filename in let output nm value = Printf.fprintf chn "%s=%S\n" nm value in let mp_todo = (* Dump data from schema *) Schema.fold (fun mp_todo nm def _ -> if def.dump then begin try let value = Schema.get schema env nm in output nm value with Not_set _ -> () end; MapString.remove nm mp_todo) !env_from_file schema in (* Dump data defined outside of schema *) MapString.iter output mp_todo; (* End of the dump *) close_out chn let print () = let printable_vars = Schema.fold (fun acc nm def short_descr_opt -> if not def.hide || bool_of_string (print_hidden ()) then begin try let value = Schema.get schema env nm in let txt = match short_descr_opt with | Some s -> s () | None -> nm in (txt, value) :: acc with Not_set _ -> acc end else acc) [] schema in let max_length = List.fold_left max 0 (List.rev_map String.length (List.rev_map fst printable_vars)) in let dot_pad str = String.make ((max_length - (String.length str)) + 3) '.' in Printf.printf "\nConfiguration: \n"; List.iter (fun (name,value) -> Printf.printf "%s: %s %s\n" name (dot_pad name) value) (List.rev printable_vars); Printf.printf "\n%!" let args () = let arg_concat = OASISUtils.varname_concat ~hyphen:'-' in [ "--override", Arg.Tuple ( let rvr = ref "" in let rvl = ref "" in [ Arg.Set_string rvr; Arg.Set_string rvl; Arg.Unit (fun () -> Schema.set schema env ~context:OCommandLine !rvr !rvl) ] ), "var+val Override any configuration variable."; ] @ List.flatten (Schema.fold (fun acc name def short_descr_opt -> let var_set s = Schema.set schema env ~context:OCommandLine name s in let arg_name = OASISUtils.varname_of_string ~hyphen:'-' name in let hlp = match short_descr_opt with | Some txt -> txt () | None -> "" in let arg_hlp = match def.arg_help with | Some s -> s | None -> "str" in let default_value = try Printf.sprintf (f_ " [%s]") (Schema.get schema env name) with Not_set _ -> "" in let args = match def.cli with | CLINone -> [] | CLIAuto -> [ arg_concat "--" arg_name, Arg.String var_set, Printf.sprintf (f_ "%s %s%s") arg_hlp hlp default_value ] | CLIWith -> [ arg_concat "--with-" arg_name, Arg.String var_set, Printf.sprintf (f_ "%s %s%s") arg_hlp hlp default_value ] | CLIEnable -> let dflt = if default_value = " [true]" then s_ " [default: enabled]" else s_ " [default: disabled]" in [ arg_concat "--enable-" arg_name, Arg.Unit (fun () -> var_set "true"), Printf.sprintf (f_ " %s%s") hlp dflt; arg_concat "--disable-" arg_name, Arg.Unit (fun () -> var_set "false"), Printf.sprintf (f_ " %s%s") hlp dflt ] | CLIUser lst -> lst in args :: acc) [] schema) end module BaseArgExt = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseArgExt.ml" open OASISUtils open OASISGettext let parse argv args = (* Simulate command line for Arg *) let current = ref 0 in try Arg.parse_argv ~current:current (Array.concat [[|"none"|]; argv]) (Arg.align args) (failwithf (f_ "Don't know what to do with arguments: '%s'")) (s_ "configure options:") with | Arg.Help txt -> print_endline txt; exit 0 | Arg.Bad txt -> prerr_endline txt; exit 1 end module BaseCheck = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseCheck.ml" open BaseEnv open BaseMessage open OASISUtils open OASISGettext let prog_best prg prg_lst = var_redefine prg (fun () -> let alternate = List.fold_left (fun res e -> match res with | Some _ -> res | None -> try Some (OASISFileUtil.which ~ctxt:!BaseContext.default e) with Not_found -> None) None prg_lst in match alternate with | Some prg -> prg | None -> raise Not_found) let prog prg = prog_best prg [prg] let prog_opt prg = prog_best prg [prg^".opt"; prg] let ocamlfind = prog "ocamlfind" let version var_prefix cmp fversion () = (* Really compare version provided *) let var = var_prefix^"_version_"^(OASISVersion.varname_of_comparator cmp) in var_redefine ~hide:true var (fun () -> let version_str = match fversion () with | "[Distributed with OCaml]" -> begin try (var_get "ocaml_version") with Not_found -> warning (f_ "Variable ocaml_version not defined, fallback \ to default"); Sys.ocaml_version end | res -> res in let version = OASISVersion.version_of_string version_str in if OASISVersion.comparator_apply version cmp then version_str else failwithf (f_ "Cannot satisfy version constraint on %s: %s (version: %s)") var_prefix (OASISVersion.string_of_comparator cmp) version_str) () let package_version pkg = OASISExec.run_read_one_line ~ctxt:!BaseContext.default (ocamlfind ()) ["query"; "-format"; "%v"; pkg] let package ?version_comparator pkg () = let var = OASISUtils.varname_concat "pkg_" (OASISUtils.varname_of_string pkg) in let findlib_dir pkg = let dir = OASISExec.run_read_one_line ~ctxt:!BaseContext.default (ocamlfind ()) ["query"; "-format"; "%d"; pkg] in if Sys.file_exists dir && Sys.is_directory dir then dir else failwithf (f_ "When looking for findlib package %s, \ directory %s return doesn't exist") pkg dir in let vl = var_redefine var (fun () -> findlib_dir pkg) () in ( match version_comparator with | Some ver_cmp -> ignore (version var ver_cmp (fun _ -> package_version pkg) ()) | None -> () ); vl end module BaseOCamlcConfig = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseOCamlcConfig.ml" open BaseEnv open OASISUtils open OASISGettext module SMap = Map.Make(String) let ocamlc = BaseCheck.prog_opt "ocamlc" let ocamlc_config_map = (* Map name to value for ocamlc -config output (name ^": "^value) *) let rec split_field mp lst = match lst with | line :: tl -> let mp = try let pos_semicolon = String.index line ':' in if pos_semicolon > 1 then ( let name = String.sub line 0 pos_semicolon in let linelen = String.length line in let value = if linelen > pos_semicolon + 2 then String.sub line (pos_semicolon + 2) (linelen - pos_semicolon - 2) else "" in SMap.add name value mp ) else ( mp ) with Not_found -> ( mp ) in split_field mp tl | [] -> mp in let cache = lazy (var_protect (Marshal.to_string (split_field SMap.empty (OASISExec.run_read_output ~ctxt:!BaseContext.default (ocamlc ()) ["-config"])) [])) in var_redefine "ocamlc_config_map" ~hide:true ~dump:false (fun () -> (* TODO: update if ocamlc change !!! *) Lazy.force cache) let var_define nm = (* Extract data from ocamlc -config *) let avlbl_config_get () = Marshal.from_string (ocamlc_config_map ()) 0 in let chop_version_suffix s = try String.sub s 0 (String.index s '+') with _ -> s in let nm_config, value_config = match nm with | "ocaml_version" -> "version", chop_version_suffix | _ -> nm, (fun x -> x) in var_redefine nm (fun () -> try let map = avlbl_config_get () in let value = SMap.find nm_config map in value_config value with Not_found -> failwithf (f_ "Cannot find field '%s' in '%s -config' output") nm (ocamlc ())) end module BaseStandardVar = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseStandardVar.ml" open OASISGettext open OASISTypes open OASISExpr open BaseCheck open BaseEnv let ocamlfind = BaseCheck.ocamlfind let ocamlc = BaseOCamlcConfig.ocamlc let ocamlopt = prog_opt "ocamlopt" let ocamlbuild = prog "ocamlbuild" (**/**) let rpkg = ref None let pkg_get () = match !rpkg with | Some pkg -> pkg | None -> failwith (s_ "OASIS Package is not set") let var_cond = ref [] let var_define_cond ~since_version f dflt = let holder = ref (fun () -> dflt) in let since_version = OASISVersion.VGreaterEqual (OASISVersion.version_of_string since_version) in var_cond := (fun ver -> if OASISVersion.comparator_apply ver since_version then holder := f ()) :: !var_cond; fun () -> !holder () (**/**) let pkg_name = var_define ~short_desc:(fun () -> s_ "Package name") "pkg_name" (fun () -> (pkg_get ()).name) let pkg_version = var_define ~short_desc:(fun () -> s_ "Package version") "pkg_version" (fun () -> (OASISVersion.string_of_version (pkg_get ()).version)) let c = BaseOCamlcConfig.var_define let os_type = c "os_type" let system = c "system" let architecture = c "architecture" let ccomp_type = c "ccomp_type" let ocaml_version = c "ocaml_version" (* TODO: Check standard variable presence at runtime *) let standard_library_default = c "standard_library_default" let standard_library = c "standard_library" let standard_runtime = c "standard_runtime" let bytecomp_c_compiler = c "bytecomp_c_compiler" let native_c_compiler = c "native_c_compiler" let model = c "model" let ext_obj = c "ext_obj" let ext_asm = c "ext_asm" let ext_lib = c "ext_lib" let ext_dll = c "ext_dll" let default_executable_name = c "default_executable_name" let systhread_supported = c "systhread_supported" (**/**) let p name hlp dflt = var_define ~short_desc:hlp ~cli:CLIAuto ~arg_help:"dir" name dflt let (/) a b = if os_type () = Sys.os_type then Filename.concat a b else if os_type () = "Unix" then OASISUnixPath.concat a b else OASISUtils.failwithf (f_ "Cannot handle os_type %s filename concat") (os_type ()) (**/**) let prefix = p "prefix" (fun () -> s_ "Install architecture-independent files dir") (fun () -> match os_type () with | "Win32" -> let program_files = Sys.getenv "PROGRAMFILES" in program_files/(pkg_name ()) | _ -> "/usr/local") let exec_prefix = p "exec_prefix" (fun () -> s_ "Install architecture-dependent files in dir") (fun () -> "$prefix") let bindir = p "bindir" (fun () -> s_ "User executables") (fun () -> "$exec_prefix"/"bin") let sbindir = p "sbindir" (fun () -> s_ "System admin executables") (fun () -> "$exec_prefix"/"sbin") let libexecdir = p "libexecdir" (fun () -> s_ "Program executables") (fun () -> "$exec_prefix"/"libexec") let sysconfdir = p "sysconfdir" (fun () -> s_ "Read-only single-machine data") (fun () -> "$prefix"/"etc") let sharedstatedir = p "sharedstatedir" (fun () -> s_ "Modifiable architecture-independent data") (fun () -> "$prefix"/"com") let localstatedir = p "localstatedir" (fun () -> s_ "Modifiable single-machine data") (fun () -> "$prefix"/"var") let libdir = p "libdir" (fun () -> s_ "Object code libraries") (fun () -> "$exec_prefix"/"lib") let datarootdir = p "datarootdir" (fun () -> s_ "Read-only arch-independent data root") (fun () -> "$prefix"/"share") let datadir = p "datadir" (fun () -> s_ "Read-only architecture-independent data") (fun () -> "$datarootdir") let infodir = p "infodir" (fun () -> s_ "Info documentation") (fun () -> "$datarootdir"/"info") let localedir = p "localedir" (fun () -> s_ "Locale-dependent data") (fun () -> "$datarootdir"/"locale") let mandir = p "mandir" (fun () -> s_ "Man documentation") (fun () -> "$datarootdir"/"man") let docdir = p "docdir" (fun () -> s_ "Documentation root") (fun () -> "$datarootdir"/"doc"/"$pkg_name") let htmldir = p "htmldir" (fun () -> s_ "HTML documentation") (fun () -> "$docdir") let dvidir = p "dvidir" (fun () -> s_ "DVI documentation") (fun () -> "$docdir") let pdfdir = p "pdfdir" (fun () -> s_ "PDF documentation") (fun () -> "$docdir") let psdir = p "psdir" (fun () -> s_ "PS documentation") (fun () -> "$docdir") let destdir = p "destdir" (fun () -> s_ "Prepend a path when installing package") (fun () -> raise (PropList.Not_set ("destdir", Some (s_ "undefined by construct")))) let findlib_version = var_define "findlib_version" (fun () -> BaseCheck.package_version "findlib") let is_native = var_define "is_native" (fun () -> try let _s : string = ocamlopt () in "true" with PropList.Not_set _ -> let _s : string = ocamlc () in "false") let ext_program = var_define "suffix_program" (fun () -> match os_type () with | "Win32" -> ".exe" | _ -> "") let rm = var_define ~short_desc:(fun () -> s_ "Remove a file.") "rm" (fun () -> match os_type () with | "Win32" -> "del" | _ -> "rm -f") let rmdir = var_define ~short_desc:(fun () -> s_ "Remove a directory.") "rmdir" (fun () -> match os_type () with | "Win32" -> "rd" | _ -> "rm -rf") let debug = var_define ~short_desc:(fun () -> s_ "Turn ocaml debug flag on") ~cli:CLIEnable "debug" (fun () -> "true") let profile = var_define ~short_desc:(fun () -> s_ "Turn ocaml profile flag on") ~cli:CLIEnable "profile" (fun () -> "false") let tests = var_define_cond ~since_version:"0.3" (fun () -> var_define ~short_desc:(fun () -> s_ "Compile tests executable and library and run them") ~cli:CLIEnable "tests" (fun () -> "false")) "true" let docs = var_define_cond ~since_version:"0.3" (fun () -> var_define ~short_desc:(fun () -> s_ "Create documentations") ~cli:CLIEnable "docs" (fun () -> "true")) "true" let native_dynlink = var_define ~short_desc:(fun () -> s_ "Compiler support generation of .cmxs.") ~cli:CLINone "native_dynlink" (fun () -> let res = if bool_of_string (is_native ()) then begin let ocamlfind = ocamlfind () in try let fn = OASISExec.run_read_one_line ~ctxt:!BaseContext.default ocamlfind ["query"; "-predicates"; "native"; "dynlink"; "-format"; "%d/%a"] in Sys.file_exists fn with _ -> false end else false in string_of_bool res) let init pkg = rpkg := Some pkg; List.iter (fun f -> f pkg.oasis_version) !var_cond end module BaseFileAB = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseFileAB.ml" open BaseEnv open OASISGettext open BaseMessage let to_filename fn = let fn = OASISHostPath.of_unix fn in if not (Filename.check_suffix fn ".ab") then warning (f_ "File '%s' doesn't have '.ab' extension") fn; Filename.chop_extension fn let replace fn_lst = let buff = Buffer.create 13 in List.iter (fun fn -> let fn = OASISHostPath.of_unix fn in let chn_in = open_in fn in let chn_out = open_out (to_filename fn) in ( try while true do Buffer.add_string buff (var_expand (input_line chn_in)); Buffer.add_char buff '\n' done with End_of_file -> () ); Buffer.output_buffer chn_out buff; Buffer.clear buff; close_in chn_in; close_out chn_out) fn_lst end module BaseLog = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseLog.ml" open OASISUtils let default_filename = Filename.concat (Filename.dirname BaseEnv.default_filename) "setup.log" module SetTupleString = Set.Make (struct type t = string * string let compare (s11, s12) (s21, s22) = match String.compare s11 s21 with | 0 -> String.compare s12 s22 | n -> n end) let load () = if Sys.file_exists default_filename then begin let chn = open_in default_filename in let scbuf = Scanf.Scanning.from_file default_filename in let rec read_aux (st, lst) = if not (Scanf.Scanning.end_of_input scbuf) then begin let acc = try Scanf.bscanf scbuf "%S %S\n" (fun e d -> let t = e, d in if SetTupleString.mem t st then st, lst else SetTupleString.add t st, t :: lst) with Scanf.Scan_failure _ -> failwith (Scanf.bscanf scbuf "%l" (fun line -> Printf.sprintf "Malformed log file '%s' at line %d" default_filename line)) in read_aux acc end else begin close_in chn; List.rev lst end in read_aux (SetTupleString.empty, []) end else begin [] end let register event data = let chn_out = open_out_gen [Open_append; Open_creat; Open_text] 0o644 default_filename in Printf.fprintf chn_out "%S %S\n" event data; close_out chn_out let unregister event data = if Sys.file_exists default_filename then begin let lst = load () in let chn_out = open_out default_filename in let write_something = ref false in List.iter (fun (e, d) -> if e <> event || d <> data then begin write_something := true; Printf.fprintf chn_out "%S %S\n" e d end) lst; close_out chn_out; if not !write_something then Sys.remove default_filename end let filter events = let st_events = List.fold_left (fun st e -> SetString.add e st) SetString.empty events in List.filter (fun (e, _) -> SetString.mem e st_events) (load ()) let exists event data = List.exists (fun v -> (event, data) = v) (load ()) end module BaseBuilt = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseBuilt.ml" open OASISTypes open OASISGettext open BaseStandardVar open BaseMessage type t = | BExec (* Executable *) | BExecLib (* Library coming with executable *) | BLib (* Library *) | BDoc (* Document *) let to_log_event_file t nm = "built_"^ (match t with | BExec -> "exec" | BExecLib -> "exec_lib" | BLib -> "lib" | BDoc -> "doc")^ "_"^nm let to_log_event_done t nm = "is_"^(to_log_event_file t nm) let register t nm lst = BaseLog.register (to_log_event_done t nm) "true"; List.iter (fun alt -> let registered = List.fold_left (fun registered fn -> if OASISFileUtil.file_exists_case fn then begin BaseLog.register (to_log_event_file t nm) (if Filename.is_relative fn then Filename.concat (Sys.getcwd ()) fn else fn); true end else registered) false alt in if not registered then warning (f_ "Cannot find an existing alternative files among: %s") (String.concat (s_ ", ") alt)) lst let unregister t nm = List.iter (fun (e, d) -> BaseLog.unregister e d) (BaseLog.filter [to_log_event_file t nm; to_log_event_done t nm]) let fold t nm f acc = List.fold_left (fun acc (_, fn) -> if OASISFileUtil.file_exists_case fn then begin f acc fn end else begin warning (f_ "File '%s' has been marked as built \ for %s but doesn't exist") fn (Printf.sprintf (match t with | BExec | BExecLib -> (f_ "executable %s") | BLib -> (f_ "library %s") | BDoc -> (f_ "documentation %s")) nm); acc end) acc (BaseLog.filter [to_log_event_file t nm]) let is_built t nm = List.fold_left (fun is_built (_, d) -> (try bool_of_string d with _ -> false)) false (BaseLog.filter [to_log_event_done t nm]) let of_executable ffn (cs, bs, exec) = let unix_exec_is, unix_dll_opt = OASISExecutable.unix_exec_is (cs, bs, exec) (fun () -> bool_of_string (is_native ())) ext_dll ext_program in let evs = (BExec, cs.cs_name, [[ffn unix_exec_is]]) :: (match unix_dll_opt with | Some fn -> [BExecLib, cs.cs_name, [[ffn fn]]] | None -> []) in evs, unix_exec_is, unix_dll_opt let of_library ffn (cs, bs, lib) = let unix_lst = OASISLibrary.generated_unix_files ~ctxt:!BaseContext.default ~source_file_exists:(fun fn -> OASISFileUtil.file_exists_case (OASISHostPath.of_unix fn)) ~is_native:(bool_of_string (is_native ())) ~has_native_dynlink:(bool_of_string (native_dynlink ())) ~ext_lib:(ext_lib ()) ~ext_dll:(ext_dll ()) (cs, bs, lib) in let evs = [BLib, cs.cs_name, List.map (List.map ffn) unix_lst] in evs, unix_lst end module BaseCustom = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseCustom.ml" open BaseEnv open BaseMessage open OASISTypes open OASISGettext let run cmd args extra_args = OASISExec.run ~ctxt:!BaseContext.default (var_expand cmd) (List.map var_expand (args @ (Array.to_list extra_args))) let hook ?(failsafe=false) cstm f e = let optional_command lst = let printer = function | Some (cmd, args) -> String.concat " " (cmd :: args) | None -> s_ "No command" in match var_choose ~name:(s_ "Pre/Post Command") ~printer lst with | Some (cmd, args) -> begin try run cmd args [||] with e when failsafe -> warning (f_ "Command '%s' fail with error: %s") (String.concat " " (cmd :: args)) (match e with | Failure msg -> msg | e -> Printexc.to_string e) end | None -> () in let res = optional_command cstm.pre_command; f e in optional_command cstm.post_command; res end module BaseDynVar = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseDynVar.ml" open OASISTypes open OASISGettext open BaseEnv open BaseBuilt let init pkg = (* TODO: disambiguate exec vs other variable by adding exec_VARNAME. *) (* TODO: provide compile option for library libary_byte_args_VARNAME... *) List.iter (function | Executable (cs, bs, exec) -> if var_choose bs.bs_build then var_ignore (var_redefine (* We don't save this variable *) ~dump:false ~short_desc:(fun () -> Printf.sprintf (f_ "Filename of executable '%s'") cs.cs_name) (OASISUtils.varname_of_string cs.cs_name) (fun () -> let fn_opt = fold BExec cs.cs_name (fun _ fn -> Some fn) None in match fn_opt with | Some fn -> fn | None -> raise (PropList.Not_set (cs.cs_name, Some (Printf.sprintf (f_ "Executable '%s' not yet built.") cs.cs_name))))) | Library _ | Flag _ | Test _ | SrcRepo _ | Doc _ -> ()) pkg.sections end module BaseTest = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseTest.ml" open BaseEnv open BaseMessage open OASISTypes open OASISExpr open OASISGettext let test lst pkg extra_args = let one_test (failure, n) (test_plugin, cs, test) = if var_choose ~name:(Printf.sprintf (f_ "test %s run") cs.cs_name) ~printer:string_of_bool test.test_run then begin let () = info (f_ "Running test '%s'") cs.cs_name in let back_cwd = match test.test_working_directory with | Some dir -> let cwd = Sys.getcwd () in let chdir d = info (f_ "Changing directory to '%s'") d; Sys.chdir d in chdir dir; fun () -> chdir cwd | None -> fun () -> () in try let failure_percent = BaseCustom.hook test.test_custom (test_plugin pkg (cs, test)) extra_args in back_cwd (); (failure_percent +. failure, n + 1) with e -> begin back_cwd (); raise e end end else begin info (f_ "Skipping test '%s'") cs.cs_name; (failure, n) end in let (failed, n) = List.fold_left one_test (0.0, 0) lst in let failure_percent = if n = 0 then 0.0 else failed /. (float_of_int n) in let msg = Printf.sprintf (f_ "Tests had a %.2f%% failure rate") (100. *. failure_percent) in if failure_percent > 0.0 then failwith msg else info "%s" msg; (* Possible explanation why the tests where not run. *) if OASISVersion.version_0_3_or_after pkg.oasis_version && not (bool_of_string (BaseStandardVar.tests ())) && lst <> [] then BaseMessage.warning "Tests are turned off, consider enabling with \ 'ocaml setup.ml -configure --enable-tests'" end module BaseDoc = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseDoc.ml" open BaseEnv open BaseMessage open OASISTypes open OASISGettext let doc lst pkg extra_args = let one_doc (doc_plugin, cs, doc) = if var_choose ~name:(Printf.sprintf (f_ "documentation %s build") cs.cs_name) ~printer:string_of_bool doc.doc_build then begin info (f_ "Building documentation '%s'") cs.cs_name; BaseCustom.hook doc.doc_custom (doc_plugin pkg (cs, doc)) extra_args end in List.iter one_doc lst; if OASISVersion.version_0_3_or_after pkg.oasis_version && not (bool_of_string (BaseStandardVar.docs ())) && lst <> [] then BaseMessage.warning "Docs are turned off, consider enabling with \ 'ocaml setup.ml -configure --enable-docs'" end module BaseSetup = struct # 21 "/home/gildor/programmation/oasis/src/base/BaseSetup.ml" open BaseEnv open BaseMessage open OASISTypes open OASISSection open OASISGettext open OASISUtils type std_args_fun = package -> string array -> unit type ('a, 'b) section_args_fun = name * (package -> (common_section * 'a) -> string array -> 'b) type t = { configure: std_args_fun; build: std_args_fun; doc: ((doc, unit) section_args_fun) list; test: ((test, float) section_args_fun) list; install: std_args_fun; uninstall: std_args_fun; clean: std_args_fun list; clean_doc: (doc, unit) section_args_fun list; clean_test: (test, unit) section_args_fun list; distclean: std_args_fun list; distclean_doc: (doc, unit) section_args_fun list; distclean_test: (test, unit) section_args_fun list; package: package; oasis_fn: string option; oasis_version: string; oasis_digest: Digest.t option; oasis_exec: string option; oasis_setup_args: string list; setup_update: bool; } (* Associate a plugin function with data from package *) let join_plugin_sections filter_map lst = List.rev (List.fold_left (fun acc sct -> match filter_map sct with | Some e -> e :: acc | None -> acc) [] lst) (* Search for plugin data associated with a section name *) let lookup_plugin_section plugin action nm lst = try List.assoc nm lst with Not_found -> failwithf (f_ "Cannot find plugin %s matching section %s for %s action") plugin nm action let configure t args = (* Run configure *) BaseCustom.hook t.package.conf_custom (fun () -> (* Reload if preconf has changed it *) begin try unload (); load (); with _ -> () end; (* Run plugin's configure *) t.configure t.package args; (* Dump to allow postconf to change it *) dump ()) (); (* Reload environment *) unload (); load (); (* Save environment *) print (); (* Replace data in file *) BaseFileAB.replace t.package.files_ab let build t args = BaseCustom.hook t.package.build_custom (t.build t.package) args let doc t args = BaseDoc.doc (join_plugin_sections (function | Doc (cs, e) -> Some (lookup_plugin_section "documentation" (s_ "build") cs.cs_name t.doc, cs, e) | _ -> None) t.package.sections) t.package args let test t args = BaseTest.test (join_plugin_sections (function | Test (cs, e) -> Some (lookup_plugin_section "test" (s_ "run") cs.cs_name t.test, cs, e) | _ -> None) t.package.sections) t.package args let all t args = let rno_doc = ref false in let rno_test = ref false in Arg.parse_argv ~current:(ref 0) (Array.of_list ((Sys.executable_name^" all") :: (Array.to_list args))) [ "-no-doc", Arg.Set rno_doc, s_ "Don't run doc target"; "-no-test", Arg.Set rno_test, s_ "Don't run test target"; ] (failwithf (f_ "Don't know what to do with '%s'")) ""; info "Running configure step"; configure t [||]; info "Running build step"; build t [||]; (* Load setup.log dynamic variables *) BaseDynVar.init t.package; if not !rno_doc then begin info "Running doc step"; doc t [||]; end else begin info "Skipping doc step" end; if not !rno_test then begin info "Running test step"; test t [||] end else begin info "Skipping test step" end let install t args = BaseCustom.hook t.package.install_custom (t.install t.package) args let uninstall t args = BaseCustom.hook t.package.uninstall_custom (t.uninstall t.package) args let reinstall t args = uninstall t args; install t args let clean, distclean = let failsafe f a = try f a with e -> warning (f_ "Action fail with error: %s") (match e with | Failure msg -> msg | e -> Printexc.to_string e) in let generic_clean t cstm mains docs tests args = BaseCustom.hook ~failsafe:true cstm (fun () -> (* Clean section *) List.iter (function | Test (cs, test) -> let f = try List.assoc cs.cs_name tests with Not_found -> fun _ _ _ -> () in failsafe (f t.package (cs, test)) args | Doc (cs, doc) -> let f = try List.assoc cs.cs_name docs with Not_found -> fun _ _ _ -> () in failsafe (f t.package (cs, doc)) args | Library _ | Executable _ | Flag _ | SrcRepo _ -> ()) t.package.sections; (* Clean whole package *) List.iter (fun f -> failsafe (f t.package) args) mains) () in let clean t args = generic_clean t t.package.clean_custom t.clean t.clean_doc t.clean_test args in let distclean t args = (* Call clean *) clean t args; (* Call distclean code *) generic_clean t t.package.distclean_custom t.distclean t.distclean_doc t.distclean_test args; (* Remove generated file *) List.iter (fun fn -> if Sys.file_exists fn then begin info (f_ "Remove '%s'") fn; Sys.remove fn end) (BaseEnv.default_filename :: BaseLog.default_filename :: (List.rev_map BaseFileAB.to_filename t.package.files_ab)) in clean, distclean let version t _ = print_endline t.oasis_version let update_setup_ml, no_update_setup_ml_cli = let b = ref true in b, ("-no-update-setup-ml", Arg.Clear b, s_ " Don't try to update setup.ml, even if _oasis has changed.") let update_setup_ml t = let oasis_fn = match t.oasis_fn with | Some fn -> fn | None -> "_oasis" in let oasis_exec = match t.oasis_exec with | Some fn -> fn | None -> "oasis" in let ocaml = Sys.executable_name in let setup_ml, args = match Array.to_list Sys.argv with | setup_ml :: args -> setup_ml, args | [] -> failwith (s_ "Expecting non-empty command line arguments.") in let ocaml, setup_ml = if Sys.executable_name = Sys.argv.(0) then (* We are not running in standard mode, probably the script * is precompiled. *) "ocaml", "setup.ml" else ocaml, setup_ml in let no_update_setup_ml_cli, _, _ = no_update_setup_ml_cli in let do_update () = let oasis_exec_version = OASISExec.run_read_one_line ~ctxt:!BaseContext.default ~f_exit_code: (function | 0 -> () | 1 -> failwithf (f_ "Executable '%s' is probably an old version \ of oasis (< 0.3.0), please update to version \ v%s.") oasis_exec t.oasis_version | 127 -> failwithf (f_ "Cannot find executable '%s', please install \ oasis v%s.") oasis_exec t.oasis_version | n -> failwithf (f_ "Command '%s version' exited with code %d.") oasis_exec n) oasis_exec ["version"] in if OASISVersion.comparator_apply (OASISVersion.version_of_string oasis_exec_version) (OASISVersion.VGreaterEqual (OASISVersion.version_of_string t.oasis_version)) then begin (* We have a version >= for the executable oasis, proceed with * update. *) (* TODO: delegate this check to 'oasis setup'. *) if Sys.os_type = "Win32" then failwithf (f_ "It is not possible to update the running script \ setup.ml on Windows. Please update setup.ml by \ running '%s'.") (String.concat " " (oasis_exec :: "setup" :: t.oasis_setup_args)) else begin OASISExec.run ~ctxt:!BaseContext.default ~f_exit_code: (function | 0 -> () | n -> failwithf (f_ "Unable to update setup.ml using '%s', \ please fix the problem and retry.") oasis_exec) oasis_exec ("setup" :: t.oasis_setup_args); OASISExec.run ~ctxt:!BaseContext.default ocaml (setup_ml :: args) end end else failwithf (f_ "The version of '%s' (v%s) doesn't match the version of \ oasis used to generate the %s file. Please install at \ least oasis v%s.") oasis_exec oasis_exec_version setup_ml t.oasis_version in if !update_setup_ml then begin try match t.oasis_digest with | Some dgst -> if Sys.file_exists oasis_fn && dgst <> Digest.file "_oasis" then begin do_update (); true end else false | None -> false with e -> error (f_ "Error when updating setup.ml. If you want to avoid this error, \ you can bypass the update of %s by running '%s %s %s %s'") setup_ml ocaml setup_ml no_update_setup_ml_cli (String.concat " " args); raise e end else false let setup t = let catch_exn = ref true in try let act_ref = ref (fun _ -> failwithf (f_ "No action defined, run '%s %s -help'") Sys.executable_name Sys.argv.(0)) in let extra_args_ref = ref [] in let allow_empty_env_ref = ref false in let arg_handle ?(allow_empty_env=false) act = Arg.Tuple [ Arg.Rest (fun str -> extra_args_ref := str :: !extra_args_ref); Arg.Unit (fun () -> allow_empty_env_ref := allow_empty_env; act_ref := act); ] in Arg.parse (Arg.align ([ "-configure", arg_handle ~allow_empty_env:true configure, s_ "[options*] Configure the whole build process."; "-build", arg_handle build, s_ "[options*] Build executables and libraries."; "-doc", arg_handle doc, s_ "[options*] Build documents."; "-test", arg_handle test, s_ "[options*] Run tests."; "-all", arg_handle ~allow_empty_env:true all, s_ "[options*] Run configure, build, doc and test targets."; "-install", arg_handle install, s_ "[options*] Install libraries, data, executables \ and documents."; "-uninstall", arg_handle uninstall, s_ "[options*] Uninstall libraries, data, executables \ and documents."; "-reinstall", arg_handle reinstall, s_ "[options*] Uninstall and install libraries, data, \ executables and documents."; "-clean", arg_handle ~allow_empty_env:true clean, s_ "[options*] Clean files generated by a build."; "-distclean", arg_handle ~allow_empty_env:true distclean, s_ "[options*] Clean files generated by a build and configure."; "-version", arg_handle ~allow_empty_env:true version, s_ " Display version of OASIS used to generate this setup.ml."; "-no-catch-exn", Arg.Clear catch_exn, s_ " Don't catch exception, useful for debugging."; ] @ (if t.setup_update then [no_update_setup_ml_cli] else []) @ (BaseContext.args ()))) (failwithf (f_ "Don't know what to do with '%s'")) (s_ "Setup and run build process current package\n"); (* Build initial environment *) load ~allow_empty:!allow_empty_env_ref (); (** Initialize flags *) List.iter (function | Flag (cs, {flag_description = hlp; flag_default = choices}) -> begin let apply ?short_desc () = var_ignore (var_define ~cli:CLIEnable ?short_desc (OASISUtils.varname_of_string cs.cs_name) (fun () -> string_of_bool (var_choose ~name:(Printf.sprintf (f_ "default value of flag %s") cs.cs_name) ~printer:string_of_bool choices))) in match hlp with | Some hlp -> apply ~short_desc:(fun () -> hlp) () | None -> apply () end | _ -> ()) t.package.sections; BaseStandardVar.init t.package; BaseDynVar.init t.package; if t.setup_update && update_setup_ml t then () else !act_ref t (Array.of_list (List.rev !extra_args_ref)) with e when !catch_exn -> error "%s" (Printexc.to_string e); exit 1 end # 4418 "setup.ml" module InternalConfigurePlugin = struct # 21 "/home/gildor/programmation/oasis/src/plugins/internal/InternalConfigurePlugin.ml" (** Configure using internal scheme @author Sylvain Le Gall *) open BaseEnv open OASISTypes open OASISUtils open OASISGettext open BaseMessage (** Configure build using provided series of check to be done * and then output corresponding file. *) let configure pkg argv = let var_ignore_eval var = let _s : string = var () in () in let errors = ref SetString.empty in let buff = Buffer.create 13 in let add_errors fmt = Printf.kbprintf (fun b -> errors := SetString.add (Buffer.contents b) !errors; Buffer.clear b) buff fmt in let warn_exception e = warning "%s" (Printexc.to_string e) in (* Check tools *) let check_tools lst = List.iter (function | ExternalTool tool -> begin try var_ignore_eval (BaseCheck.prog tool) with e -> warn_exception e; add_errors (f_ "Cannot find external tool '%s'") tool end | InternalExecutable nm1 -> (* Check that matching tool is built *) List.iter (function | Executable ({cs_name = nm2}, {bs_build = build}, _) when nm1 = nm2 -> if not (var_choose build) then add_errors (f_ "Cannot find buildable internal executable \ '%s' when checking build depends") nm1 | _ -> ()) pkg.sections) lst in let build_checks sct bs = if var_choose bs.bs_build then begin if bs.bs_compiled_object = Native then begin try var_ignore_eval BaseStandardVar.ocamlopt with e -> warn_exception e; add_errors (f_ "Section %s requires native compilation") (OASISSection.string_of_section sct) end; (* Check tools *) check_tools bs.bs_build_tools; (* Check depends *) List.iter (function | FindlibPackage (findlib_pkg, version_comparator) -> begin try var_ignore_eval (BaseCheck.package ?version_comparator findlib_pkg) with e -> warn_exception e; match version_comparator with | None -> add_errors (f_ "Cannot find findlib package %s") findlib_pkg | Some ver_cmp -> add_errors (f_ "Cannot find findlib package %s (%s)") findlib_pkg (OASISVersion.string_of_comparator ver_cmp) end | InternalLibrary nm1 -> (* Check that matching library is built *) List.iter (function | Library ({cs_name = nm2}, {bs_build = build}, _) when nm1 = nm2 -> if not (var_choose build) then add_errors (f_ "Cannot find buildable internal library \ '%s' when checking build depends") nm1 | _ -> ()) pkg.sections) bs.bs_build_depends end in (* Parse command line *) BaseArgExt.parse argv (BaseEnv.args ()); (* OCaml version *) begin match pkg.ocaml_version with | Some ver_cmp -> begin try var_ignore_eval (BaseCheck.version "ocaml" ver_cmp BaseStandardVar.ocaml_version) with e -> warn_exception e; add_errors (f_ "OCaml version %s doesn't match version constraint %s") (BaseStandardVar.ocaml_version ()) (OASISVersion.string_of_comparator ver_cmp) end | None -> () end; (* Findlib version *) begin match pkg.findlib_version with | Some ver_cmp -> begin try var_ignore_eval (BaseCheck.version "findlib" ver_cmp BaseStandardVar.findlib_version) with e -> warn_exception e; add_errors (f_ "Findlib version %s doesn't match version constraint %s") (BaseStandardVar.findlib_version ()) (OASISVersion.string_of_comparator ver_cmp) end | None -> () end; (* Check build depends *) List.iter (function | Executable (_, bs, _) | Library (_, bs, _) as sct -> build_checks sct bs | Doc (_, doc) -> if var_choose doc.doc_build then check_tools doc.doc_build_tools | Test (_, test) -> if var_choose test.test_run then check_tools test.test_tools | _ -> ()) pkg.sections; (* Check if we need native dynlink (presence of libraries that compile to * native) *) begin let has_cmxa = List.exists (function | Library (_, bs, _) -> var_choose bs.bs_build && (bs.bs_compiled_object = Native || (bs.bs_compiled_object = Best && bool_of_string (BaseStandardVar.is_native ()))) | _ -> false) pkg.sections in if has_cmxa then var_ignore_eval BaseStandardVar.native_dynlink end; (* Check errors *) if SetString.empty != !errors then begin List.iter (fun e -> error "%s" e) (SetString.elements !errors); failwithf (fn_ "%d configuration error" "%d configuration errors" (SetString.cardinal !errors)) (SetString.cardinal !errors) end end module InternalInstallPlugin = struct # 21 "/home/gildor/programmation/oasis/src/plugins/internal/InternalInstallPlugin.ml" (** Install using internal scheme @author Sylvain Le Gall *) open BaseEnv open BaseStandardVar open BaseMessage open OASISTypes open OASISLibrary open OASISGettext open OASISUtils let exec_hook = ref (fun (cs, bs, exec) -> cs, bs, exec) let lib_hook = ref (fun (cs, bs, lib) -> cs, bs, lib, []) let doc_hook = ref (fun (cs, doc) -> cs, doc) let install_file_ev = "install-file" let install_dir_ev = "install-dir" let install_findlib_ev = "install-findlib" let install pkg argv = let in_destdir = try let destdir = destdir () in (* Practically speaking destdir is prepended * at the beginning of the target filename *) fun fn -> destdir^fn with PropList.Not_set _ -> fun fn -> fn in let install_file ?tgt_fn src_file envdir = let tgt_dir = in_destdir (envdir ()) in let tgt_file = Filename.concat tgt_dir (match tgt_fn with | Some fn -> fn | None -> Filename.basename src_file) in (* Create target directory if needed *) OASISFileUtil.mkdir_parent ~ctxt:!BaseContext.default (fun dn -> info (f_ "Creating directory '%s'") dn; BaseLog.register install_dir_ev dn) tgt_dir; (* Really install files *) info (f_ "Copying file '%s' to '%s'") src_file tgt_file; OASISFileUtil.cp ~ctxt:!BaseContext.default src_file tgt_file; BaseLog.register install_file_ev tgt_file in (* Install data into defined directory *) let install_data srcdir lst tgtdir = let tgtdir = OASISHostPath.of_unix (var_expand tgtdir) in List.iter (fun (src, tgt_opt) -> let real_srcs = OASISFileUtil.glob ~ctxt:!BaseContext.default (Filename.concat srcdir src) in if real_srcs = [] then failwithf (f_ "Wildcard '%s' doesn't match any files") src; List.iter (fun fn -> install_file fn (fun () -> match tgt_opt with | Some s -> OASISHostPath.of_unix (var_expand s) | None -> tgtdir)) real_srcs) lst in (** Install all libraries *) let install_libs pkg = let files_of_library (f_data, acc) data_lib = let cs, bs, lib, lib_extra = !lib_hook data_lib in if var_choose bs.bs_install && BaseBuilt.is_built BaseBuilt.BLib cs.cs_name then begin let acc = (* Start with acc + lib_extra *) List.rev_append lib_extra acc in let acc = (* Add uncompiled header from the source tree *) let path = OASISHostPath.of_unix bs.bs_path in List.fold_left (fun acc modul -> try List.find OASISFileUtil.file_exists_case (List.map (Filename.concat path) [modul^".mli"; modul^".ml"; String.uncapitalize modul^".mli"; String.capitalize modul^".mli"; String.uncapitalize modul^".ml"; String.capitalize modul^".ml"]) :: acc with Not_found -> begin warning (f_ "Cannot find source header for module %s \ in library %s") modul cs.cs_name; acc end) acc lib.lib_modules in let acc = (* Get generated files *) BaseBuilt.fold BaseBuilt.BLib cs.cs_name (fun acc fn -> fn :: acc) acc in let f_data () = (* Install data associated with the library *) install_data bs.bs_path bs.bs_data_files (Filename.concat (datarootdir ()) pkg.name); f_data () in (f_data, acc) end else begin (f_data, acc) end in (* Install one group of library *) let install_group_lib grp = (* Iterate through all group nodes *) let rec install_group_lib_aux data_and_files grp = let data_and_files, children = match grp with | Container (_, children) -> data_and_files, children | Package (_, cs, bs, lib, children) -> files_of_library data_and_files (cs, bs, lib), children in List.fold_left install_group_lib_aux data_and_files children in (* Findlib name of the root library *) let findlib_name = findlib_of_group grp in (* Determine root library *) let root_lib = root_of_group grp in (* All files to install for this library *) let f_data, files = install_group_lib_aux (ignore, []) grp in (* Really install, if there is something to install *) if files = [] then begin warning (f_ "Nothing to install for findlib library '%s'") findlib_name end else begin let meta = (* Search META file *) let (_, bs, _) = root_lib in let res = Filename.concat bs.bs_path "META" in if not (OASISFileUtil.file_exists_case res) then failwithf (f_ "Cannot find file '%s' for findlib library %s") res findlib_name; res in let files = (* Make filename shorter to avoid hitting command max line length * too early, esp. on Windows. *) let remove_prefix p n = let plen = String.length p in let nlen = String.length n in if plen <= nlen && String.sub n 0 plen = p then begin let fn_sep = if Sys.os_type = "Win32" then '\\' else '/' in let cutpoint = plen + (if plen < nlen && n.[plen] = fn_sep then 1 else 0) in String.sub n cutpoint (nlen - cutpoint) end else n in List.map (remove_prefix (Sys.getcwd ())) files in info (f_ "Installing findlib library '%s'") findlib_name; OASISExec.run ~ctxt:!BaseContext.default (ocamlfind ()) ("install" :: findlib_name :: meta :: files); BaseLog.register install_findlib_ev findlib_name end; (* Install data files *) f_data (); in let group_libs, _, _ = findlib_mapping pkg in (* We install libraries in groups *) List.iter install_group_lib group_libs in let install_execs pkg = let install_exec data_exec = let (cs, bs, exec) = !exec_hook data_exec in if var_choose bs.bs_install && BaseBuilt.is_built BaseBuilt.BExec cs.cs_name then begin let exec_libdir () = Filename.concat (libdir ()) pkg.name in BaseBuilt.fold BaseBuilt.BExec cs.cs_name (fun () fn -> install_file ~tgt_fn:(cs.cs_name ^ ext_program ()) fn bindir) (); BaseBuilt.fold BaseBuilt.BExecLib cs.cs_name (fun () fn -> install_file fn exec_libdir) (); install_data bs.bs_path bs.bs_data_files (Filename.concat (datarootdir ()) pkg.name) end in List.iter (function | Executable (cs, bs, exec)-> install_exec (cs, bs, exec) | _ -> ()) pkg.sections in let install_docs pkg = let install_doc data = let (cs, doc) = !doc_hook data in if var_choose doc.doc_install && BaseBuilt.is_built BaseBuilt.BDoc cs.cs_name then begin let tgt_dir = OASISHostPath.of_unix (var_expand doc.doc_install_dir) in BaseBuilt.fold BaseBuilt.BDoc cs.cs_name (fun () fn -> install_file fn (fun () -> tgt_dir)) (); install_data Filename.current_dir_name doc.doc_data_files doc.doc_install_dir end in List.iter (function | Doc (cs, doc) -> install_doc (cs, doc) | _ -> ()) pkg.sections in install_libs pkg; install_execs pkg; install_docs pkg (* Uninstall already installed data *) let uninstall _ argv = List.iter (fun (ev, data) -> if ev = install_file_ev then begin if OASISFileUtil.file_exists_case data then begin info (f_ "Removing file '%s'") data; Sys.remove data end else begin warning (f_ "File '%s' doesn't exist anymore") data end end else if ev = install_dir_ev then begin if Sys.file_exists data && Sys.is_directory data then begin if Sys.readdir data = [||] then begin info (f_ "Removing directory '%s'") data; OASISFileUtil.rmdir ~ctxt:!BaseContext.default data end else begin warning (f_ "Directory '%s' is not empty (%s)") data (String.concat ", " (Array.to_list (Sys.readdir data))) end end else begin warning (f_ "Directory '%s' doesn't exist anymore") data end end else if ev = install_findlib_ev then begin info (f_ "Removing findlib library '%s'") data; OASISExec.run ~ctxt:!BaseContext.default (ocamlfind ()) ["remove"; data] end else failwithf (f_ "Unknown log event '%s'") ev; BaseLog.unregister ev data) (* We process event in reverse order *) (List.rev (BaseLog.filter [install_file_ev; install_dir_ev; install_findlib_ev;])) end # 5086 "setup.ml" module OCamlbuildCommon = struct # 21 "/home/gildor/programmation/oasis/src/plugins/ocamlbuild/OCamlbuildCommon.ml" (** Functions common to OCamlbuild build and doc plugin *) open OASISGettext open BaseEnv open BaseStandardVar let ocamlbuild_clean_ev = "ocamlbuild-clean" let ocamlbuildflags = var_define ~short_desc:(fun () -> "OCamlbuild additional flags") "ocamlbuildflags" (fun () -> "") (** Fix special arguments depending on environment *) let fix_args args extra_argv = List.flatten [ if (os_type ()) = "Win32" then [ "-classic-display"; "-no-log"; "-no-links"; "-install-lib-dir"; (Filename.concat (standard_library ()) "ocamlbuild") ] else []; if not (bool_of_string (is_native ())) || (os_type ()) = "Win32" then [ "-byte-plugin" ] else []; args; if bool_of_string (debug ()) then ["-tag"; "debug"] else []; if bool_of_string (profile ()) then ["-tag"; "profile"] else []; OASISString.nsplit (ocamlbuildflags ()) ' '; Array.to_list extra_argv; ] (** Run 'ocamlbuild -clean' if not already done *) let run_clean extra_argv = let extra_cli = String.concat " " (Array.to_list extra_argv) in (* Run if never called with these args *) if not (BaseLog.exists ocamlbuild_clean_ev extra_cli) then begin OASISExec.run ~ctxt:!BaseContext.default (ocamlbuild ()) (fix_args ["-clean"] extra_argv); BaseLog.register ocamlbuild_clean_ev extra_cli; at_exit (fun () -> try BaseLog.unregister ocamlbuild_clean_ev extra_cli with _ -> ()) end (** Run ocamlbuild, unregister all clean events *) let run_ocamlbuild args extra_argv = (* TODO: enforce that target in args must be UNIX encoded i.e. toto/index.html *) OASISExec.run ~ctxt:!BaseContext.default (ocamlbuild ()) (fix_args args extra_argv); (* Remove any clean event, we must run it again *) List.iter (fun (e, d) -> BaseLog.unregister e d) (BaseLog.filter [ocamlbuild_clean_ev]) (** Determine real build directory *) let build_dir extra_argv = let rec search_args dir = function | "-build-dir" :: dir :: tl -> search_args dir tl | _ :: tl -> search_args dir tl | [] -> dir in search_args "_build" (fix_args [] extra_argv) end module OCamlbuildPlugin = struct # 21 "/home/gildor/programmation/oasis/src/plugins/ocamlbuild/OCamlbuildPlugin.ml" (** Build using ocamlbuild @author Sylvain Le Gall *) open OASISTypes open OASISGettext open OASISUtils open BaseEnv open OCamlbuildCommon open BaseStandardVar open BaseMessage let cond_targets_hook = ref (fun lst -> lst) let build pkg argv = (* Return the filename in build directory *) let in_build_dir fn = Filename.concat (build_dir argv) fn in (* Return the unix filename in host build directory *) let in_build_dir_of_unix fn = in_build_dir (OASISHostPath.of_unix fn) in let cond_targets = List.fold_left (fun acc -> function | Library (cs, bs, lib) when var_choose bs.bs_build -> begin let evs, unix_files = BaseBuilt.of_library in_build_dir_of_unix (cs, bs, lib) in let ends_with nd fn = let nd_len = String.length nd in (String.length fn >= nd_len) && (String.sub fn (String.length fn - nd_len) nd_len) = nd in let tgts = List.flatten (List.filter (fun l -> l <> []) (List.map (List.filter (fun fn -> ends_with ".cma" fn || ends_with ".cmxs" fn || ends_with ".cmxa" fn || ends_with (ext_lib ()) fn || ends_with (ext_dll ()) fn)) unix_files)) in match tgts with | _ :: _ -> (evs, tgts) :: acc | [] -> failwithf (f_ "No possible ocamlbuild targets for library %s") cs.cs_name end | Executable (cs, bs, exec) when var_choose bs.bs_build -> begin let evs, unix_exec_is, unix_dll_opt = BaseBuilt.of_executable in_build_dir_of_unix (cs, bs, exec) in let target ext = let unix_tgt = (OASISUnixPath.concat bs.bs_path (OASISUnixPath.chop_extension exec.exec_main_is))^ext in let evs = (* Fix evs, we want to use the unix_tgt, without copying *) List.map (function | BaseBuilt.BExec, nm, lst when nm = cs.cs_name -> BaseBuilt.BExec, nm, [[in_build_dir_of_unix unix_tgt]] | ev -> ev) evs in evs, [unix_tgt] in (* Add executable *) let acc = match bs.bs_compiled_object with | Native -> (target ".native") :: acc | Best when bool_of_string (is_native ()) -> (target ".native") :: acc | Byte | Best -> (target ".byte") :: acc in acc end | Library _ | Executable _ | Test _ | SrcRepo _ | Flag _ | Doc _ -> acc) [] (* Keep the pkg.sections ordered *) (List.rev pkg.sections); in (* Check and register built files *) let check_and_register (bt, bnm, lst) = List.iter (fun fns -> if not (List.exists OASISFileUtil.file_exists_case fns) then failwithf (f_ "No one of expected built files %s exists") (String.concat (s_ ", ") (List.map (Printf.sprintf "'%s'") fns))) lst; (BaseBuilt.register bt bnm lst) in let cond_targets = (* Run the hook *) !cond_targets_hook cond_targets in (* Run a list of target... *) run_ocamlbuild (List.flatten (List.map snd cond_targets)) argv; (* ... and register events *) List.iter check_and_register (List.flatten (List.map fst cond_targets)) let clean pkg extra_args = run_clean extra_args; List.iter (function | Library (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BLib cs.cs_name | Executable (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BExec cs.cs_name; BaseBuilt.unregister BaseBuilt.BExecLib cs.cs_name | _ -> ()) pkg.sections end module OCamlbuildDocPlugin = struct # 21 "/home/gildor/programmation/oasis/src/plugins/ocamlbuild/OCamlbuildDocPlugin.ml" (* Create documentation using ocamlbuild .odocl files @author Sylvain Le Gall *) open OASISTypes open OASISGettext open OASISMessage open OCamlbuildCommon open BaseStandardVar let doc_build path pkg (cs, doc) argv = let index_html = OASISUnixPath.make [ path; cs.cs_name^".docdir"; "index.html"; ] in let tgt_dir = OASISHostPath.make [ build_dir argv; OASISHostPath.of_unix path; cs.cs_name^".docdir"; ] in run_ocamlbuild [index_html] argv; List.iter (fun glb -> BaseBuilt.register BaseBuilt.BDoc cs.cs_name [OASISFileUtil.glob ~ctxt:!BaseContext.default (Filename.concat tgt_dir glb)]) ["*.html"; "*.css"] let doc_clean t pkg (cs, doc) argv = run_clean argv; BaseBuilt.unregister BaseBuilt.BDoc cs.cs_name end # 5411 "setup.ml" module CustomPlugin = struct # 21 "/home/gildor/programmation/oasis/src/plugins/custom/CustomPlugin.ml" (** Generate custom configure/build/doc/test/install system @author *) open BaseEnv open OASISGettext open OASISTypes type t = { cmd_main: command_line conditional; cmd_clean: (command_line option) conditional; cmd_distclean: (command_line option) conditional; } let run = BaseCustom.run let main t _ extra_args = let cmd, args = var_choose ~name:(s_ "main command") t.cmd_main in run cmd args extra_args let clean t pkg extra_args = match var_choose t.cmd_clean with | Some (cmd, args) -> run cmd args extra_args | _ -> () let distclean t pkg extra_args = match var_choose t.cmd_distclean with | Some (cmd, args) -> run cmd args extra_args | _ -> () module Build = struct let main t pkg extra_args = main t pkg extra_args; List.iter (fun sct -> let evs = match sct with | Library (cs, bs, lib) when var_choose bs.bs_build -> begin let evs, _ = BaseBuilt.of_library OASISHostPath.of_unix (cs, bs, lib) in evs end | Executable (cs, bs, exec) when var_choose bs.bs_build -> begin let evs, _, _ = BaseBuilt.of_executable OASISHostPath.of_unix (cs, bs, exec) in evs end | _ -> [] in List.iter (fun (bt, bnm, lst) -> BaseBuilt.register bt bnm lst) evs) pkg.sections let clean t pkg extra_args = clean t pkg extra_args; (* TODO: this seems to be pretty generic (at least wrt to ocamlbuild * considering moving this to BaseSetup? *) List.iter (function | Library (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BLib cs.cs_name | Executable (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BExec cs.cs_name; BaseBuilt.unregister BaseBuilt.BExecLib cs.cs_name | _ -> ()) pkg.sections let distclean t pkg extra_args = distclean t pkg extra_args end module Test = struct let main t pkg (cs, test) extra_args = try main t pkg extra_args; 0.0 with Failure s -> BaseMessage.warning (f_ "Test '%s' fails: %s") cs.cs_name s; 1.0 let clean t pkg (cs, test) extra_args = clean t pkg extra_args let distclean t pkg (cs, test) extra_args = distclean t pkg extra_args end module Doc = struct let main t pkg (cs, _) extra_args = main t pkg extra_args; BaseBuilt.register BaseBuilt.BDoc cs.cs_name [] let clean t pkg (cs, _) extra_args = clean t pkg extra_args; BaseBuilt.unregister BaseBuilt.BDoc cs.cs_name let distclean t pkg (cs, _) extra_args = distclean t pkg extra_args end end # 5547 "setup.ml" open OASISTypes;; let setup_t = { BaseSetup.configure = InternalConfigurePlugin.configure; build = OCamlbuildPlugin.build; test = [ ("main", CustomPlugin.Test.main { CustomPlugin.cmd_main = [(OASISExpr.EBool true, ("$test", []))]; cmd_clean = [(OASISExpr.EBool true, None)]; cmd_distclean = [(OASISExpr.EBool true, None)]; }) ]; doc = [("api-ounit", OCamlbuildDocPlugin.doc_build "src/")]; install = InternalInstallPlugin.install; uninstall = InternalInstallPlugin.uninstall; clean = [OCamlbuildPlugin.clean]; clean_test = [ ("main", CustomPlugin.Test.clean { CustomPlugin.cmd_main = [(OASISExpr.EBool true, ("$test", []))]; cmd_clean = [(OASISExpr.EBool true, None)]; cmd_distclean = [(OASISExpr.EBool true, None)]; }) ]; clean_doc = [("api-ounit", OCamlbuildDocPlugin.doc_clean "src/")]; distclean = []; distclean_test = [ ("main", CustomPlugin.Test.distclean { CustomPlugin.cmd_main = [(OASISExpr.EBool true, ("$test", []))]; cmd_clean = [(OASISExpr.EBool true, None)]; cmd_distclean = [(OASISExpr.EBool true, None)]; }) ]; distclean_doc = []; package = { oasis_version = "0.2"; ocaml_version = None; findlib_version = None; name = "ounit"; version = "1.1.2"; license = OASISLicense.DEP5License (OASISLicense.DEP5Unit { OASISLicense.license = "MIT"; excption = None; version = OASISLicense.NoVersion; }); license_file = Some "LICENSE.txt"; copyrights = ["(C) 2002-2008 Maas-Maarten Zeeman"; "(C) 2010 OCamlCore SARL"]; maintainers = []; authors = ["Maas-Maarten Zeeman"; "Sylvain Le Gall"]; homepage = Some "http://ounit.forge.ocamlcore.org"; synopsis = "Unit testing framework"; description = Some "OUnit is a unit testing framework for OCaml, inspired by the JUnit tool for\nJava, and the HUnit tool for Haskell.\n\nMore information on [HUnit](http://hunit.sourceforge.net)"; categories = []; conf_type = (`Configure, "internal", Some "0.3"); conf_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; build_type = (`Build, "ocamlbuild", Some "0.3"); build_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; install_type = (`Install, "internal", Some "0.3"); install_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; uninstall_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; clean_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; distclean_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; files_ab = []; sections = [ Flag ({ cs_name = "backtrace"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { flag_description = Some "Enable backtrace display in exception"; flag_default = [(OASISExpr.EBool true, true)]; }); Library ({ cs_name = "oUnit"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { bs_build = [(OASISExpr.EBool true, true)]; bs_install = [(OASISExpr.EBool true, true)]; bs_path = "src"; bs_compiled_object = Best; bs_build_depends = [FindlibPackage ("unix", None)]; bs_build_tools = [ExternalTool "ocamlbuild"; ExternalTool "camlp4"]; bs_c_sources = []; bs_data_files = []; bs_ccopt = [(OASISExpr.EBool true, [])]; bs_cclib = [(OASISExpr.EBool true, [])]; bs_dlllib = [(OASISExpr.EBool true, [])]; bs_dllpath = [(OASISExpr.EBool true, [])]; bs_byteopt = [ (OASISExpr.EBool true, []); (OASISExpr.EFlag "backtrace", ["-ppopt"; "-DBACKTRACE"]) ]; bs_nativeopt = [ (OASISExpr.EBool true, []); (OASISExpr.EFlag "backtrace", ["-ppopt"; "-DBACKTRACE"]) ]; }, { lib_modules = ["OUnit"; "OUnitDiff"]; lib_pack = false; lib_internal_modules = []; lib_findlib_parent = None; lib_findlib_name = None; lib_findlib_containers = []; }); Executable ({ cs_name = "test"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { bs_build = [(OASISExpr.EBool true, true)]; bs_install = [(OASISExpr.EBool true, false)]; bs_path = "test"; bs_compiled_object = Byte; bs_build_depends = [InternalLibrary "oUnit"]; bs_build_tools = [ExternalTool "ocamlbuild"; ExternalTool "camlp4"]; bs_c_sources = []; bs_data_files = []; bs_ccopt = [(OASISExpr.EBool true, [])]; bs_cclib = [(OASISExpr.EBool true, [])]; bs_dlllib = [(OASISExpr.EBool true, [])]; bs_dllpath = [(OASISExpr.EBool true, [])]; bs_byteopt = [(OASISExpr.EBool true, [])]; bs_nativeopt = [(OASISExpr.EBool true, [])]; }, {exec_custom = false; exec_main_is = "test.ml"; }); Test ({ cs_name = "main"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { test_type = (`Test, "custom", Some "0.3"); test_command = [(OASISExpr.EBool true, ("$test", []))]; test_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; test_working_directory = None; test_run = [(OASISExpr.EBool true, true)]; test_tools = [ExternalTool "ocamlbuild"; ExternalTool "camlp4"]; }); Doc ({ cs_name = "api-ounit"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { doc_type = (`Doc, "ocamlbuild", Some "0.2"); doc_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; doc_build = [(OASISExpr.EBool true, true)]; doc_install = [(OASISExpr.EBool true, true)]; doc_install_dir = "$docdir"; doc_title = "API reference for OUnit"; doc_authors = []; doc_abstract = None; doc_format = OtherDoc; doc_data_files = []; doc_build_tools = [ ExternalTool "ocamlbuild"; ExternalTool "camlp4"; ExternalTool "ocamldoc" ]; }); SrcRepo ({ cs_name = "head"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { src_repo_type = Darcs; src_repo_location = "http://darcs.ocamlcore.org/repos/ounit"; src_repo_browser = Some "http://darcs.ocamlcore.org/cgi-bin/darcsweb.cgi?r=ounit;a=summary"; src_repo_module = None; src_repo_branch = None; src_repo_tag = None; src_repo_subdir = None; }) ]; plugins = [ (`Extra, "META", Some "0.2"); (`Extra, "StdFiles", Some "0.2"); (`Extra, "DevFiles", Some "0.2") ]; schema_data = PropList.Data.create (); plugin_data = []; }; oasis_fn = Some "_oasis"; oasis_version = "0.3.0~rc6"; oasis_digest = Some "\184<\231n\240\011uzpZ]\"~\207\162#"; oasis_exec = None; oasis_setup_args = []; setup_update = false; };; let setup () = BaseSetup.setup setup_t;; # 5818 "setup.ml" (* OASIS_STOP *) let () = setup ();; ounit-1.1.2/changelog0000644000175000017500000000341011765510533014051 0ustar gildorgildorounit-1.1.2 - regenerate with oasis v0.3.0~rc6 ounit-1.1.1 - bracket now enforce returning unit - update examples - ListSimpleMake now use the provided comparator for all elements ounit-1.1.0 - Add a ~pp_diff parameter to assert_equal and some classic diff operations (Closes: #635, #642) - Add an assert_command function (Closes: #641) - Add a bracket_tmpfile to ease temporary file use - Enhance documentation, translate the docbook manual into ocamldoc and add content - Allow to add extra command line arguments to run_test_tt_main (Closes: #640) - Add a -list-test options to run_test_tt_main, to list available tests - Skip tests when using "-only-test", rather than removing it. This way the path is the same even if some tests don't pass (Closes: #637) - Add backtrace support (Closes: #639), thanks to Michael Ekstrand - Use OASIS - Move to OCaml Forge: http://ounit.forge.ocamlcore.org - Maintainance is now done by Sylvain Le Gall (OCamlCore SARL), thanks to Maas-Maarten Zeeman for all his work ounit-1.0.3 - Add the possibility to skip test and mark tests as todo ounit-1.0.2 - Refactored OUnit package. The test result and test event data structures are now clearly separated. ounit-1.0.1 - Added optional compare function to assert_equal, and a float compare function. Thanks go to Daniel Buenzli ounit-1.0.0 - Add bracket support (Thanks go to Laurent Vaucher) - Add an example for bracket usage ounit-0.1.0 - Makefile improvements ounit-0.0.3 - Added findlib support ounit-0.0.2 - Added assert_raises which checkes if an exception is raised. (thanks go to Keita Yamaguchi, for the idea) - Fixed (hopefully) the .depend file ounit-0.0.1 - First release of ocaml-unit ounit-1.1.2/configure0000755000175000017500000000055411765510533014114 0ustar gildorgildor#!/bin/sh # OASIS_START # DO NOT EDIT (digest: 425187ed8bfdbdd207fd76392dd243a7) set -e FST=true for i in "$@"; do if $FST; then set -- FST=false fi case $i in --*=*) ARG=${i%%=*} VAL=${i##*=} set -- "$@" "$ARG" "$VAL" ;; *) set -- "$@" "$i" ;; esac done ocaml setup.ml -configure "$@" # OASIS_STOP ounit-1.1.2/test/0000755000175000017500000000000011765510533013160 5ustar gildorgildorounit-1.1.2/test/test.ml0000644000175000017500000002075311765510533014500 0ustar gildorgildor(***********************************************************************) (* The OUnit library *) (* *) (* Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2008 *) (* Maas-Maarten Zeeman. *) (* Copyright 2010 OCamlCore SARL *) (* All rights reserved. See LICENCE for details. *) (***********************************************************************) open OUnit let test_case = TestCase (fun () -> ()) let labeled_test_case = "label" >: test_case let suite_a = "suite_a" >: TestList [test_case] let suite_b = "suite_b" >: TestList [labeled_test_case] let suite_c = "suite_c" >: TestList [test_case; labeled_test_case] let suite_d = "suite_d" >: TestList [suite_a; suite_c] let rec string_of_paths = function [] -> "" | h::t -> (string_of_path h) ^ "\n" ^ (string_of_paths t) (* Test which checks if the test case count function works correctly *) let test_case_count _ = let assert_equal ?msg = assert_equal ?msg ~printer:string_of_int in assert_equal 0 (test_case_count (TestList [])); assert_equal 0 (test_case_count (TestLabel("label", TestList []))); assert_equal 0 (test_case_count (TestList [TestList []; TestList [TestList []]])); assert_equal 1 (test_case_count test_case); assert_equal 1 (test_case_count labeled_test_case); assert_equal 1 (test_case_count suite_a); assert_equal 1 (test_case_count suite_b); assert_equal 1 (test_case_count (TestList [suite_a; TestList []])); assert_equal 1 (test_case_count (TestList [TestList []; TestList [suite_b]])); assert_equal 2 (test_case_count suite_c); assert_equal 3 (test_case_count suite_d) (* Test which checks if the paths are correctly constructed *) let test_case_paths _ = (* A single testcase results in a list countaining an empty list *) let assert_equal ?msg = assert_equal ?msg ~printer:string_of_paths in assert_equal [[]] (test_case_paths test_case); assert_equal [[Label "label"]] (test_case_paths labeled_test_case); assert_equal [[ListItem 0; Label "suite_a"]] (test_case_paths suite_a); assert_equal [[Label "label"; ListItem 0; Label "suite_b"]] (test_case_paths suite_b); assert_equal [[ListItem 0; Label "suite_c"]; [Label "label"; ListItem 1; Label "suite_c"]] (test_case_paths suite_c); assert_equal [[ListItem 0; Label "suite_a"; ListItem 0; Label "suite_d"]; [ListItem 0; Label "suite_c"; ListItem 1; Label "suite_d"]; [Label "label"; ListItem 1; Label "suite_c"; ListItem 1; Label "suite_d"]] (test_case_paths suite_d) let test_assert_raises _ = assert_raises (Failure "OUnit: expected: Failure(\"Boo\") but got: Failure(\"Foo\")") (fun _ -> (assert_raises (Failure "Boo") (fun _ -> raise (Failure "Foo")))); assert_raises (Failure "OUnit: A label\nexpected: Failure(\"Boo\") but got: Failure(\"Foo\")") (fun _ -> (assert_raises ~msg:"A label" (Failure "Boo") (fun _ -> raise (Failure "Foo")))); assert_raises (Failure "OUnit: expected exception Failure(\"Boo\"), but no exception was raised.") (fun _ -> (assert_raises (Failure "Boo") (fun _ -> ()))); assert_raises (Failure "OUnit: A label\nexpected exception Failure(\"Boo\"), but no exception was raised.") (fun _ -> (assert_raises ~msg:"A label" (Failure "Boo") (fun _ -> ()))) (* Test the float compare, and use the cmp label *) let test_cmp_float _ = assert_equal ~cmp: cmp_float 0.0001 0.0001; assert_equal ~cmp: (cmp_float ~epsilon: 0.001) 1.0001 1.00001; assert_raises (Failure "OUnit: not equal") (fun _ -> assert_equal ~cmp: cmp_float 100.0001 101.001) let test_assert_string _ = assert_string ""; assert_raises (Failure "OUnit: A string") (fun _ -> assert_string "A string") let test_assert_bool _ = assert_bool "true" true; assert_raises (Failure "OUnit: false") (fun _ -> assert_bool "false" false) let test_case_filter () = let assert_test_case_count res tst_opt = match tst_opt with | Some tst -> assert_equal res (OUnit.test_case_count tst) | None -> assert_failure "Unexpected empty filter result" in assert_equal None (test_filter [] suite_a); assert_equal None (test_filter [] suite_b); assert_equal None (test_filter [] suite_c); assert_equal None (test_filter [] suite_d); assert_test_case_count 1 (test_filter ["suite_a"] suite_a); assert_test_case_count 1 (test_filter ["suite_a:0"] suite_a); assert_test_case_count 1 (test_filter ["suite_b:0:label"] suite_b); assert_test_case_count 1 (test_filter ["suite_c:0"] suite_c); assert_test_case_count 2 (test_filter ["suite_c:0";"suite_c:1:label"] suite_c) let assert_equal_test_result = assert_equal ~printer:(fun tst_results -> String.concat "; " (List.map (function | RSuccess path -> Printf.sprintf "RSuccess %S" (string_of_path path) | RFailure (path, str) -> Printf.sprintf "RFailure(%S, %S)" (string_of_path path) str | RError (path, str) -> Printf.sprintf "RError(%S, %S)" (string_of_path path) str | RSkip (path, str) -> Printf.sprintf "RSkip(%S, %S)" (string_of_path path) str | RTodo (path, str) -> Printf.sprintf "RTodo(%S, %S)" (string_of_path path) str ) tst_results )) let test_case_decorate () = assert_equal_test_result [RSuccess [Label "label"; ListItem 1; Label "suite_c"]; RSuccess [ListItem 0; Label "suite_c"]] (perform_test ignore suite_c); assert_equal_test_result [RFailure([Label "label"; ListItem 1; Label "suite_c"], "OUnit: fail"); RFailure([ListItem 0; Label "suite_c"], "OUnit: fail")] (perform_test ignore (test_decorate (fun _ -> (fun () -> assert_failure "fail")) suite_c)) let test_case_skip () = assert_equal_test_result [RSkip ([Label "skip"], "test")] (perform_test ignore ("skip" >:: (fun () -> skip_if true "test"))) let test_case_todo () = assert_equal_test_result [RTodo ([Label "todo"], "test")] (perform_test ignore ("todo" >:: (fun () -> todo "test"))) let test_assert_command () = assert_command Sys.executable_name ["-help"] module EInt = struct type t = int let compare = ( - ) let pp_printer = Format.pp_print_int let pp_print_sep = OUnitDiff.pp_comma_separator end module DiffSetInt = OUnitDiff.SetMake(EInt) module DiffListSimpleInt = OUnitDiff.ListSimpleMake(EInt) let test_diff () = let lst_exp = [1; 2; 3; 4; 5] in let lst_real = [1; 2; 5; 4] in assert_raises (Failure "OUnit: expected: 1, 2, 3, 4, 5 but got: 1, 2, 4, 5\ndifferences: -3") (fun () -> DiffSetInt.assert_equal (DiffSetInt.of_list lst_exp) (DiffSetInt.of_list lst_real)); DiffSetInt.assert_equal (DiffSetInt.of_list lst_exp) (DiffSetInt.of_list lst_exp); assert_raises (Failure "OUnit: expected: 1, 2, 3, 4, 5 but got: 1, 2, 5, 4\ \ndifferences: element number 2 differ (3 <> 5)") (fun () -> DiffListSimpleInt.assert_equal lst_exp lst_real); DiffListSimpleInt.assert_equal lst_exp lst_exp (* Construct the test suite *) let suite = "OUnit" >::: [ "test_case_count" >:: test_case_count; "test_case_paths" >:: test_case_paths; "test_assert_raises" >:: test_assert_raises; "test_assert_string" >:: test_assert_string; "test_assert_bool" >:: test_assert_bool; "test_cmp_float" >:: test_cmp_float; "test_case_filter" >:: test_case_filter; "test_case_decorate" >:: test_case_decorate; "test_case_skip" >:: test_case_skip; "test_case_todo" >:: test_case_todo; "test_assert_command" >:: test_assert_command; "test_diff" >:: test_diff; ] (* Run the tests in test suite *) let _ = run_test_tt_main suite ounit-1.1.2/doc/0000755000175000017500000000000011765510533012746 5ustar gildorgildorounit-1.1.2/doc/manual.txt0000644000175000017500000002066011765510533014770 0ustar gildorgildor{!indexlist} {2 What is unit Testing?} A test-oriented methodology for software development is most effective whent tests are easy to create, change, and execute. The JUnit tool pioneerded for test-first development in Java. OUnit is an adaptation of JUnit to OCaml. With OUnit, as with JUnit, you can easily create tests, name them, group them into suites, and execute them, with the framework checking the results automatically. {2 Getting Started} The basic principle of a test suite is to have a file {i test.ml} which will contain the tests, and an OCaml module under test, named {i foo.ml}. File {i foo.ml}: {[ (* The functions we wish to test *) let unity x = x;; let funix ()= 0;; let fgeneric () = failwith "Not implemented";; ]} The main point of a test is to check that the function under test has the expected behavior. You check the behavior using assert functions. The most simple one is {!OUnit.assert_equal}. This function compares the result of the function with an expected result. The most useful functions are: - {!OUnit.assert_equal} the basic assert function - {!OUnit.(>:::)} to define a list of tests - {!OUnit.(>::)} to name a test - {!OUnit.run_test_tt_main} to run the test suite you define - {!OUnit.bracket} that can help to set and clean environment, it is especially useful if you deal with temporary filename. File {i test.ml}: {[ open OUnit;; let test1 () = assert_equal "x" (Foo.unity "x");; let test2 () = assert_equal 100 (Foo.unity 100);; (* Name the test cases and group them together *) let suite = "suite">::: ["test1">:: test1; "test2">:: test2] ;; let _ = run_test_tt_main suite ;; ]} And compile the module {[ $ ocamlfind ocamlc -o test -package oUnit -linkpkg -g foo.ml test.ml ]} A executable named "test" will be created. When run it produces the following output. {[ $ ./tests .. Ran: 2 tests in: 0.00 Seconds OK ]} When using {!OUnit.run_test_tt_main}, a non zero exit code signals that the test suite was not successful. {2 Advanced usage} The topics, cover here, are only for advanced users who wish to unravel the power of OUnit. {!modules: OUnit OUnitDiff} {3 Error reporting} The error reporting part of OUnit is quite important. If you want to identify the failure, you should tune the display of the value and the test. Here is a list of thing you can display: - name of the test: OUnit use numbers to define path's test. But an error reporting about a failed test "0:1:2" is less explicit than "OUnit:0:comparator:1:float_comparator:2" - [~msg] parameter: it allows you to define say which assert has failed in your test. When you have more than one assert in a test, you should provide a [~msg] to be able to make the difference - [~printer] parameter: {!OUnit.assert_equal} allows you to define a printer for compared values. A message ["abcd" is not equal to "defg"] is better than [not equal] {[ open OUnit;; let _ = "mytest">:: (fun () -> assert_equal ~msg:"int value" ~printer:string_of_int 1 (Foo.unity 1)) ;; ]} {3 Command line arguments} {!OUnit.run_test_tt_main} already provides a set of command line argument to help user to run only the test he wants: - [-only-test]: skip all the tests except this one, you can use this flag several time to select more than one test to run - [-list-test]: list all the available tests and exit - [-verbose]: rather than displaying dots while running the test, be more verbose - [-help]: display help message and exit It is also possible to add your own command-line arguments. You should do it if you want to define some extra arguments. For example: {[ open OUnit;; let my_program_to_test = ref None ;; let test1 () = match !my_program_to_test with | Some prg -> assert_command prg [] | None -> skip_if true "My program is not defined" ;; let _ = run_test_tt_main ~arg_specs:["-my-program", Arg.String (fun fn -> my_program_to_test := Some fn), "fn Program to test"] ("test1" >:: test1) ;; ]} {3 Skip and todo tests} Tests are not always meaningful and can even fail because something is missing in the environment. In order to manage this, you can define a skip condition that will skip the test. If you start by defining your tests rather than implementing the functions under test, you know that some tests will just fail. You can mark these tests as to do tests, this way they will be reported differently in your test suite. {[ open OUnit;; let _ = "allfuns" >::: [ "funix">:: (fun () -> skip_if (Sys.os_type = "Win32") "Don't work on Windows"; assert_equal 0 (Foo.funix ())); "fgeneric">:: (fun () -> todo "fgeneric not implemented"; assert_equal 0 (Foo.fgeneric ())); ] ;; ]} {3 Effective OUnit} This section is about general tips about unit testing and OUnit. It is the result of some years using OUnit in real world applications. - test everything: the more you create tests, the better chance you have to catch early an error in your program. Every submitted bugs to your application should have a matching tests. This is a good practice, but it is not always easy to implement. - test only what is really exported: on the long term, you have to maintain your test suite. If you test low-level functions, you'll have a lot of tests to rewrite. You should focus on creating tests for functions for which the behavior shouldn't change. - test fast: the best test suite is the one that runs after every single build. You should set your default Makefile target to run the test suite. It means that your test suite should be fast to run, typically, a 10s test suite is fine. - test long: contrary to the former tip, you should also have a complete test suite which can be very long to run. The best way to achieve both tips, is to define a command line arguments [-long] and skip the tests that are too long in your test suite according to it. When you do a release, you should use run your long test suite. - family tests: when testing behavior, most of the time you call exactly the same code with different arguments. In this case [List.map] and {!OUnit.(>:::)} are your friends. For example: {[ open OUnit;; let _ = "Family">::: (List.map (fun (arg,res) -> let title = Printf.sprintf "%s->%s" arg res in title >:: (fun () -> assert_equal res (Foo.unity arg))) ["abcd", "abcd"; "defg", "defg"; "wxyz", "wxyz"]) ;; ]} - test failures and successes: the most obvious thing you want to test are successes, i.e. that you get the expected behavior in the normal case. But most of the errors arise in corner cases and in the code of the test itself. For example, you can have a partial application of your {!OUnit.assert_equal} and never encounter any errors, just because the [assert_equal] is not called. In this case, if you test errors as well, you will have a missing errors as well. - set up and clean your environment in the test: you should not set up and clean your test environment outside the test. Ideally, if you run no tests, the program should do nothing. This is also a sane way to be sure that you are always testing in a clean environment, not polluted by the result of failed tests run before. {[ open OUnit;; let _ = (* We need to call a function in a particular directory *) "change-dir-and-run">:: bracket (fun () -> let pwd = Sys.getcwd () in Sys.chdir "test"; pwd) (fun _ -> assert_command "ls" []) (fun pwd -> Sys.chdir pwd) ;; ]} - separate your test: OUnit test code should live outside the code under tests. This allow to drop the dependency on OUnit when distributing your library/application. This also enables people to easily make a difference from what really matters (the main code) and what are only tests. It is possible to have it directly in the code, like in Quickcheck style tests. The unit testing scope is always hard to define. Unit testing should be about testing a single features. But OUnit can help you to test higher level behavior, by running a full program for example. While it isn't real unit testing, you can use OUnit to do it and should not hesitate to do it. In term of line of codes, a test suite can represent from 10% to 150% of the code under test. With time, your test suite will grow faster than your program/library. A good ratio is 33%. @author Maas-Maarten Zeeman @author Sylvain Le Gall ounit-1.1.2/src/0000755000175000017500000000000011765510533012770 5ustar gildorgildorounit-1.1.2/src/api-ounit.odocl0000644000175000017500000000014411765510533015716 0ustar gildorgildor# OASIS_START # DO NOT EDIT (digest: badb307dc88ab237e46550b25a383039) OUnit OUnitDiff # OASIS_STOP ounit-1.1.2/src/oUnit.ml0000644000175000017500000004712711765510533014433 0ustar gildorgildor(***********************************************************************) (* The OUnit library *) (* *) (* Copyright (C) 2002-2008 Maas-Maarten Zeeman. *) (* Copyright (C) 2010 OCamlCore SARL *) (* *) (* See LICENSE for details. *) (***********************************************************************) open Format (* TODO: really use Format in printf call. Most of the time, not * cuts/spaces/boxes are used *) let global_verbose = ref false let buff_printf f = let buff = Buffer.create 13 in let fmt = formatter_of_buffer buff in f fmt; pp_print_flush fmt (); Buffer.contents buff let bracket set_up f tear_down () = let fixture = set_up () in let () = try let () = f fixture in tear_down fixture with e -> let () = tear_down fixture in raise e in () let bracket_tmpfile ?(prefix="ounit-") ?(suffix=".txt") ?mode f = bracket (fun () -> Filename.open_temp_file ?mode prefix suffix) f (fun (fn, chn) -> begin try close_out chn with _ -> () end; begin try Sys.remove fn with _ -> () end) exception Skip of string let skip_if b msg = if b then raise (Skip msg) exception Todo of string let todo msg = raise (Todo msg) let assert_failure msg = failwith ("OUnit: " ^ msg) let assert_bool msg b = if not b then assert_failure msg let assert_string str = if not (str = "") then assert_failure str let assert_equal ?(cmp = ( = )) ?printer ?pp_diff ?msg expected actual = let get_error_string () = (* let max_len = pp_get_margin fmt () in *) (* let ellipsis_text = "[...]" in *) let print_ellipsis p fmt s = (* TODO: find a way to do this let res = p s in let len = String.length res in if diff <> None && len > max_len then begin let len_with_ellipsis = (max_len - (String.length ellipsis_text)) / 2 in (* TODO: we should use %a here to print values *) fprintf fmt "@[%s[...]%s@]" (String.sub res 0 len_with_ellipsis) (String.sub res (len - len_with_ellipsis) len_with_ellipsis) end else begin (* TODO: we should use %a here to print values *) fprintf fmt "@[%s@]" res end *) pp_print_string fmt (p s) in let res = buff_printf (fun fmt -> pp_open_vbox fmt 0; begin match msg with | Some s -> pp_open_box fmt 0; pp_print_string fmt s; pp_close_box fmt (); pp_print_cut fmt () | None -> () end; begin match printer with | Some p -> let p_ellipsis = print_ellipsis p in fprintf fmt "@[expected: @[%a@]@ but got: @[%a@]@]@," p_ellipsis expected p_ellipsis actual | None -> fprintf fmt "@[not equal@]@," end; begin match pp_diff with | Some d -> fprintf fmt "@[differences: %a@]@," d (expected, actual) | None -> () end; pp_close_box fmt ()) in let len = String.length res in if len > 0 && res.[len - 1] = '\n' then String.sub res 0 (len - 1) else res in if not (cmp expected actual) then assert_failure (get_error_string ()) let assert_command ?(exit_code=Unix.WEXITED 0) ?(sinput=Stream.of_list []) ?(foutput=ignore) ?(use_stderr=true) ?env ?verbose prg args = let verbose = match verbose with | Some v -> v | None -> !global_verbose in bracket_tmpfile (fun (fn_out, chn_out) -> let cmd_print fmt = let () = match env with | Some e -> begin pp_print_string fmt "env"; Array.iter (fprintf fmt "@ %s") e; pp_print_space fmt () end | None -> () in pp_print_string fmt prg; List.iter (fprintf fmt "@ %s") args in (* Start the process *) let in_write = Unix.dup (Unix.descr_of_out_channel chn_out) in let (out_read, out_write) = Unix.pipe () in let err = if use_stderr then in_write else Unix.stderr in let args = Array.of_list (prg :: args) in let pid = Unix.set_close_on_exec out_write; if verbose then printf "@[Starting command '%t'@]\n" cmd_print; match env with | Some e -> Unix.create_process_env prg args e out_read in_write err | None -> Unix.create_process prg args out_read in_write err in let () = Unix.close out_read; Unix.close in_write in let () = (* Dump sinput into the process stdin *) let buff = " " in Stream.iter (fun c -> let _i : int = buff.[0] <- c; Unix.write out_write buff 0 1 in ()) sinput; Unix.close out_write in let _, real_exit_code = let rec wait_intr () = try Unix.waitpid [] pid with Unix.Unix_error (Unix.EINTR, _, _) -> wait_intr () in wait_intr () in let exit_code_printer = function | Unix.WEXITED n -> Printf.sprintf "exit code %d" n | Unix.WSTOPPED n -> Printf.sprintf "stopped by signal %d" n | Unix.WSIGNALED n -> Printf.sprintf "killed by signal %d" n in (* Dump process output to stderr *) if verbose then begin let chn = open_in fn_out in let buff = String.make 4096 'X' in let len = ref (-1) in while !len <> 0 do len := input chn buff 0 (String.length buff); printf "%s" (String.sub buff 0 !len); done; printf "@?"; close_in chn end; (* Check process status *) assert_equal ~msg:(buff_printf (fun fmt -> fprintf fmt "@[Exit status of command '%t'@]" cmd_print)) ~printer:exit_code_printer exit_code real_exit_code; begin let chn = open_in fn_out in try foutput (Stream.of_channel chn) with e -> close_in chn; raise e end) () let raises f = try f (); None with e -> Some e let assert_raises ?msg exn (f: unit -> 'a) = let pexn = Printexc.to_string in let get_error_string () = let str = Format.sprintf "expected exception %s, but no exception was raised." (pexn exn) in match msg with | None -> assert_failure str | Some s -> assert_failure (Format.sprintf "%s\n%s" s str) in match raises f with | None -> assert_failure (get_error_string ()) | Some e -> assert_equal ?msg ~printer:pexn exn e (* Compare floats up to a given relative error *) let cmp_float ?(epsilon = 0.00001) a b = abs_float (a -. b) <= epsilon *. (abs_float a) || abs_float (a -. b) <= epsilon *. (abs_float b) (* Now some handy shorthands *) let (@?) = assert_bool (* The type of test function *) type test_fun = unit -> unit (* The type of tests *) type test = | TestCase of test_fun | TestList of test list | TestLabel of string * test (* Some shorthands which allows easy test construction *) let (>:) s t = TestLabel(s, t) (* infix *) let (>::) s f = TestLabel(s, TestCase(f)) (* infix *) let (>:::) s l = TestLabel(s, TestList(l)) (* infix *) (* Utility function to manipulate test *) let rec test_decorate g = function | TestCase f -> TestCase (g f) | TestList tst_lst -> TestList (List.map (test_decorate g) tst_lst) | TestLabel (str, tst) -> TestLabel (str, test_decorate g tst) (* Return the number of available tests *) let rec test_case_count = function | TestCase _ -> 1 | TestLabel (_, t) -> test_case_count t | TestList l -> List.fold_left (fun c t -> c + test_case_count t) 0 l type node = | ListItem of int | Label of string type path = node list let string_of_node = function | ListItem n -> string_of_int n | Label s -> s let string_of_path path = String.concat ":" (List.rev_map string_of_node path) (* Some helper function, they are generally applicable *) (* Applies function f in turn to each element in list. Function f takes one element, and integer indicating its location in the list *) let mapi f l = let rec rmapi cnt l = match l with | [] -> [] | h :: t -> (f h cnt) :: (rmapi (cnt + 1) t) in rmapi 0 l let fold_lefti f accu l = let rec rfold_lefti cnt accup l = match l with | [] -> accup | h::t -> rfold_lefti (cnt + 1) (f accup h cnt) t in rfold_lefti 0 accu l (* Returns all possible paths in the test. The order is from test case to root *) let test_case_paths test = let rec tcps path test = match test with | TestCase _ -> [path] | TestList tests -> List.concat (mapi (fun t i -> tcps ((ListItem i)::path) t) tests) | TestLabel (l, t) -> tcps ((Label l)::path) t in tcps [] test (* Test filtering with their path *) module SetTestPath = Set.Make(String) let test_filter ?(skip=false) only test = let set_test = List.fold_left (fun st str -> SetTestPath.add str st) SetTestPath.empty only in let rec filter_test path tst = if SetTestPath.mem (string_of_path path) set_test then begin Some tst end else begin match tst with | TestCase f -> begin if skip then Some (TestCase (fun () -> skip_if true "Test disabled"; f ())) else None end | TestList tst_lst -> begin let ntst_lst = fold_lefti (fun ntst_lst tst i -> let nntst_lst = match filter_test ((ListItem i) :: path) tst with | Some tst -> tst :: ntst_lst | None -> ntst_lst in nntst_lst) [] tst_lst in if not skip && ntst_lst = [] then None else Some (TestList (List.rev ntst_lst)) end | TestLabel (lbl, tst) -> begin let ntst_opt = filter_test ((Label lbl) :: path) tst in match ntst_opt with | Some ntst -> Some (TestLabel (lbl, ntst)) | None -> if skip then Some (TestLabel (lbl, tst)) else None end end in filter_test [] test (* The possible test results *) type test_result = | RSuccess of path | RFailure of path * string | RError of path * string | RSkip of path * string | RTodo of path * string let is_success = function | RSuccess _ -> true | RFailure _ | RError _ | RSkip _ | RTodo _ -> false let is_failure = function | RFailure _ -> true | RSuccess _ | RError _ | RSkip _ | RTodo _ -> false let is_error = function | RError _ -> true | RSuccess _ | RFailure _ | RSkip _ | RTodo _ -> false let is_skip = function | RSkip _ -> true | RSuccess _ | RFailure _ | RError _ | RTodo _ -> false let is_todo = function | RTodo _ -> true | RSuccess _ | RFailure _ | RError _ | RSkip _ -> false let result_flavour = function | RError _ -> "Error" | RFailure _ -> "Failure" | RSuccess _ -> "Success" | RSkip _ -> "Skip" | RTodo _ -> "Todo" let result_path = function | RSuccess path | RError (path, _) | RFailure (path, _) | RSkip (path, _) | RTodo (path, _) -> path let result_msg = function | RSuccess _ -> "Success" | RError (_, msg) | RFailure (_, msg) | RSkip (_, msg) | RTodo (_, msg) -> msg (* Returns true if the result list contains successes only *) let rec was_successful = function | [] -> true | RSuccess _::t | RSkip _::t -> was_successful t | RFailure _::_ | RError _::_ | RTodo _::_ -> false (* Events which can happen during testing *) type test_event = | EStart of path | EEnd of path | EResult of test_result DEFINE MAYBE_BACKTRACE = IFDEF BACKTRACE THEN (if Printexc.backtrace_status () then "\n" ^ Printexc.get_backtrace () else "") ELSE "" ENDIF (* Run all tests, report starts, errors, failures, and return the results *) let perform_test report test = let run_test_case f path = try f (); RSuccess path with | Failure s -> RFailure (path, s ^ MAYBE_BACKTRACE) | Skip s -> RSkip (path, s) | Todo s -> RTodo (path, s) | s -> RError (path, (Printexc.to_string s) ^ MAYBE_BACKTRACE) in let rec run_test path results = function | TestCase(f) -> begin let result = report (EStart path); run_test_case f path in report (EResult result); report (EEnd path); result::results end | TestList (tests) -> begin fold_lefti (fun results t cnt -> run_test ((ListItem cnt)::path) results t) results tests end | TestLabel (label, t) -> begin run_test ((Label label)::path) results t end in run_test [] [] test (* Function which runs the given function and returns the running time of the function, and the original result in a tuple *) let time_fun f x y = let begin_time = Unix.gettimeofday () in (Unix.gettimeofday () -. begin_time, f x y) (* A simple (currently too simple) text based test runner *) let run_test_tt ?verbose test = let verbose = match verbose with | Some v -> v | None -> !global_verbose in let printf = Format.printf in let separator1 = String.make (get_margin ()) '=' in let separator2 = String.make (get_margin ()) '-' in let string_of_result = function | RSuccess _ -> if verbose then "ok\n" else "." | RFailure (_, _) -> if verbose then "FAIL\n" else "F" | RError (_, _) -> if verbose then "ERROR\n" else "E" | RSkip (_, _) -> if verbose then "SKIP\n" else "S" | RTodo (_, _) -> if verbose then "TODO\n" else "T" in let report_event = function | EStart p -> if verbose then printf "%s ...\n" (string_of_path p) | EEnd _ -> () | EResult result -> printf "%s@?" (string_of_result result) in let print_result_list results = List.iter (fun result -> printf "%s\n%s: %s\n\n%s\n%s\n" separator1 (result_flavour result) (string_of_path (result_path result)) (result_msg result) separator2) results in (* Now start the test *) let running_time, results = time_fun perform_test report_event test in let errors = List.filter is_error results in let failures = List.filter is_failure results in let skips = List.filter is_skip results in let todos = List.filter is_todo results in if not verbose then printf "\n"; (* Print test report *) print_result_list errors; print_result_list failures; printf "Ran: %d tests in: %.2f seconds.\n" (List.length results) running_time; (* Print final verdict *) if was_successful results then ( if skips = [] then printf "OK" else printf "OK: Cases: %d Skip: %d\n" (test_case_count test) (List.length skips) ) else printf "FAILED: Cases: %d Tried: %d Errors: %d \ Failures: %d Skip:%d Todo:%d\n" (test_case_count test) (List.length results) (List.length errors) (List.length failures) (List.length skips) (List.length todos); (* Return the results possibly for further processing *) results (* Call this one from you test suites *) let run_test_tt_main ?(arg_specs=[]) ?(set_verbose=ignore) suite = let only_test = ref [] in let () = Arg.parse (Arg.align [ "-verbose", Arg.Set global_verbose, " Run the test in verbose mode."; "-only-test", Arg.String (fun str -> only_test := str :: !only_test), "path Run only the selected test"; "-list-test", Arg.Unit (fun () -> List.iter (fun pth -> print_endline (string_of_path pth)) (test_case_paths suite); exit 0), " List tests"; ] @ arg_specs ) (fun x -> raise (Arg.Bad ("Bad argument : " ^ x))) ("usage: " ^ Sys.argv.(0) ^ " [-verbose] [-only-test path]*") in let nsuite = if !only_test = [] then suite else begin match test_filter ~skip:true !only_test suite with | Some test -> test | None -> failwith ("Filtering test "^ (String.concat ", " !only_test)^ " lead to no test") end in let result = set_verbose !global_verbose; run_test_tt ~verbose:!global_verbose nsuite in if not (was_successful result) then exit 1 else result ounit-1.1.2/src/oUnit.mli0000644000175000017500000001746111765510533014602 0ustar gildorgildor(***********************************************************************) (* The OUnit library *) (* *) (* Copyright (C) 2002-2008 Maas-Maarten Zeeman. *) (* Copyright (C) 2010 OCamlCore SARL *) (* *) (* See LICENSE for details. *) (***********************************************************************) (** Unit test building blocks @author Maas-Maarten Zeeman @author Sylvain Le Gall *) (** {2 Assertions} Assertions are the basic building blocks of unittests. *) (** Signals a failure. This will raise an exception with the specified string. @raise Failure signal a failure *) val assert_failure : string -> 'a (** Signals a failure when bool is false. The string identifies the failure. @raise Failure signal a failure *) val assert_bool : string -> bool -> unit (** Shorthand for assert_bool @raise Failure to signal a failure *) val ( @? ) : string -> bool -> unit (** Signals a failure when the string is non-empty. The string identifies the failure. @raise Failure signal a failure *) val assert_string : string -> unit (** [assert_command prg args] Run the command provided. @param exit_code expected exit code @param sinput provide this [char Stream.t] as input of the process @param foutput run this function on output, it can contains an [assert_equal] to check it @param use_stderr redirect [stderr] to [stdout] @param env Unix environment @param verbose if a failure arise, dump stdout/stderr of the process to stderr @since 1.1.0 *) val assert_command : ?exit_code:Unix.process_status -> ?sinput:char Stream.t -> ?foutput:(char Stream.t -> unit) -> ?use_stderr:bool -> ?env:string array -> ?verbose:bool -> string -> string list -> unit (** [assert_equal expected real] Compares two values, when they are not equal a failure is signaled. @param cmp customize function to compare, default is [=] @param printer value printer, don't print value otherwise @param pp_diff if not equal, ask a custom display of the difference using [diff fmt exp real] where [fmt] is the formatter to use @param msg custom message to identify the failure @raise Failure signal a failure @version 1.1.0 *) val assert_equal : ?cmp:('a -> 'a -> bool) -> ?printer:('a -> string) -> ?pp_diff:(Format.formatter -> ('a * 'a) -> unit) -> ?msg:string -> 'a -> 'a -> unit (** Asserts if the expected exception was raised. @param msg identify the failure @raise Failure description *) val assert_raises : ?msg:string -> exn -> (unit -> 'a) -> unit (** {2 Skipping tests } In certain condition test can be written but there is no point running it, because they are not significant (missing OS features for example). In this case this is not a failure nor a success. Following functions allow you to escape test, just as assertion but without the same error status. A test skipped is counted as success. A test todo is counted as failure. *) (** [skip cond msg] If [cond] is true, skip the test for the reason explain in [msg]. For example [skip_if (Sys.os_type = "Win32") "Test a doesn't run on windows"]. @since 1.0.3 *) val skip_if : bool -> string -> unit (** The associated test is still to be done, for the reason given. @since 1.0.3 *) val todo : string -> unit (** {2 Compare Functions} *) (** Compare floats up to a given relative error. @param epsilon if the difference is smaller [epsilon] values are equal *) val cmp_float : ?epsilon:float -> float -> float -> bool (** {2 Bracket} A bracket is a functional implementation of the commonly used setUp and tearDown feature in unittests. It can be used like this: ["MyTestCase" >:: (bracket test_set_up test_fun test_tear_down)] *) (** [bracket set_up test tear_down] The [set_up] function runs first, then the [test] function runs and at the end [tear_down] runs. The [tear_down] function runs even if the [test] failed and help to clean the environment. *) val bracket: (unit -> 'a) -> ('a -> unit) -> ('a -> unit) -> unit -> unit (** [bracket_tmpfile test] The [test] function takes a temporary filename and matching output channel as arguments. The temporary file is created before the test and removed after the test. @param prefix see [Filename.open_temp_file] @param suffix see [Filename.open_temp_file] @param mode see [Filename.open_temp_file] @since 1.1.0 *) val bracket_tmpfile: ?prefix:string -> ?suffix:string -> ?mode:open_flag list -> ((string * out_channel) -> unit) -> unit -> unit (** {2 Constructing Tests} *) (** The type of test function *) type test_fun = unit -> unit (** The type of tests *) type test = TestCase of test_fun | TestList of test list | TestLabel of string * test (** Create a TestLabel for a test *) val (>:) : string -> test -> test (** Create a TestLabel for a TestCase *) val (>::) : string -> test_fun -> test (** Create a TestLabel for a TestList *) val (>:::) : string -> test list -> test (** Some shorthands which allows easy test construction. Examples: - ["test1" >: TestCase((fun _ -> ()))] => [TestLabel("test2", TestCase((fun _ -> ())))] - ["test2" >:: (fun _ -> ())] => [TestLabel("test2", TestCase((fun _ -> ())))] - ["test-suite" >::: ["test2" >:: (fun _ -> ());]] => [TestLabel("test-suite", TestSuite([TestLabel("test2", TestCase((fun _ -> ())))]))] *) (** [test_decorate g tst] Apply [g] to test function contains in [tst] tree. @since 1.0.3 *) val test_decorate : (test_fun -> test_fun) -> test -> test (** [test_filter paths tst] Filter test based on their path string representation. @param skip] if set, just use [skip_if] for the matching tests. @since 1.0.3 *) val test_filter : ?skip:bool -> string list -> test -> test option (** {2 Retrieve Information from Tests} *) (** Returns the number of available test cases *) val test_case_count : test -> int (** Types which represent the path of a test *) type node = ListItem of int | Label of string type path = node list (** The path to the test (in reverse order). *) (** Make a string from a node *) val string_of_node : node -> string (** Make a string from a path. The path will be reversed before it is tranlated into a string *) val string_of_path : path -> string (** Returns a list with paths of the test *) val test_case_paths : test -> path list (** {2 Performing Tests} *) (** The possible results of a test *) type test_result = RSuccess of path | RFailure of path * string | RError of path * string | RSkip of path * string | RTodo of path * string (** Events which occur during a test run *) type test_event = EStart of path | EEnd of path | EResult of test_result (** Perform the test, allows you to build your own test runner *) val perform_test : (test_event -> 'a) -> test -> test_result list (** A simple text based test runner. It prints out information during the test. @param verbose print verbose message *) val run_test_tt : ?verbose:bool -> test -> test_result list (** Main version of the text based test runner. It reads the supplied command line arguments to set the verbose level and limit the number of test to run. @param arg_specs add extra command line arguments @param set_verbose call a function to set verbosity @version 1.1.0 *) val run_test_tt_main : ?arg_specs:(Arg.key * Arg.spec * Arg.doc) list -> ?set_verbose:(bool -> unit) -> test -> test_result list ounit-1.1.2/src/META0000644000175000017500000000047611765510533013450 0ustar gildorgildor# OASIS_START # DO NOT EDIT (digest: 61707d1b080e36d947156b3beaac22fe) version = "1.1.2" description = "Unit testing framework" requires = "unix" archive(byte) = "oUnit.cma" archive(byte, plugin) = "oUnit.cma" archive(native) = "oUnit.cmxa" archive(native, plugin) = "oUnit.cmxs" exists_if = "oUnit.cma" # OASIS_STOP ounit-1.1.2/src/oUnit.mllib0000644000175000017500000000014411765510533015106 0ustar gildorgildor# OASIS_START # DO NOT EDIT (digest: badb307dc88ab237e46550b25a383039) OUnit OUnitDiff # OASIS_STOP ounit-1.1.2/src/oUnitDiff.mli0000644000175000017500000000567111765510533015373 0ustar gildorgildor(***********************************************************************) (* The OUnit library *) (* *) (* Copyright (C) 2010 OCamlCore SARL *) (* *) (* See LICENSE for details. *) (***********************************************************************) (** Unit tests for collection of elements This module allows to define a more precise way to display differences between collection of elements. When collection differ, the tester is interested by what are the missing/extra elements. This module provides a [diff] operation to spot the difference quickly between two sets of elements. Example: {[ open OUnit;; module EInt = struct type t = int let compare = ( - ) let pp_print = Format.pp_print_int let pp_print_sep = OUnitDiff.comma_separator end module ListInt = OUnitDiff.ListSimpleMake(EInt);; let test_diff () = ListInt.assert_equal [1; 2; 3; 4; 5] [1; 2; 5; 4] ;; let _ = run_test_tt_main ("test_diff" >:: test_diff) ;; ]} when run this test outputs: {[ OUnit: expected: 1, 2, 3, 4, 5 but got: 1, 2, 5, 4 differences: element number 2 differ (3 <> 5) ]} @since 1.1.0 @author Sylvain Le Gall *) (** {2 Signatures} *) (** Definition of an element *) module type DIFF_ELEMENT = sig (** Type of an element *) type t (** Pretty printer for an element *) val pp_printer : Format.formatter -> t -> unit (** Element comparison *) val compare : t -> t -> int (** Pretty print element separator *) val pp_print_sep : Format.formatter -> unit -> unit end (** Definition of standard operations *) module type S = sig (** Type of an element *) type e (** Type of a collection of element *) type t (** Compare a collection of element *) val compare : t -> t -> int (** Pretty printer a collection of element *) val pp_printer : Format.formatter -> t -> unit (** Pretty printer for collection differences *) val pp_diff : Format.formatter -> t * t -> unit (** {!assert_equal} with [~diff], [~cmp] and [~printer] predefined for this collection events *) val assert_equal : ?msg:string -> t -> t -> unit (** Create [t] using of list *) val of_list : e list -> t end (** {2 Implementations} *) (** Collection of elements based on a Set, elements order doesn't matter *) module SetMake : functor (D : DIFF_ELEMENT) -> S with type e = D.t (** Collection of elements based on a List, order matters but difference display is very simple. It stops at the first element which differs. *) module ListSimpleMake : functor (D: DIFF_ELEMENT) -> S with type e = D.t and type t = D.t list val pp_comma_separator : Format.formatter -> unit -> unit ounit-1.1.2/src/oUnitDiff.ml0000644000175000017500000001020411765510533015206 0ustar gildorgildor(***********************************************************************) (* The OUnit library *) (* *) (* Copyright (C) 2010 OCamlCore SARL *) (* *) (* See LICENSE for details. *) (***********************************************************************) open Format module type DIFF_ELEMENT = sig type t val pp_printer: Format.formatter -> t -> unit val compare: t -> t -> int val pp_print_sep: Format.formatter -> unit -> unit end module type S = sig type e type t val compare: t -> t -> int val pp_printer: Format.formatter -> t -> unit val pp_diff: Format.formatter -> (t * t) -> unit val assert_equal: ?msg:string -> t -> t -> unit val of_list: e list -> t end let assert_equal ?msg compare pp_printer pp_diff exp act = OUnit.assert_equal ~cmp:(fun t1 t2 -> (compare t1 t2) = 0) ~printer:(fun t -> let buff = Buffer.create 13 in let fmt = formatter_of_buffer buff in pp_printer fmt t; pp_print_flush fmt (); Buffer.contents buff) ~pp_diff ?msg exp act module SetMake (D: DIFF_ELEMENT) : S with type e = D.t = struct module Set = Set.Make(D) type e = D.t type t = Set.t let compare = Set.compare let pp_printer fmt t = let first = ref true in pp_open_box fmt 0; Set.iter (fun e -> if not !first then D.pp_print_sep fmt (); D.pp_printer fmt e; first := false) t; pp_close_box fmt () let pp_diff fmt (t1, t2) = let first = ref true in let print_list c t = Set.iter (fun e -> if not !first then D.pp_print_sep fmt (); pp_print_char fmt c; D.pp_printer fmt e; first := false) t in pp_open_box fmt 0; print_list '+' (Set.diff t2 t1); print_list '-' (Set.diff t1 t2); pp_close_box fmt () let assert_equal ?msg exp act = assert_equal ?msg compare pp_printer pp_diff exp act let of_list lst = List.fold_left (fun acc e -> Set.add e acc) Set.empty lst end module ListSimpleMake (D: DIFF_ELEMENT) : S with type e = D.t and type t = D.t list = struct type e = D.t type t = e list let rec compare t1 t2 = match t1, t2 with | e1 :: tl1, e2 :: tl2 -> begin match D.compare e1 e2 with | 0 -> compare tl1 tl2 | n -> n end | [], [] -> 0 | _, [] -> -1 | [], _ -> 1 let pp_print_gen pre fmt t = let first = ref true in pp_open_box fmt 0; List.iter (fun e -> if not !first then D.pp_print_sep fmt (); fprintf fmt "%s%a" pre D.pp_printer e; first := false) t; pp_close_box fmt () let pp_printer fmt t = pp_print_gen "" fmt t let pp_diff fmt (t1, t2) = let rec pp_diff' n t1 t2 = match t1, t2 with | e1 :: tl1, e2 :: tl2 -> begin match D.compare e1 e2 with | 0 -> pp_diff' (n + 1) tl1 tl2 | _ -> fprintf fmt "element number %d differ (%a <> %a)" n D.pp_printer e1 D.pp_printer e2 end | [], [] -> () | [], lst -> fprintf fmt "at end,@ "; pp_print_gen "+" fmt lst | lst, [] -> fprintf fmt "at end,@ "; pp_print_gen "-" fmt lst in pp_open_box fmt 0; pp_diff' 0 t1 t2; pp_close_box fmt () let assert_equal ?msg exp act = assert_equal ?msg compare pp_printer pp_diff exp act let of_list lst = lst end let pp_comma_separator fmt () = fprintf fmt ",@ " ounit-1.1.2/_tags0000644000175000017500000000205111765510533013217 0ustar gildorgildor# OASIS_START # DO NOT EDIT (digest: 952340aed2c8f8e3f857f8ab2e3228e7) # Ignore VCS directories, you can use the same kind of rule outside # OASIS_START/STOP if you want to exclude directories that contains # useless stuff for the build process <**/.svn>: -traverse <**/.svn>: not_hygienic ".bzr": -traverse ".bzr": not_hygienic ".hg": -traverse ".hg": not_hygienic ".git": -traverse ".git": not_hygienic "_darcs": -traverse "_darcs": not_hygienic # Library oUnit "src/oUnit.cmxs": use_oUnit : oasis_library_ounit_byte : oasis_library_ounit_byte : oasis_library_ounit_native : oasis_library_ounit_native : pkg_unix # Executable test "test/test.byte": use_oUnit "test/test.byte": pkg_unix : use_oUnit : pkg_unix # OASIS_STOP "src/oUnit.ml": syntax_camlp4o, pkg_camlp4.macro "src/oUnit.odoc": oasis_document_api_ounit "src/oUnit.ml": oasis_document_api_ounit "src/api-ounit.docdir": oasis_document_api_ounit "build": -traverse "build": not_hygienic ounit-1.1.2/AUTHORS.txt0000644000175000017500000000022511765510533014066 0ustar gildorgildor(* OASIS_START *) (* DO NOT EDIT (digest: 2915822545ee2a6c6708508e9418550d) *) Authors of ounit Maas-Maarten Zeeman Sylvain Le Gall (* OASIS_STOP *) ounit-1.1.2/.boring0000644000175000017500000000403611765510533013465 0ustar gildorgildor# Boring file regexps: ### compiler and interpreter intermediate files # haskell (ghc) interfaces \.hi$ \.hi-boot$ \.o-boot$ # object files \.o$ \.o\.cmd$ # profiling haskell \.p_hi$ \.p_o$ # haskell program coverage resp. profiling info \.tix$ \.prof$ # fortran module files \.mod$ # linux kernel \.ko\.cmd$ \.mod\.c$ (^|/)\.tmp_versions($|/) # *.ko files aren't boring by default because they might # be Korean translations rather than kernel modules # \.ko$ # python, emacs, java byte code \.py[co]$ \.elc$ \.class$ # objects and libraries; lo and la are libtool things \.(obj|a|exe|so|lo|la)$ # compiled zsh configuration files \.zwc$ # Common LISP output files for CLISP and CMUCL \.(fas|fasl|sparcf|x86f)$ ### build and packaging systems # cabal intermediates \.installed-pkg-config \.setup-config # standard cabal build dir, might not be boring for everybody # ^dist(/|$) # autotools (^|/)autom4te\.cache($|/) (^|/)config\.(log|status)$ # microsoft web expression, visual studio metadata directories \_vti_cnf$ \_vti_pvt$ # gentoo tools \.revdep-rebuild.* # generated dependencies ^\.depend$ ### version control systems # cvs (^|/)CVS($|/) \.cvsignore$ # cvs, emacs locks ^\.# # rcs (^|/)RCS($|/) ,v$ # subversion (^|/)\.svn($|/) # mercurial (^|/)\.hg($|/) # git (^|/)\.git($|/) # bzr \.bzr$ # sccs (^|/)SCCS($|/) # darcs (^|/)_darcs($|/) (^|/)\.darcsrepo($|/) ^\.darcs-temp-mail$ -darcs-backup[[:digit:]]+$ # gnu arch (^|/)(\+|,) (^|/)vssver\.scc$ \.swp$ (^|/)MT($|/) (^|/)\{arch\}($|/) (^|/).arch-ids($|/) # bitkeeper (^|/)BitKeeper($|/) (^|/)ChangeSet($|/) ### miscellaneous # backup files ~$ \.bak$ \.BAK$ # patch originals and rejects \.orig$ \.rej$ # X server \..serverauth.* # image spam \# (^|/)Thumbs\.db$ # vi, emacs tags (^|/)(tags|TAGS)$ #(^|/)\.[^/] # core dumps (^|/|\.)core$ # partial broken files (KIO copy operations) \.part$ # waf files, see http://code.google.com/p/waf/ (^|/)\.waf-[[:digit:].]+-[[:digit:]]+($|/) (^|/)\.lock-wscript$ # mac os finder (^|/)\.DS_Store$ ^setup.log$ ^setup.data$ ^_build$ ^ounit-.*\.tar\.gz$ ^ounit-.*\.tar\.gz\.asc$ ounit-1.1.2/ci-main.lua0000644000175000017500000000071311765510533014222 0ustar gildorgildor bootstrap = require("bootstrap") bootstrap.init() oasis = require("oasis") darcs = require("darcs") ci = require("ci") godi = require("godi") ci.init() godi.init() oasis.init() darcs.init() godi.bootstrap("3.12") godi.update() godi.upgrade() godi.build("godi-findlib") ci.exec("ocaml", "setup.ml", "-configure", "--enable-backtrace") ci.exec("ocaml", "setup.ml", "-build") ci.exec("ocaml", "setup.ml", "-test") darcs.create_tag(oasis.package_version()) ounit-1.1.2/bootstrap.lua0000644000175000017500000000203111765510533014715 0ustar gildorgildor local os = os local error = error local lfs = require("lfs") local package = package module("bootstrap") function init () local ci_url = os.getenv("CI_URL") if not ci_url then ci_url = "http://mini:8080/job/continuous-integration/label=debian-squeeze64/lastSuccessfulBuild/artifact/dist/ci.zip" end local bootstrapdir = "build/bootstrap" if lfs.attributes(bootstrapdir) then for fn in lfs.dir(bootstrapdir) do if fn ~= "." and fn ~= ".." then local realfn = bootstrapdir .. "/" .. fn if not os.remove(realfn) then error("Cannot remove " .. realfn) end end end lfs.rmdir("build/bootstrap") end lfs.mkdir("build") lfs.mkdir("build/bootstrap") local topdir = lfs.currentdir() lfs.chdir("build/bootstrap") if os.execute("curl -o ci.zip " .. ci_url) ~= 0 then error "Cannot download ci.zip" end if os.execute("unzip ci.zip") ~= 0 then error "Cannot unzip ci.zip" end lfs.chdir(topdir) package.path = "./build/bootstrap/?.lua;" .. package.path end ounit-1.1.2/LICENSE.txt0000644000175000017500000000221111765510533014020 0ustar gildorgildorCopyright (c) 2002, 2003 by Maas-Maarten Zeeman Copyright (c) 2010 by OCamlCore SARL The package OUnit is copyright by Maas-Maarten Zeeman and OCamlCore SARL. Permission is hereby granted, free of charge, to any person obtaining a copy of this document and the OUnit software ("the Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software is provided ``as is'', without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall Maas-Maarten Zeeman be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the software. ounit-1.1.2/INSTALL.txt0000644000175000017500000000155211765510533014053 0ustar gildorgildor(* OASIS_START *) (* DO NOT EDIT (digest: 7dd488eb577090ee24e1a336e5a18a9a) *) This is the INSTALL file for the ounit distribution. This package uses OASIS to generate its build system. See section OASIS for full information. Dependencies ============ In order to compile this package, you will need: * ocaml for all, test main, doc api-ounit * findlib Installing ========== 1. Uncompress the source archive and go to the root of the package 2. Run 'ocaml setup.ml -configure' 3. Run 'ocaml setup.ml -build' 4. Run 'ocaml setup.ml -install' Uninstalling ============ 1. Go to the root of the package 2. Run 'ocaml setup.ml -uninstall' OASIS ===== OASIS is a program that generates a setup.ml file using a simple '_oasis' configuration file. The generated setup only depends on the standard OCaml installation: no additional library is required. (* OASIS_STOP *)