common/mlstdutils: Add chomp function to remove \n from end of strings.

This is like the Perl chomp function, it removes a single \n from the
end of a string if present, else leaves the string alone.

I believe I found the only (two) places where such a function is used,
but there may be a few more lurking.
This commit is contained in:
Richard W.M. Jones
2017-07-21 14:50:08 +01:00
parent 95dfa054c0
commit ac3db3d664
5 changed files with 23 additions and 14 deletions

View File

@@ -229,6 +229,13 @@ module String = struct
let trim ?(test = Char.isspace) str =
trimr ~test (triml ~test str)
let chomp str =
let n = String.length str in
if n > 0 && str.[n-1] = '\n' then
String.sub str 0 (n-1)
else
str
let count_chars c str =
let count = ref 0 in
for i = 0 to String.length str - 1 do

View File

@@ -107,6 +107,8 @@ module String : sig
(** Trim right. *)
val trim : ?test:(char -> bool) -> string -> string
(** Trim left and right. *)
val chomp : string -> string
(** If the string ends with [\n], remove it. *)
val count_chars : char -> string -> int
(** Count number of times the character occurs in string. *)
val explode : string -> char list

View File

@@ -110,6 +110,15 @@ let test_string_span ctx =
assert_equal_int 3 (String.cspan "def" "ab");
assert_equal_int 0 (String.cspan "" "ab")
(* Test Std_utils.String.chomp. *)
let test_string_chomp ctx =
assert_equal_string "a" (String.chomp "a");
assert_equal_string "a" (String.chomp "a\n");
assert_equal_string "a\nb" (String.chomp "a\nb");
assert_equal_string "" (String.chomp "");
assert_equal_string "" (String.chomp "\n");
assert_equal_string "\n" (String.chomp "\n\n") (* only removes one *)
(* Suites declaration. *)
let suite =
"mllib Std_utils" >:::
@@ -122,6 +131,7 @@ let suite =
"strings.find" >:: test_string_find;
"strings.lines_split" >:: test_string_lines_split;
"strings.span" >:: test_string_span;
"strings.chomp" >:: test_string_chomp;
]
let () =

View File

@@ -376,14 +376,8 @@ let shell_command ?(echo_cmd = true) cmd =
let uuidgen () =
let lines = external_command "uuidgen -r" in
assert (List.length lines >= 1);
let uuid = List.hd lines in
let len = String.length uuid in
let uuid, len =
if len > 0 && uuid.[len-1] = '\n' then
String.sub uuid 0 (len-1), len-1
else
uuid, len in
if len < 10 then assert false; (* sanity check on uuidgen *)
let uuid = String.chomp (List.hd lines) in
if String.length uuid < 10 then assert false; (* sanity check on uuidgen *)
uuid
(* Remove a temporary directory on exit. *)

View File

@@ -296,12 +296,8 @@ object (self)
match res with
| None -> None
| Some k ->
let len = String.length k in
let k =
if len > 0 && k.[len-1] = '\n' then
String.sub k 0 (len-1)
else k in
Some (remove_hd_prefix k)
let k = String.chomp k in
Some (remove_hd_prefix k)
in
let vmlinuzes =