ocaml.lang.portability.crlf-support.broken-input-line

profile photo of semgrepsemgrep
Author
109
Download Count*

'input_line' leaves a '\r' (CR) character when reading lines from a Windows text file, whose lines end in "\r\n" (CRLF). This is a problem for any Windows file that is being read either on a Unix-like platform or on Windows in binary mode. If the code already takes care of removing any trailing '\r' after reading the line, add a '(* nosemgrep *)' comment to disable this warning.

Run Locally

Run in CI

Defintion

rules:
  - id: broken-input-line
    pattern: |
      input_line
    message: "'input_line' leaves a '\\r' (CR) character when reading lines from a
      Windows text file, whose lines end in \"\\r\\n\" (CRLF). This is a problem
      for any Windows file that is being read either on a Unix-like platform or
      on Windows in binary mode. If the code already takes care of removing any
      trailing '\\r' after reading the line, add a '(* nosemgrep *)' comment to
      disable this warning."
    languages:
      - ocaml
    severity: WARNING
    metadata:
      category: portability
      technology:
        - ocaml
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

crlf-support.ml

let get_line ic =
  try
    (* ruleid:broken-input-line *)
    Some (input_line ic)
  with
    End_of_file -> None

let with_in_file path f =
  (* ruleid:prefer-read-in-binary-mode *)
  let ic = open_in path in
  Fun.protect
    ~finally:(fun () -> close_in_noerr ic)
    (fun () -> f ic)

let with_in_file path f =
  (* ruleid:prefer-write-in-binary-mode *)
  let oc = open_out path in
  Fun.protect
    ~finally:(fun () -> close_out_noerr oc)
    (fun () -> f oc)

(* Force text mode without triggering alert *)
let with_in_text path f =
  let ic = open_in_gen [Open_text] 0o000 path in
  Fun.protect
    ~finally:(fun () -> close_in_noerr ic)
    (fun () -> f ic)

(* Force text mode without triggering alert *)
let with_out_text path f =
  let oc = open_out_gen [Open_text] 0o666 path in
  Fun.protect
    ~finally:(fun () -> close_out_noerr oc)
    (fun () -> f oc)