]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/library/librarian.ml
Preparing for 0.5.9 release.
[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 0
27
28 let time_stamp =
29    let old = ref 0.0 in
30    fun msg -> 
31       if !debug > 0 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 find_root_for ~include_paths file = 
92   let include_paths = "" :: Sys.getcwd () :: include_paths in
93    let rec find_path_for file =
94       try HExtlib.find_in include_paths file
95       with Failure "find_in" -> 
96          if Filename.check_suffix file ".ma" then begin
97             let mma = Filename.chop_suffix file ".ma" ^ ".mma" in
98             HLog.warn ("We look for: " ^ mma);
99             let path = find_path_for mma in
100             Filename.chop_suffix path ".mma" ^ ".ma"
101          end else begin
102             HLog.error ("We are in: " ^ Sys.getcwd ());
103             HLog.error ("Unable to find: "^file^"\nPaths explored:");
104             List.iter (fun x -> HLog.error (" - "^x)) include_paths;
105             raise (NoRootFor file)
106          end         
107    in
108    let path = find_path_for file in   
109    let path = absolutize path in
110 (*     HLog.debug ("file "^file^" resolved as "^path);  *)
111    let rootpath, root, buri = 
112      try
113        let mburi = Helm_registry.get "matita.baseuri" in
114        match Str.split (Str.regexp " ") mburi with
115        | [root; buri] when HExtlib.is_prefix_of root path -> 
116            ":registry:", root, buri
117        | _ -> raise (Helm_registry.Key_not_found "matita.baseuri")
118      with Helm_registry.Key_not_found "matita.baseuri" -> 
119        let rootpath = find_root path in
120        let buri = List.assoc "baseuri" (load_root_file rootpath) in
121        rootpath, Filename.dirname rootpath, buri
122    in
123 (*     HLog.debug ("file "^file^" rooted by "^rootpath^"");  *)
124    let uri = Http_getter_misc.strip_trailing_slash buri in
125    if String.length uri < 5 || String.sub uri 0 5 <> "cic:/" then
126      HLog.error (rootpath ^ " sets an incorrect baseuri: " ^ buri);
127    ensure_trailing_slash root, remove_trailing_slash uri, path
128  
129 ;;
130
131 let mk_baseuri root extra =
132   let chop name = 
133     assert(Filename.check_suffix name ".ma" ||
134       Filename.check_suffix name ".mma");
135     try Filename.chop_extension name
136     with Invalid_argument "Filename.chop_extension" -> name
137   in
138    remove_trailing_slash (HExtlib.normalize_path (root ^ "/" ^ chop extra))
139 ;;
140
141 let baseuri_of_script ~include_paths file = 
142   let root, buri, path = find_root_for ~include_paths file in
143   let path = HExtlib.normalize_path path in
144   let root = HExtlib.normalize_path root in
145   let lpath = Str.split (Str.regexp "/") path in
146   let lroot = Str.split (Str.regexp "/") root in
147   let rec substract l1 l2 =
148     match l1, l2 with
149     | h1::tl1,h2::tl2 when h1 = h2 -> substract tl1 tl2
150     | l,[] -> l
151     | _ -> raise (NoRootFor (file ^" "^path^" "^root))
152   in
153   let extra_buri = substract lpath lroot in
154   let extra = String.concat "/" extra_buri in
155    root,
156    mk_baseuri buri extra,
157    path,
158    extra
159 ;;
160
161 let find_roots_in_dir dir =
162   HExtlib.find ~test:(fun f ->
163     Filename.basename f = "root" &&
164     try (Unix.stat f).Unix.st_kind = Unix.S_REG 
165     with Unix.Unix_error _ -> false)
166     dir
167 ;;
168
169 (* make *)
170 let load_deps_file f = 
171   let deps = ref [] in
172   let ic = open_in f in
173   try
174     while true do
175       begin
176         let l = input_line ic in
177         match Str.split (Str.regexp " ") l with
178         | [] -> 
179             HLog.error ("Malformed deps file: " ^ f); 
180             raise (Failure ("Malformed deps file: " ^ f)) 
181         | he::tl -> deps := (he,tl) :: !deps
182       end
183     done; !deps
184     with End_of_file -> !deps
185 ;;
186
187 type options = (string * string) list
188
189 module type Format =
190   sig
191     type source_object
192     type target_object
193     val load_deps_file: string -> (source_object * source_object list) list
194     val string_of_source_object: source_object -> string
195     val string_of_target_object: target_object -> string
196     val build: options -> source_object -> bool
197     val root_and_target_of: 
198           options -> source_object -> 
199            (* root, relative source, writeable target, read only target *)
200            string option * source_object * target_object * target_object
201     val mtime_of_source_object: source_object -> float option
202     val mtime_of_target_object: target_object -> float option
203     val is_readonly_buri_of: options -> source_object -> bool
204   end
205
206 module Make = functor (F:Format) -> struct
207
208   type status = Done of bool
209               | Ready of bool
210
211   let say s = if !debug > 0 then prerr_endline ("make: "^s);; 
212
213   let unopt_or_call x f y = match x with Some _ -> x | None -> f y;;
214
215   let fst4 = function (x,_,_,_) -> x;;
216
217   let modified_before_s_t (_,cs, ct, _, _) a b = 
218    
219     if !debug > 1 then time_stamp ("L s_t: a " ^ F.string_of_source_object a);
220     if !debug > 1 then time_stamp ("L s_t: b " ^ F.string_of_target_object b);
221     
222     let a = try Hashtbl.find cs a with Not_found -> assert false in
223     let b = 
224       try
225         match Hashtbl.find ct b with
226         | Some _ as x -> x
227         | None ->
228            match F.mtime_of_target_object b with
229            | Some t as x -> 
230                Hashtbl.remove ct b;
231                Hashtbl.add ct b x; x
232            | x -> x
233       with Not_found -> assert false
234     in
235     let r = match a, b with 
236        | Some a, Some b -> a <= b
237        | _ -> false
238     in
239
240     if !debug > 1 then time_stamp ("L s_t: " ^ string_of_bool r);
241
242     r
243
244   let modified_before_t_t (_,_,ct, _, _) a b =
245
246     if !debug > 1 then time_stamp ("L t_t: a " ^ F.string_of_target_object a);
247     if !debug > 1 then time_stamp ("L t_t: b " ^ F.string_of_target_object b);
248     
249     let a = 
250       try
251         match Hashtbl.find ct a with
252         | Some _ as x -> x
253         | None ->
254            match F.mtime_of_target_object a with
255            | Some t as x -> 
256                Hashtbl.remove ct a;
257                Hashtbl.add ct a x; x
258            | x -> x
259       with Not_found -> assert false
260     in
261     let b = 
262       try
263         match Hashtbl.find ct b with
264         | Some _ as x -> x
265         | None ->
266            match F.mtime_of_target_object b with
267            | Some t as x -> 
268                Hashtbl.remove ct b;
269                Hashtbl.add ct b x; x
270            | x -> x
271       with Not_found -> assert false
272     in
273     let r = match a, b with
274        | Some a, Some b ->
275
276        if !debug > 1 then time_stamp ("tt: a " ^ string_of_float a);
277        if !debug > 1 then time_stamp ("tt: b " ^ string_of_float b);
278
279           a <= b
280        | _ -> false
281     in
282
283     if !debug > 1 then time_stamp ("L t_t: " ^ string_of_bool r);
284
285     r
286
287   let rec purge_unwanted_roots wanted deps =
288     let roots, rest = 
289        List.partition 
290          (fun (t,_,d,_,_) ->
291            not (List.exists (fun (_,_,d1,_,_) -> List.mem t d1) deps))
292          deps
293     in
294     let newroots = List.filter (fun (t,_,_,_,_) -> List.mem t wanted) roots in
295     if newroots = roots then
296       deps
297     else
298       purge_unwanted_roots wanted (newroots @ rest)
299   ;;
300
301   let is_not_ro (opts,_,_,_,_) (f,_,_,r,_) =
302     match r with
303     | Some root -> not (F.is_readonly_buri_of opts f)
304     | None -> assert false
305   ;;
306
307 (* FG: new sorting algorithm ************************************************)
308
309   let rec make_aux root opts ok deps =
310     List.fold_left (make_one root opts) ok deps
311      
312   and make_one root opts ok what =
313     let lo, _, ct, cc, cd = opts in
314     let t, path, deps, froot, tgt = what in
315     let str = F.string_of_source_object t in
316     let map (okd, okt) d =
317        let (_, _, _, _, tgtd) as whatd = (Hashtbl.find cd d) in
318        let r = make_one root opts okd whatd in 
319        r, okt && modified_before_t_t opts tgtd tgt
320     in
321     time_stamp ("L : processing " ^ str);
322     try 
323        let r = Hashtbl.find cc t in
324        time_stamp ("L : " ^ string_of_bool r ^ " " ^ str);
325        ok && r
326 (* say "already built" *)
327     with Not_found ->
328        let okd, okt = List.fold_left map (true, modified_before_s_t opts t tgt) deps in       
329        let res = 
330           if okd then 
331           if okt then true else
332           let build path = match froot with
333              | Some froot when froot = root -> 
334                 if is_not_ro opts what then F.build lo path else
335                 (HLog.error ("Read only baseuri for: " ^ str ^
336                    ", I won't compile it even if it is out of date"); 
337                 false)
338              | Some froot -> make froot [path]
339              | None -> HLog.error ("No root for: " ^ str); false
340           in
341           Hashtbl.remove ct tgt;
342           Hashtbl.add ct tgt None;
343           time_stamp ("L : BUILDING " ^ str);
344           let res = build path in
345           time_stamp ("L : DONE     " ^ str); res
346           else false
347        in
348        time_stamp ("L : " ^ string_of_bool res ^ " " ^ str);
349        Hashtbl.add cc t res; ok && res
350
351 (****************************************************************************)
352
353   and make root targets = 
354     time_stamp "L : ENTERING";
355     HLog.debug ("Entering directory '"^root^"'");
356     let old_root = Sys.getcwd () in
357     Sys.chdir root;
358     let deps = F.load_deps_file (root^"/depends") in
359     let local_options = load_root_file (root^"/root") in
360     let baseuri = List.assoc "baseuri" local_options in
361     print_endline ("Entering HELM directory: " ^ baseuri); flush stdout;    
362     let caches,cachet,cachec,cached = 
363        Hashtbl.create 73, Hashtbl.create 73, Hashtbl.create 73, Hashtbl.create 73
364     in
365     (* deps are enriched with these informations to sped up things later *)
366     let deps = 
367       List.map 
368         (fun (file,d) -> 
369           let r,path,wtgt,rotgt = F.root_and_target_of local_options file in
370           Hashtbl.add caches file (F.mtime_of_source_object file);
371           (* if a read only target exists, we use that one, otherwise
372              we use the writeable one that may be compiled *)
373           let _,_,_,_, tgt as tuple = 
374             match F.mtime_of_target_object rotgt with
375             | Some _ as mtime ->
376                Hashtbl.add cachet rotgt mtime; 
377                (file, path, d, r, rotgt)
378             | None -> 
379                Hashtbl.add cachet wtgt (F.mtime_of_target_object wtgt); 
380                (file, path, d, r, wtgt)
381           in
382           Hashtbl.add cached file tuple;
383           tuple
384         )
385         deps
386     in
387     let opts = local_options, caches, cachet, cachec, cached in
388     let ok =
389       if targets = [] then 
390         make_aux root opts true deps
391       else
392         make_aux root opts true (purge_unwanted_roots targets deps)
393     in
394     print_endline ("Leaving HELM directory: " ^ baseuri); flush stdout;
395     HLog.debug ("Leaving directory '"^root^"'");
396     Sys.chdir old_root;
397     time_stamp "L : LEAVING";
398     ok
399   ;;
400
401 end
402   
403 let write_deps_file where deps = match where with 
404    | Some root ->
405       let oc = open_out (root ^ "/depends") in
406       let map (t, d) = output_string oc (t^" "^String.concat " " d^"\n") in
407       List.iter map deps; close_out oc;
408       HLog.message ("Generated: " ^ root ^ "/depends")
409    | None -> 
410       print_endline (String.concat " " (List.flatten (List.map snd deps)))
411       
412 (* FG ***********************************************************************)
413
414 (* scheme uri part as defined in URI Generic Syntax (RFC 3986) *)
415 let uri_scheme_rex = Pcre.regexp "^[[:alpha:]][[:alnum:]\-+.]*:"
416
417 let is_uri str =
418    Pcre.pmatch ~rex:uri_scheme_rex str