rprojroot

repository·main·Indexed 41 days ago

https://github.com/r-lib/rprojroot

An R utility package for reliable file path resolution that identifies a project root based on specific criteria, such as the presence of a DESCRIPTION file, to avoid reliance on the current working directory.

Tokens
662
Snippets
2
Records
3
Agent score
50%

What's inside rprojroot

  1. Overview of rprojroot

    main
    The rprojroot package provides tools for accessing files relative to a project root. This helps prevent issues caused by relying on the current working directory, which can change unexpectedly. It is designed as a low-level helper package for the here package and works by using 'criteria' to identify the root of a project based on the presence of specific files.
  2. How criteria and find_file() work

    main

    In rprojroot, a criterion is an object that contains a find_file() function. This function identifies the project root by looking for a specific file pattern (e.g., an R package root is identified by the presence of a DESCRIPTION file).

    When you call criterion$find_file(...), it behaves similarly to file.path(), but it is always rooted at the identified project root rather than the current working directory. This allows you to reliably locate files regardless of where your R session is currently pointed, as long as your working directory is somewhere within the project.

    Key behaviors:

    • Relative paths: If you pass relative components to find_file(), they are appended to the project root.
    • Absolute paths: If the first component passed to find_file() is an absolute path, the function uses that path as the starting point, allowing for safe path manipulation even when the input path is already absolute.
    library(rprojroot)
    
    # Assuming 'is_r_package' is a criterion for R packages
    # and 'pkg' is the path to an R package root
    
    # 1. Find the root
    root_path <- is_r_package$find_file()
    
    # 2. Find a file relative to that root
    # This works even if your working directory is set to a subdirectory of the project
    setwd(file.path(pkg, "R"))
    target_file <- is_r_package$find_file("tests", "testthat")
    
    # 3. Safely handle absolute paths
    # If 'root_path' is absolute, find_file() handles it correctly
    path_from_absolute <- is_r_package$find_file(root_path, "tests", "testthat")