this.path {this.path}R Documentation

Determine Executing Script's Filename

Description

this.path() returns the normalized path of the executing script.

this.dir() returns the normalized path of the directory in which the executing script is located.

this.path2(), this.dir2(), and this.dir3() are from an old release that did not include default as an argument in this.path() or this.dir(). They should not be used in future code development and should be removed from older code.

Usage

this.path(verbose = getOption("verbose"), default, else.)
this.dir(..., default, else.)

this.path2(...)  # deprecated, use this.path(..., default = NULL) instead
this.dir2(...)   # deprecated, use this.dir(..., default = NULL) instead

this.dir3(...)   # deprecated, use this.dir(..., default = getwd()) instead

Arguments

verbose

TRUE or FALSE; should the method in which the path was determined be printed?

default

if there is no executing script, this value is returned.

else.

missing or a function to call on the return value if there is an executing script. See tryCatch2 for inspiration.

...

arguments passed to this.path.

Details

There are three ways in which R code is typically run:

  1. in ‘RStudio’ / / ‘Rgui’ / / ‘VSCode’ by running the current line / / selection with the Run button / / appropriate keyboard shortcut

  2. through a source call: a call to function source, sys.source, debugSource in ‘RStudio’, or testthat::source_file

  3. from a shell, such as the Windows command-line / / Unix terminal

If you are using this.path in ‘VSCode’, see this.path.in.VSCode

To retrieve the executing script's filename, first an attempt is made to find a source call. The calls are searched in reverse order so as to grab the most recent source call in the case of nested source calls. If a source call was found, the argument file (fileName in the case of debugSource, path in the case of testthat::source_file) is returned from the function's evaluation environment. If you have your own source-like function that you'd like to be recognized by this.path, please contact the package maintainer so that it can be implemented.

If no source call is found up the calling stack, then an attempt is made to figure out how R is currently being used.

If R is being run from a shell, the shell arguments are searched for -f FILE or --file=FILE (the two methods of taking input from FILE). If exactly one of either type of argument is supplied, the text FILE is returned. It is an error to use this.path when none or multiple arguments of either type are supplied.

If R is being run from a shell under Unix-alikes with -g Tk or --gui=Tk, this.path() will signal an error. This is because ‘Tk’ does not make use of its -f FILE, --file=FILE argument.

If R is being run from ‘RStudio’, the active document's filename (the document in which the cursor is active) is returned (at the time of evaluation). If the active document is the R console, the source document's filename (the document open in the current tab) is returned (at the time of evaluation). Please note that the source document will NEVER be a document open in another window (with the Show in new window button). It is important to not leave the current tab (either by closing or switching tabs) while any calls to this.path have yet to be evaluated in the run selection. It is an error for no documents to be open or for a document to not exist (not saved anywhere).

If R is being run ‘VSCode’, the source document's filename is returned (at the time of evaluation). It is important to not leave the current tab (either by closing or switching tabs) while any calls to this.path have yet to be evaluated in the run selection. It is an error for a document to not exist (not saved anywhere).

If R is being run from ‘Rgui’, the source document's filename (the document most recently interacted with besides the R Console) is returned (at the time of evaluation). Please note that minimized documents will be INCLUDED when looking for the most recently used document. It is important to not leave the current document (either by closing the document or interacting with another document) while any calls to this.path have yet to be evaluated in the run selection. It is an error for no documents to be open or for a document to not exist (not saved anywhere).

If R is being run from ‘AQUA’, the executing script's path cannot be determined. Unlike ‘RStudio’ and ‘Rgui’, there is currently no way to request the path of an open document. Until such a time that there is a method for requesting the path of an open document, consider using ‘RStudio’ or ‘VSCode’.

If R is being run in another manner, it is an error to use this.path.

If your GUI of choice is not implemented with this.path, please contact the package maintainer so that it can be implemented.

Value

character string; the executing script's filename.

Note

The first time this.path is called within a script, it will normalize the script's path, check that the script exists (throwing an error if it does not), and save it in the appropriate environment. When this.path is called subsequent times within the same script, it returns the saved path. This will be faster than the first time, will not check for file existence, and will be independent of the working directory.

As a side effect, this means that a script can delete itself using file.remove or unlink but still know its own path for the remainder of the script.

Within a script that contains calls to both this.path and setwd, this.path MUST be used AT LEAST once before the first call to setwd. This isn't always necessary; for instance if you ran a script using its absolute path as opposed to its relative path, changing the working directory has no effect. However, it is still advised against.

The following is NOT an example of bad practice:

setwd(this.path::this.dir())

setwd is most certainly written before this.path(), but this.path() will be evaluated first. It is not the written order that is bad practice, but the order of evaluation. Do not change the working directory before calling this.path at least once.

See Also

here

shFILE

this.path-package

source, sys.source, debugSource, testthat::source_file

R.from.shell

Examples


this.path:::write.code(file = FILE <- tempfile(), {

    withAutoprint({

        cat(sQuote(this.path::this.path(verbose = TRUE, default = {
            stop("interestingly enough, because the executing script's\n",
                "  path will be found, argument 'default' won't be evaluated,\n",
                "  and so this error won't actually print, isn't that\n",
                "  neat? you can use this to your advantage in a similar\n",
                "  manner, doing arbitrary things only if the executing\n",
                "  script does not exist")
        })), "\n\n")

    }, width.cutoff = 60L, verbose = FALSE)

})


source(FILE, verbose = FALSE)
sys.source(FILE, envir = environment())
if (.Platform$GUI == "RStudio")
    get("debugSource", "tools:rstudio", inherits = FALSE)(FILE)
if (requireNamespace("testthat"))
    testthat::source_file(FILE, chdir = FALSE, wrap = FALSE)


this.path:::.Rscript(c("--default-packages=NULL", "--vanilla", FILE))


# this.path also works when source-ing a URL
# (included tryCatch in case an internet connection is not available)
tryCatch({
    source("https://raw.githubusercontent.com/ArcadeAntics/this.path/main/tests/this.path_w_URLs.R")
}, condition = message)


for (expr in c("this.path()",
               "this.path(default = NULL)",
               "this.dir()",
               "this.dir(default = NULL)",
               "this.dir(default = getwd())"))
    this.path:::.Rscript(c("--default-packages=this.path", "--vanilla", "-e", expr))


# an example from R package 'logr'
this.path::this.path(verbose = FALSE, default = "script.log",
    else. = function(x) {
        x <- if (.Platform$OS.type == "windows")
            sub("[.][^.\\/]+$", "", x)
        else sub("[.][^./]+$", "", x)
        paste0(x, ".log")
    })

[Package this.path version 0.11.0 Index]