first_time <- function(path) {
  description <- file.path(path, "DESCRIPTION")
  if (!file.exists(description)) {
    stop(
      "`package.dir` must include a DESCRIPTION file:\n",
      "  * \"", path, "\" does not.\n",
      "Did you call `roxygenize()` in a directory ",
      "that is not the package root?",
      call. = FALSE
    )
  }

  generated <- dir(file.path(path, "man"), full.names = TRUE)
  generated <- generated[!file.info(generated)$isdir]

  namespace <- file.path(path, "NAMESPACE")
  if (file.exists(namespace)) {
    generated <- c(generated, namespace)
  }

  roxy <- map_lgl(generated, made_by_roxygen)
  all(!roxy)
}

made_by_roxygen <- function(path) {
  if (!file.exists(path)) return(TRUE)

  first <- read_lines(path, n = 1)
  check_made_by(first)
}

check_made_by <- function(first) {
  if (length(first) == 0L) return(FALSE)
  grepl("^. Generated by roxygen2", first)
}

made_by <- function(comment) {
  # This text is used by IDE to display a special warning. DO NOT CHANGE
  # without consulting the IDE team
  paste0(comment, " Generated by roxygen2: do not edit by hand\n")
}

update_roxygen_version <- function(base_path) {
  desc_path <- file.path(base_path, "DESCRIPTION")

  cur <- as.character(utils::packageVersion("roxygen2"))
  prev <- stringr::str_trim(desc::desc_get("RoxygenNote", file = desc_path)[[1]])

  if (!is.na(cur) && !is.na(prev) && package_version(cur) < package_version(prev)) {
    warning("Version of roxygen2 last used with this package is ", prev, ". ",
      " You only have version ", cur, call. = FALSE, immediate. = TRUE)
  } else if (!identical(cur, prev)) {
    message("Updating roxygen version in ", desc_path)
    upgrade_7_0_0(cur)
    desc::desc_set(RoxygenNote = cur, file = desc_path)
  }
}

upgrade_7_0_0 <- function(cur_version) {
  if (numeric_version(cur_version) > "6.1.99") {
    return()
  }
  rule <- paste0(paste(rep("-", options('width')), collapse = ""))
  inform(c(
    rule,
    "Changes in roxygen2 7.0.0:",
    "* `%` is now escaped automatically in Markdown mode.",
    "Please carefully check .Rd files for changes",
    rule
  ))
}
