X-Git-Url: http://matita.cs.unibo.it/gitweb/?a=blobdiff_plain;f=helm%2Fhttp_getter%2Fhttp_getter_misc.ml;h=9ab7082974b5603e342f46b507a9e0b5dc12e1ab;hb=96204969d2611dc618f7ed72ae40612b9526c763;hp=70bd814ce581648adac236d19710777b643ac11b;hpb=a888f480029a073f9b5a71a9a9dc10904efb7657;p=helm.git diff --git a/helm/http_getter/http_getter_misc.ml b/helm/http_getter/http_getter_misc.ml index 70bd814ce..9ab708297 100644 --- a/helm/http_getter/http_getter_misc.ml +++ b/helm/http_getter/http_getter_misc.ml @@ -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)) +;; +