Search code examples
rstringrbookdown

Building `bookdown` book in 1-up level directory


Background -
My entire bookdown project is in _source directory, and I wanted to have the compiled book in the 1-up directory in docs. The full path is - "C:/Users/kbc/project1/docs/_source"

Working solution -
I am able to do this by hardcoding the output directory in _bookdown.yml using -
output_dir: 'C:/Users/kbc/project1/docs'

Issue -
However, I wanted to be flexible with paths by using here::here() to retrieve the present location and strip the last /_source part using -
output_dir: stringr::str_remove_all(here::here(), "/_source").

But the build fails with following error -

Error in file(con, "w") : cannot open the connection
Calls: <Anonymous> ... write_ref_keys -> <Anonymous> -> writeLines -> file
In addition: There were 32 warnings (use warnings() to see them)
Execution halted

Exited with status 1.

Why output_dir: accepts the hardcoded character array, but not the character array from the function? What can I do for the flexible-approach?


Solution

  • Perhaps you can just use output_dir: ../ (the trailing slash is optional). The two dots ../ means exactly what you were looking for, and you don't need to rely on two additional packages (here and stringr).

    That said, I don't recommend this directory structure, because the source is contained in the output directory. I'd recommend separating the source from the output directory, so that the output directory contains purely output, otherwise you might accidentally delete the full source when cleaning up the output directory (e.g., running bookdown::clean_book()). You may consider putting the source under C:/Users/kbc/project1/Rmd, and set output_dir: ../docs/.