---
title: "b2 - Setting up and using Nix and rix on macOS"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{b2-setting-up-and-using-rix-on-macos}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r, include=FALSE}
library(rix)
```

*This vignette will discuss macOS-specific topics. If you're not using macOS,
you can ignore this vignette, and read the
`vignette("b1-setting-up-and-using-rix-on-linux-and-windows")` vignette
instead.*

## Introduction

When it comes to Nix, there are really only two supported operating systems:
macOS and Linux distributions. Windows is "supported" because it is actually
running Linux thanks to WSL2. In practice this means that Linux distributions
and Windows can be considered one system, and macOS another, separate, system,
with its own idiosyncrasies. This vignette details these.

## Why rix *and* Nix?

You don't have to install Nix to use `{rix}`: you can generate valid Nix
expressions using `{rix}` even on a system where Nix isn't present. However, this
means that you won't be able to build these expressions on that system.

## Installing Nix

You can use `{rix}` to generate Nix expressions even if you don't have Nix
installed on your system, but obviously, you need to install Nix if you actually
want to build the defined development environment and use them. Installing (and
uninstalling) Nix is quite simple, thanks to the installer from
[Determinate Systems](https://determinate.systems/posts/determinate-nix-installer),
a company that provides services and tools built on Nix. Simply open a terminal
and run the following line:


```{sh parsermd-chunk-1, eval = FALSE}
curl --proto '=https' --tlsv1.2 -sSf \
    -L https://install.determinate.systems/nix | \
     sh -s -- install
```

Then, install the `cachix` client and configure our `rstats-on-nix` cache: this
will install binary versions of many R packages which will speed up the building
process of environments:

```bash
nix-env -iA cachix -f https://cachix.org/api/v1/install
```

then use the cache:

```bash
cachix use rstats-on-nix
```

You only need to do this once per machine you want to use `{rix}` on. Many thanks
to [Cachix](https://www.cachix.org/) for sponsoring the `rstats-on-nix` cache!

`{rix}` also includes a function called `setup_cachix()` which will configure
the cache but it is recommended to use the `cachix` client instead. This is
because `setup_cachix()` will not edit the files that require admin/root
privileges and only edit the user-level files. This may not be enough depending
on how you installed Nix. Using the `cachix` client takes care of everything.
Use `setup_cachix()` when building a Docker image or if you somehow mess up
the configuration file (which should be located in `~/.config/nix.conf`).

Once you have Nix installed, you can build the expressions you generate with
`{rix}`!

## What if you don't have R already installed?

If you have successfully installed Nix, but don't have yet R installed on your
system, you could install R as you would usually do on your operating system,
and then install the `{rix}` package, and from there, generated project-specific
expressions and build them. But you could also install R using Nix. Running the
following line in a terminal will drop you in an interactive R session that you
can use to start generating expressions:

```
nix-shell --expr "$(curl -sl https://raw.githubusercontent.com/ropensci/rix/main/inst/extdata/default.nix)"
```

This should immediately start an R session inside your terminal. You can now run
something like this:

```
rix(r_ver = "4.4.2",
    r_pkgs = c("dplyr", "ggplot2"),
    system_pkgs = NULL,
    git_pkgs = NULL,
    ide = "other",
    project_path = ".",
    overwrite = TRUE)
```

to generate a `default.nix`, and then use that file to generate an environment
with R, `{dplyr}` and `{ggplot2}`. If you need to add packages for your project,
rerun the command above, but add the needed packages to `r_pkgs`. This is
detailed in the vignettes
`vignette("d1-installing-r-packages-in-a-nix-environment")` and
`vignette("d2-installing-system-tools-and-texlive-packages-in-a-nix-environment")`.

## Generating expressions

Once you have R installed, either through the usual installer for your operating
system, or through Nix as explained previously, you can now start building
project-specific development environments.

On macOS, generating expressions works just like on Linux and Windows. Start an
R session, and install `{rix}` if that's not already done. Because `{rix}` is
not yet on CRAN, the easiest way is to install it from its r-universe:

```{r parsermd-chunk-2, eval = FALSE}
install.packages("rix", repos = c(
  "https://ropensci.r-universe.dev",
  "https://cloud.r-project.org"
))
```

You can then use the `{rix}` package to generate expressions. Consult the
next vignette `vignette("c-using-rix-to-build-project-specific-environments")`
to learn more.

## More macOS specificities

### R Support for Apple Silicon in Nixpkgs

The Apple Silicon architecture wasn't well supported before 2021 on Nix. Our
`rstats-on-nix` fork of `nixpkgs` provides improved compatibility by backporting
fixes to R and R packages, but only from 2021 onwards. If you need to use an
older R version, it is quite unlikely that it is going to work.

### Shared libraries issue

When using environments built with Nix on macOS, you might get crashes
(segmentation faults) refering to "shared libraries". These indicate that your
user library of R packages is interfering with the project-specific Nix
environment. The system's user library that Nix packaged R by default includes
appears in the search paths (check `libPaths()`). For macOS, the user library is
at
`/Library/Frameworks/R.framework/Versions/<major>.<minor>-<arch>/Resources/library`;
we have observed crashes with R packages that depend on system libraries, such
as `{data.table}` or `{dplyr}`, and their (reverse) dependencies. Because user
libraries from the system would also appear on the search path in R from
`nixpkgs` for Linux, running `rix()` also runs `rix_init()` which creates a
custom `.Rprofile` in your project's path. This custom `.Rprofile` ensures that
only packages declaratively defined in your `default.nix` and built to be part
of the Nix store (one R package is one separate derivation listed in a unique
Nix path) appear on the R library path.

### RStudio and other development interfaces on macOS

As of writing, RStudio cannot be installed through `nixpkgs` for macOS, and if
you wish to use RStudio with a Nix environment, you have to install it through
`nixpkgs`. This means that it is impossible to use RStudio and a Nix environment
on macOS. When you try to generate an expression with `ide =
"rstudio"` on macOS, this will raise a warning. Here are the options you have:

- ignore the warning, because the environment will be built on a Linux
  distribution (even though you generated the expression on macOS) and used on a
  Linux distribution;
- change the `ide =` argument to either `"other"` or `"code"`. Use `"code"` if
  you want to use VS Code and `"other"` for any other editor, like Vim or Emacs.
  These other editors don't need to be installed through `nixpkgs` to use Nix 
  environments, unlike RStudio;
- if you're working on a pipeline with the `{targets}` package, you could run it
  on GitHub Actions. This means you could work on the code on RStudio outside
  of the Nix environment, as the code will only be executed on GitHub Actions 
  runners. See this vignette 
  `vignette("z-advanced-topic-reproducible-analytical-pipelines-with-nix")` for
  further details;
- work on your project as usual, using your usual installation of R and RStudio,
  but generate a `default.nix` at the end with `ide = "other"` with the right
  version of R for reproducibility purposes;
- use *subshells* to execute only the code you need to run in a specific
  environment. See this vignette 
  `vignette("z-advanced-topic-running-r-or-shell-code-in-nix-from-r")`;
- help us package RStudio for macOS on `nixpgs`. See
  [here](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/editors/rstudio/default.nix),
  the Nix expression for RStudio.

We recommend you continue with the next vignette before tackling the more
advanced topics listed above: `vignette("c-using-rix-to-build-project-specific-environments")`.

## Why do we need all these special tweaks?

### Path of Nix installation not in `PATH`

When using RStudio Desktop on macOS, you typically launch it from the
Applications folder. However, RStudio currently lacks an option to start an
integrated R session via a shell startup on macOS (see this
[issue](https://github.com/rstudio/rstudio/issues/13341). On RStudio for Linux
flavors, `PATH` is properly inherited in R sessions. As a result, key
environmental variables for UNIX systems, like PATH, are not be properly loaded
from your default shell (e.g., `zsh`, via `~/.zshrc`). Also, RStudio overwrites
a `PATH` variable set via `.Rprofile` or `.Renviron` with its own defaults,
which makes it impossible to find Nix and standard Nix tools like `nix-build`.
It's worth noting that this doesn't impact `rix::rix()`, which generates Nix
expressions and doesn't require a Nix installation. As a workaround, we have
added mechanisms in `nix_build()` and `with_nix()` that append the path of the
Nix store to the `PATH` variable in an active session automatically (via
`Sys.setenv()`, when you use RStudio on macOS. You don't have to do anything. We
have you covered, and you get a friendly message that informs you.

## Other "Nix"es

There are several implementations of the Nix package manager that you might want
to try if you're feeling adventurous... for now, we recommend to stick with Nix.

You can give [Lix](https://lix.systems/install/) a try, or
[Tvix](https://tvix.dev/).
