diff --git a/.github/workflows/quarto-site.yaml b/.github/workflows/quarto-site.yaml index e2b10e5..985e885 100644 --- a/.github/workflows/quarto-site.yaml +++ b/.github/workflows/quarto-site.yaml @@ -50,6 +50,7 @@ jobs: packages: > local::./_packages/segue any::cli + any::covr any::downlit any::gt any::haven diff --git a/README.md b/README.md index e503a76..b34816b 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,10 @@ The R code runs when the site is built, so you need R with segue installed: ```r pak::pak("posit-dev/segue") -install.packages(c("tidyverse", "gt", "scales", "cli", "knitr", "rmarkdown", "modeldata", "haven", "downlit", "xml2")) +install.packages( + c("cli", "covr", "downlit", "gt", "haven", "knitr", "modeldata", + "pkgsite", "remotes", "rmarkdown", "scales", "segue", "tidyverse", "xml2") +) ``` Then, from this folder: @@ -25,14 +28,6 @@ quarto preview Locally, results are cached in `_freeze/` (`freeze: auto`), so a page re-runs only when its source changes. `_freeze/` is not committed: the GitHub Actions workflow in `.github/workflows/quarto-site.yaml` runs all the code on each push to `main` and publishes the site to the `gh-pages` branch. -## Data - -`data/` holds the SAS results that each page compares against. They come from the private `r-to-sas-comparisons` repository. To refresh them, clone that repository next to this one and run: - -```bash -Rscript data-raw/prepare-data.R ../r-to-sas-comparisons -``` - ## Reference pages The pages in `reference/` are written by [pkgsite](https://edgararuiz.github.io/pkgsite/) from segue's `.Rd` help files. Don't edit them by hand. The GitHub Actions workflow rebuilds them from the latest segue on every publish, so you only need to rebuild them locally to preview changes. @@ -78,16 +73,39 @@ What controls the output: When segue gains a new exported function, add its `.qmd` file to a section under `contents` and to the reference sidebar. Functions marked `@keywords internal` are skipped. +## Test coverage + +`coverage.qmd` shows segue's test coverage, overall and per file, with a [covr](https://covr.r-lib.org/) report for each line. The numbers are computed here, not read from Codecov. You need covr 4.0.0 or later. + +Then, from this folder, pass a branch, tag, or commit SHA of `posit-dev/segue` (the default is `main`): + +```bash +Rscript _coverage/build.R +Rscript _coverage/build.R v0.1.0 +Rscript _coverage/build.R 4c9dddd +Rscript _coverage/build.R --local ../segue # a local working tree +``` + +The script exports that commit from `_packages/segue` into a temporary folder (so the checkout used by `_pkgsite/build.R` doesn't change), installs segue's dependencies, and runs `covr::package_coverage()`. It writes: + +| Output | Contents | +|---|---| +| `data/coverage.rds` | The covr object, the ref and SHA, versions, and a per-file summary | +| `assets/coverage-badge.svg` | Badge for the whole package | +| `assets/coverage/.svg` | One badge per file in segue's `R/` folder, e.g. `assets/coverage/sas_round.svg` | + +Then render `coverage.qmd` again. A badge can be used on any page, e.g. `![](../assets/coverage/sas_round.svg)` on a comparison page. + ## Links to function documentation After each render, `_post-render.R` runs [downlit](https://downlit.r-lib.org/) on the new HTML files. It turns R function names in code blocks and inline code, such as `sas_round()`, into links: - segue functions link to this site's `reference/` pages, with paths relative to each page, so the links work on Posit Connect and in a local preview. -- Functions from other packages link to their published documentation, for example `round()` to rdrr.io and `haven::read_sas()` to the haven site. Finding those links needs an internet connection during the render. +- Functions from other packages link to their published documentation, for example `round()` to rdrr.io and `haven::read_sas()` to the haven site. Finding those links requires an internet connection during rendering. - SAS code is not changed. -- Links to segue functions that have no reference page, such as `exact_binom_test_sas()` (marked `@keywords internal`), are removed and the text is kept. +- Links to segue functions that have no reference page, such as `exact_binom_test_sas()` (marked `@keywords internal`), are removed, and the text is kept. -Quarto runs the script for you because of `post-render` in `_quarto.yml`. It needs downlit (`install.packages("downlit")`); without it, the script prints a message and the site is left without links. To add the links to an existing `_site` folder by hand, from this folder: +Quarto runs the script for you because of `post-render` in `_quarto.yml`. It needs downlit (`install.packages("downlit")`); without it, the script prints a message, and the site is left without links. To add the links to an existing `_site` folder by hand, from this folder: ```bash Rscript _post-render.R @@ -95,30 +113,6 @@ Rscript _post-render.R When Quarto lists no new files, the script processes every HTML file in `_site`. -## Add a comparison - -1. Add the SAS results to `data-raw/prepare-data.R` and run it. -2. Copy one of the pages in `comparisons/`. Fill in the front matter: `sas`, `r`, `agreement`, `agreement-label` and `order` feed the comparison lists. -3. Add the page to the sidebar in `_quarto.yml`. - -Put SAS and R code side by side with: - -````markdown -::: {.translation} -::: {.pane .sas what="PROC FREQ"} -```sas -proc freq data=trial; ... run; -``` -::: - -::: {.pane .r what="segue"} -```{r} -bin_prop_test(...) -``` -::: -::: -```` - ## Files | Path | What it does | @@ -129,5 +123,6 @@ bin_prop_test(...) | `comparisons/_rows.ejs` | Template for the comparison lists | | `_post-render.R` | Adds downlit links to the rendered pages | | `_pkgsite/` | Templates and build script for the reference pages | +| `_coverage/build.R` | Computes segue's test coverage and badges | | `R/setup.R` | Plot theme and table helpers used by every page | | `styles.scss` | Site theme | diff --git a/_coverage/build.R b/_coverage/build.R new file mode 100644 index 0000000..1557c90 --- /dev/null +++ b/_coverage/build.R @@ -0,0 +1,195 @@ +# Computes the test coverage of segue and saves it for coverage.qmd. +# +# Run from the root of this project: +# +# Rscript _coverage/build.R # main on GitHub +# Rscript _coverage/build.R v0.1.0 # a tag or release +# Rscript _coverage/build.R 046b2ac # a commit SHA +# Rscript _coverage/build.R my-branch # a branch on GitHub +# Rscript _coverage/build.R --local ../segue # a local working tree +# +# Writes data/coverage.rds, one SVG badge per R file in assets/coverage/, +# and a badge for the whole package in assets/coverage-badge.svg. + +library(cli) +options(rlang_backtrace_on_error = "none") + +repo_url <- "https://github.com/posit-dev/segue" +clone_dir <- file.path("_packages", "segue") +badge_dir <- file.path("assets", "coverage") +# Outside badge_dir so it can't clash with the badge for R/segue.R. +overall_badge <- file.path("assets", "coverage-badge.svg") +out_file <- file.path("data", "coverage.rds") + +git <- function(...) { + res <- suppressWarnings( + system2("git", c("-C", clone_dir, ...), stdout = TRUE, stderr = TRUE) + ) + status <- attr(res, "status") + if (is.null(status)) { + status <- 0L + } + list(out = res, ok = status == 0L) +} + +args <- commandArgs(trailingOnly = TRUE) + +local_path <- NULL +if (length(args) > 0 && args[1] == "--local") { + if (length(args) < 2) { + cli_abort("{.arg --local} needs the path to a segue checkout.") + } + local_path <- normalizePath(args[2], mustWork = TRUE) + ref <- "local" +} else if (length(args) > 0) { + ref <- args[1] +} else { + ref <- "main" +} + +if (!is.null(local_path)) { + pkg <- local_path + ref_type <- "local" + sha <- NA_character_ + commit_date <- NA_character_ + local_git <- suppressWarnings(system2( + "git", + c("-C", pkg, "rev-parse", "HEAD"), + stdout = TRUE, + stderr = TRUE + )) + if (is.null(attr(local_git, "status"))) { + sha <- local_git[1] + } +} else { + cli_progress_step("Updating {.path {clone_dir}}") + if (!dir.exists(clone_dir)) { + dir.create(dirname(clone_dir), showWarnings = FALSE) + system2("git", c("clone", "--quiet", repo_url, clone_dir)) + } + fetched <- git("fetch", "--quiet", "--tags", "--prune", "--force", "origin") + if (!fetched$ok) { + cli_abort(c("Can't fetch from {.url {repo_url}}.", fetched$out)) + } + + # Check the remote branch before the bare name, so a branch reflects GitHub + # rather than a stale local branch in the clone. + candidates <- c( + branch = paste0("refs/remotes/origin/", ref), + tag = paste0("refs/tags/", ref), + sha = ref + ) + sha <- NA_character_ + ref_type <- NA_character_ + for (type in names(candidates)) { + res <- git( + "rev-parse", + "--verify", + "--quiet", + paste0(candidates[[type]], "^{commit}") + ) + if (res$ok) { + sha <- res$out[1] + ref_type <- type + break + } + } + if (is.na(sha)) { + cli_abort( + "{.val {ref}} is not a branch, tag, or commit in {.url {repo_url}}." + ) + } + commit_date <- git("log", "-1", "--format=%cI", sha)$out[1] + + # Export the commit instead of checking it out, so _pkgsite/build.R keeps + # the checkout it expects. + pkg <- file.path(tempfile("segue-"), "segue") + dir.create(pkg, recursive = TRUE) + cli_progress_step("Exporting {ref_type} {.val {ref}} ({substr(sha, 1, 7)})") + status <- system(paste( + "git -C", + shQuote(clone_dir), + "archive", + sha, + "| tar -x -C", + shQuote(pkg) + )) + if (status != 0) { + cli_abort("Can't export {.val {sha}}.") + } +} + +if (!file.exists(file.path(pkg, "DESCRIPTION"))) { + cli_abort("No {.file DESCRIPTION} in {.path {pkg}}.") +} + +cli_progress_step("Installing segue's dependencies") +remotes::install_deps(pkg, dependencies = TRUE, upgrade = "never", quiet = TRUE) + +cli_progress_step("Running the tests with covr") +cov <- covr::package_coverage(pkg, quiet = TRUE) + +# One file name per element of `cov`. The rows of as.data.frame(cov) are +# sorted, so they can't be used to subset `cov`. +cov_files <- vapply( + unclass(cov), + function(x) { + getSrcFilename(x$srcref, full.names = TRUE) + }, + character(1) +) +cov_files <- file.path("R", basename(cov_files)) +files <- sort(unique(cov_files)) + +per_file <- lapply(files, function(f) { + sub_cov <- cov[cov_files == f] + counts <- covr::tally_coverage(sub_cov, by = "line") + data.frame( + file = f, + lines = nrow(counts), + covered = sum(counts$value > 0), + percent = covr::percent_coverage(sub_cov) + ) +}) +summary <- tibble::as_tibble(do.call(rbind, per_file)) + +cli_progress_step("Writing badges to {.path {badge_dir}}") +unlink(badge_dir, recursive = TRUE) +dir.create(badge_dir, recursive = TRUE) +covr::badge(cov, overall_badge, label = "coverage") +for (f in files) { + covr::badge( + cov[cov_files == f], + file.path( + badge_dir, + paste0(tools::file_path_sans_ext(basename(f)), ".svg") + ), + label = basename(f) + ) +} + +desc <- read.dcf(file.path(pkg, "DESCRIPTION"), fields = "Version") + +result <- list( + coverage = cov, + ref = ref, + ref_type = ref_type, + sha = sha, + date = commit_date, + computed = Sys.time(), + versions = c( + segue = unname(desc[1, "Version"]), + covr = as.character(packageVersion("covr")), + R = paste(R.version$major, R.version$minor, sep = ".") + ), + percent = covr::percent_coverage(cov), + summary = summary +) + +dir.create(dirname(out_file), showWarnings = FALSE) +saveRDS(result, out_file) +cli_progress_done() + +cli_alert_success( + "segue {.val {ref}}: {round(result$percent, 1)}% coverage, written to {.path {out_file}}" +) diff --git a/_quarto.yml b/_quarto.yml index 972fa80..43976a9 100644 --- a/_quarto.yml +++ b/_quarto.yml @@ -60,7 +60,9 @@ website: - text: "Methodology" href: methodology.qmd - text: "Design" - href: design.qmd + href: design.qmd + - text: "Test Coverage" + href: coverage.qmd right: - text: "segue on GitHub" href: https://github.com/posit-dev/segue diff --git a/assets/coverage-badge.svg b/assets/coverage-badge.svg new file mode 100644 index 0000000..ee56bcb --- /dev/null +++ b/assets/coverage-badge.svg @@ -0,0 +1,21 @@ + +coverage: 100% + + + + + + + + + + + + + + +coverage + +100% + + diff --git a/assets/coverage/alternative.svg b/assets/coverage/alternative.svg new file mode 100644 index 0000000..8fb5673 --- /dev/null +++ b/assets/coverage/alternative.svg @@ -0,0 +1,21 @@ + +alternative.R: 100% + + + + + + + + + + + + + + +alternative.R + +100% + + diff --git a/assets/coverage/bin_prop_test.svg b/assets/coverage/bin_prop_test.svg new file mode 100644 index 0000000..5ba36d9 --- /dev/null +++ b/assets/coverage/bin_prop_test.svg @@ -0,0 +1,21 @@ + +bin_prop_test.R: 100% + + + + + + + + + + + + + + +bin_prop_test.R + +100% + + diff --git a/assets/coverage/checks.svg b/assets/coverage/checks.svg new file mode 100644 index 0000000..8f6835d --- /dev/null +++ b/assets/coverage/checks.svg @@ -0,0 +1,21 @@ + +checks.R: 100% + + + + + + + + + + + + + + +checks.R + +100% + + diff --git a/assets/coverage/exact_binom_test_sas.svg b/assets/coverage/exact_binom_test_sas.svg new file mode 100644 index 0000000..f19f604 --- /dev/null +++ b/assets/coverage/exact_binom_test_sas.svg @@ -0,0 +1,21 @@ + +exact_binom_test_sas.R: 100% + + + + + + + + + + + + + + +exact_binom_test_sas.R + +100% + + diff --git a/assets/coverage/helpers-printing.svg b/assets/coverage/helpers-printing.svg new file mode 100644 index 0000000..7a82f49 --- /dev/null +++ b/assets/coverage/helpers-printing.svg @@ -0,0 +1,21 @@ + +helpers-printing.R: 100% + + + + + + + + + + + + + + +helpers-printing.R + +100% + + diff --git a/assets/coverage/sas-proc.svg b/assets/coverage/sas-proc.svg new file mode 100644 index 0000000..4669d5b --- /dev/null +++ b/assets/coverage/sas-proc.svg @@ -0,0 +1,21 @@ + +sas-proc.R: 100% + + + + + + + + + + + + + + +sas-proc.R + +100% + + diff --git a/assets/coverage/sas_round.svg b/assets/coverage/sas_round.svg new file mode 100644 index 0000000..339d699 --- /dev/null +++ b/assets/coverage/sas_round.svg @@ -0,0 +1,21 @@ + +sas_round.R: 100% + + + + + + + + + + + + + + +sas_round.R + +100% + + diff --git a/assets/coverage/segue.svg b/assets/coverage/segue.svg new file mode 100644 index 0000000..23d7925 --- /dev/null +++ b/assets/coverage/segue.svg @@ -0,0 +1,21 @@ + +segue.R: 100% + + + + + + + + + + + + + + +segue.R + +100% + + diff --git a/assets/coverage/translate.svg b/assets/coverage/translate.svg new file mode 100644 index 0000000..9f1068a --- /dev/null +++ b/assets/coverage/translate.svg @@ -0,0 +1,21 @@ + +translate.R: 100% + + + + + + + + + + + + + + +translate.R + +100% + + diff --git a/comparisons/bin-prop-test.qmd b/comparisons/bin-prop-test.qmd index 82f2ba0..01ec878 100644 --- a/comparisons/bin-prop-test.qmd +++ b/comparisons/bin-prop-test.qmd @@ -83,7 +83,7 @@ $$ When $p_R$ is small, $\Pr(X \le x - 1)$ is close to 1 and the subtraction loses relative precision. For example, with $n = 6$, $x = 6$, and $p_0 = 0.01$, $p_R = 10^{-12}$, and SAS's value is correct to only about four significant digits instead of the usual 15 or 16. Right tails below about $10^{-16}$ come out as exactly 0. -The results are not identical to `Proc Freq`'s to the last bit. R's +segue's results are not identical to `Proc Freq`'s to the last bit. R's `stats::pbinom()` and `Proc Freq` use different algorithms for the binomial distribution function, and their results usually differ by a few dozen units in the last place (at most a few hundred). This is random rounding error in both, not a bias in either. Over `r exact_sas_n_tests` combinations of $`r exact_sas_x_min` \le x \le n$, $`r exact_sas_n_range[1]` \le n \le `r exact_sas_n_range[2]`$, $p_0 \in \{`r paste(exact_sas_nulls, collapse = ", ")`\}$, and the three alternatives, the p-values from `exact_binom_test_sas()` are within $`r fmt_sci_tex(exact_sas_max_diff)`$ (absolute) of `Proc Freq`'s. Because of the cancellation, the agreement for small right tails is only absolute: a right tail that is 0 in one can be about $10^{-16}$ in the other. diff --git a/coverage.qmd b/coverage.qmd new file mode 100644 index 0000000..b366ddf --- /dev/null +++ b/coverage.qmd @@ -0,0 +1,91 @@ +--- +title: "Test coverage" +subtitle: "How much of segue's code its unit tests run." +resources: + - assets/coverage/*.svg +--- + +```{r} +#| label: setup +#| include: false +source("R/setup.R") + +cov <- readRDS("data/coverage.rds") +repo <- "https://github.com/posit-dev/segue" + +if (is.na(cov$sha)) { + commit <- "a local working tree" + file_url <- function(f) { + rep(NA_character_, length(f)) + } +} else { + short <- substr(cov$sha, 1, 7) + commit <- sprintf("[`%s`](%s/tree/%s)", short, repo, cov$sha) + file_url <- function(f) { + sprintf("%s/blob/%s/%s", repo, cov$sha, f) + } +} + +if (is.na(cov$date)) { + commit_date <- format(cov$computed, "%Y-%m-%d") +} else { + commit_date <- substr(cov$date, 1, 10) +} +``` + +![](assets/coverage-badge.svg){fig-alt="Coverage badge"} + +These numbers come from running segue's tests with [covr](https://covr.r-lib.org/) `r cov$versions[["covr"]]` on segue `r cov$versions[["segue"]]`, `r cov$ref_type` `r cov$ref` (commit `r commit`, `r commit_date`), using R `r cov$versions[["R"]]`. + +Overall, the tests run **`r pct(cov$percent, 1)`** of segue's lines of R code. + +## By file + +```{r} +#| label: by-file +#| echo: false +by_file <- cov$summary[order(cov$summary$percent, cov$summary$file), ] + +badges <- sprintf( + '%s', + tools::file_path_sans_ext(basename(by_file$file)), + pct(by_file$percent, 0) +) +urls <- file_url(by_file$file) +files <- ifelse( + is.na(urls), + sprintf("%s", by_file$file), + sprintf('%s', urls, by_file$file) +) + +show_table( + data.frame( + File = files, + Lines = comma(by_file$lines), + Covered = comma(by_file$covered), + Coverage = badges + ), + align = c("l", "r", "r", "l") +) +``` + +## Line by line + +Click a file to see which lines the tests run. + +```{r} +#| label: report +#| echo: false +covr::report_html(cov$coverage) +``` + +## Update these numbers + +The coverage is computed when this site is built, not read from a coverage service. To compute it for a branch, tag, or commit of segue, run this from the root of the site: + +```bash +Rscript _coverage/build.R # main +Rscript _coverage/build.R v0.1.0 # a tag, a commit SHA, or a branch +``` + +Then render this page again. diff --git a/data/coverage.rds b/data/coverage.rds new file mode 100644 index 0000000..8c167cb Binary files /dev/null and b/data/coverage.rds differ