Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created May 18, 2018 12:41
Show Gist options
  • Select an option

  • Save jtpaasch/aeaf4b9aa78a6299dbaebe01d1f0ffb6 to your computer and use it in GitHub Desktop.

Select an option

Save jtpaasch/aeaf4b9aa78a6299dbaebe01d1f0ffb6 to your computer and use it in GitHub Desktop.
Simple colorizer/formatter (Ocaml)
type ttyfmt =
| Plain
| Red
| Green
| Warn
| Emph
let reset_tag = "\x1b[0m"
let start_of fmt =
match fmt with
| Plain -> ""
| Red -> "\x1b[31m"
| Green -> "\x1b[32m"
| Warn -> "\x1b[33m"
| Emph -> "\x1b[;1m"
let end_of fmt =
match fmt with
| Plain -> ""
| _ -> reset_tag
let is_tty oc =
let fd = Unix.descr_of_out_channel oc in
Unix.isatty fd
let log ?(fmt = Plain) oc msg =
let do_fmt = is_tty oc in
let start_tag =
match do_fmt with
| false -> ""
| true -> start_of fmt
in
let end_tag =
match do_fmt with
| false -> ""
| true -> end_of fmt
in
Printf.fprintf oc "%s%s%s\n%!" start_tag msg end_tag
let main () =
let oc = Unix.out_channel_of_descr Unix.stdout in
try
log oc "Lorem ipsum";
log ~fmt:Red oc "dolor sit amet";
log ~fmt:Green oc "quintinquit ne tollet";
log ~fmt:Warn oc "lipsum dixit";
log ~fmt:Emph oc "numquam ubi sub ubi"
with e ->
close_out oc;
raise e
let () = main ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment