Skip to contents

Check that imported packages are actually used

Usage

unused_import_linter(
  allow_ns_usage = FALSE,
  except_packages = c("bit64", "data.table", "tidyverse"),
  interpret_glue = TRUE
)

Arguments

allow_ns_usage

Suppress lints for packages only used via namespace. This is FALSE by default because pkg::fun() doesn't require library(pkg). You can use requireNamespace("pkg") to ensure a package is installed without attaching it.

except_packages

Character vector of packages that are ignored. These are usually attached for their side effects.

interpret_glue

If TRUE, interpret glue::glue() calls to avoid false positives caused by local variables which are only used in a glue expression.

See also

linters for a complete list of linters available in lintr.

Examples

# will produce lints
code_lines <- "library(dplyr)\n1 + 1"
writeLines(code_lines)
#> library(dplyr)
#> 1 + 1
lint(
  text = code_lines,
  linters = unused_import_linter()
)
#> <text>:1:1: warning: [unused_import_linter] Package 'dplyr' is attached but never used.
#> library(dplyr)
#> ^~~~~~~~~~~~~~

code_lines <- "library(dplyr)\ndplyr::tibble(a = 1)"
writeLines(code_lines)
#> library(dplyr)
#> dplyr::tibble(a = 1)
lint(
  text = code_lines,
  linters = unused_import_linter()
)
#> <text>:1:1: warning: [unused_import_linter] Don't attach package 'dplyr', which is only used by namespace. Check that it is installed using loadNamespace() instead.
#> library(dplyr)
#> ^~~~~~~~~~~~~~

# okay
code_lines <- "library(dplyr)\ntibble(a = 1)"
writeLines(code_lines)
#> library(dplyr)
#> tibble(a = 1)
lint(
  text = code_lines,
  linters = unused_import_linter()
)
#>  No lints found.

code_lines <- "library(dplyr)\ndplyr::tibble(a = 1)"
writeLines(code_lines)
#> library(dplyr)
#> dplyr::tibble(a = 1)
lint(
  text = code_lines,
  linters = unused_import_linter(allow_ns_usage = TRUE)
)
#>  No lints found.