---
title: "Finding files in project subdirectories"
author: "Kirill Müller"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Finding files in project subdirectories}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

The `rprojroot` package solves a seemingly trivial but annoying problem
that occurs sooner or later
in any largish project:
How to find files in subdirectories?
Ideally, file paths are relative to the *project root*.

Unfortunately, we cannot always be sure about the current working directory:
For instance, in RStudio it's sometimes:

- the project root (when running R scripts),
- a subdirectory (when building vignettes),
- again the project root (when executing chunks of a vignette).

```{r}
basename(getwd())
```

In some cases, it's even outside the project root.

This vignette starts with a very brief summary that helps you get started,
followed by a longer description of the features.

## TL;DR

What is your project: An R package?

```{r}
rprojroot::is_r_package
```

Or an RStudio project?

```{r}
rprojroot::is_rstudio_project
```

Or something else?

```{r}
rprojroot::has_file(".git/index")
```

For now, we assume it's an R package:

```{r}
root <- rprojroot::is_r_package
```

The `root` object contains a function that helps locating files below the root
of your package, regardless of your current working directory.
If you are sure that your working directory is somewhere below your project's root,
use the `root$find_file()` function:

```{r}
readLines(root$find_file("DESCRIPTION"), 3)
```

You can also
construct an accessor to your root using the `root$make_fix_file()` function:

```{r}
root_file <- root$make_fix_file()
```


Note that `root_file()` is a *function* that works just like `$find_file()` but
will find the files even if the current working directory is outside your project:

```{r}
withr::with_dir(
  "../..",
  readLines(root_file("DESCRIPTION"), 3)
)
```

If you know the absolute path of some directory below your project,
but cannot be sure of your current working directory,
pass that absolute path to `root$make_fix_file()`:

```r
root_file <- root$make_fix_file("C:\\Users\\User Name\\...")
```

Get the path of standalone R scripts or vignettes
using the `thisfile()` function in the `kimisc` package:

```r
root_file <- root$make_fix_file(dirname(kimisc::thisfile()))
```

The remainder of this vignette describes implementation details and advanced features.


## Project root

We assume a self-contained project
where all files and directories are located below a common *root* directory.
Also, there should be a way to unambiguously identify this root directory.
(Often, the root contains a regular file whose name matches a given pattern,
and/or whose contents match another pattern.)
In this case, the following method reliably finds our project root:

- Start the search in any subdirectory of our project
- Proceed up the directory hierarchy until the root directory has been identified

The Git version control system (and probably many other tools) use a similar
approach: A Git command can be executed from within any subdirectory of a
repository.


### A simple example

The `find_root()` function implements the core functionality.
It returns the path to the first directory that matches the filtering criteria,
or throws an error if there is no such directory.
Filtering criteria are constructed in a generic fashion using the 
`root_criterion()` function,
the `has_file()` function constructs a criterion that checks for the presence
of a file with a specific name and specific contents.

```{r}
library(rprojroot)

# List all files and directories below the root
dir(find_root(has_file("DESCRIPTION")))

# Find a file relative to the root
file.exists(find_root_file("R", "root.R", criterion = has_file("DESCRIPTION")))
```

Note that the following code produces identical results when building the
vignette *and* when sourcing the chunk in RStudio,
provided that the current working directory is the project root
or anywhere below.


### Criteria

The `has_file()` function (and the more general `root_criterion()`)
both return an S3 object of class `root_criterion`:

```{r}
has_file("DESCRIPTION")
```

In addition, character values are coerced to `has_file` criteria by default, this coercion is applied automatically by `find_root()`.
(This feature is used by the introductory example.)

```{r}
as.root_criterion("DESCRIPTION")
```

The return value of these functions can be stored and reused;
in fact, the package provides `r length(criteria)` such criteria:

```{r}
criteria
```

Defining new criteria is easy:

```{r}
has_license <- has_file("LICENSE")
has_license

is_projecttemplate_project <- has_file("config/global.dcf", "^version: ")
is_projecttemplate_project
```

You can also combine criteria via the `|` operator:

```{r}
is_r_package | is_rstudio_project
```



### Shortcuts

To avoid specifying the search criteria for the project root every time,
shortcut functions can be created.
The `find_package_root_file()` is a shortcut for
`find_root_file(..., criterion = is_r_package)`:

```{r}
# Print first lines of the source for this document
head(readLines(find_package_root_file("vignettes", "rprojroot.Rmd")))
```

To save typing effort, define a shorter alias:

```{r}
P <- find_package_root_file

# Use a shorter alias
file.exists(P("vignettes", "rprojroot.Rmd"))
```

Each criterion actually contains a function that allows finding a file below the root specified by this criterion.
As our project does not have a file named `LICENSE`, querying the root results in an error:

```{r error = TRUE}
# Use the has_license criterion to find the root
R <- has_license$find_file
R

# Our package does not have a LICENSE file, trying to find the root results in an error
R()
```


### Fixed root

We can also create a function
that computes a path relative to the root *at creation time*.

```{r}
# Define a function that computes file paths below the current root
F <- is_r_package$make_fix_file()
F

# Show contents of the NAMESPACE file in our project
readLines(F("NAMESPACE"))
```

This is a more robust alternative to `$find_file()`, because it *fixes* the project
directory when `$make_fix_file()` is called, instead of searching for it every
time.  (For that reason it is also slightly faster, but I doubt this matters
in practice.)

This function can be used even if we later change the working directory to somewhere outside the project:

```{r}
# Print the size of the namespace file, working directory outside the project
withr::with_dir(
  "../..",
  file.size(F("NAMESPACE"))
)
```

The `make_fix_file()` member function also accepts an optional `path` argument,
in case you know your project's root but the current working directory is somewhere outside.
Take a look at the `thisfile()` function in the `kimisc` package for getting
the path to the current script or `knitr` document.


## `testthat` files

Tests run with [`testthat`](https://cran.r-project.org/package=testthat)
commonly use files that live below the `tests/testthat` directory.
Ideally, this should work in the following situation:

- During package development (working directory: package root)
- When testing with `devtools::test()` (working directory: `tests/testthat`)
- When running `R CMD check` (working directory: a renamed recursive copy of `tests`)

The `is_testthat` criterion allows robust lookup of test files.

```{r}
is_testthat
```

The example code below lists all files in the
[hierarchy](https://github.com/krlmlr/rprojroot/tree/master/tests/testthat/hierarchy)
test directory.
It uses two project root lookups in total,
so that it also works when rendering the vignette (*sigh*):

```{r}
dir(is_testthat$find_file("hierarchy", path = is_r_package$find_file()))
```


## Summary

The `rprojroot` package allows easy access to files below a project root
if the project root can be identified easily, e.g. if it is the only directory
in the whole hierarchy that contains a specific file.
This is a robust solution for finding files in largish projects
with a subdirectory hierarchy if the current working directory cannot be assumed
fixed.
(However, at least initially, the current working directory must be
somewhere below the project root.)


## Acknowledgement

This package was inspired by the gist
["Stop the working directory insanity"](https://gist.github.com/jennybc/362f52446fe1ebc4c49f)
by Jennifer Bryan, and by the way Git knows where its files are.
