# Companion code checker for Quarto sites and blogs # Scans posts and templates to verify companion assets are linked, included, # and published without broken references or unlinked paths in prose. # # Usage: # Rscript companion-check.R # Or from R: # source("companion-check.R") # problems <- check_companions( # root = ".", # allow = c('- "templates/**"', '- "posts/*/scripts/**"') # ) extract_markdown_links <- function(lines) { matches <- gregexpr("\\[[^\\]]*\\]\\(([^)]+)\\)", lines, perl = TRUE) reg_matches <- regmatches(lines, matches) results <- list() for (i in seq_along(lines)) { hits <- reg_matches[[i]] if (length(hits) > 0L) { raw_targets <- sub(".*\\]\\(([^)]+)\\).*", "\\1", hits) clean_targets <- vapply( raw_targets, function(tgt) { # Strip optional trailing attributes like {download="x.R"} or quotes clean <- sub("\\{.*$", "", tgt) trimws(clean) }, character(1), USE.NAMES = FALSE ) results[[length(results) + 1L]] <- data.frame( line = rep(i, length(clean_targets)), target = clean_targets, stringsAsFactors = FALSE ) } } if (length(results) == 0L) { return(data.frame( line = integer(0), target = character(0), stringsAsFactors = FALSE )) } do.call(rbind, results) } extract_includes <- function(lines) { # Match {{< include ... >}} only when not preceded by { (ignoring escaped {{{< ... >}}}) matches <- gregexpr( "(?]+)\\s*>\\}\\}", lines, perl = TRUE ) reg_matches <- regmatches(lines, matches) results <- list() for (i in seq_along(lines)) { hits <- reg_matches[[i]] if (length(hits) > 0L) { targets <- sub(".*include\\s+([^ >]+).*", "\\1", hits) results[[length(results) + 1L]] <- data.frame( line = rep(i, length(targets)), target = trimws(targets), stringsAsFactors = FALSE ) } } if (length(results) == 0L) { return(data.frame( line = integer(0), target = character(0), stringsAsFactors = FALSE )) } do.call(rbind, results) } check_companions <- function(root = ".", allow = character()) { root <- normalizePath(root, mustWork = TRUE) posts_dir <- file.path(root, "posts") templates_dir <- file.path(root, "templates") problems <- list() add_problem <- function(file, line, rule, message) { norm_file <- normalizePath(file, mustWork = FALSE) rel_file <- if (startsWith(norm_file, paste0(root, "/"))) { substring(norm_file, nchar(root) + 2L) } else { norm_file } problems[[length(problems) + 1L]] <<- data.frame( file = rel_file, line = as.integer(line), rule = rule, message = message, stringsAsFactors = FALSE ) } # 1. Discover all posts post_qmds <- character(0) if (dir.exists(posts_dir)) { candidate_dirs <- list.dirs(posts_dir, recursive = FALSE) candidate_indices <- file.path(candidate_dirs, "index.qmd") post_qmds <- candidate_indices[file.exists(candidate_indices)] } # 2. Discover all companion scripts all_scripts <- character(0) if (dir.exists(posts_dir)) { all_post_files <- list.files(posts_dir, recursive = TRUE, full.names = TRUE) all_scripts <- all_post_files[grepl("/scripts/[^/]+$", all_post_files)] } # 3. Discover all templates all_templates <- character(0) if (dir.exists(templates_dir)) { all_templates <- list.files( templates_dir, recursive = TRUE, full.names = TRUE ) } # Track linked templates across all posts linked_template_paths <- character(0) # Check each post for (qmd in post_qmds) { lines <- readLines(qmd, warn = FALSE) checked_lines <- lines checked_lines[trimws(lines) %in% allow] <- "" link_info <- extract_markdown_links(checked_lines) include_info <- extract_includes(checked_lines) # Validate Markdown links pointing to scripts or templates companion_links <- link_info[ grepl( "^(scripts/|templates/|\\.\\./\\.\\./templates/)", link_info$target ), ] for (j in seq_len(nrow(companion_links))) { tgt <- companion_links$target[j] line_num <- companion_links$line[j] full_path <- normalizePath(file.path(dirname(qmd), tgt), mustWork = FALSE) if (!file.exists(full_path)) { add_problem( qmd, line_num, "broken_link", sprintf("Markdown link target '%s' does not exist on disk", tgt) ) } else if ( startsWith( full_path, paste0(normalizePath(templates_dir, mustWork = FALSE), "/") ) ) { linked_template_paths <- c(linked_template_paths, full_path) } } # Validate include shortcodes for (j in seq_len(nrow(include_info))) { inc <- include_info$target[j] line_num <- include_info$line[j] full_inc <- normalizePath(file.path(dirname(qmd), inc), mustWork = FALSE) if (!file.exists(full_inc)) { add_problem( qmd, line_num, "missing_include_target", sprintf("Include target '%s' does not exist on disk", inc) ) } } # Verify script linkage and companion code sections for this post's scripts post_scripts <- all_scripts[dirname(dirname(all_scripts)) == dirname(qmd)] has_companion_section <- any(lines == "## Companion code") if (length(post_scripts) > 0L && !has_companion_section) { add_problem( qmd, 1L, "missing_section", "Post contains companion scripts but has no '## Companion code' section" ) } for (s in post_scripts) { script_file <- basename(s) rel_script_link <- file.path("scripts", script_file) # Check script is linked if (!rel_script_link %in% link_info$target) { add_problem( qmd, 1L, "unlinked_script", sprintf( "Companion script '%s' is not linked in %s", rel_script_link, basename(qmd) ) ) } # Check script is included expected_include <- file.path("scripts", script_file) if (!expected_include %in% include_info$target) { add_problem( qmd, 1L, "missing_include", sprintf( "Companion script '%s' is not embedded with {{< include %s >}}", rel_script_link, rel_script_link ) ) } } # Check for unlinked prose paths path_pattern <- "(?:^|[^a-zA-Z0-9_.-])(?:scripts/|templates/|\\.\\./\\.\\./templates/)" # A fence closes only on a bare run of at least as many backticks as # opened it, so a ```` fence can show a ``` example inside it. fence_len <- 0L for (i in seq_along(lines)) { line <- lines[i] ticks <- nchar(sub("^(`*).*$", "\\1", line)) if (ticks >= 3L) { if (fence_len == 0L) { fence_len <- ticks next } if (ticks >= fence_len && grepl("^`+\\s*$", line)) { fence_len <- 0L next } } in_fence <- fence_len > 0L if (trimws(line) %in% allow) { next } # Full URLs in hosting examples are not repository-relative paths. path_text <- gsub("https?://[^[:space:]`\"<>]+", "", line, perl = TRUE) if (in_fence) { if (grepl(path_pattern, path_text, perl = TRUE)) { if (!grepl("^\\s*\\{\\{<\\s*include\\s+\\S+\\s*>\\}\\}\\s*$", line)) { add_problem( qmd, i, "forbidden_code_path", sprintf( "Forbidden companion path inside code block: %s", trimws(line) ) ) } } } else { stripped <- gsub("\\[[^\\]]*\\]\\([^)]+\\)", "", path_text, perl = TRUE) if (grepl(path_pattern, stripped, perl = TRUE)) { add_problem( qmd, i, "unlinked_prose", sprintf("Unlinked companion path in prose: %s", trimws(line)) ) } } } } # Check for orphaned template files for (tmpl in all_templates) { tmpl_norm <- normalizePath(tmpl, mustWork = FALSE) if (!tmpl_norm %in% linked_template_paths) { rel_tmpl <- if (startsWith(tmpl_norm, paste0(root, "/"))) { substring(tmpl_norm, nchar(root) + 2L) } else { tmpl_norm } add_problem( tmpl, 1L, "unlinked_template", sprintf("Template file '%s' is not linked from any post", rel_tmpl) ) } } if (length(problems) == 0L) { return(data.frame( file = character(0), line = integer(0), rule = character(0), message = character(0), stringsAsFactors = FALSE )) } do.call(rbind, problems) } # Standalone demo: builds a mock site in tempdir(), seeds issues, and prints report if (sys.nframe() == 0L) { demo_root <- file.path(tempdir(), paste0("companion-demo-", Sys.getpid())) dir.create( file.path(demo_root, "posts", "analysis-demo", "scripts"), recursive = TRUE ) dir.create(file.path(demo_root, "templates"), recursive = TRUE) # Create mock template tmpl_file <- file.path(demo_root, "templates", "pipeline.yml") writeLines("name: pipeline", tmpl_file) # Create mock script script_file <- file.path( demo_root, "posts", "analysis-demo", "scripts", "demo.R" ) writeLines(c("# Demo script", "message('Hello from demo!')"), script_file) # Create mock post with deliberate defects: # 1. Unlinked script (script exists, but never linked or included) # 2. Broken link to non-existent script # 3. Unlinked prose path # 4. Missing ## Companion code section post_file <- file.path(demo_root, "posts", "analysis-demo", "index.qmd") writeLines( c( "---", "title: 'Mock Analysis'", "---", "", "This post discusses scripts/demo.R in prose without linking it.", "", "Check out [broken file](scripts/missing.R).", "" ), post_file ) cat("Running companion check on mock Quarto site with planted defects...\n") report <- check_companions(demo_root) if (nrow(report) > 0L) { cat(sprintf("Identified %d companion code issues:\n\n", nrow(report))) for (k in seq_len(nrow(report))) { cat(sprintf( "- [%s] %s:%d - %s\n", report$rule[k], report$file[k], report$line[k], report$message[k] )) } } else { cat("All companion checks passed cleanly.\n") } unlink(demo_root, recursive = TRUE) }