Something went wrong. Try again.
Git format in pure OCaml
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192(* Copyright (c) 2026 Thomas Gazagnaire <thomas@gazagnaire.org>
Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
type event = | Counted of int | Written of int | Sent of int | Received of int | Remote of string | Hook of string
let pp ppf = function | Counted n -> Fmt.pf ppf "%d objects counted" n | Written n -> Fmt.pf ppf "%d objects written" n | Sent n -> Fmt.pf ppf "%d bytes sent" n | Received n -> Fmt.pf ppf "%d bytes received" n | Remote l -> Fmt.pf ppf "remote: %s" l | Hook l -> Fmt.pf ppf "hook: %s" l
let equal a b = match (a, b) with | Counted a, Counted b | Written a, Written b | Sent a, Sent b | Received a, Received b -> Int.equal a b | Remote a, Remote b | Hook a, Hook b -> String.equal a b | (Counted _ | Written _ | Sent _ | Received _ | Remote _ | Hook _), _ -> false
let counter f = let n = ref 0 in fun () -> incr n; f (Counted !n)
type lines = { event : string -> event; emit : event -> unit; pending : Buffer.t;}
let lines ?(event = fun l -> Remote l) emit = { event; emit; pending = Buffer.create 128 }
(* [s] with each C0 control but tab, DEL, and each C1 control in its UTF-8 form, U+0080 to U+009F, which a terminal may read as the start of an escape sequence, as the [\xhh] escapes of its bytes. *)let pp_escaped ppf s = let n = String.length s in let hex c = Fmt.pf ppf "\\x%02x" (Char.code c) in let rec go i = if i < n then match s.[i] with | ('\x00' .. '\x08' | '\x0a' .. '\x1f' | '\x7f') as c -> hex c; go (i + 1) | '\xc2' when i + 1 < n && Char.code s.[i + 1] land 0xe0 = 0x80 -> hex s.[i]; hex s.[i + 1]; go (i + 2) | c -> Fmt.char ppf c; go (i + 1) in go 0
let line t = if Buffer.length t.pending > 0 then begin let text = Buffer.contents t.pending in Buffer.clear t.pending; t.emit (Fmt.kstr t.event "%a" pp_escaped text) end
let feed t s = String.iter (function '\r' | '\n' -> line t | c -> Buffer.add_char t.pending c) s
let flush t = line t