Something went wrong. Try again.
Git format in pure OCaml
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364(* A stand-in for ssh that records what git sends over it.
git runs $GIT_SSH_COMMAND with the host and the command to run there as its last argument (connect.c). This runs that command on this machine instead, relays git's standard input and output to it, and, when $RECORD names a file prefix, writes RECORD.client, the bytes git sent, RECORD.server, the bytes the command sent back, and RECORD.eof, how many of those git had been sent when it ended its standard input, as ssh ends the channel then. Without $RECORD it only relays. *)
(* Each chunk read from [src] written to [dst] and kept in [kept], until [src] ends. *)let relay ~src ~dst kept = let buf = Cstruct.create 65536 in let rec go () = match Eio.Flow.single_read src buf with | n -> let chunk = Cstruct.to_string ~len:n buf in Buffer.add_string kept chunk; Eio.Flow.copy_string chunk dst; go () | exception End_of_file -> () in go ()
let write path contents = Out_channel.with_open_bin path (fun oc -> Out_channel.output_string oc contents)
let () = let command = Sys.argv.(Array.length Sys.argv - 1) in let sent = Buffer.create 4096 and received = Buffer.create 4096 in let ended = ref 0 in let status = Eio_main.run @@ fun env -> let mgr = Eio.Stdenv.process_mgr env in Eio.Switch.run @@ fun sw -> let child_in, to_child = Eio.Process.pipe ~sw mgr in let from_child, child_out = Eio.Process.pipe ~sw mgr in let child = Eio.Process.spawn ~sw mgr ~stdin:child_in ~stdout:child_out [ "/bin/sh"; "-c"; command ] in Eio.Flow.close child_in; Eio.Flow.close child_out; Eio.Fiber.both (fun () -> relay ~src:(Eio.Stdenv.stdin env) ~dst:to_child sent; ended := Buffer.length received; Eio.Flow.close to_child) (fun () -> relay ~src:from_child ~dst:(Eio.Stdenv.stdout env) received; (* git reads to the end of its channel before it ends its own. *) Unix.close Unix.stdout); Eio.Process.await child in (match Sys.getenv_opt "RECORD" with | Some record -> write (record ^ ".client") (Buffer.contents sent); write (record ^ ".server") (Buffer.contents received); write (record ^ ".eof") (Fmt.str "%d\n" !ended) | None -> ()); match status with `Exited n -> exit n | `Signaled n -> exit (128 + n)