]> matita.cs.unibo.it Git - helm.git/blob - matita/matitamakeLib.ml
2bf01f8979a32ad38caeb40cb80770c0d966c186
[helm.git] / matita / matitamakeLib.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 (* $Id$ *)
27
28 open Printf
29
30 let logger = fun mark -> 
31   match mark with 
32   | `Error -> HLog.error
33   | `Warning -> HLog.warn
34   | `Debug -> HLog.debug
35   | `Message -> HLog.message
36
37 type development = 
38   { root: string ; name: string }
39
40 let developments = ref []
41   
42 let pool () = Helm_registry.get "matita.basedir" ^ "/matitamake/" ;;
43 let rootfile = "/root" ;;
44
45 (* /foo/./bar/..//baz -> /foo/baz *)
46 let normalize_path s = 
47   let s = Str.global_replace (Str.regexp "//") "/" s in
48   let l = Str.split (Str.regexp "/") s in
49   let rec aux = function
50     | [] -> []
51     | he::".."::tl -> aux tl
52     | he::"."::tl -> aux (he::tl)
53     | he::tl -> he :: aux tl
54   in
55   (if Str.string_match (Str.regexp "^/") s 0 then "/" else "") ^
56   String.concat "/" (aux l)
57   ^ (if Str.string_match (Str.regexp "/$") s 0 then "/" else "")
58 ;;
59
60 let ls_dir dir = 
61   try
62     let d = Unix.opendir dir in
63     let content = ref [] in
64     try
65       while true do
66         let name = Unix.readdir d in
67         if name <> "." && name <> ".." then
68           content := name :: !content
69       done;
70       Some []
71     with End_of_file -> Unix.closedir d; Some !content
72   with Unix.Unix_error _ -> None
73
74 let initialize () = 
75   (* create a base env if none *)
76   HExtlib.mkdir (pool ());
77   (* load developments *)
78   match ls_dir (pool ()) with
79   | None -> logger `Error ("Unable to list directory " ^ pool ()) 
80   | Some l -> 
81       List.iter 
82         (fun name -> 
83           let root = 
84             try 
85               Some (HExtlib.input_file (pool () ^ name ^ rootfile))
86             with Unix.Unix_error _ -> 
87               logger `Warning ("Malformed development " ^ name);
88               None
89           in 
90           match root with 
91           | None -> ()
92           | Some root -> 
93               developments := {root = root ; name = name} :: !developments;
94               let inc = Helm_registry.get_list 
95                 Helm_registry.string "matita.includes" in
96               Helm_registry.set_list Helm_registry.of_string 
97                 ~key:"matita.includes" ~value:(inc @ [root])
98           ) 
99       l
100
101 (* finds the makefile path for development devel *)
102 let makefile_for_development devel =
103   let develdir = pool () ^ devel.name in
104   develdir ^ "/makefile"
105
106 let dot_for_development devel = 
107   let dot_fname = pool () ^ devel.name ^ "/depend.dot" in
108   if Sys.file_exists dot_fname then Some dot_fname else None
109
110 (* given a dir finds a development that is radicated in it or below *)
111 let development_for_dir dir =
112   let dir = normalize_path dir in
113   let is_prefix_of d1 d2 =
114     let len1 = String.length d1 in
115     let len2 = String.length d2 in
116     if len2 < len1 then 
117       false
118     else
119       let pref = String.sub d2 0 len1 in
120       pref = d1 && (len1 = len2 || d2.[len1] = '/')
121   in
122   try
123     Some (List.find (fun d -> is_prefix_of d.root dir) !developments)
124   with Not_found | Failure _ -> None
125
126 let development_for_name name =
127   try 
128     Some (List.find (fun d -> d.name = name) !developments)
129   with Not_found -> None
130
131 (* dumps the deveopment to disk *)
132 let dump_development devel =
133   let devel_dir = pool () ^ devel.name in 
134   HExtlib.mkdir devel_dir;
135   HExtlib.output_file ~filename:(devel_dir ^ rootfile) ~text:devel.root
136
137 let list_known_developments () = 
138   List.map (fun r -> r.name,r.root) !developments
139
140 let am_i_opt = lazy (
141   if Pcre.pmatch ~pat:"\\.opt$" Sys.argv.(0) then ".opt" else "")
142   
143 let rebuild_makefile development = 
144   let makefilepath = makefile_for_development development in
145   let template = 
146     HExtlib.input_file BuildTimeConf.matitamake_makefile_template 
147   in
148   let ext = Lazy.force am_i_opt in
149   let binpath = 
150     if HExtlib.is_executable 
151       (BuildTimeConf.runtime_base_dir ^ "/matitac" ^ ext)
152     then BuildTimeConf.runtime_base_dir ^ "/" else ""
153   in
154   let cc = binpath ^ "matitac" ^ ext in
155   let rm = binpath ^ "matitaclean" ^ ext in
156   let mm = binpath ^ "matitadep" ^ ext in
157   let df = pool () ^ development.name ^ "/depend" in
158   let template = Pcre.replace ~pat:"@ROOT@" ~templ:development.root template in
159   let template = Pcre.replace ~pat:"@CC@" ~templ:cc template in
160   let template = Pcre.replace ~pat:"@DEP@" ~templ:mm template in
161   let template = Pcre.replace ~pat:"@DEPFILE@" ~templ:df template in
162   let template = Pcre.replace ~pat:"@CLEAN@" ~templ:rm template in
163   HExtlib.output_file ~filename:makefilepath ~text:template
164   
165 let rebuild_makefile_devel development = 
166   let path = development.root ^ "/makefile" in
167   if not (Sys.file_exists path) then
168     begin
169       let template = 
170         HExtlib.input_file BuildTimeConf.matitamake_makefile_template_devel
171       in
172       let template = 
173         Pcre.replace ~pat:"@MATITA_RT_BASE_DIR@"
174           ~templ:BuildTimeConf.runtime_base_dir template
175       in
176       HExtlib.output_file ~filename:path ~text:template
177     end
178   
179 (* creates a new development if possible *)
180 let initialize_development name dir =
181   let dir = normalize_path dir in
182   let name = Pcre.replace ~pat:" " ~templ:"_" name in 
183   let dev = {name = name ; root = dir} in
184   dump_development dev;
185   rebuild_makefile dev;
186   rebuild_makefile_devel dev;
187   developments := dev :: !developments;
188   Some dev
189
190 let make chdir args = 
191   let old = Unix.getcwd () in
192   try
193     Unix.chdir chdir;
194     let cmd = String.concat " " ("make" :: List.map Filename.quote args) in
195     let rc = Unix.system cmd in
196     Unix.chdir old;
197     match rc with
198     | Unix.WEXITED 0 -> true
199     | Unix.WEXITED i -> logger `Error ("make returned " ^ string_of_int i);false
200     | _ -> logger `Error "make STOPPED or SIGNALED!";false
201   with Unix.Unix_error (_,cmd,err) -> 
202     logger `Warning ("Unix Error: " ^ cmd ^ ": " ^ err);
203     false
204       
205 let call_make ?matita_flags development target make =
206   let matita_flags = 
207     let already_defined = 
208       match matita_flags with 
209       | None -> (try Sys.getenv "MATITA_FLAGS" with Not_found -> "")
210       | Some s -> s 
211     in
212     let bench = 
213       if Helm_registry.get_bool "matita.bench" then " -bench" else ""
214     in
215     let system = 
216       if Helm_registry.get_bool "matita.system" then " -system" else ""
217     in
218     let noinnertypes = 
219       if Helm_registry.get_bool "matita.noinnertypes" then " -noinnertypes" else ""
220     in
221     already_defined ^ bench ^ system ^ noinnertypes
222   in
223   let csc = try ["SRC=" ^ Sys.getenv "SRC"] with Not_found -> [] in
224   rebuild_makefile development;
225   let makefile = makefile_for_development development in
226   let flags = [] in 
227   let flags =
228     try
229       flags @ [ sprintf "MATITA_FLAGS=%s" matita_flags ]
230     with Not_found -> flags in
231   let flags = flags @ csc in
232   let args = 
233     ["--no-print-directory"; "-s"; "-k"; "-f"; makefile; target] @ flags 
234   in
235  (*    prerr_endline (String.concat " " args);   *)
236   make development.root args
237       
238 let build_development ?matita_flags ?(target="all") development =
239   call_make ?matita_flags development target make
240
241 (* not really good vt100 *)
242 let vt100 s =
243   let rex = Pcre.regexp "\e\\[[0-9;]+m" in
244   let rex_i = Pcre.regexp "^Info" in
245   let rex_w = Pcre.regexp "^Warning" in
246   let rex_e = Pcre.regexp "^Error" in
247   let rex_d = Pcre.regexp "^Debug" in
248   let rex_noendline = Pcre.regexp "\\n" in
249   let s = Pcre.replace ~rex:rex_noendline s in
250   let tokens = Pcre.split ~rex s in
251   let logger = ref HLog.message in
252   let rec aux = 
253     function
254     | [] -> ()
255     | s::tl ->
256         (if Pcre.pmatch ~rex:rex_i s then
257           logger := HLog.message
258         else if Pcre.pmatch ~rex:rex_w s then
259           logger := HLog.warn
260         else if Pcre.pmatch ~rex:rex_e s then
261           logger := HLog.error
262         else if Pcre.pmatch ~rex:rex_d s then
263           logger := HLog.debug
264         else 
265           !logger s);
266         aux tl
267   in
268   aux tokens
269   
270
271 let mk_maker refresh_cb =
272   (fun chdir args ->
273     let out_r,out_w = Unix.pipe () in
274     let err_r,err_w = Unix.pipe () in
275     let pid = ref ~-1 in
276     let oldhandler = Sys.signal Sys.sigchld (Sys.Signal_ignore) in
277     try
278 (*       prerr_endline (String.concat " " args); *)
279       let argv = Array.of_list ("make"::args) in
280       pid := Unix.create_process "make" argv Unix.stdin out_w err_w;
281       Unix.close out_w;
282       Unix.close err_w;
283       let buf = String.create 1024 in
284       let rec aux = function 
285         | f::tl ->
286             let len = Unix.read f buf 0 1024 in
287             if len = 0 then 
288               raise 
289                 (Unix.Unix_error 
290                   (Unix.EPIPE,"read","len = 0 (matita internal)"));
291             vt100 (String.sub buf 0 len);
292             aux tl
293         | _ -> ()
294       in
295       while true do
296         let r,_,_ = Unix.select [out_r; err_r] [] [] (-. 1.) in
297         aux r;
298         refresh_cb ()
299       done;
300       ignore(Sys.signal Sys.sigchld oldhandler);
301       true
302     with 
303     | Unix.Unix_error (_,"read",_)
304     | Unix.Unix_error (_,"select",_) -> 
305         ignore(Sys.signal Sys.sigchld oldhandler);
306         true)
307
308 let build_development_in_bg ?matita_flags ?(target="all") refresh_cb development =
309   call_make ?matita_flags development target (mk_maker refresh_cb)
310
311 let clean_development ?matita_flags development =
312   call_make ?matita_flags development "clean" make
313
314 let clean_development_in_bg ?matita_flags  refresh_cb development =
315   call_make development ?matita_flags  "clean" (mk_maker refresh_cb)
316
317 let destroy_development_aux development clean_development =
318   let delete_development development = 
319     let unlink = HExtlib.safe_remove in
320     let rmdir dir =
321       try
322         Unix.rmdir dir 
323       with Unix.Unix_error _ -> 
324         logger `Warning ("Unable to remove dir " ^ dir);
325         match ls_dir dir with
326         | None -> logger `Error ("Unable to list directory " ^ dir) 
327         | Some [] -> ()
328         | Some l -> logger `Error ("The directory is not empty")
329     in
330     unlink (makefile_for_development development);
331     unlink (pool () ^ development.name ^ rootfile);
332     unlink (pool () ^ development.name ^ "/depend");
333     unlink (pool () ^ development.name ^ "/depend.errors");
334     unlink (pool () ^ development.name ^ "/depend.dot");
335     rmdir (pool () ^ development.name);
336     developments := 
337       List.filter (fun d -> d.name <> development.name) !developments
338   in
339   if not(clean_development development) then
340     begin
341       logger `Warning "Unable to clean the development problerly.";
342       logger `Warning "This may cause garbage."
343     end;
344   delete_development development 
345  
346 let destroy_development ?matita_flags development = 
347   destroy_development_aux development (clean_development ?matita_flags)
348
349 let destroy_development_in_bg ?matita_flags refresh development = 
350   destroy_development_aux development 
351     (clean_development_in_bg refresh ?matita_flags ) 
352   
353 let root_for_development development = development.root
354 let name_for_development development = development.name
355
356 let publish_development_bstract build clean devel = 
357   let matita_flags, matita_flags_system = 
358     let orig_matita_flags = 
359       try Sys.getenv "MATITA_FLAGS" with Not_found -> "" 
360     in
361     orig_matita_flags, orig_matita_flags ^ " -system" 
362   in
363   HLog.message "cleaning the development before publishing";
364   if clean ~matita_flags devel then
365     begin
366       HLog.message "rebuilding the development in 'system' space";
367       (* here we should use pristine metadata if we use sqlite *)
368       if build ~matita_flags:matita_flags_system devel then
369         begin
370           HLog.message "publishing succeded";
371           true
372         end
373       else
374         begin
375           HLog.error "building process failed, reverting";
376           if not (clean ~matita_flags devel) then
377             HLog.error "cleaning failed, end of the world (2)";
378           false
379         end
380     end
381   else
382     (HLog.error "unable to clean the development, publishing failed"; false)
383   
384 let publish_development devel = 
385   publish_development_bstract 
386     (fun ~matita_flags devel -> build_development ~matita_flags devel) 
387     (fun ~matita_flags devel -> clean_development ~matita_flags devel) devel
388 let publish_development_in_bg cb devel = 
389   publish_development_bstract 
390     (fun ~matita_flags devel -> build_development_in_bg cb ~matita_flags devel)
391     (fun ~matita_flags devel -> clean_development_in_bg cb ~matita_flags devel)
392     devel
393