]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/library/librarian.ml
62a8a892c3887f5b965266e49077846456ffa227
[helm.git] / helm / software / components / library / librarian.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 let debug = ref false
27
28 let time_stamp =
29    let old = ref 0.0 in
30    fun msg -> 
31       if !debug then begin
32          let times = Unix.times () in
33          let stamp = times.Unix.tms_utime +. times.Unix.tms_stime in
34          let lap = stamp -. !old in
35          Printf.eprintf "TIME STAMP (%s): %f\n" msg lap; flush stderr;
36          old := stamp
37       end
38
39 exception NoRootFor of string
40
41 let absolutize path =
42  let path = 
43    if String.length path > 0 && path.[0] <> '/' then
44      Sys.getcwd () ^ "/" ^ path
45    else 
46      path
47  in
48    HExtlib.normalize_path path
49 ;;
50
51
52 let find_root path =
53   let path = absolutize path in
54   let paths = List.rev (Str.split (Str.regexp "/") path) in
55   let rec build = function
56     | he::tl as l -> ("/" ^ String.concat "/" (List.rev l) ^ "/") :: build tl
57     | [] -> ["/"]
58   in
59   let paths = List.map HExtlib.normalize_path (build paths) in
60   try HExtlib.find_in paths "root"
61   with Failure "find_in" -> 
62     raise (NoRootFor (path ^ " (" ^ String.concat ", " paths ^ ")"))
63 ;;
64   
65 let ensure_trailing_slash s = 
66   if s = "" then "/" else
67   if s.[String.length s-1] <> '/' then s^"/" else s
68 ;;
69
70 let remove_trailing_slash s = 
71   if s = "" then "" else
72   let len = String.length s in
73   if s.[len-1] = '/' then String.sub s 0 (len-1) else s
74 ;;
75
76 let load_root_file rootpath =
77   let data = HExtlib.input_file rootpath in
78   let lines = Str.split (Str.regexp "\n") data in
79   let clean s = 
80     Pcre.replace ~pat:"[ \t]+" ~templ:" "
81       (Pcre.replace ~pat:"^ *" (Pcre.replace ~pat:" *$" s))
82   in
83   List.map 
84     (fun l -> 
85       match Str.split (Str.regexp "=") l with
86       | [k;v] -> clean k, Http_getter_misc.strip_trailing_slash (clean v)
87       | _ -> raise (Failure ("Malformed root file: " ^ rootpath)))
88     lines
89 ;;
90
91 let rec find_root_for ~include_paths file = 
92  let include_paths = "" :: Sys.getcwd () :: include_paths in
93  try 
94    let path = HExtlib.find_in include_paths file in
95    let path = absolutize path in
96 (*     HLog.debug ("file "^file^" resolved as "^path);  *)
97    let rootpath, root, buri = 
98      try
99        let mburi = Helm_registry.get "matita.baseuri" in
100        match Str.split (Str.regexp " ") mburi with
101        | [root; buri] when HExtlib.is_prefix_of root path -> 
102            ":registry:", root, buri
103        | _ -> raise (Helm_registry.Key_not_found "matita.baseuri")
104      with Helm_registry.Key_not_found "matita.baseuri" -> 
105        let rootpath = find_root path in
106        let buri = List.assoc "baseuri" (load_root_file rootpath) in
107        rootpath, Filename.dirname rootpath, buri
108    in
109 (*     HLog.debug ("file "^file^" rooted by "^rootpath^"");  *)
110    let uri = Http_getter_misc.strip_trailing_slash buri in
111    if String.length uri < 5 || String.sub uri 0 5 <> "cic:/" then
112      HLog.error (rootpath ^ " sets an incorrect baseuri: " ^ buri);
113    ensure_trailing_slash root, remove_trailing_slash uri, path
114  with Failure "find_in" -> 
115    if Filename.check_suffix file ".ma" then begin
116       let mma = Filename.chop_suffix file ".ma" ^ ".mma" in
117       HLog.warn ("We look for: " ^ mma);
118       find_root_for ~include_paths mma
119    end else begin
120       HLog.error ("We are in: " ^ Sys.getcwd ());
121       HLog.error ("Unable to find: "^file^"\nPaths explored:");
122       List.iter (fun x -> HLog.error (" - "^x)) include_paths;
123       raise (NoRootFor file)
124    end
125 ;;
126
127 let mk_baseuri root extra =
128   let chop name = 
129     assert(Filename.check_suffix name ".ma" ||
130       Filename.check_suffix name ".mma");
131     try Filename.chop_extension name
132     with Invalid_argument "Filename.chop_extension" -> name
133   in
134    remove_trailing_slash (HExtlib.normalize_path (root ^ "/" ^ chop extra))
135 ;;
136
137 let baseuri_of_script ~include_paths file = 
138   let root, buri, path = find_root_for ~include_paths file in
139   let path = HExtlib.normalize_path path in
140   let root = HExtlib.normalize_path root in
141   let lpath = Str.split (Str.regexp "/") path in
142   let lroot = Str.split (Str.regexp "/") root in
143   let rec substract l1 l2 =
144     match l1, l2 with
145     | h1::tl1,h2::tl2 when h1 = h2 -> substract tl1 tl2
146     | l,[] -> l
147     | _ -> raise (NoRootFor (file ^" "^path^" "^root))
148   in
149   let extra_buri = substract lpath lroot in
150   let extra = String.concat "/" extra_buri in
151    root,
152    mk_baseuri buri extra,
153    path,
154    extra
155 ;;
156
157 let find_roots_in_dir dir =
158   HExtlib.find ~test:(fun f ->
159     Filename.basename f = "root" &&
160     try (Unix.stat f).Unix.st_kind = Unix.S_REG 
161     with Unix.Unix_error _ -> false)
162     dir
163 ;;
164
165 (* make *)
166 let load_deps_file f = 
167   let deps = ref [] in
168   let ic = open_in f in
169   try
170     while true do
171       begin
172         let l = input_line ic in
173         match Str.split (Str.regexp " ") l with
174         | [] -> 
175             HLog.error ("Malformed deps file: " ^ f); 
176             raise (Failure ("Malformed deps file: " ^ f)) 
177         | he::tl -> deps := (he,tl) :: !deps
178       end
179     done; !deps
180     with End_of_file -> !deps
181 ;;
182
183 type options = (string * string) list
184
185 module type Format =
186   sig
187     type source_object
188     type target_object
189     val load_deps_file: string -> (source_object * source_object list) list
190     val string_of_source_object: source_object -> string
191     val string_of_target_object: target_object -> string
192     val build: options -> source_object -> bool
193     val root_and_target_of: 
194           options -> source_object -> 
195            (* root, writeable target, read only target *)
196            string option * target_object * target_object
197     val mtime_of_source_object: source_object -> float option
198     val mtime_of_target_object: target_object -> float option
199     val is_readonly_buri_of: options -> source_object -> bool
200   end
201
202 module Make = functor (F:Format) -> struct
203
204   type status = Done of bool
205               | Ready of bool
206
207   let say s = if !debug then prerr_endline ("make: "^s);; 
208
209   let unopt_or_call x f y = match x with Some _ -> x | None -> f y;;
210
211   let fst4 = function (x,_,_,_) -> x;;
212
213   let modified_before_s_t (_,cs, ct, _, _) a b = 
214 (*   
215     time_stamp ("L s_t: a " ^ F.string_of_source_object a);
216     time_stamp ("L s_t: b " ^ F.string_of_target_object b);
217 *)    
218     let a = try Hashtbl.find cs a with Not_found -> assert false in
219     let b = 
220       try
221         match Hashtbl.find ct b with
222         | Some _ as x -> x
223         | None ->
224            match F.mtime_of_target_object b with
225            | Some t as x -> 
226                Hashtbl.remove ct b;
227                Hashtbl.add ct b x; x
228            | x -> x
229       with Not_found -> assert false
230     in
231     let r = match a, b with 
232        | Some a, Some b -> a <= b
233        | _ -> false
234     in
235 (*
236     time_stamp ("L s_t: " ^ string_of_bool r);
237 *)
238     r
239
240   let modified_before_t_t (_,_,ct, _, _) a b =
241 (*
242     time_stamp ("L t_t: a " ^ F.string_of_target_object a);
243     time_stamp ("L t_t: b " ^ F.string_of_target_object b);
244 *)    
245     let a = 
246       try
247         match Hashtbl.find ct a with
248         | Some _ as x -> x
249         | None ->
250            match F.mtime_of_target_object a with
251            | Some t as x -> 
252                Hashtbl.remove ct a;
253                Hashtbl.add ct a x; x
254            | x -> x
255       with Not_found -> assert false
256     in
257     let b = 
258       try
259         match Hashtbl.find ct b with
260         | Some _ as x -> x
261         | None ->
262            match F.mtime_of_target_object b with
263            | Some t as x -> 
264                Hashtbl.remove ct b;
265                Hashtbl.add ct b x; x
266            | x -> x
267       with Not_found -> assert false
268     in
269     let r = match a, b with
270        | Some a, Some b ->
271 (*
272        time_stamp ("tt: a " ^ string_of_float a);
273        time_stamp ("tt: b " ^ string_of_float b);
274 *)
275           a <= b
276        | _ -> false
277     in
278 (*
279     time_stamp ("L t_t: " ^ string_of_bool r);
280 *)
281     r
282
283   let rec purge_unwanted_roots wanted deps =
284     let roots, rest = 
285        List.partition 
286          (fun (t,d,_,_) ->
287            not (List.exists (fun (_,d1,_,_) -> List.mem t d1) deps))
288          deps
289     in
290     let newroots = List.filter (fun (t,_,_,_) -> List.mem t wanted) roots in
291     if newroots = roots then
292       deps
293     else
294       purge_unwanted_roots wanted (newroots @ rest)
295   ;;
296
297   let is_not_ro (opts,_,_,_,_) (f,_,r,_) =
298     match r with
299     | Some root -> not (F.is_readonly_buri_of opts f)
300     | None -> assert false
301   ;;
302 (* FG: Old sorting algorithm ************************************************)
303 (*
304   let rec get_status opts what =
305      let _, _, _, cc, cd = opts in
306      let t, dependencies, root, tgt = what in
307      try Done (Hashtbl.find cc t)
308 (* say "already built" *)
309      with Not_found ->
310         let map st d = match st with
311            | Done false  -> st
312            | Ready false -> st
313            | _           ->
314               let whatd = Hashtbl.find cd d in
315               let _, _, _, tgtd = whatd in
316               begin match st, get_status opts whatd with
317                  | _, Done false         -> Hashtbl.add cc t false; Done false
318                  | Done true, Done true  -> 
319                     if modified_before_t_t opts tgt tgtd then Ready true else Done true  
320 (* say (F.string_of_source_object t^" depends on "^F.string_of_target_object unsat^" and "^F.string_of_source_object t^".o is younger than "^ F.string_of_target_object unsat^", thus needs to be built") *)
321                  | Done true, Ready _    -> Ready false
322                  | Ready true, Ready _   -> Ready false
323 (* say (F.string_of_source_object t^" depends on "^ F.string_of_source_object (fst4 unsat)^ " that is not built, thus is not ready") *)
324                  | Ready true, Done true -> Ready true
325                  | _                     -> st
326               end
327         in
328         let st = if modified_before_s_t opts t tgt then Done true else Ready true in
329         match List.fold_left map st dependencies with
330            | Done true -> Hashtbl.add cc t true; Done true
331 (* say(F.string_of_source_object t^" is built" *)
332            | st     -> st
333
334   let list_partition_filter_rev filter l =
335      let rec aux l1 l2 = function
336         | []       -> l1, l2
337         | hd :: tl ->
338            begin match filter hd with
339               | None       -> aux l1 l2 tl
340               | Some true  -> aux (hd :: l1) l2 tl
341               | Some false -> aux l1 (hd :: l2) tl
342            end
343      in
344      aux [] [] l
345
346   let rec make_aux root (lo,_,ct, cc, _ as opts) ok deps = 
347     time_stamp "filter get_status: begin";
348     let map what = match get_status opts what with
349        | Done _  -> None
350        | Ready b -> Some b
351     in
352     let todo, deps = list_partition_filter_rev map deps in
353     time_stamp "filter get_status: end";
354     let todo =
355       let local, remote =
356         List.partition (fun (_,_,froot,_) -> froot = Some root) todo
357       in
358       let local, skipped = List.partition (is_not_ro opts) local in
359       List.iter 
360        (fun x -> 
361         HLog.warn("Read only baseuri for: "^F.string_of_source_object(fst4 x)))
362        skipped;
363       remote @ local
364     in
365     if todo <> [] then begin
366        let ok = List.fold_left  
367           (fun ok (file,_,froot,tgt) ->
368             let rc = 
369               match froot with
370               | Some froot when froot = root -> 
371                   Hashtbl.remove ct tgt;
372                   Hashtbl.add ct tgt None;
373                   time_stamp "building";
374                   let r = F.build lo file in
375                   time_stamp "done"; r
376               | Some froot -> make froot [file]
377               | None -> 
378                   HLog.error ("No root for: "^F.string_of_source_object file);
379                   false
380             in
381             Hashtbl.add cc file rc;
382             ok && rc 
383           )
384           ok (List.rev todo)
385        in
386       make_aux root opts ok (List.rev deps)
387     end
388     else
389       ok
390 *)
391 (* FG: new sorting algorithm ************************************************)
392
393   let rec make_aux root opts ok deps =
394     List.fold_left (make_one root opts) ok deps
395      
396   and make_one root opts ok what =
397     let lo, _, ct, cc, cd = opts in
398     let t, deps, froot, tgt = what in
399     let str = F.string_of_source_object t in
400     let map (okd, okt) d =
401        let (_, _, _, tgtd) as whatd = (Hashtbl.find cd d) in
402        let r = make_one root opts okd whatd in 
403        r, okt && modified_before_t_t opts tgtd tgt
404     in
405     time_stamp ("L : processing " ^ str);
406     try 
407        let r = Hashtbl.find cc t in
408        time_stamp ("L : " ^ string_of_bool r ^ " " ^ str);
409        ok && r
410 (* say "already built" *)
411     with Not_found ->
412        let okd, okt = List.fold_left map (true, modified_before_s_t opts t tgt) deps in       
413        let res = 
414           if okd then 
415           if okt then true else
416           match froot with
417              | Some froot when froot = root -> 
418                 if is_not_ro opts what then begin 
419                    Hashtbl.remove ct tgt;
420                    Hashtbl.add ct tgt None;
421                    time_stamp ("L : BUILDING " ^ str);
422                    let res = F.build lo t in
423                    time_stamp ("L : DONE     " ^ str); res
424                 end else begin
425                    HLog.error ("Read only baseuri for: "^ str^
426                      ", I won't compile it even if it is out of date"); 
427                    false
428                 end
429              | Some froot -> make froot [t]
430              | None -> 
431                 HLog.error ("No root for: " ^ str); false
432           else false
433        in
434        time_stamp ("L : " ^ string_of_bool res ^ " " ^ str);
435        Hashtbl.add cc t res; ok && res
436
437 (****************************************************************************)
438
439   and make root targets = 
440     time_stamp "L : ENTERING";
441     HLog.debug ("Entering directory '"^root^"'");
442     let old_root = Sys.getcwd () in
443     Sys.chdir root;
444     let deps = F.load_deps_file (root^"/depends") in
445     let local_options = load_root_file (root^"/root") in
446     let caches,cachet,cachec,cached = 
447        Hashtbl.create 73, Hashtbl.create 73, Hashtbl.create 73, Hashtbl.create 73
448     in
449     (* deps are enriched with these informations to sped up things later *)
450     let deps = 
451       List.map 
452         (fun (file,d) -> 
453           let r,wtgt,rotgt = F.root_and_target_of local_options file in
454           Hashtbl.add caches file (F.mtime_of_source_object file);
455           (* if a read only target exists, we use that one, otherwise
456              we use the writeable one that may be compiled *)
457           let _,_,_, tgt as tuple = 
458             match F.mtime_of_target_object rotgt with
459             | Some _ as mtime ->
460                Hashtbl.add cachet rotgt mtime; 
461                (file, d, r, rotgt)
462             | None -> 
463                Hashtbl.add cachet wtgt (F.mtime_of_target_object wtgt); 
464                (file, d, r, wtgt)
465           in
466           Hashtbl.add cached file tuple;
467           tuple
468         )
469         deps
470     in
471     let opts = local_options, caches, cachet, cachec, cached in
472     let ok =
473       if targets = [] then 
474         make_aux root opts true deps
475       else
476         make_aux root opts true 
477           (purge_unwanted_roots targets deps)
478     in
479     HLog.debug ("Leaving directory '"^root^"'");
480     Sys.chdir old_root;
481     time_stamp "L : LEAVING";
482     ok
483   ;;
484
485 end
486   
487 let write_deps_file where deps = match where with 
488    | Some root ->
489       let oc = open_out (root ^ "/depends") in
490       let map (t, d) = output_string oc (t^" "^String.concat " " d^"\n") in
491       List.iter map deps; close_out oc;
492       HLog.message ("Generated: " ^ root ^ "/depends")
493    | None -> 
494       print_endline (String.concat " " (List.flatten (List.map snd deps)))
495       
496 (* FG ***********************************************************************)
497
498 (* scheme uri part as defined in URI Generic Syntax (RFC 3986) *)
499 let uri_scheme_rex = Pcre.regexp "^[[:alpha:]][[:alnum:]\-+.]*:"
500
501 let is_uri str =
502    Pcre.pmatch ~rex:uri_scheme_rex str