]> matita.cs.unibo.it Git - helm.git/blob - components/library/librarian.ml
f2268488f2afbc3ce975578c072a172af1ec72ac
[helm.git] / components / library / librarian.ml
1 exception NoRootFor of string
2
3 let absolutize path =
4  let path = 
5    if String.length path > 0 && path.[0] <> '/' then
6      Sys.getcwd () ^ "/" ^ path
7    else 
8      path
9  in
10    HExtlib.normalize_path path
11 ;;
12
13
14 let find_root path =
15   let path = absolutize path in
16   let paths = List.rev (Str.split (Str.regexp "/") path) in
17   let rec build = function
18     | he::tl as l -> ("/" ^ String.concat "/" (List.rev l) ^ "/") :: build tl
19     | [] -> ["/"]
20   in
21   let paths = List.map HExtlib.normalize_path (build paths) in
22   try HExtlib.find_in paths "root"
23   with Failure "find_in" -> 
24     raise (NoRootFor (path ^ " (" ^ String.concat ", " paths ^ ")"))
25 ;;
26   
27 let ensure_trailing_slash s = 
28   if s = "" then "/" else
29   if s.[String.length s-1] <> '/' then s^"/" else s
30 ;;
31
32 let remove_trailing_slash s = 
33   if s = "" then "" else
34   let len = String.length s in
35   if s.[len-1] = '/' then String.sub s 0 (len-1) else s
36 ;;
37
38 let load_root_file rootpath =
39   let data = HExtlib.input_file rootpath in
40   let lines = Str.split (Str.regexp "\n") data in
41   let clean s = Pcre.replace ~pat:"^ *" (Pcre.replace ~pat:" *$" s) in
42   List.map 
43     (fun l -> 
44       match Str.split (Str.regexp "=") l with
45       | [k;v] -> clean k, Http_getter_misc.strip_trailing_slash (clean v)
46       | _ -> raise (Failure ("Malformed root file: " ^ rootpath)))
47     lines
48 ;;
49
50 let find_root_for ~include_paths file = 
51  let include_paths = "" :: Sys.getcwd () :: include_paths in
52  try 
53    let path = HExtlib.find_in include_paths file in
54    let path = absolutize path in
55    (* HLog.debug ("file "^file^" resolved as "^path); *)
56    let rootpath, root, buri = 
57      try
58        let mburi = Helm_registry.get "matita.baseuri" in
59        match Str.split (Str.regexp " ") mburi with
60        | [root; buri] when HExtlib.is_prefix_of root path -> 
61            ":registry:", root, buri
62        | _ -> raise (Helm_registry.Key_not_found "matita.baseuri")
63      with Helm_registry.Key_not_found "matita.baseuri" -> 
64        let rootpath = find_root path in
65        let buri = List.assoc "baseuri" (load_root_file rootpath) in
66        rootpath, Filename.dirname rootpath, buri
67    in
68    (* HLog.debug ("file "^file^" rooted by "^rootpath^""); *)
69    let uri = Http_getter_misc.strip_trailing_slash buri in
70    if String.length uri < 5 || String.sub uri 0 5 <> "cic:/" then
71      HLog.error (rootpath ^ " sets an incorrect baseuri: " ^ buri);
72    ensure_trailing_slash root, remove_trailing_slash uri, path
73  with Failure "find_in" -> 
74    HLog.error ("Unable to find: "^file^"\nPaths explored:");
75    List.iter (fun x -> HLog.error (" - "^x)) include_paths;
76    raise (NoRootFor file)
77 ;;
78
79 let baseuri_of_script ~include_paths file = 
80   let root, buri, path = find_root_for ~include_paths file in
81   let path = HExtlib.normalize_path path in
82   let root = HExtlib.normalize_path root in
83   let lpath = Str.split (Str.regexp "/") path in
84   let lroot = Str.split (Str.regexp "/") root in
85   let rec substract l1 l2 =
86     match l1, l2 with
87     | h1::tl1,h2::tl2 when h1 = h2 -> substract tl1 tl2
88     | l,[] -> l
89     | _ -> raise (NoRootFor (file ^" "^path^" "^root))
90   in
91   let extra_buri = substract lpath lroot in
92   let chop name = 
93     assert(Filename.check_suffix name ".ma");
94     try Filename.chop_extension name
95     with Invalid_argument "Filename.chop_extension" -> name
96   in
97   let extra = String.concat "/" extra_buri in
98    root,
99    remove_trailing_slash (HExtlib.normalize_path 
100     (buri ^ "/" ^ chop extra)),
101    path,
102    extra
103 ;;
104
105 let find_roots_in_dir dir =
106   HExtlib.find ~test:(fun f ->
107     Filename.basename f = "root" &&
108     try (Unix.stat f).Unix.st_kind = Unix.S_REG 
109     with Unix.Unix_error _ -> false)
110     dir
111 ;;
112
113 (* make *)
114 let load_deps_file f = 
115   let deps = ref [] in
116   let ic = open_in f in
117   try
118     while true do
119       begin
120         let l = input_line ic in
121         match Str.split (Str.regexp " ") l with
122         | [] -> 
123             HLog.error ("Malformed deps file: " ^ f); 
124             raise (Failure ("Malformed deps file: " ^ f)) 
125         | he::tl -> deps := (he,tl) :: !deps
126       end
127     done; !deps
128     with End_of_file -> !deps
129 ;;
130
131 type options = (string * string) list
132
133 module type Format =
134   sig
135     type source_object
136     type target_object
137     val load_deps_file: string -> (source_object * source_object list) list
138     val target_of: options -> source_object -> target_object
139     val string_of_source_object: source_object -> string
140     val string_of_target_object: target_object -> string
141     val build: options -> source_object -> bool
142     val root_of: options -> source_object -> string option
143     val mtime_of_source_object: source_object -> float option
144     val mtime_of_target_object: target_object -> float option
145   end
146
147 module Make = functor (F:Format) -> struct
148
149   let prerr_endline _ = ();; 
150
151   let younger_s_t a b = 
152     match F.mtime_of_source_object a, F.mtime_of_target_object b with
153     | Some a, Some b -> a < b
154     | _ -> false (* XXX check if correct *)
155   ;;
156   let younger_t_t a b = 
157     match F.mtime_of_target_object a, F.mtime_of_target_object b with
158     | Some a, Some b -> a < b
159     | _ -> false (* XXX check if correct *)
160   ;;
161
162   let is_built opts t = younger_s_t t (F.target_of opts t);;
163
164   let rec needs_build opts deps compiled (t,dependencies) =
165     prerr_endline ("Checking if "^F.string_of_source_object t^" needs to be built");
166     if List.mem t compiled then
167       (prerr_endline "already compiled";
168       false)
169     else
170     if not (is_built opts t) then
171       (prerr_endline (F.string_of_source_object t^
172        " is not built, thus needs to be built");
173       true)
174     else
175     try
176       let unsat =
177         List.find
178           (needs_build opts deps compiled) 
179           (List.map (fun x -> x, List.assoc x deps) dependencies)
180       in
181         prerr_endline 
182          (F.string_of_source_object t^" depends on "^F.string_of_source_object (fst unsat)^
183          " that needs to be built, thus needs to be built");
184         true
185     with Not_found ->
186       try 
187         let unsat = 
188           List.find (younger_t_t (F.target_of opts t)) 
189            (List.map (F.target_of opts) dependencies)
190         in
191           prerr_endline 
192            (F.string_of_source_object t^" depends on "^F.string_of_target_object
193            unsat^" and "^F.string_of_source_object t^".o is younger than "^
194            F.string_of_target_object unsat^", thus needs to be built");
195           true
196       with Not_found -> false
197   ;;
198
199   let is_buildable opts compiled deps (t,dependencies) =
200     prerr_endline ("Checking if "^F.string_of_source_object t^" is buildable");
201     let b = needs_build opts deps compiled (t,dependencies) in
202     if not b then
203       (prerr_endline (F.string_of_source_object t^
204        " does not need to be built, thus it not buildable");
205       false)
206     else
207     try  
208       let unsat =
209         List.find (needs_build opts deps compiled) 
210           (List.map (fun x -> x, List.assoc x deps) dependencies)
211       in
212         prerr_endline 
213           (F.string_of_source_object t^" depends on "^
214           F.string_of_source_object (fst unsat)^
215           " that needs build, thus is not buildable");
216         false
217     with Not_found -> 
218       prerr_endline 
219         ("None of "^F.string_of_source_object t^
220         " dependencies needs to be built, thus it is buildable");
221       true
222   ;;
223
224   let rec purge_unwanted_roots wanted deps =
225     let roots, rest = 
226        List.partition 
227          (fun (t,d) ->
228            not (List.exists (fun (_,d1) -> List.mem t d1) deps))
229          deps
230     in
231     let newroots = List.filter (fun (t,_) -> List.mem t wanted) roots in
232     if newroots = roots then
233       deps
234     else
235       purge_unwanted_roots wanted (newroots @ rest)
236   ;;
237
238
239   let rec make_aux root local_options compiled failed deps = 
240     let todo = List.filter (is_buildable local_options compiled deps) deps in
241     let todo = List.filter (fun (f,_) -> not (List.mem f failed)) todo in
242     if todo <> [] then
243       let compiled, failed = 
244         let todo =
245           let local, remote =
246             List.partition
247               (fun (file,d) -> 
248                 d<>[] || F.root_of local_options file = Some root)
249               todo
250           in
251           remote @ local
252         in
253         List.fold_left 
254           (fun (c,f) (file,_) ->
255             let froot = F.root_of local_options file in
256             let rc = 
257               match froot with
258               | Some froot when froot = root ->
259                   F.build local_options file 
260               | Some froot ->
261                   make froot [file]
262               | None -> 
263                   HLog.error ("No root for: "^F.string_of_source_object file);
264                   false
265             in
266             if rc then (file::c,f)
267             else (c,file::f))
268           (compiled,failed) todo
269       in
270         make_aux root local_options compiled failed deps
271     else
272       compiled, failed
273
274   and  make root targets = 
275     let deps = F.load_deps_file (root^"/depends") in
276     let local_options = load_root_file (root^"/root") in
277     HLog.debug ("Entering directory '"^root^"'");
278     let old_root = Sys.getcwd () in
279     Sys.chdir root;
280     let _compiled, failed =
281       if targets = [] then 
282         make_aux root local_options [] [] deps
283       else
284         make_aux root local_options [] [] (purge_unwanted_roots targets deps)
285     in
286     HLog.debug ("Leaving directory '"^root^"'");
287     Sys.chdir old_root;
288     failed = []
289   ;;
290
291 end
292   
293 let write_deps_file root deps =
294   let oc = open_out (root ^ "/depends") in
295   List.iter 
296     (fun (t,d) -> output_string oc (t^" "^String.concat " " d^"\n")) 
297     deps;
298   close_out oc;
299   HLog.message ("Generated: " ^ root ^ "/depends")
300 ;;
301