R/code_prompts.r

Defines functions test_function explain_code annotate_code document_code

Documented in annotate_code document_code explain_code test_function

#' Document R Code
#'
#' @param code A character vector of R code. If missing the code currently
#'   selected in RStudio is documented (If RStudio is used).
#' @param ... passed on to \code{\link{askgpt}}.
#'
#' @return A character vector.
#' @export
#'
#' @examples
#' \dontrun{
#' document_code()
#' }
document_code <- function(code, ...) {
  context <- NULL
  if (missing(code)) {
    selection <- get_selection()
    code <- selection$code
    context <- selection$context
  }

  prompt <- glue::glue("Document this R function using roxygen2 syntax:",
                       "\n{code}")
  out <- askgpt(prompt, chat = FALSE, return_answer = TRUE, ...)

  if (rstudio_available()) {
    if (!is.null(context)) {
      rstudioapi::modifyRange(
        context$selection[[1L]]$range,
        paste0(out, collapse = "\n"),
        id = context$id
      )
      invisible(rstudioapi::documentSave(context$id))
    }
  }
  invisible(out)
}


#' Annotate R code with inline comments
#'
#' @inheritParams document_code
#' @return A character vector.
#' @export
annotate_code <- function(code, ...) {
  context <- NULL
  if (missing(code)) {
    selection <- get_selection()
    code <- selection$code
    context <- selection$context
  }

  prompt <- glue::glue("Add inline comments to this R code:",
                       "\n{code}")
  out <- askgpt(prompt, chat = FALSE, return_answer = TRUE, ...)

  if (rstudio_available()) {
    if (!is.null(context)) {
      rstudioapi::modifyRange(
        context$selection[[1L]]$range,
        paste0(out, collapse = "\n"),
        id = context$id
      )
      invisible(rstudioapi::documentSave(context$id))
    }
  }
  invisible(out)
}


#' Explain R code
#'
#' @inheritParams document_code
#' @return A character vector.
#' @export
explain_code <- function(code, ...) {
  if (missing(code)) {
    code <- get_selection()$code
  }
  prompt <- glue::glue("Explain the following R code to me:",
                       "\n{code}")
  askgpt(prompt, chat = TRUE, ...)
}

#' Test R code
#'
#' @inheritParams document_code
#' @return A character vector.
#' @export
test_function <- function(code, ...) {
  if (missing(code)) {
    code <- get_selection()$code
  }
  prompt <- glue::glue("Write a testthat unit test for this R function:",
                       "\n{code}")
  askgpt(prompt, chat = TRUE, ...)
}

Try the askgpt package in your browser

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

askgpt documentation built on Sept. 8, 2023, 5:42 p.m.