From f4ef486ffbb451816a257049bbbb07356a540b36 Mon Sep 17 00:00:00 2001 From: Leonidas Zhak <70497898+LeonidasZhak@users.noreply.github.com> Date: Sun, 7 Jun 2026 00:45:53 +0800 Subject: [PATCH] docs: add examples for local_tempdir() and with_tempdir() Closes #283 --- DESCRIPTION | 2 +- R/tempfile.R | 21 +++++++++++++++++++++ man/with_tempfile.Rd | 21 +++++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 30a2eb52..577b7678 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -39,7 +39,6 @@ Config/Needs/website: tidyverse/tidytemplate Config/testthat/edition: 3 Encoding: UTF-8 Roxygen: list(markdown = TRUE) -RoxygenNote: 7.3.2 Collate: 'aaa.R' 'collate.R' @@ -71,3 +70,4 @@ Collate: 'torture.R' 'utils.R' 'with.R' +Config/roxygen2/version: 8.0.0 diff --git a/R/tempfile.R b/R/tempfile.R index ed6e3dec..101099a6 100644 --- a/R/tempfile.R +++ b/R/tempfile.R @@ -29,6 +29,27 @@ #' #' # Note that this variable is only available in the scope of with_tempfile #' try(path2) +#' +#' # local_tempdir() creates a temporary directory and returns its path +#' local({ +#' dir_path <- local_tempdir() +#' dir.exists(dir_path) +#' # create a file inside it +#' writeLines("hello", file.path(dir_path, "test.txt")) +#' file.exists(file.path(dir_path, "test.txt")) +#' }) +#' # the directory and its contents are deleted automatically +#' file.exists(dir_path) +#' +#' # with_tempdir() temporarily changes the working directory to a temp dir +#' getwd() +#' with_tempdir({ +#' getwd() +#' writeLines("test", "example.txt") +#' list.files() +#' }) +#' # the original working directory is restored +#' getwd() #' @export with_tempfile <- function(new, code, envir = parent.frame(), .local_envir = parent.frame(), pattern = "file", tmpdir = tempdir(), fileext = "") { diff --git a/man/with_tempfile.Rd b/man/with_tempfile.Rd index 6f4a479e..5c16fec0 100644 --- a/man/with_tempfile.Rd +++ b/man/with_tempfile.Rd @@ -93,6 +93,27 @@ with_tempfile("path2", { # Note that this variable is only available in the scope of with_tempfile try(path2) + +# local_tempdir() creates a temporary directory and returns its path +local({ + dir_path <- local_tempdir() + dir.exists(dir_path) + # create a file inside it + writeLines("hello", file.path(dir_path, "test.txt")) + file.exists(file.path(dir_path, "test.txt")) +}) +# the directory and its contents are deleted automatically +file.exists(dir_path) + +# with_tempdir() temporarily changes the working directory to a temp dir +getwd() +with_tempdir({ + getwd() + writeLines("test", "example.txt") + list.files() +}) +# the original working directory is restored +getwd() } \seealso{ \code{\link{withr}} for examples