Skip to contents

Functions that end in close(x) are almost always better written by using on.exit(close(x)) close to where x is defined and/or opened.

Usage

terminal_close_linter()

See also

linters for a complete list of linters available in lintr.

Examples

# will produce lints
code <- paste(
  "f <- function(fl) {",
  "  conn <- file(fl, open = 'r')",
  "  readLines(conn)",
  "  close(conn)",
  "}",
  sep = "\n"
)
writeLines(code)
#> f <- function(fl) {
#>   conn <- file(fl, open = 'r')
#>   readLines(conn)
#>   close(conn)
#> }
lint(
  text = code,
  linters = terminal_close_linter()
)
#> ::warning file=<text>,line=4,col=3::file=<text>,line=4,col=3,[terminal_close_linter] Use on.exit(close(x)) to close connections instead of running it as the last call in a function.

# okay
code <- paste(
  "f <- function(fl) {",
  "  conn <- file(fl, open = 'r')",
  "  on.exit(close(conn))",
  "  readLines(conn)",
  "}",
  sep = "\n"
)
writeLines(code)
#> f <- function(fl) {
#>   conn <- file(fl, open = 'r')
#>   on.exit(close(conn))
#>   readLines(conn)
#> }
lint(
  text = code,
  linters = terminal_close_linter()
)