view Intchecks/parseargs.R @ 6:ec75de7f1e08 draft default tip

Uploaded
author melpetera
date Mon, 11 Dec 2023 12:56:20 +0000
parents
children
line wrap: on
line source

# parseCommandArgs function
parse_args <- function(
  args = NULL,
  convert_booleans = TRUE,
  convert_numerics = TRUE
) {
  if (is.null(args)) {
    args <- commandArgs()
  }
  start <- which(args == "--args")[1] + 1
  if (is.na(start)) {
    return(list())
  }
  seq_by2 <- seq(start, length(args), by = 2)
  result <- as.list(args[seq_by2 + 1])
  names(result) <- args[seq_by2]
  converters <- c()
  if (convert_booleans) {
    converters <- c(
      converters,
      function(x) {
        return(if (x == "TRUE") TRUE else if (x == "FALSE") FALSE else x)
      }
    )
  }
  if (convert_numerics) {
    converters <- c(
      converters,
      function(x) {
        return(if (is.na(y <- as.numeric(x))) x else y)
      }
    )
  }
  return(convert_parameters(result, converters))
}

convert_parameters <- function(args, converters) {
  suppressWarnings(
    for (param in names(args)) {
      for (converter in converters) {
        old_value <- args[[param]]
        args[[param]] <- converter(args[[param]])
        if (!identical(args[[param]], old_value)) {
          ## The value has been modified by the converter, and
          ## we don't want values to be converted multiple times,
          ## so we pass to the next value.
          break
        }
      }
    }
  )
  return(args)
}