---
title: "Automating Workflows<br/>(make)"
subtitle: "Lecture 15"
author: "Dr. Colin Rundel"
footer: "Sta 523 - Fall 2026"
format:
  revealjs:
    theme: slides.scss
    transition: fade
    slide-number: true
    code-line-numbers: false
    preserve-tabs: true
    self-contained: true
execute:
  echo: true
  warning: true
engine: knitr
filters:
  - _makefile-tabs.lua
---

```{r setup}
#| message: false
#| warning: false
#| include: false
options(
  width = 80
)

knitr::opts_chunk$set(
  fig.align = "center", fig.retina = 2, dpi = 150,
  out.width = "100%"
)
```

```{python py_setup}
#| include: false
import builtins
import os
import pprint
import sys

def _display(value):
    if value is None:
        return
    builtins._ = value
    if isinstance(value, (list, dict)):
        pprint.pprint(value, width=45, sort_dicts=False)
    else:
        print(repr(value))

sys.displayhook = _display
```


## Relative and absolute paths

An absolute path starts at the root of the file system and specifies one location.

::: {.small}
```
/Users/colin/project/data/raw.csv
```
:::

A relative path starts from the working directory (usually where the process was started).

::: {.medium}
| Path              | Meaning                                                   |
|:------------------|:----------------------------------------------------------|
| `data/raw.csv`    | `raw.csv` inside `data`, inside the working directory     |
| `./clean_data.R`  | `clean_data.R` in the working directory                   |
| `../other/x.csv`  | up one directory, then into `other`                       |
:::

. . .

Absolute paths almost always break when a project moves or is copied to another computer.

For reproducibility, never use absolute paths. Instead use relative paths that assume the project root will be the working directory.


## {#jenny-fire data-menu-title="setwd()"}

![](imgs/jenny_fire.png){fig-align="center" width="66%"}

::: {.aside}
Source: Jenny Bryan's [Zen and the Art of Workflow Maintenance](https://speakerdeck.com/jennybc/zen-and-the-art-of-workflow-maintenance)
:::

# Automating a project

## A typical report

A data analysis often involves several scripts that read files and write results which are then used by subsequent steps. 

Below is a toy project that combines Python, R, and Quarto to produce an HTML report.

::: {.small}
```
project/
├── get_data.py       # downloads the raw data to data/raw.csv
├── clean_data.R      # cleans it into data/clean.csv
├── plot_scores.py    # draws figs/scores.png from the clean data
├── plot_counts.py    # draws figs/counts.png from the clean data
├── report.qmd        # renders report.html from the clean data and the figures
├── pyproject.toml    # declares the Python dependencies
└── uv.lock           # records their resolved versions
```
:::

Our goal is to keep `report.html` up to date as the scripts and data change, without rerunning steps unnecessarily.

::: {.aside}
The example project is in the course [exercises repository](https://github.com/sta523-fa26/exercises).
:::


## What depends on what?

```{mermaid}
%%| echo: false
%%{init: {"htmlLabels": false, "flowchart": {"padding": 12}}}%%
flowchart LR
    classDef script fill:#E69F00,stroke:#D55E00,color:#000
    classDef data   fill:#56B4E9,stroke:#0072B2,color:#000
    classDef output fill:#009E73,stroke:#006B4F,color:#fff
    get([get_data.py]):::script --> raw[data/raw.csv]:::data
    raw --> clean[data/clean.csv]:::data
    cleanR([clean_data.R]):::script --> clean
    clean --> scores[figs/scores.png]:::data
    plots([plot_scores.py]):::script --> scores
    clean --> counts[figs/counts.png]:::data
    plotc([plot_counts.py]):::script --> counts
    clean --> html[report.html]:::output
    scores --> html
    counts --> html
    qmd([report.qmd]):::script --> html
```

If we edit `clean_data.R`, which steps must run again to bring the report up to date?

. . .

What about `report.qmd`?

## `make`

* Is a build tool that creates files from other files by following a set of rules you write down.

* Originally created by Stuart Feldman in 1976 at Bell Labs to build C programs. It is language agnostic, anything that reads and writes files can be automated with `make`.

* Available on almost any operating system with basic development tools installed.

* The rules (usually) live in a text file named `Makefile` in the project directory that uses simple syntax to specify the dependency graph from the previous slide.


## Example rule - `data/clean.csv`

The dependency diagram shows two inputs for this file: 

::: {.columns}
::: {.column}
* the cleaning script 
:::

::: {.column}
* the raw data
:::
:::

We can express that relationship as a rule using the following Make syntax:

::: {.small .pt-3}
```makefile
data/clean.csv: clean_data.R data/raw.csv
	mkdir -p data
	Rscript clean_data.R
```
:::

::: {.pt-3}
The pieces of this rule are:

* The *target* (`data/clean.csv`) - is the file we want to build.
* The *prerequisites* (`clean_data.R` and `data/raw.csv`) - are the inputs. Changing either can make the output outdated.
* The *recipe* - is the two indented shell commands that generate the output from the prequisites.
:::



## A full Makefile

We can express the full dependency graph as follows:

::: {.small}
```makefile
report.html: report.qmd data/clean.csv figs/scores.png figs/counts.png
	quarto render report.qmd

figs/scores.png: plot_scores.py data/clean.csv
	mkdir -p figs
	uv run python plot_scores.py

figs/counts.png: plot_counts.py data/clean.csv
	mkdir -p figs
	uv run python plot_counts.py

data/clean.csv: clean_data.R data/raw.csv
	mkdir -p data
	Rscript clean_data.R

data/raw.csv: get_data.py
	mkdir -p data
	uv run python get_data.py
```
:::


## Previewing a build

With no target named, `make` selects the first target in the Makefile.

If we invoke `make` with the `-n` flag it previews the build's commands without running them.

::: {.small}
```bash
make -n
```
```
mkdir -p data
uv run python get_data.py
mkdir -p data
Rscript clean_data.R
mkdir -p figs
uv run python plot_scores.py
mkdir -p figs
uv run python plot_counts.py
quarto render report.qmd
```
:::

. . .

From this we can see that `make` works backward from the report to find its prerequisites, then plans the commands in dependency order.


## From preview to build

:::: {.columns}
::: {.column width='48%'}
First run:

::: {.small}
```bash
make
```
```
mkdir -p data
uv run python get_data.py
mkdir -p data
Rscript clean_data.R
mkdir -p figs
uv run python plot_scores.py
mkdir -p figs
uv run python plot_counts.py
quarto render report.qmd
```
:::
:::

::: {.column width='48%'}
Second run:

::: {.small}
```bash
make
```
```
make: `report.html' is up to date.
```
:::

Third run:

::: {.small}
```bash
make
```
```
make: `report.html' is up to date.
```
:::
:::
::::


::: {.aside}
We have removed R and Python output to make things fit on the slide.
:::

## Requesting an output

Specific targets can be built directly by passing their name as an argument to `make`.

::: {.small}
```bash
rm -f data/clean.csv # remove existing file
make data/clean.csv
```
```
mkdir -p data
Rscript clean_data.R
```
:::



## How Make decides what to run

For each requested file, Make follows the same simple procedure:

1. Check its prerequisites, updating any that need rebuilding.
2. Run the recipe if the target is missing *or* a prerequisite has a newer modification time.
3. Otherwise, reuse the existing target.

Make compares modification times (timestamps), not file contents. Saving a script can trigger a rebuild even if its output would be unchanged.


## What reruns after a change?

Once the project is built, Make reruns only the steps downstream of what changed, which answers the questions from the dependency diagram. Each row starts from an up-to-date project, makes one change, and runs `make`.

::: {.medium}
| Change                   | Steps that run                       | Steps skipped                 |
|:-------------------------|:-------------------------------------|:------------------------------|
| Edit `clean_data.R`      | Clean, both plots, render            | Download                      |
| Edit `report.qmd`        | Render                               | Download, clean, both plots   |
| Delete `figs/scores.png` | Plot scores, render                  | Download, clean, plot counts  |
| Edit `get_data.py`       | Everything                           | None                          |
| Nothing                  | None                                 | Everything                    |
:::

A deleted output is rebuilt even though its inputs did not change, and the steps after it rerun because the new file is newer.


## Make only sees declared dependencies

Make does not inspect scripts to discover their inputs and outputs. The `Makefile` must describe those relationships.

* An omitted input can leave an outdated result that Make considers up to date. Include data, helper scripts, and configuration.

* Changes outside the project are invisible. If the file `get_data.py` downloads is updated online, nothing local is newer, so the raw data is not refreshed.

* A recipe that never creates its target runs again each time that missing target is requested.

* An extra output with no rule of its own may not be recreated if it is deleted.

Editing a recipe also does not trigger a rebuild, because `Makefile` is not listed as a prerequisite. Use `make -B report.html` to force a rebuild of the report and all of its prerequisites, including the download.


## Tabs, not spaces

A common error is indenting a recipe with spaces. By default, Make requires a tab at the start of each recipe line.

Spaces will produce a `missing separator` error like the following:

::: {.small}
```bash
make
```
```
Makefile:2: *** missing separator.  Stop.
```
:::

If your editor converts tabs to spaces, disable that setting for `Makefile` files. Showing whitespace characters can help you spot the difference.


## Recipe lines use separate shells

By default, each recipe line runs in a separate shell. Changes to the working directory, shell variables, or an activated environment do not carry over to the next line.

:::: {.columns}
::: {.column width="48%"}
`Rscript` runs in the original directory:

::: {.xsmall}
```makefile
preview:
	cd analysis
	Rscript summary.R
```
:::
:::
::: {.column width="48%"}
`Rscript` runs inside `analysis`:

::: {.xsmall}
```makefile
preview:
	cd analysis && Rscript summary.R
```
:::
:::
::::

* `&&` runs the second command only if the first succeeds. With `;`, the second command runs even if `cd` fails.

* A trailing `\` continues a recipe onto the next line, keeping it in the same shell.

* On Unix, the default shell is `/bin/sh`. Do not assume your interactive aliases or Bash/Zsh-specific syntax will work.


## Phony targets

Sometimes we want a target that is not a file but rather describes an action. These are called phony targets. Common examples are an `all` target that builds everything and a `clean` target that removes generated files.

::: {.small}
```makefile
all: report.html

clean:
	rm -f data/raw.csv data/clean.csv figs/scores.png figs/counts.png report.html

.PHONY: all clean
```
:::

`.PHONY` tells Make that these names are actions, so it never looks for files called `all` or `clean`.

## Useful make flags

As we have seen, `make` accepts flags that change what it builds and how. The following are some of the more useful / common.

::: {.medium}
| Option        | Effect                                                              |
|:--------------|:--------------------------------------------------------------------|
| `-n`          | print the recipes that would run without running them               |
| `-B`          | rebuild requested targets and prerequisites, ignoring timestamps    |
| `-j N`        | run up to `N` recipes in parallel where the graph allows            |
| `-k`          | keep going after an error and build what can still be built         |
| `-s`          | do not echo commands                                                |
| `-f file`     | use `file` instead of `Makefile`                                    |
| `-C dir`      | change to `dir` before doing anything                               |
:::

# Intermediate Make

## Variables

Make variables hold text, such as commands or paths, for reuse. `:=` expands any variable references on the right and stores the result when Make reads the file. `$(NAME)` inserts the stored value.

::: {.xsmall}
```makefile
PY := uv run python
R  := Rscript

figs/scores.png: plot_scores.py data/clean.csv
	mkdir -p figs
	$(PY) plot_scores.py

data/clean.csv: clean_data.R data/raw.csv
	mkdir -p data
	$(R) clean_data.R

data/raw.csv: get_data.py
	mkdir -p data
	$(PY) get_data.py
```
:::

::: {.aside}
Make expands recipe variables before the shell runs. Use `$$` to pass a dollar sign to the shell, as in `echo "$$HOME"` to print your home directory.
:::


## Automatic variables

Make also supplies automatic variables whose values depend on the rule being run. They let a recipe refer to its target and prerequisites without hard coding their names.

Some useful builtin variables:

::: {.medium}
| Variable | Meaning                                  |
|:---------|:-----------------------------------------|
| `$@`     | the target                               |
| `$<`     | the first prerequisite                   |
| `$^`     | all prerequisites, without duplicates    |
| `$(@D)`  | the directory part of the target         |
:::

::: {.small .pt-4}
```makefile
data/clean.csv: clean_data.R data/raw.csv
	mkdir -p "$(@D)"
	$(R) "$<"
```
:::


::: {.aside}
These are one-character variable names, so `$<` is shorthand for `$(<)`. The parentheses are only needed for longer names like `@D`. See the [GNU Make reference](https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html) for more.
:::




## Pattern rules

The project's two plotting scripts, `plot_scores.py` and `plot_counts.py`, each write a PNG to `figs/`. Their rules are identical apart from the names from them.

A single pattern rule covers both. `%` stands for the part of the name that varies, here `scores` or `counts`, and the same text is substituted into the prerequisites.

:::: {.columns .mxsmall}
::: {.column width='48%'}
```makefile
figs/scores.png: plot_scores.py data/clean.csv
	mkdir -p figs
	uv run python plot_scores.py

figs/counts.png: plot_counts.py data/clean.csv
	mkdir -p figs
	uv run python plot_counts.py
```
:::

::: {.column width='48%'}
```makefile
figs/%.png: plot_%.py data/clean.csv
	mkdir -p "$(@D)"
	$(PY) "$<"
```
:::
::::

A pattern rule only applies to targets that are asked for, so both figures still need to be listed as prerequisites of `report.html`.


## Wildcards and functions

Make functions use a `$(name arguments)` syntax. Here we find `.qmd` files in the working directory and construct the corresponding `.html` target names.

::: {.small}
```makefile
QMD  := $(wildcard *.qmd)
HTML := $(patsubst %.qmd,%.html,$(QMD))

all: $(HTML)

.PHONY: all

%.html: %.qmd
	quarto render "$<"
```
:::

* `wildcard` finds existing `.qmd` files using globbing.

* `patsubst` replaces `.qmd` with `.html` in each name.



## This course's website

The following is a simplified version of the Makefile used to generate this course's website:

::: {.xsmall}
```makefile
QMD   := $(wildcard static/slides/*.qmd)
HTML  := $(patsubst %.qmd,%.html,$(QMD))
PDF   := $(patsubst %.html,%.pdf,$(HTML))
THEME := static/slides/slides.scss static/slides/_bootstrap-utilities.scss

all: build

build: $(HTML) $(PDF)
	hugo

static/slides/%.html: static/slides/%.qmd $(THEME)
	quarto render "$<"

static/slides/%.pdf: static/slides/%.html
	Rscript -e "renderthis::to_pdf('$<')"

.PHONY: all build
```
:::

Because `build` is phony, `hugo` runs on every `make`, after the required slide updates.


## Environments as prerequisites

Python results also depend on package versions. In a uv project, `pyproject.toml` declares the dependencies and `uv run` keeps `.venv` in step with them, but Make does not know that outputs built with older packages are now stale.

. . .

An marker file can be used to connect the two. Make rebuilds it when `pyproject.toml` changes, and every rule that runs Python lists it as a prerequisite, here shown for the figures.

::: {.small}
```makefile
.venv/.synced: pyproject.toml
	uv sync
	touch "$@"

figs/%.png: plot_%.py data/clean.csv .venv/.synced
	mkdir -p "$(@D)"
	$(PY) "$<"
```
:::

::: {.aside}
We don't want to depend on pyproject.toml directly because the `uv sync` step is required be recreating the figs.
:::


## Failed recipes and partial outputs

A command can write part of its output before failing. Make stops on the error, but normally leaves that file behind. A later run may consider it up-to-date because its timestamp is new.

Add this special target to the Makefile:

::: {.small}
```makefile
.DELETE_ON_ERROR:
```
:::

If a recipe changes its target and exits with an error, Make deletes the target so the next run tries again. This protects against an incomplete `data/raw.csv` after a failed partial download.

It does not remove other files the command wrote, and the command must report failure with a nonzero exit status.


## Beyond Make

Make coordinates commands using file dependencies and timestamps. Tools designed for data analysis extend this approach to other kinds of dependencies and execution environments.

::: {.medium}
* `targets` for R tracks R objects and declared file targets. It uses hashes of code and data to detect changes and supports parallel execution.

* `Snakemake` uses a Python-based workflow language with explicit inputs and outputs. It adds support for software environments, clusters, and containers.
:::

Make is a useful starting point for projects organized around scripts and files. Consider these tools when you need to track R objects or manage more complex computing environments.


# Summary {visibility="uncounted"}

## Takeaways {visibility="uncounted"}

::: {.medium}
* A file rule names an output, its prerequisite inputs, and a recipe that builds it. Recipe lines start with a tab.

* Make rebuilds missing or outdated targets using modification times, not file contents.

* Phony targets like `all` and `clean` name tasks. 

* Use `make -n` to preview the commands for a build.

* Variables and pattern rules reduce repetition when several outputs are built in the same way.

* Make only knows the dependencies you declare, so list every input and check both a fresh build and a second run.
:::


## Learning more {visibility="uncounted"}

::: {.medium}
- [GNU make manual](https://www.gnu.org/software/make/manual/make.html)
- [minimal make](https://kbroman.org/minimal_make/), a short introduction for reproducible research
- [Software Carpentry - Automation and Make](https://swcarpentry.github.io/make-novice/)
- [targets](https://docs.ropensci.org/targets/) and the [targets user manual](https://books.ropensci.org/targets/)
- [Snakemake](https://snakemake.readthedocs.io/)
:::


# File-system reference {visibility="uncounted"}

## Path shortcuts {visibility="uncounted"}

In a relative path, `.` refers to the working directory and `..` moves up one directory, wherever it appears. A leading `~` is a shortcut for your home directory when expanded by the shell or a path function.

::: {.small}
```{r}
fs::path_abs("..")
fs::path_expand("~/Desktop")
```

```{python}
os.path.abspath("..")
os.path.expanduser("~/Desktop")
```
:::

::: {.aside}
Not every function expands `~`. In Python, use `os.path.expanduser()` before passing such a path to `open()`.
:::


## Building and taking apart paths {visibility="uncounted"}

Use path functions to join directory and file names with the appropriate separator for your operating system.

Other path functions extract the file name, directory, or extension. Python's `splitext()` returns both the path without its extension and the extension, including the dot.


:::: {.columns .small}
::: {.column width='50%'}
```{r}
file.path("data", "penguins.csv")
basename("data/penguins.csv")
dirname("data/penguins.csv")
tools::file_ext("data/penguins.csv")
```
:::

::: {.column width='50%'}
```{python}
os.path.join("data", "penguins.csv")
os.path.basename("data/penguins.csv")
os.path.dirname("data/penguins.csv")
os.path.splitext("data/penguins.csv")
```
:::
::::


## Listing and checking {visibility="uncounted"}

These calls list names inside `data`, without the `data/` prefix. Join each name to `"data"` before opening it, or use `full.names = TRUE` with R's `list.files()`.

```{r}
#| include: false
options(width = 38)
```

:::: {.columns .small}
::: {.column width='50%'}
```{r}
list.files("data", pattern = "\\.csv$")
file.exists("data/penguins.csv")
```
:::

::: {.column width='50%'}
```{python}
files = sorted(os.listdir("data"))
[f for f in files if f.endswith(".csv")]
os.path.exists("data/penguins.csv")
```
:::
::::

```{r}
#| include: false
options(width = 80)
```


## Creating and deleting {visibility="uncounted"}

These examples create `out` and an empty placeholder file, then delete them. Creating an existing directory warns in R. Python raises an error unless `exist_ok=True`.

Both file-creation calls overwrite an existing file with an empty one. Deletion bypasses the trash, so check the path first. `os.rmdir()` removes only empty directories.

:::: {.columns .small}
::: {.column width='50%'}
```{r}
dir.create("out")
file.create("out/a.png")
```
:::

::: {.column width='50%'}
```{python}
os.makedirs("out", exist_ok=True)
open("out/a.png", "w").close()
```
:::
::::

:::: {.columns .small}
::: {.column width='50%'}
```{r}
unlink("out", recursive = TRUE)
```

```{r}
#| include: false
dir.create("out")
file.create("out/a.png")
```
:::

::: {.column width='50%'}
```{python}
os.remove("out/a.png")
os.rmdir("out")
```
:::
::::

:::: {.columns .small}
::: {.column width='50%'}
```{r}
dir.exists("out")
```
:::

::: {.column width='50%'}
```{python}
os.path.exists("out")
```
:::
::::


## The `fs` package {visibility="uncounted"}

The `fs` package gives R's file operations consistent names and behavior.

* Names group by task, with `path_`, `file_`, and `dir_` prefixes.
* Functions accept vectors of paths. Failed operations raise errors. Existence checks return `TRUE` or `FALSE`.
* Paths always use `/` as the separator, even on Windows.

::: {.small}
```{r}
fs::dir_info("data", glob = "*.csv") |>
  dplyr::select(path, size, modification_time)
```
:::


## Function reference {visibility="uncounted"}

These functions serve similar purposes, but their arguments and return values differ. Names in the `fs` column assume the `fs::` prefix.

::: {.small}
| Task                | Base R              | `fs`                          | Python                          |
|---------------------|---------------------|-------------------------------|---------------------------------|
| Working directory   | `getwd()`           | `path_wd()`                   | `os.getcwd()`                   |
| Absolute path       | `normalizePath()`   | `path_abs()`                  | `os.path.abspath()`             |
| Join paths          | `file.path()`       | `path()`                      | `os.path.join()`                |
| File name           | `basename()`        | `path_file()`                 | `os.path.basename()`            |
| Directory name      | `dirname()`         | `path_dir()`                  | `os.path.dirname()`             |
| Extension           | `tools::file_ext()` | `path_ext()`                  | `os.path.splitext()`            |
| List files          | `list.files()`      | `dir_ls()`                    | `os.listdir()`                  |
| Check existence     | `file.exists()`     | `file_exists()`               | `os.path.exists()`              |
| Create directory    | `dir.create()`      | `dir_create()`                | `os.makedirs()`                 |
| Delete              | `unlink()`          | `file_delete()`, `dir_delete()` | `os.remove()`, `os.rmdir()`   |
| Copy                | `file.copy()`       | `file_copy()`                 | `shutil.copy()`                 |
| Move or rename      | `file.rename()`     | `file_move()`                 | `os.rename()`                   |
| Size, times, etc.   | `file.info()`       | `file_info()`                 | `os.stat()`                     |
:::
