]> matita.cs.unibo.it Git - helm.git/blobdiff - helm/http_getter/http_getter_misc.ml
- added functions "add_line" and "remove_line" to edit line oriented files
[helm.git] / helm / http_getter / http_getter_misc.ml
index 70bd814ce581648adac236d19710777b643ac11b..9ab7082974b5603e342f46b507a9e0b5dc12e1ab 100644 (file)
@@ -41,15 +41,14 @@ let tcp_bufsiz = 4096 (* for TCP I/O *)
 
 let fold_file f init fname =
   let inchan = open_in fname in
-  let rec fold_lines' value =
-    try 
-      let line = input_line inchan in 
-      fold_lines' (f value line)
-    with End_of_file -> value
+  let res =
+    try
+      Zack.fold_in f init inchan
+    with e -> close_in inchan; raise e
   in
-  let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
   close_in inchan;
   res
+
 let iter_file f = fold_file (fun _ line -> f line) ()
 
 let hashtbl_sorted_fold f tbl init =
@@ -231,3 +230,46 @@ let http_get url =
       Some (Http_client.Convenience.http_get url)
     with Http_client.Http_error (code, _) -> None
 
+  (** apply a transformation "string list -> string list" to file lines *)
+let mangle_file ~fname f =
+  let ic = open_in fname in
+  let lines = Zack.input_lines ic in
+  close_in ic;
+  let oc = open_out fname in
+  Zack.output_lines (f lines) oc;
+  close_out oc
+;;
+
+let add_line ~fname ?position line =
+  mangle_file ~fname
+    (fun lines ->
+      match position with
+      | None -> lines @ [line]
+      | Some i ->
+          assert (i >= 0);
+          let rec add_after i = function
+            | (acc, []) -> acc @ [line] (* eof *)
+            | (acc, ((hd::tl) as l)) ->
+                if i = 0 then
+                  acc @ [line] @ l
+                else
+                  add_after (i-1) (acc @ [hd], tl)
+          in
+          add_after i ([], lines))
+;;
+
+let remove_line ~fname position =
+  mangle_file ~fname
+    (fun lines ->
+      assert (position >= 0);
+      let rec remove i = function
+        | (acc, []) -> acc  (* eof *)
+        | (acc, ((hd::tl) as l)) ->
+            if i = 0 then
+              acc @ tl
+            else
+              remove (i-1) (acc @ [hd], tl)
+      in
+      remove position ([], lines))
+;;
+