Skip to content

Commit

Permalink
Merge pull request #465 from jonahbeckford/fix-stdout-binary-mode
Browse files Browse the repository at this point in the history
Set appropriate binary mode writing stdout
  • Loading branch information
pitag-ha authored Feb 1, 2024
2 parents 9b55562 + 167d0f1 commit 3473e52
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ unreleased
- Fix a small mistake in the man pages: Embededding errors is done by default with
`-as-pp`, not with `-dump-ast` (#464, @pitag-ha)

- Set appropriate binary mode when writing to `stdout` especially for Windows
compatibility. (#466, @jonahbeckford)

0.31.0 (2023-09-21)
-------------------

Expand Down
21 changes: 19 additions & 2 deletions src/utils.ml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,18 @@ open Import

let with_output fn ~binary ~f =
match fn with
| None | Some "-" -> f stdout
| None | Some "-" ->
(* Flipping back and forth from binary to text is not
a good idea, so we'll make two simplifying assumptions:
1. Assume that nothing is buffered on stdout before
entering [with_output]. That means we don't need to
flush the stdout on entry.
2. Assume that nothing else is sent to stdout after
[with_output]. That means it is safe to leave stdout
channel in binary mode (or text mode if [binary=true])
after the function is done. *)
set_binary_mode_out stdout binary;
f stdout
| Some fn -> Out_channel.with_file fn ~binary ~f

module Kind = struct
Expand Down Expand Up @@ -112,6 +123,10 @@ module Ast_io = struct
parse_source_code ~kind ~input_name ~prefix_read_from_source ch
| Necessarily_binary -> Error Not_a_binary_ast
in
(* Marshalled AST must be read in binary mode. Even though we don't know
before reading the magic number when the file has a marshalled AST,
it is safe to read source files in binary mode. *)
set_binary_mode_in ch true;
match read_magic ch with
| Error s -> handle_non_binary s
| Ok s -> (
Expand Down Expand Up @@ -152,7 +167,9 @@ module Ast_io = struct
let read input_source ~input_kind =
try
match input_source with
| Stdin -> from_channel stdin ~input_kind
| Stdin ->
set_binary_mode_in stdin true;
from_channel stdin ~input_kind
| File fn -> In_channel.with_file fn ~f:(from_channel ~input_kind)
with exn -> (
match Location.Error.of_exn exn with
Expand Down

0 comments on commit 3473e52

Please sign in to comment.