R/assertions.R

Defines functions assert_one_of assert_paired assert_exclusive assert_period assert_timestampish check_timestampish assert_dateish check_dateish

check_dateish = function(x, null.ok = FALSE) {
  if (null.ok && is.null(x)) {
    return(TRUE)
  }
  if (test_date(x, any.missing = FALSE, len = 1L)) {
    return(TRUE)
  }
  if (
    test_string(x, pattern = "^\\d{4}-\\d{2}-\\d{2}$") &&
      !is.na(as.Date(x, format = "%Y-%m-%d"))
  ) {
    return(TRUE)
  }
  if (null.ok) {
    "Must be `NULL`, a Date, or a valid date string in 'YYYY-MM-DD' format"
  } else {
    "Must be a Date or a valid date string in 'YYYY-MM-DD' format"
  }
}

assert_dateish = function(x, null.ok = FALSE, .var.name = vname(x), add = NULL) {
  res = check_dateish(x, null.ok)
  makeAssertion(x, res, .var.name, add)
  if (!is.null(x) && !inherits(x, "Date")) {
    x = as.Date(x, format = "%Y-%m-%d")
  }
  invisible(x)
}

check_timestampish = function(x, null.ok = FALSE) {
  if (null.ok && is.null(x)) {
    return(TRUE)
  }
  if (test_multi_class(x, c("POSIXt", "Date")) && length(x) == 1L && !anyNA(x)) {
    return(TRUE)
  }
  if (test_string(x, min.chars = 4L)) {
    return(TRUE)
  }
  if (null.ok) {
    "Must be `NULL`, a Date, a POSIXct, or an ISO 8601 string"
  } else {
    "Must be a Date, a POSIXct, or an ISO 8601 string"
  }
}

assert_timestampish = function(x, null.ok = FALSE, .var.name = vname(x), add = NULL) {
  res = check_timestampish(x, null.ok)
  makeAssertion(x, res, .var.name, add)
  if (is.null(x)) {
    return(invisible())
  }
  if (inherits(x, c("POSIXt", "Date"))) {
    x = format(as.POSIXct(x), "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
  }
  invisible(x)
}

assert_period = function(x, .var.name = vname(x)) {
  assert(
    check_null(x),
    check_string(x, min.chars = 1L),
    check_count(x, positive = TRUE),
    .var.name = .var.name
  )
  invisible(x)
}

assert_exclusive = function(x, y) {
  if (!is.null(x) && !is.null(y)) {
    stop(sprintf("`%s` and `%s` are mutually exclusive.", vname(x), vname(y)), call. = FALSE)
  }
}

assert_paired = function(x, y) {
  if (xor(is.null(x), is.null(y))) {
    stop(sprintf("`%s` and `%s` must be supplied together.", vname(x), vname(y)), call. = FALSE)
  }
}

assert_one_of = function(...) {
  if (sum(!map_lgl(list(...), is.null)) != 1L) {
    nms = sprintf("`%s`", map_chr(as.list(substitute(list(...)))[-1L], deparse))
    n = length(nms)
    nms = if (n == 2L) paste(nms, collapse = " or ") else paste0(toString(nms[-n]), ", or ", nms[n])
    stop(sprintf("Exactly one of %s must be provided.", nms), call. = FALSE)
  }
}

Try the bbk package in your browser

Any scripts or data that you put into this service are public.

bbk documentation built on Oct. 21, 2026, 5:14 p.m.