check_modules_stay_under_500_lines

Roc

It also imports Text from the shared Roc library.

roc_platform/examples/check_modules_stay_under_500_lines.roc, 219 lines

## cookbook/roc/check_modules_stay_under_500_lines.shale, ported to Roc on Shale's platform:
## each Roc module held to a size, 500 lines at most, the whole file
## counted. Its header says the rules; this port keeps its arguments, its
## output and its stops, and leaves out `self_test` (the original's plants
## stay its own).
##
##   shale roc_platform/run.shale script=roc_platform/examples/check_modules_stay_under_500_lines.roc glob=app/**/*.roc
##
## The arguments: `glob` (commas between several, `**/*.roc` by default),
## `tests` (`*Spec.roc,test/`), `exempt` (an exemptions file, `path --
## reason` a line), `limit` (500) and `all` (`all=1` lists every module).
## budget: steps=50000000 reads=100000
app [main!] { lib: "../../cookbook/roc/lib/main.roc", pf: platform "../platform/main.roc" }

import pf.Shale
import lib.Text

main! : {} => {}
main! = |{}| {
	limit_text = Shale.arg!("limit", "500")
	limit = match U64.from_str(limit_text) {
		Ok(n) => n
		Err(_) => {
			Shale.fail!("check_modules_stay_under_500_lines: limit=${limit_text} is no number")
			0
		}
	}
	opts = {
		glob: Shale.arg!("glob", "**/*.roc"),
		tests: Shale.arg!("tests", "*Spec.roc,test/"),
		exempt: Shale.arg!("exempt", ""),
		limit,
	}
	all = Shale.arg!("all", "") == "1"
	r = module_sizes!(opts)
	if all {
		for l in r.listing {
			Shale.print!(l)
		}
	}
	print_findings!(r.summary, r.found)
	if !(List.is_empty(r.found)) {
		Shale.fail!(r.summary)
	}
}

## The summary, each finding, then the summary again (cookbook/findings.shale).
print_findings! : Str, List(Str) => {}
print_findings! = |summary, found| {
	Shale.print!(summary)
	if !(List.is_empty(found)) {
		for l in found {
			Shale.print!(l)
		}
		Shale.print!(summary)
	}
}

comma_items : Str -> List(Str)
comma_items = |s|
	Str.split_on(s, ",")
		.map(Str.trim)
		.keep_if(|x| !(Str.is_empty(x)))

## Whether `path` is in one of the test roots: a folder anywhere in it (`x/`),
## a file name's ending (`*X`), or a whole file name.
in_test_root : Str, List(Str) -> Bool
in_test_root = |path, roots| {
	base = basename(path)
	List.any(
		roots,
		|r|
			if Str.ends_with(r, "/") {
				Str.starts_with(path, r) or Str.contains(path, "/${r}") or Str.contains(path, ":${r}")
			} else if Str.starts_with(r, "*") {
				Str.ends_with(base, Str.drop_prefix(r, "*"))
			} else {
				base == r
			},
	)
}

basename : Str -> Str
basename = |path|
	match List.last(Str.split_on(path, "/")) {
		Ok(b) => b
		Err(_) => path
	}

Exemption : { path : Str, reason : Str }

## The exemptions, each `path -- reason`; a malformed line, a missing path or
## one given twice stops the run.
exemptions_of! : Str => List(Exemption)
exemptions_of! = |file| {
	if file == "" {
		return []
	}
	text = match Shale.read!(file) {
		Found(t) => t
		Missing => {
			Shale.fail!("check_modules_stay_under_500_lines: no exemptions file ${file}")
			""
		}
	}
	var $out = []
	var $number = 0
	for raw in lines(text) {
		$number = $number + 1
		l = Str.trim(raw)
		if l != "" and !(Str.starts_with(l, "#")) {
			place = "${file}:${U64.to_str($number)}: "
			match Str.split_first(l, " -- ") {
				Ok({ before, after }) => {
					reason = Str.trim(after)
					path = Str.trim(before)
					if reason == "" {
						Shale.fail!("check_modules_stay_under_500_lines: ${place}expected `path -- reason`, got `${l}`")
					}
					if !(Shale.exists!(path)) {
						Shale.fail!("check_modules_stay_under_500_lines: ${place}`${path}` is no file")
					}
					if List.any($out, |e| e.path == path) {
						Shale.fail!("check_modules_stay_under_500_lines: ${place}`${path}` is exempted twice")
					}
					$out = $out.append({ path, reason })
				}
				Err(_) => Shale.fail!("check_modules_stay_under_500_lines: ${place}expected `path -- reason`, got `${l}`")
			}
		}
	}
	$out
}

## A text's lines, as Shale's `lines` splits it: a last newline ends a line,
## it does not begin one.
lines : Str -> List(Str)
lines = |text| {
	parts = Str.split_on(text, "\n")
	if Str.ends_with(text, "\n") {
		List.sublist(parts, { start: 0, len: List.len(parts) - 1 })
	} else {
		parts
	}
}

## A file's lines as Shale's `count_lines` counts them: the newlines, and a
## last line that has none.
count_lines : Str -> U64
count_lines = |text| {
	bytes = Str.to_utf8(text)
	newlines = List.count_if(bytes, |b| b == 10)
	match List.last(bytes) {
		Ok(10) => newlines
		Ok(_) => newlines + 1
		Err(_) => 0
	}
}

## The paths the globs name, each once, sorted, build output left out.
module_paths! : Str => List(Str)
module_paths! = |globs| {
	var $seen = []
	for g in comma_items(globs) {
		for p in Shale.glob!(g) {
			if !(Str.contains(p, "zig-out/")) and !(Str.contains(p, "node_modules/")) and !(List.contains($seen, p)) {
				$seen = $seen.append(p)
			}
		}
	}
	Text.sort_bytewise($seen)
}

module_sizes! : { glob : Str, tests : Str, exempt : Str, limit : U64 } => { summary : Str, found : List(Str), listing : List(Str) }
module_sizes! = |opts| {
	exemptions = exemptions_of!(opts.exempt)
	roots = comma_items(opts.tests)
	limit = opts.limit
	limit_s = U64.to_str(limit)
	var $found = []
	var $listing = []
	var $modules = 0
	var $tests = 0
	var $over = 0
	var $exempt = 0
	var $unneeded = 0
	for path in module_paths!(opts.glob) {
		n = match Shale.read!(path) {
			Found(text) => count_lines(text)
			Missing => 0
		}
		n_s = U64.to_str(n)
		if in_test_root(path, roots) {
			$tests = $tests + 1
			$listing = $listing.append("${path}: ${n_s} lines, a test root's, no limit")
		} else {
			$modules = $modules + 1
			var $note = ""
			match List.find_first(exemptions, |e| e.path == path) {
				Ok(e) => {
					$exempt = $exempt + 1
					$note = " (exempt: ${e.reason})"
					if n <= limit {
						$unneeded = $unneeded + 1
						$found = $found.append("${path}: unneeded_exemption: ${n_s} lines (limit ${limit_s}) needs no exemption")
					}
				}
				Err(_) =>
					if n > limit {
						$over = $over + 1
						$found = $found.append("${path}: module_size: ${n_s} lines (limit ${limit_s})")
					}
			}
			$listing = $listing.append("${path}: ${n_s} lines${$note}")
		}
	}
	summary = "check_modules_stay_under_500_lines (Roc): ${U64.to_str($modules)} modules, ${U64.to_str($tests)} test files left out; module_size ${U64.to_str($over)} over ${limit_s} lines, ${U64.to_str($exempt)} exempt, unneeded_exemption ${U64.to_str($unneeded)}"
	{ summary, found: $found, listing: $listing }
}

Shale original

cookbook/roc/check_module_size.shale, 206 lines, at 9349d37b

The libraries it loads: cookbook/findings.shale (21 lines).

-- This recipe holds each Roc module to a size: 500 lines is our most, the
-- whole file counted, its expects, blank lines and comments included.
-- Someone composing a program from ours should be able to take a module
-- whole, and a module big enough that they would take half of it is the
-- smell. A small module may keep its expects inside it, one-stop shopping;
-- a module with extensive tests moves them to a `*Spec.roc` beside it.
--
--   cd <repo> && shale <shale>/cookbook/roc/check_module_size.shale glob='app/**/*.roc'
--   cd <repo> && shale <shale>/cookbook/roc/check_module_size.shale tests='*Spec.roc,gates/'
--   cd <repo> && shale <shale>/cookbook/roc/check_module_size.shale exempt=tools/module_size.txt all=1
--   cd <shale> && shale cookbook:roc/check_module_size.shale self_test=1
--
-- The arguments:
--   glob       the files to read, several separated by commas, `**/*.roc` by
--              default; a path holding `zig-out/` or `node_modules/` is left out;
--   tests      the project's test roots, separated by commas, `*Spec.roc,test/`
--              by default: an entry ending in `/` is a folder anywhere in a
--              path, `*X` a file name ending in `X`, anything else a whole
--              file name;
--   exempt     the project's exemptions file, below;
--   limit      the most lines a module may have, 500 by default;
--   all        with `all=1`, each module's count too;
--   self_test  with `self_test=1`, check the plants in
--              `cookbook/roc/plants/check_module_size/` (run from the shale
--              checkout's root).
--
-- Tests have no limit (Steve, 2026-11-19), so a file of a test root is
-- left out of the check by rule, not by an exemption line: a Spec is where a
-- module's extensive tests go once they would crowd it, and what someone
-- takes whole is the module, not its tests. A module's own expects count,
-- since they are part of what is taken.
--
-- The exemptions file names the modules that may be bigger, one `path --
-- reason` a line, the path as this recipe prints it (from the root the run
-- starts at). A blank line or one starting with `#` is skipped. A line with
-- no reason, a path that isn't there, or a path given twice stops the run,
-- and an exempt module now within the limit is a finding. Exemptions are
-- rare: a module that properly shows the workhorse pattern.
--
-- The findings, between two copies of the summary (cookbook/findings.shale):
--   path: module_size: N lines (limit L)
--   path: unneeded_exemption: N lines (limit L) needs no exemption
-- The run fails on any finding.
-- budget: steps=50000000 reads=100000

const SELF_TEST = arg("self_test", "") == "1"
const GLOB = arg("glob", "**/*.roc")
const TESTS = arg("tests", "*Spec.roc,test/")
const EXEMPT_FILE = arg("exempt", "")
const LIMIT = arg("limit", 500)
const ALL = arg("all", "") == "1"
const PLANTS = "cookbook/roc/plants/check_module_size/"
use("cookbook:findings.shale")

function comma_items(s)
  local out = {}
  for x in split(s, ",") do
    if trim(x) ~= "" then push(out, trim(x)) end
  end
  return out
end

-- Whether `path` is in one of the test roots `roots`, as the header says.
function in_test_root(path, roots)
  local base = basename(path)
  for r in roots do
    if ends_with(r, "/") then
      if starts_with(path, r) or contains(path, "/" .. r) or contains(path, ":" .. r) then return true end
    elseif starts_with(r, "*") then
      if ends_with(base, sub(r, 2)) then return true end
    elseif base == r then
      return true
    end
  end
  return false
end

-- The exemptions by path, each `{path, reason, line}`.
function exemptions_of(file)
  local by_path = {}
  if file == "" then return by_path end
  if not exists(file) then fail("check_module_size: no exemptions file " .. file) end
  local number = 0
  for raw in lines(read(file)) do
    number = number + 1
    local l = trim(raw)
    if l ~= "" and not starts_with(l, "#") then
      local at = find(l, " -- ")
      local where = file .. ":" .. number .. ": "
      if at == nil or trim(sub(l, at + 4)) == "" then fail("check_module_size: " .. where .. "expected `path -- reason`, got `" .. l .. "`") end
      local path = trim(sub(l, 1, at - 1))
      if not exists(path) then fail("check_module_size: " .. where .. "`" .. path .. "` is no file") end
      if has_key(by_path, path) then fail("check_module_size: " .. where .. "`" .. path .. "` is exempted twice") end
      by_path[path] = {path = path, reason = trim(sub(l, at + 4)), line = number}
    end
  end
  return by_path
end

-- The paths `globs` names, each once, sorted, build output left out.
function module_paths(globs)
  local seen = {}
  for g in comma_items(globs) do
    for p in glob(g) do
      if not contains(p, "zig-out/") and not contains(p, "node_modules/") then seen[p] = true end
    end
  end
  local out = keys(seen)
  sort(out)
  return out
end

-- The whole check, as `{summary, found, listing}`.
function module_sizes(opts)
  local exemptions = exemptions_of(opts.exempt)
  local roots = comma_items(opts.tests)
  local limit = opts.limit
  local found = {}
  local listing = {}
  local counts = {modules = 0, tests = 0, over = 0, exempt = 0, unneeded = 0}
  for path in module_paths(opts.glob) do
    local n = count_lines(path)
    if in_test_root(path, roots) then
      counts.tests = counts.tests + 1
      push(listing, path .. ": " .. n .. " lines, a test root's, no limit")
    else
      counts.modules = counts.modules + 1
      local exemption = get(exemptions, path)
      local note = ""
      if exemption ~= nil then
        counts.exempt = counts.exempt + 1
        note = " (exempt: " .. exemption.reason .. ")"
        if n <= limit then
          counts.unneeded = counts.unneeded + 1
          push(found, path .. ": unneeded_exemption: " .. n .. " lines (limit " .. limit .. ") needs no exemption")
        end
      elseif n > limit then
        counts.over = counts.over + 1
        push(found, path .. ": module_size: " .. n .. " lines (limit " .. limit .. ")")
      end
      push(listing, path .. ": " .. n .. " lines" .. note)
    end
  end
  local summary = "check_module_size (Roc): " .. counts.modules .. " modules, " .. counts.tests .. " test files left out; module_size " .. counts.over .. " over " .. limit .. " lines, " .. counts.exempt .. " exempt, unneeded_exemption " .. counts.unneeded
  return {summary = summary, found = found, listing = listing}
end

-- One self-test row: `{name, opts, found, says, stops}`. `found` is how many
-- findings it must give; `says` literals its output must hold, or its stop
-- with `stops`.
function self_test_row(row)
  local opts = {glob = PLANTS .. "*.roc", tests = "*Spec.roc,test/", exempt = "", limit = 20}
  for k in keys(get(row, "opts", {})) do opts[k] = row.opts[k] end
  local r = attempt(module_sizes, opts)
  local faults = {}
  local said = ""
  if get(row, "stops", false) then
    if r.ok then push(faults, "it didn't stop") else said = r.error end
  elseif not r.ok then
    push(faults, "it stopped: " .. r.error)
  else
    said = r.value.summary .. "\n" .. join(r.value.found, "\n") .. "\n" .. join(r.value.listing, "\n")
    if #r.value.found ~= get(row, "found", 0) then push(faults, #r.value.found .. " findings, not " .. get(row, "found", 0)) end
  end
  for literal in get(row, "says", {}) do
    if not contains(said, literal) then push(faults, "it lacks `" .. literal .. "`") end
  end
  print((#faults == 0 and "ok   " or "FAIL ") .. row.name .. (#faults == 0 and "" or ": " .. join(faults, "; ")))
  if #faults > 0 then print(said) end
  return #faults
end

function self_test()
  local at = PLANTS
  local rows = {
    {name = "a module one line over the limit is caught, one at it left alone", found = 1, says = {at .. "Over.roc: module_size: 21 lines (limit 20)", at .. "Under.roc: 20 lines"}},
    {name = "a Spec over the limit is a test root's, with no limit", found = 1, says = {at .. "OverSpec.roc: 22 lines, a test root's, no limit", "1 test files left out"}},
    {name = "an exempt module is left alone", opts = {exempt = at .. "exempt.txt"}, found = 0, says = {at .. "Over.roc: 21 lines (exempt: a plant past the limit on purpose)"}},
    {name = "an exemption of a module within the limit is a finding", opts = {exempt = at .. "exempt_unneeded.txt"}, found = 1, says = {at .. "Under.roc: unneeded_exemption: 20 lines (limit 20) needs no exemption"}},
    {name = "an exemption with no reason stops the run", opts = {exempt = at .. "exempt_no_reason.txt"}, stops = true, says = {"exempt_no_reason.txt:1: expected `path -- reason`"}},
    {name = "an exemption of a file that isn't there stops the run", opts = {exempt = at .. "exempt_missing.txt"}, stops = true, says = {"Gone.roc` is no file"}},
  }
  local wrong = 0
  for row in rows do wrong = wrong + self_test_row(row) end
  if wrong > 0 then fail("check_module_size self_test: " .. wrong .. " wrong") end
  print("check_module_size self_test: PASS (" .. #rows .. " rows)")
  return nil
end

function run_check()
  local r = module_sizes({glob = GLOB, tests = TESTS, exempt = EXEMPT_FILE, limit = LIMIT})
  if ALL then
    for l in r.listing do print(l) end
  end
  print_findings(r.summary, r.found)
  return r
end

-- This `fail` stands at the top level so the summary is the last line a
-- caller reads: a stop inside a function prints the calls after it.
if SELF_TEST then
  self_test()
else
  local r = run_check()
  if #r.found > 0 then fail(r.summary) end
end