Skip to content

Commit b2307a7

Browse files
authored
Preserve trailing newline characters at the end of template files when present (#123)
* Add new Spin_std.Sys test This test verifies that newline char at end of file are preserved during templating. This test is currently broken and is fixed by the next commit. * Fix Spin_std.Sys.read_file Make it preserve newline characters at the end of the template files. Files without trailing newline make dune @fmt and git produce warnings.
1 parent 7fc6742 commit b2307a7

File tree

3 files changed

+31
-17
lines changed

3 files changed

+31
-17
lines changed

CHANGES.md

+7
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
# Unreleased
2+
3+
## Fixed
4+
5+
- Preserve trailing newline characters at the end of template files
6+
when present
7+
18
# 0.8.3
29

310
## Fixed

lib/spin_std/sys.ml

+10-16
Original file line numberDiff line numberDiff line change
@@ -88,20 +88,14 @@ let with_chdir dir f =
8888

8989
let write_file file content =
9090
let oc = open_out file in
91-
Printf.fprintf oc "%s" content;
92-
close_out oc
91+
Fun.protect
92+
(fun () -> output_string oc content)
93+
~finally:(fun () -> close_out oc)
9394

94-
let read_lines file : string list =
95-
let ic = open_in file in
96-
let try_read () = try Some (input_line ic) with End_of_file -> None in
97-
let rec loop acc =
98-
match try_read () with
99-
| Some s ->
100-
loop (s :: acc)
101-
| None ->
102-
close_in ic;
103-
List.rev acc
104-
in
105-
loop []
106-
107-
let read_file file = String.concat "\n" (read_lines file)
95+
let read_file file =
96+
let ic = open_in_bin file in
97+
Fun.protect
98+
(fun () ->
99+
let length = in_channel_length ic in
100+
really_input_string ic length)
101+
~finally:(fun () -> close_in ic)

test/spin_std/sys_test.ml

+14-1
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,17 @@ let test_ls_dir () =
99
let f_list = Spin_std.Sys.ls_dir (Filename.dirname temp_file) in
1010
check (list string) "equals" f_list [ temp_file ]
1111

12-
let suite = [ "ls_dir returns the files in the directory", `Quick, test_ls_dir ]
12+
let test_read_write_file () =
13+
let temp_dir = Spin_std.Sys.mk_temp_dir "spin-test" in
14+
let temp_file = Filename.concat temp_dir "file" in
15+
let contents = "Hello world!\n" in
16+
Spin_std.Sys.write_file temp_file contents;
17+
let read_contents = Spin_std.Sys.read_file temp_file in
18+
check string "equals" contents read_contents
19+
20+
let suite =
21+
[ "ls_dir returns the files in the directory", `Quick, test_ls_dir
22+
; ( "write_file/read_file preserves newlines at end of file"
23+
, `Quick
24+
, test_read_write_file )
25+
]

0 commit comments

Comments
 (0)