wrap_long_lines_with_trailing_commas

Roc

It also imports Bytes, Stacking, Text from the shared Roc library.

cookbook/roc/wrap_long_lines_with_trailing_commas/wrap_long_lines_with_trailing_commas.roc, 158 lines

## wrap_long_lines_with_trailing_commas, in Roc on Shale's platform (roc_platform/README.md): long
## Roc lines shortened, and with `tokens=N` groups laid out by the stacking
## rule, by trailing commas that `roc fmt` reads. Its launcher,
## cookbook/roc/wrap_long_lines_with_trailing_commas.shale, is how it is run, and its header says
## the rule, the rewrite and the list it prints. check_goldens.shale, beside
## this, holds its output and the files it rewrites to its goldens.
##
##   cd <repo> && shale cookbook:roc/wrap_long_lines_with_trailing_commas.shale dir=roc width=100
##   cd <repo> && shale cookbook:roc/wrap_long_lines_with_trailing_commas.shale dir=app,platform tokens=6
##   shale cookbook:roc/wrap_long_lines_with_trailing_commas.shale self_test=1
##
## The arguments: `dir` (`roc`; several, comma-separated), `width` (100),
## `tokens` (0, wide lines alone), `write` (`write=0` reports and writes
## nothing), `self_test` and `work_base`, the folder the work copies go in,
## which the launcher gives.
##
## This root reads the arguments, rewrites each folder (Rewrite) and prints
## the lines left wide (WideLines); SelfTest is the self-test. Groups,
## Stacking, Packed and Bytes are the cookbook's Roc library,
## cookbook/roc/lib/, the one home of the stacking rule.
## budget: steps=1000000000 read_bytes=2000000000 arena_bytes=2000000000 output_bytes=4000000 changes=5000 roc_cpu_ms=600000
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }

import pf.Shale
import lib.Stacking
import lib.Text
import Rewrite
import SelfTest
import WideLines

main! : {} => {}
main! = |{}| {
	self_test = Shale.arg!("self_test", "") == "1"
	work_base = Shale.arg!("work_base", "scratch:")
	dirs_given = Shale.arg!("dir", "roc")
	width = integer_of!("width", Shale.arg!("width", "100"))
	tokens = if self_test {
		Stacking.stack_tokens
	} else {
		integer_of!("tokens", Shale.arg!("tokens", "0"))
	}
	write_given = Shale.arg!("write", "1")
	if write_given != "0" and write_given != "1" {
		Shale.fail!("wrap_long_lines_with_trailing_commas: write=${write_given}: write must be 1 (the default) or 0")
	}
	write = self_test or write_given == "1"
	roc = Rewrite.roc_bin!(self_test)
	settings = { rule: { tokens, width }, roc, work_base }
	if self_test {
		SelfTest.run!(settings)
	} else {
		var $report = WideLines.fresh
		for dir in dirs_of!(dirs_given) {
			work = Rewrite.work_of!(dir, { self_test: Bool.False, work_base })
			done = match Rewrite.rewrite_in_work!(dir, { work, settings }) {
				Ok(finished) => finished
				Err(StillChanging(touched)) => {
					Shale.fail!(Rewrite.still_changing(touched))
					{ work, paths: [] }
				}
			}
			at = if write {
				Rewrite.write_back!(dir, done)
				dir
			} else {
				done.work
			}
			$report = WideLines.report_wide_lines!($report, { dir, at, paths: done.paths, width })
			Shale.remove_tree!(done.work)
		}
		remove_work_base!(work_base)
		report = $report
		said = if write {
			""
		} else {
			"report, nothing written: "
		}
		print_findings!("${said}${WideLines.summary(report, width)}", report.long)
		fail_if_refused!(report.refused)
	}
	if self_test {
		remove_work_base!(work_base)
	}
}

## The whole number an argument gives; another value stops the run, as
## Shale's `arg` does for an integer default. (Each `Shale.arg!` names its
## argument as a literal, so the launcher's check of the values finds it.)
integer_of! : Str, Str => U64
integer_of! = |name, given|
	match I64.from_str(given) {
		Ok(value) if value >= 0 => value.to_u64_wrap()
		Ok(_) => {
			Shale.fail!("wrap_long_lines_with_trailing_commas: ${name}=${given} is below 0")
			0
		}
		Err(_) => {
			Shale.fail!("`arg`: ${name}=${given} is not an integer, and its default is one")
			0
		}
	}

## The folders `dir=` names, each held to be a path and not an option.
dirs_of! : Str => List(Str)
dirs_of! = |given| {
	var $dirs = []
	for piece in given.split_on(",") {
		dir = Text.trim(piece)
		if dir.starts_with("-") {
			Shale.fail!("`wrap_long_lines_with_trailing_commas`'s `dir` is \"${dir}\": a value that starts with `-` would be one of the program's options")
		}
		if dir != "" {
			$dirs = $dirs.append(dir)
		}
	}
	if $dirs.is_empty() {
		Shale.fail!("wrap_long_lines_with_trailing_commas: dir= names no folder")
	}
	$dirs
}

## The work folder, when the launcher made a fresh one for want of a
## `scratch:` mount, removed once the run has finished.
remove_work_base! : Str => {}
remove_work_base! = |work_base| {
	if work_base != "scratch:" {
		Shale.remove_tree!(work_base)
	}
}

## The summary, each line listed, then the summary again
## (cookbook/findings.shale): the first copy survives a cut output, and a
## gate reads the last line.
print_findings! : Str, List(Str) => {}
print_findings! = |summary, listed| {
	Shale.print!(summary)
	if !(listed.is_empty()) {
		for line in listed {
			Shale.print!(line)
		}
		Shale.print!(summary)
	}
}

## The files Roc's parser refused, named, then a stop
## (cookbook/roc/parsed.shale's `fail_if_refused`); nothing when it refused
## none.
fail_if_refused! : List(Str) => {}
fail_if_refused! = |refused| {
	if !(refused.is_empty()) {
		for refusal in refused {
			Shale.print!("refused: ${refusal}")
		}
		refusals = "roc-ast refused ${refused.len().to_str()} files (named above)"
		why = "which have no tree to judge; every other file was judged"
		Shale.fail!("wrap_long_lines_with_trailing_commas: ${refusals}, ${why}")
	}
}

cookbook/roc/wrap_long_lines_with_trailing_commas/Rewrite.roc, 276 lines

## The rewrite of a folder: its .roc files copied to a work copy, then pass
## after pass, each a trailing comma given to each line's group that should
## stack and taken from each stacked group that should sit on one line, with
## `roc fmt` run on the work copy after each, until a pass changes nothing.
## The changed files are written back only once the rewrite has finished, so
## a rewrite that never settles leaves the folder as it was. The rule and its
## pieces are the cookbook's Roc library's Stacking; the Roc is the tree's
## own (cookbook/roc/pinned.shale), run by its OS path.
import pf.Shale
import lib.Bytes
import lib.Stacking
import lib.Text

Rewrite := [].{

	## What a rewrite runs by: the stacking rule (`tokens` 0 wraps wide lines
	## alone), the Roc's OS path, and the folder the work copies go in.
	Settings : { rule : Stacking.Rule, roc : Str, work_base : Str }

	## A finished rewrite: the work copy that holds it, and the folder's .roc
	## files, each as its path inside the folder.
	Done : { work : Str, paths : List(Str) }

	## The most passes a rewrite makes.
	max_passes : U64
	max_passes = 8

	## The work copy of folder `dir`: the self-test's is a name of its own,
	## any other's is named for the folder's OS path.
	work_of! : Str, { self_test : Bool, work_base : Str } => Str
	work_of! = |dir, given|
		if given.self_test {
			Text.path_under(given.work_base, "roc_commas_work/self_test")
		} else {
			named = Shale.re_replace!(Shale.real!(dir), "[^A-Za-z0-9]", "_")
			Text.path_under(given.work_base, "roc_commas_work/${named}")
		}

	## The .roc files of folder `dir`, each as its path inside it.
	roc_paths_in_dir! : Str => List(Str)
	roc_paths_in_dir! = |dir| {
		cut = dir.count_utf8_bytes() + 1
		Shale.glob!("${dir}/**/*.roc").map(|path| Text.bytes_of(path, { start: cut, count: path.count_utf8_bytes() }))
	}

	## Rewrites the work copy `work` of folder `dir` until a pass changes
	## nothing, printing each pass. A rewrite still changing after
	## `max_passes` passes is `StillChanging`, with the files the last pass
	## changed, named as the folder's.
	rewrite_in_work! : Str, { work : Str, settings : Rewrite.Settings } => Try(Rewrite.Done, [StillChanging(List(Str))])
	rewrite_in_work! = |dir, at| {
		work = at.work
		rule = at.settings.rule
		paths = Rewrite.roc_paths_in_dir!(dir)
		fresh_work_copy!(dir, { work, paths })
		run_roc_fmt!(work, at.settings.roc)
		$pass : U64
		var $pass = 1
		$changed : U64
		var $changed = 1
		var $touched = []
		# A file's text when a pass last left it alone. A later pass would
		# leave the same text alone again, so it is not read for groups twice.
		var $settled = Dict.empty()
		while $changed > 0 and $pass <= Rewrite.max_passes {
			$changed = 0
			$touched = []
			for path in paths {
				text = Rewrite.read_text!("${work}/${path}")
				if $settled.get(path) != Ok(text) {
					n = rewrite_file!("${work}/${path}", { text, rule })
					if n > 0 {
						$changed = $changed + n
						$touched = $touched.append("${dir}/${path}")
					} else {
						$settled = $settled.insert(path, text)
					}
				}
			}
			Shale.print!("${dir}: pass ${$pass.to_str()}: ${$changed.to_str()} trailing commas added or taken out")
			run_roc_fmt!(work, at.settings.roc)
			$pass = $pass + 1
		}
		if $changed > 0 {
			Err(StillChanging($touched))
		} else {
			Ok({ work, paths })
		}
	}

	## The stop a rewrite still changing makes, naming the files it changed.
	still_changing : List(Str) -> Str
	still_changing = |touched|
		"wrap_long_lines_with_trailing_commas: still changing after ${Rewrite.max_passes.to_str()} passes, so no file was written: ${Str.join_with(touched, ", ")}"

	## Writes each file the rewrite changed back to folder `dir`, and says
	## how many.
	write_back! : Str, Rewrite.Done => {}
	write_back! = |dir, done| {
		var $changed = []
		for path in done.paths {
			text = Rewrite.read_text!("${done.work}/${path}")
			if text != Rewrite.read_text!("${dir}/${path}") {
				$changed = $changed.append({ path: "${dir}/${path}", text })
			}
		}
		for change in $changed {
			Shale.write!(change.path, change.text)
		}
		Shale.print!("${dir}: ${$changed.len().to_str()} files rewritten")
	}

	## A file's text; a file gone since the glob stops the run.
	read_text! : Str => Str
	read_text! = |path|
		match Shale.read!(path) {
			Found(text) => text
			Missing => {
				Shale.fail!("wrap_long_lines_with_trailing_commas: no file ${path}")
				""
			}
		}

	## Whether a line is a comment's, which no trailing comma shortens.
	is_comment : Str -> Bool
	is_comment = |text| Text.trim(text).starts_with("#")

	## The OS path of the Roc to rewrite with: in a self-test the pin every
	## recipe's self-test runs (pinned.shale's `SELF_TEST_PIN`, read there),
	## else the one the `roc-version` where the run starts names.
	roc_bin! : Bool => Str
	roc_bin! = |self_test| {
		pin = if self_test {
			self_test_pin!({})
		} else {
			if !(Shale.exists!("roc-version")) {
				Shale.fail!("wrap_long_lines_with_trailing_commas: no roc-version where the run starts: run it from the repository's root, whose roc-version pins its Roc")
			}
			Text.trim(Rewrite.read_text!("roc-version"))
		}
		roc = "tools:roc-${pin}/roc"
		if !(Shale.exists!(roc)) {
			Shale.fail!("wrap_long_lines_with_trailing_commas: no ${roc}: install Roc ${pin} into ~/tools/roc-${pin}/ (roc-apps's toolchain release carries it)")
		}
		real = Shale.real!(roc)
		said = Shale.run!({ argv: [real, "version"], keep: Whole(4000), timeout_ms: 30000, want: "" })
		if Text.trim(said.out) != "Roc compiler version ${pin}" {
			Shale.fail!("wrap_long_lines_with_trailing_commas: ${roc} says ${Text.trim(said.out)}, not Roc compiler version ${pin}")
		}
		real
	}
}

## The work copy made afresh: the folder's .roc files copied into it.
fresh_work_copy! : Str, { work : Str, paths : List(Str) } => {}
fresh_work_copy! = |dir, copy| {
	if Shale.exists!(copy.work) {
		Shale.remove_tree!(copy.work)
	}
	Shale.mkdir!(copy.work)
	for path in copy.paths {
		Shale.write!("${copy.work}/${path}", Rewrite.read_text!("${dir}/${path}"))
	}
}

## `roc fmt` run on the work copy; a file that does not parse stops the run,
## after its output.
run_roc_fmt! : Str, Str => {}
run_roc_fmt! = |work, roc| {
	result = Shale.run!({
		argv: [roc, "fmt", Shale.real!(work)],
		keep: Tail(20),
		timeout_ms: 60000,
		want: "",
	})
	if result.code != 0 {
		Shale.print!(result.out)
		Shale.fail!("roc fmt failed")
	}
}

## One pass over one file, whose text is `text`: the groups that should
## unstack lose their trailing commas, then each code line gets one for its
## group that should stack, if any; the file is written when any changed,
## and the answer is how many did.
rewrite_file! : Str, { text : Str, rule : Stacking.Rule } => U64
rewrite_file! = |path, given| {
	rule = given.rule
	source_lines = given.text.split_on("\n")
	unstacked = if rule.tokens > 0 {
		match Stacking.groups_to_unstack(source_lines, rule) {
			Ok(found) => found
			Err(NoComma(line)) => {
				Shale.fail!("groups: line ${line.to_str()} does not end in its group's trailing comma")
				[]
			}
		}
	} else {
		[]
	}
	unstacked_lines = Stacking.without_trailing_commas(source_lines, unstacked)
	reachable = Stacking.without_targets_section(unstacked_lines)
	var $lines = unstacked_lines
	$changed : U64
	var $changed = unstacked.len()
	$index : U64
	var $index = 0
	for text in unstacked_lines {
		if !(Rewrite.is_comment(text)) {
			match line_with_comma(reachable.get($index) ?? "", rule) {
				Ok(with_comma) => {
					$lines = $lines.set($index, with_comma) ?? crash "wrap_long_lines_with_trailing_commas: a line past the file's end"
					$changed = $changed + 1
				}
				Err(_) => {}
			}
		}
		$index = $index + 1
	}
	if $changed > 0 {
		Shale.write!(path, Str.join_with($lines, "\n"))
	}
	$changed
}

## The line with a trailing comma for its outermost group that should
## stack, or else, when it is wider than the width, for the group that
## stacking brings within it. A line of data gets none.
line_with_comma : Str, Stacking.Rule -> Try(Str, [NoComma])
line_with_comma = |text, rule| {
	few_commas = rule.tokens == 0 or commas_before_the_last(text) < Stacking.stack_items - 1
	if Bytes.line_width(text) <= rule.width and few_commas {
		Err(NoComma)
	} else {
		match Stacking.group_to_stack(text, rule) {
			Ok(group) => Ok(Stacking.with_trailing_comma({ line: text, group }))
			Err(_) => Err(NoComma)
		}
	}
}

## How many commas a line holds, not counting one that ends it. A group of
## `stack_items` items that opens and closes on the line holds one fewer at
## least, so a line that fits with fewer has no group to stack. Counting is
## far cheaper than reading the line's groups, and most of a data file's
## lines are like `{ x: 0.5, y: 0.25 },`.
commas_before_the_last : Str -> U64
commas_before_the_last = |text| {
	bytes = text.to_utf8()
	commas = bytes.count_if(|byte| byte == ',')
	if Bytes.trimmed_end(bytes).last() == Ok(',') {
		commas - 1
	} else {
		commas
	}
}

## pinned.shale's `SELF_TEST_PIN`, the one home of the self-tests' Roc.
self_test_pin! : {} => Str
self_test_pin! = |{}| {
	pinned = "cookbook:roc/pinned.shale"
	groups = match Shale.re_find!(
		Rewrite.read_text!(pinned),
		"\nconst SELF_TEST_PIN = \"([^\"]+)\"",
	) {
		Found(found) => found.groups
		NoMatch => []
	}
	match groups {
		[pin, ..] => pin
		[] => {
			Shale.fail!("wrap_long_lines_with_trailing_commas: no SELF_TEST_PIN in ${pinned}")
			""
		}
	}
}

cookbook/roc/wrap_long_lines_with_trailing_commas/SelfTest.roc, 171 lines

## The recipe's self-test, the Shale original's: the plants in
## cookbook/roc/plants/wrap_long_lines_with_trailing_commas/ are copied into the work folder and
## rewritten there with the rule's six tokens and the self-tests' Roc. The
## rewrite must end, each plant must come out as its `.want` file, no group
## may be left to stack or to unstack, and the lines left wide must be
## exactly `long_plants`' listed, with `wide_string_plants` wide strings and
## `data_plants` lines of data counted. Then `too_deep/too_deep.roc`, one
## group deeper than the passes reach, must stop the rewrite, naming its
## file, and be left as it was.
import pf.Shale
import lib.Stacking
import lib.Text
import Rewrite
import WideLines

SelfTest := [].{

	## The self-test, its copies and work copies under `settings.work_base`.
	run! : Rewrite.Settings => {}
	run! = |settings| {
		dir = Text.path_under(settings.work_base, "wrap_long_lines_with_trailing_commas")
		work = Rewrite.work_of!(dir, { self_test: Bool.True, work_base: settings.work_base })
		fresh_copies!(dir, plants)
		match Rewrite.rewrite_in_work!(dir, { work, settings }) {
			Ok(done) => {
				Rewrite.write_back!(dir, done)
				Shale.remove_tree!(done.work)
			}
			Err(StillChanging(touched)) => Shale.fail!(Rewrite.still_changing(touched))
		}
		$bad : U64
		var $bad = 0
		for plant in Shale.glob!("${plants}/*.roc") {
			$bad = $bad + plant_wrong!(plant, { dir, rule: settings.rule })
		}
		$bad = $bad + report_wrong!(dir, settings.rule.width)
		if $bad > 0 {
			Shale.fail!("${$bad.to_str()} checks failed")
		}
		if Shale.exists!(work) {
			Shale.fail!("wrap_long_lines_with_trailing_commas: a finished rewrite should remove its work copy, ${work}")
		}
		fresh_copies!(dir, "${plants}/too_deep")
		named = Rewrite.still_changing(["${dir}/too_deep.roc"])
		stopped = match Rewrite.rewrite_in_work!(dir, { work, settings }) {
			Ok(_) => Bool.False
			Err(StillChanging(touched)) => Rewrite.still_changing(touched) == named
		}
		if !(stopped) {
			Shale.fail!("wrap_long_lines_with_trailing_commas: too_deep.roc should stop with `${named.drop_prefix("wrap_long_lines_with_trailing_commas: ")}`")
		}
		copy = Rewrite.read_text!("${dir}/too_deep.roc")
		if copy != Rewrite.read_text!("${plants}/too_deep/too_deep.roc") {
			Shale.fail!("wrap_long_lines_with_trailing_commas: a rewrite that stops should leave too_deep.roc as it was")
		}
		Shale.print!("ok   too_deep.roc: stops naming its file, and is left as it was")
		Shale.remove_tree!(work)
		Shale.remove_tree!(dir)
		Shale.print!("PASS: the rewrite ends, every plant comes out as its .want, no group is left to stack or to unstack, the lines left wide are listed or counted, and a rewrite past its passes stops naming its file and changes none")
	}
}

## The plants, whose `*.roc` the self-test rewrites.
plants : Str
plants = "cookbook:roc/plants/wrap_long_lines_with_trailing_commas"

## The plant lines left wide with nothing to stack.
long_plants : List(Str)
long_plants = ["function_type.roc:4"]

## How many plant lines are wide only for their strings.
wide_string_plants : U64
wide_string_plants = 1

## How many plant lines are numeric data.
data_plants : U64
data_plants = 2

## The start of a verdict's line.
verdict : Bool -> Str
verdict = |ok|
	if ok {
		"ok   "
	} else {
		"FAIL "
	}

## Folder `dir` made afresh with a copy of each `*.roc` in folder `from`.
fresh_copies! : Str, Str => {}
fresh_copies! = |dir, from| {
	if Shale.exists!(dir) {
		Shale.remove_tree!(dir)
	}
	Shale.mkdir!(dir)
	for plant in Shale.glob!("${from}/*.roc") {
		Shale.write!("${dir}/${Text.basename(plant)}", Rewrite.read_text!(plant))
	}
}

## One plant's rewrite held to its `.want`, and to no group left to stack or
## to unstack, a line printed for each wrong: the answer is how many were.
plant_wrong! : Str, { dir : Str, rule : Stacking.Rule } => U64
plant_wrong! = |plant, given| {
	name = Text.basename(plant)
	want = "${plants}/${name.drop_suffix(".roc")}.want"
	got = Rewrite.read_text!("${given.dir}/${name}")
	ok = got == Rewrite.read_text!(want)
	Shale.print!("${verdict(ok)}${name}: comes out as its .want")
	$bad : U64
	var $bad = if ok {
		0
	} else {
		1
	}
	got_lines = got.split_on("\n")
	$number : U64
	var $number = 0
	for text in Stacking.without_targets_section(got_lines) {
		$number = $number + 1
		left = !(Rewrite.is_comment(text)) and Stacking.group_to_stack(text, given.rule) != Err(NoGroup)
		if left {
			Shale.print!("FAIL ${name}:${$number.to_str()}: a group left to stack: ${Text.trim(text)}")
			$bad = $bad + 1
		}
	}
	unstacked = match Stacking.groups_to_unstack(got_lines, given.rule) {
		Ok(found) => found
		Err(NoComma(line)) => {
			Shale.fail!("groups: line ${line.to_str()} does not end in its group's trailing comma")
			[]
		}
	}
	for found in unstacked {
		Shale.print!("FAIL ${name}:${found.group.line.to_str()}: a group left to unstack")
		$bad = $bad + 1
	}
	$bad
}

## The lines the rewrite left wide held to `long_plants`, and the wide
## strings and data counted, a line printed for each: the answer is how many
## were wrong.
report_wrong! : Str, U64 => U64
report_wrong! = |dir, width| {
	report = WideLines.report_wide_lines!(
		WideLines.fresh,
		{ dir, at: dir, paths: Rewrite.roc_paths_in_dir!(dir), width },
	)
	cut = dir.count_utf8_bytes() + 1
	listed = report.long.map(
		|line| {
			place = Text.before_first(line, " ")
			Text.bytes_of(place, { start: cut, count: place.count_utf8_bytes() })
		},
	)
	list_ok = Text.sort_bytewise(listed) == Text.sort_bytewise(long_plants)
	Shale.print!("${verdict(list_ok)}the list of lines left wide is ${Str.join_with(long_plants, ", ")} (${Str.join_with(report.long, "; ")})")
	counts = "${report.wide_strings.to_str()} lines wide only for their strings and ${report.data.to_str()} of numeric data"
	wanted = "want ${wide_string_plants.to_str()} and ${data_plants.to_str()} (${report.refused.len().to_str()} refused)"
	counts_ok = report.wide_strings == wide_string_plants and report.data == data_plants and report.refused.is_empty()
	Shale.print!("${verdict(counts_ok)}${counts}, counted and not listed, ${wanted}")
	$bad : U64
	var $bad = 0
	if !(list_ok) {
		$bad = $bad + 1
	}
	if !(counts_ok) {
		$bad = $bad + 1
	}
	$bad
}

cookbook/roc/wrap_long_lines_with_trailing_commas/WideLines.roc, 125 lines

## The lines a rewrite leaves wider than the width. A comment, a line wide
## only for the text of its strings (by Roc's parser, as check_and_fix_group_stacking's
## `wide string`) and a line of numeric data, which stays packed, are
## counted, as no trailing comma shortens one; any other is listed, as
## `path:line (width): nothing to stack: text`. Only a file with a wide line
## is parsed, for its strings.
import pf.Shale
import lib.Bytes
import lib.Stacking
import lib.Text
import Rewrite

WideLines := [].{

	## The lines left wide so far: those listed, the counts of the rest, and
	## why each file roc-ast refused was refused.
	Report : {
		long : List(Str),
		wide_strings : U64,
		data : U64,
		comments : U64,
		refused : List(Str),
	}

	## A report with nothing in it yet.
	fresh : WideLines.Report
	fresh = { long: [], wide_strings: 0, data: 0, comments: 0, refused: [] }

	## The report with the lines wider than `width` in the files `paths` of
	## folder `at` added, each named as folder `dir`'s.
	report_wide_lines! : WideLines.Report,
	{
		dir : Str,
		at : Str,
		paths : List(Str),
		width : U64,
	} => WideLines.Report
	report_wide_lines! = |before, given| {
		width = given.width
		is_wide = |text| Bytes.line_width(text) > width
		var $wide = []
		for path in given.paths {
			at_path = "${given.at}/${path}"
			if Rewrite.read_text!(at_path).split_on("\n").any(is_wide) {
				$wide = $wide.append(at_path)
			}
		}
		wide = $wide
		if wide.is_empty() {
			return before
		}
		var $report = before
		var $parsed = []
		for file in Shale.roc_tree!(wide) {
			if file.err == "" {
				$parsed = $parsed.append(file)
			} else if file.err.starts_with(file.path) {
				$report = { ..$report, refused: $report.refused.append(file.err) }
			} else {
				$report = { ..$report, refused: $report.refused.append("${file.path}: ${file.err}") }
			}
		}
		cut = given.at.count_utf8_bytes()
		for file in $parsed {
			source_lines = Rewrite.read_text!(file.path).split_on("\n")
			strings = match Stacking.string_columns_on_lines(file.nodes, source_lines) {
				Ok(by_line) => by_line
				Err(CrossesLine(line)) => {
					Shale.fail!("wrap_long_lines_with_trailing_commas: ${file.path}: line ${line.to_str()}: a run of string text crosses a line")
					Dict.empty()
				}
			}
			named = "${given.dir}${Text.bytes_of(file.path, { start: cut, count: file.path.count_utf8_bytes() })}"
			$number : U64
			var $number = 0
			for text in source_lines {
				$number = $number + 1
				line_width = Bytes.line_width(text)
				if line_width > width {
					$report = judged_line(
						$report,
						{
							text,
							line_width,
							string_width: strings.get($number) ?? 0,
							place: "${named}:${$number.to_str()}",
							width,
						},
					)
				}
			}
		}
		$report
	}

	## The report's counts, as its summary line says them.
	summary : WideLines.Report, U64 -> Str
	summary = |report, width| {
		listed = "${report.long.len().to_str()} code lines with nothing to stack"
		counted = "${report.wide_strings.to_str()} wide only for their strings, ${report.data.to_str()} of numeric data, ${report.comments.to_str()} comment lines"
		"still over ${width.to_str()}: ${listed}, ${counted}"
	}
}

## The report with one line wider than the width counted or listed.
judged_line : WideLines.Report,
{
	text : Str,
	line_width : U64,
	string_width : U64,
	place : Str,
	width : U64,
} -> WideLines.Report
judged_line = |report, line|
	if Rewrite.is_comment(line.text) {
		{ ..report, comments: report.comments + 1 }
	} else if line.line_width - line.string_width <= line.width {
		{ ..report, wide_strings: report.wide_strings + 1 }
	} else if Stacking.is_data_line(line.text, line.width) {
		{ ..report, data: report.data + 1 }
	} else {
		shown = Str.from_utf8_lossy(Bytes.trimmed(Bytes.span(line.text.to_utf8(), 1, 140)))
		listed = "${line.place} (${line.line_width.to_str()}): nothing to stack: ${shown}"
		{ ..report, long: report.long.append(listed) }
	}

Shale original

cookbook/roc/wrap_long_lines.shale, 405 lines, at 00559b61

The libraries it loads: cookbook/findings.shale (21 lines), cookbook/roc/pinned.shale (20 lines), cookbook/roc/groups.shale (465 lines), cookbook/roc/parsed.shale (34 lines).

-- Shorten long Roc lines by letting `roc fmt` lay them out. roc fmt never
-- wraps a line, but it puts the items of a record, list, call or lambda's
-- arguments one to a line when the last item has a trailing comma. For each
-- code line wider than `width`, this script adds that comma to the widest
-- group of two or more items whose stacking brings the line within `width`:
-- the text up to its opening bracket fits, and so does its closing bracket
-- with what follows it (groups.shale's `group_to_wrap`). A group beside the
-- wide part, as a list pattern in a `match` arm whose string makes the line
-- wide, is left alone, and so are a function type's arguments, which can't
-- take the comma. It runs roc fmt, and repeats until no line changes; a
-- folder still changing after 8 passes stops the run, naming its files. The
-- passes work on a copy of the folder's .roc files under
-- `scratch:roc_commas_work/`, and the changed files are written back only
-- once the rewrite has finished, so a run that stops, on a pass too many or
-- on a budget, leaves the folder as it was. Under a mounts file with no
-- `scratch:` mount, the copies go in a fresh hidden folder at the root
-- instead (`.wrap_long_lines.XXXXXX`, named in the output), removed when the
-- run ends; a run that stops leaves it, for `git status` to show.
--
-- Then it lists each code line still too wide, as `path:line (width): why:
-- text`, `why` being `nothing to stack`: no group whose stacking would bring
-- it within `width`. A line wide only for the text of its strings, by Roc's
-- parser (as check_stacking.shale's `wide string`), and a comment line are
-- counted, not listed, as no trailing comma shortens either; so is a line
-- of numeric data, which stays packed (below). The list is
-- printed between its counts, as cookbook/findings.shale describes. It runs
-- the Roc that the repository's roc-version file names.
--
-- With `tokens=N`, the script holds the folder to roc-style.md's stacking
-- rule, whose six tokens are `tokens=6`, whatever a line's width: a group of
-- three or more items and N or more tokens gets the trailing comma, and a
-- stacked group that should sit on one line loses it, which is how `roc fmt`
-- is asked to join it. A group and its tokens are read as check_stacking.shale reads
-- them (cookbook/roc/groups.shale), so after `tokens=6` check_stacking.shale finds no
-- group left to stack or to unstack. A line's outermost group goes first, and
-- the next pass reaches the groups inside it. A function type's arguments and
-- a row of literals are left alone, as check_stacking.shale leaves them, and so is a
-- platform header's `targets:` section, which `roc fmt` lays out by itself.
--
-- The arguments:
--   dir     the folders to rewrite, `roc` by default; several may be given,
--           separated by commas, each rewritten in turn.
--   width   the widest a line may be, 100 by default.
--   tokens  the stacking rule's tokens, as above; 0 (the default) wraps
--           wide lines alone.
--   write   with `write=0`, the rewrite runs in the work copy, the list is
--           of the lines it would leave, and no folder is written: a
--           report.
--
--   cd <repo> && shale <shale>/cookbook/roc/wrap_long_lines.shale dir=roc width=100
--   cd <repo> && shale <shale>/cookbook/roc/wrap_long_lines.shale dir=app,platform tokens=6
--   cd <repo> && shale <shale>/cookbook/roc/wrap_long_lines.shale dir=roc tokens=6 write=0
--   shale cookbook:roc/wrap_long_lines.shale self_test=1
--
-- `self_test=1` copies the plants in `cookbook/roc/plants/wrap_long_lines/` to
-- `scratch:wrap_long_lines/` (or the hidden folder above), rewrites them there with `tokens=6` and the
-- self-test's Roc, and checks that the rewrite ends, that each plant comes
-- out as its `.want` file, that no group is left to stack or to unstack, and
-- that the list holds exactly `LONG_PLANTS`' lines and counts
-- `WIDE_STRING_PLANTS` wide strings and `DATA_PLANTS` lines of data.
-- `at_the_cap.roc` nests as deep as 8 passes reach, and `too_deep/` one group
-- deeper, which has to stop the rewrite, name its file and leave it as it was.
--
-- Numeric data stays packed, as groups.shale's is_data_line and
-- is_number_data say: a number list never stacks, and nothing on a line wider
-- than `width` that holds one does. `numbers.roc` in the plants checks both
-- and that a list of names beside them still stacks.
--
-- roc-apps' canvas_apps/safari, with its 70,000-byte lines of polygon data,
-- takes about 160,000,000 steps with `tokens=6`.
--
-- budget: steps=1000000000 arena_bytes=2000000000 output_bytes=4000000 changes=5000

use("cookbook:findings.shale")
use("./pinned.shale")
use("./groups.shale")
use("./parsed.shale")
const SELF_TEST = arg("self_test", "") == "1"
const PLANTS = "cookbook:roc/plants/wrap_long_lines"

-- Where the work copies go: `scratch:` when the mounts file has it, else a
-- fresh hidden folder at the root, which the run removes when it ends.
function work_base()
  if attempt(real, "scratch:.").ok then return "scratch:" end
  local base = fresh_dir("", ".wrap_long_lines")
  print("wrap_long_lines: no `scratch:` mount, so the work copies go in " .. base .. ", removed when the run ends")
  return base
end

const WORK_BASE = work_base()
const SELF_TEST_DIR = path_under(WORK_BASE, "wrap_long_lines")
const DIRS_ARG = SELF_TEST and SELF_TEST_DIR or arg("dir", "roc")
const WIDTH = arg("width", 100)
const TOKENS = SELF_TEST and STACK_TOKENS or arg("tokens", 0)
const WRITE_ARG = arg("write", "1")
if WRITE_ARG ~= "0" and WRITE_ARG ~= "1" then fail("wrap_long_lines: write=" .. WRITE_ARG .. ": write must be 1 (the default) or 0") end
const WRITE = SELF_TEST or WRITE_ARG == "1"
const MAX_PASSES = 8
const ROC = roc_bin("wrap_long_lines", SELF_TEST)

-- The self-test's list: the plant lines left wide with nothing to stack, and
-- how many lines are wide only for their strings.
const LONG_PLANTS = {"function_type.roc:4"}
const WIDE_STRING_PLANTS = 1
const DATA_PLANTS = 2

function is_comment(line)
  return starts_with(trim(line), "#")
end

-- The folders of `dir=`, each held to be a path and not an option.
function dirs_of(text)
  local out = {}
  for d in split(text, ",") do
    local dir = trim(d)
    not_option("wrap_long_lines", "dir", dir)
    if dir ~= "" then push(out, dir) end
  end
  if #out == 0 then fail("wrap_long_lines: dir= names no folder") end
  return out
end

function roc_files(dir)
  local out = {}
  for e in walk_all(dir) do
    if e.kind == "file" and ends_with(e.path, ".roc") then push(out, e.path) end
  end
  return out
end

-- The .roc files of `dir`, each as its path inside it.
function roc_paths_in_dir(dir)
  local out = {}
  for path in roc_files(dir) do push(out, sub(path, #dir + 2)) end
  return out
end

-- The rewrite of `dir` works on a copy of its .roc files, so a run that
-- stops, on a budget or a pass too many, leaves the folder as it was.
function work_of(dir)
  if SELF_TEST then return path_under(WORK_BASE, "roc_commas_work/self_test") end
  return path_under(WORK_BASE, "roc_commas_work/" .. re_replace(real(dir), "[^A-Za-z0-9]", "_"))
end

function fresh_work_copy(dir, work, paths)
  if is_dir(work) then remove_tree(work) end
  mkdir(work)
  for p in paths do replace(work .. "/" .. p, read(dir .. "/" .. p)) end
end

-- Writes each file the rewrite changed back to the folder. It reads them all
-- first and checks that what is left of the budgets covers every write, so
-- the folder gets all of the rewrite or none of it.
function write_back(dir, work, paths)
  local changed = {}
  local bytes = 0
  for p in paths do
    local text = read(work .. "/" .. p)
    if text ~= read(dir .. "/" .. p) then
      push(changed, {path = dir .. "/" .. p, text = text})
      bytes = bytes + #text
    end
  end
  local left = budget()
  if left.changes < #changed + 1 or left.change_bytes < bytes or left.steps < 2 * bytes + 1000 * #changed + 100000 then
    fail("wrap_long_lines: too little budget left to write the " .. #changed .. " changed files, so none was written")
  end
  for c in changed do replace(c.path, c.text) end
  print(dir .. ": " .. #changed .. " files rewritten")
end

function run_roc_fmt(work)
  local r = run({ROC, "fmt", real(work)}, {timeout_ms = 60000, tail = 20})
  if r.code ~= 0 then
    print(r.out)
    fail("roc fmt failed")
  end
end

-- How many commas line `l` holds, not counting one that ends it. A group of
-- STACK_ITEMS items that opens and closes on the line holds STACK_ITEMS - 1 of
-- them at least, and a comma that ends the line is inside no such group, so a
-- line that fits with fewer has no group to stack. Counting is far cheaper
-- than reading the line's groups, and most of a data file's lines are like
-- `{ x: 0.5, y: 0.25 },`.
function commas_before_the_last(l)
  local commas = #split(l, ",") - 1
  if ends_with(trim_end(l), ",") then commas = commas - 1 end
  return commas
end

-- Line `l` with a trailing comma for its outermost group that should stack,
-- or else, when it is wider than WIDTH, for groups.shale's `group_to_wrap`.
-- nil when it gets none. A line of data, by groups.shale's is_data_line,
-- gets none.
function line_with_comma(l)
  if line_width(l) <= WIDTH and (TOKENS == 0 or commas_before_the_last(l) < STACK_ITEMS - 1) then return nil end
  local g = group_to_stack(l, TOKENS, WIDTH)
  if g == nil then return nil end
  return with_trailing_comma(l, g)
end

-- Takes the trailing comma from each group of the file at `path`, whose text
-- is `text`, that should unstack, adds one to each code line that should get
-- one, and returns how many groups and lines it changed.
function rewrite_trailing_commas(path, text)
  local ls = split(text, "\n")
  local unstacked = {}
  if TOKENS > 0 then unstacked = groups_to_unstack(ls, TOKENS, WIDTH) end
  ls = without_trailing_commas(ls, unstacked)
  local reachable = without_targets_section(ls)
  local changed = #unstacked
  for i = 1, #ls do
    if not is_comment(ls[i]) then
      local with_comma = line_with_comma(reachable[i])
      if with_comma ~= nil then
        ls[i] = with_comma
        changed = changed + 1
      end
    end
  end
  if changed > 0 then replace(path, join(ls, "\n")) end
  return changed
end

-- Rewrites commas and runs roc fmt in `dir`'s work copy until a pass changes
-- nothing. Files still changing after MAX_PASSES stop the run, since the list
-- of long lines would otherwise judge a rewrite that never finished. Returns
-- `{work, paths}`, the work copy holding the rewrite.
function rewrite_in_work(dir)
  local work = work_of(dir)
  local paths = roc_paths_in_dir(dir)
  fresh_work_copy(dir, work, paths)
  run_roc_fmt(work)
  local pass = 1
  local changed = 1
  local touched = {}
  -- A file's text when a pass last left it alone. A later pass would leave
  -- the same text alone again, so it is not read for groups a second time.
  local settled = {}
  while changed > 0 and pass <= MAX_PASSES do
    changed = 0
    touched = {}
    for p in paths do
      local text = read(work .. "/" .. p)
      if not has_key(settled, p) or settled[p] ~= text then
        local n = rewrite_trailing_commas(work .. "/" .. p, text)
        if n > 0 then
          changed = changed + n
          push(touched, dir .. "/" .. p)
        else
          settled[p] = text
        end
      end
    end
    print(dir .. ": pass " .. pass .. ": " .. changed .. " trailing commas added or taken out")
    run_roc_fmt(work)
    pass = pass + 1
  end
  if changed > 0 then fail("wrap_long_lines: still changing after " .. MAX_PASSES .. " passes, so no file was written: " .. join(touched, ", ")) end
  return {work = work, paths = paths}
end

-- Rewrites `dir` and writes it back (with WRITE).
function rewrite_dir(dir)
  local r = rewrite_in_work(dir)
  if WRITE then write_back(dir, r.work, r.paths) end
  remove_tree(r.work)
  return nil
end

-- The self-test's folder rewritten, for its `attempt`, which takes no
-- arguments.
function rewrite_self_test_dir()
  return rewrite_dir(SELF_TEST_DIR)
end

-- The lines wider than WIDTH in the files `paths` of folder `at`, named as
-- `dir`'s, added to `report`: a comment and a line wide only for its strings'
-- text are counted, any other is listed. Only a file with a wide line is
-- parsed, for its strings; a file roc-ast refuses goes in `report.refused`.
function report_wide_lines(report, dir, at, paths)
  local wide = {}
  for p in paths do
    for l in lines(read(at .. "/" .. p)) do
      if line_width(l) > WIDTH then
        push(wide, at .. "/" .. p)
        break
      end
    end
  end
  if #wide == 0 then return nil end
  local parsed = parse_roc_files(wide)
  for r in parsed.refused do push(report.refused, r) end
  for f in parsed.files do
    local ls = split(read(f.path), "\n")
    local strings = string_columns_on_lines(f.nodes, ls, "wrap_long_lines: " .. f.path)
    local named = dir .. sub(f.path, #at + 1)
    for i = 1, #ls do
      local w = line_width(ls[i])
      if w > WIDTH then
        if is_comment(ls[i]) then
          report.comments = report.comments + 1
        elseif w - get(strings, "" .. i, 0) <= WIDTH then
          report.wide_strings = report.wide_strings + 1
        elseif is_data_line(ls[i], WIDTH) then
          report.data = report.data + 1
        else
          push(report.long, named .. ":" .. i .. " (" .. w .. "): nothing to stack: " .. trim(sub(ls[i], 1, 140)))
        end
      end
    end
  end
  return nil
end

function fresh_report()
  return {long = {}, wide_strings = 0, data = 0, comments = 0, refused = {}}
end

function report_summary(report)
  return "still over " .. WIDTH .. ": " .. #report.long .. " code lines with nothing to stack, " .. report.wide_strings .. " wide only for their strings, " .. report.data .. " of numeric data, " .. report.comments .. " comment lines"
end

function fresh_copies(plants)
  if is_dir(SELF_TEST_DIR) then remove_tree(SELF_TEST_DIR) end
  mkdir(SELF_TEST_DIR)
  for p in glob(plants .. "/*.roc") do replace(SELF_TEST_DIR .. "/" .. basename(p), read(p)) end
end

function self_test()
  local dir = SELF_TEST_DIR
  fresh_copies(PLANTS)
  rewrite_dir(dir)
  local bad = 0
  for p in glob(PLANTS .. "/*.roc") do
    local name = basename(p)
    local want = PLANTS .. "/" .. sub(name, 1, #name - 4) .. ".want"
    local got = read(dir .. "/" .. name)
    local ok = got == read(want)
    print((ok and "ok   " or "FAIL ") .. name .. ": comes out as its .want")
    if not ok then bad = bad + 1 end
    local reachable = without_targets_section(split(got, "\n"))
    for n = 1, #reachable do
      local l = reachable[n]
      if not is_comment(l) and group_to_stack(l, TOKENS, WIDTH) ~= nil then
        print("FAIL " .. name .. ":" .. n .. ": a group left to stack: " .. trim(l))
        bad = bad + 1
      end
    end
    for g in groups_to_unstack(split(got, "\n"), TOKENS, WIDTH) do
      print("FAIL " .. name .. ":" .. g.line .. ": a group left to unstack")
      bad = bad + 1
    end
  end
  -- The list after the rewrite: exactly LONG_PLANTS' lines, and the wide
  -- strings counted.
  local report = fresh_report()
  report_wide_lines(report, dir, dir, roc_paths_in_dir(dir))
  local listed = {}
  for l in report.long do push(listed, sub(split(l, " ")[1], #dir + 2)) end
  local list_ok = join(sort(listed), ",") == join(sort(LONG_PLANTS), ",")
  print((list_ok and "ok   " or "FAIL ") .. "the list of lines left wide is " .. join(LONG_PLANTS, ", ") .. " (" .. join(report.long, "; ") .. ")")
  if not list_ok then bad = bad + 1 end
  local wide_ok = report.wide_strings == WIDE_STRING_PLANTS and report.data == DATA_PLANTS and #report.refused == 0
  print((wide_ok and "ok   " or "FAIL ") .. report.wide_strings .. " lines wide only for their strings and " .. report.data .. " of numeric data, counted and not listed, want " .. WIDE_STRING_PLANTS .. " and " .. DATA_PLANTS .. " (" .. #report.refused .. " refused)")
  if not wide_ok then bad = bad + 1 end
  if bad > 0 then fail(bad .. " checks failed") end
  if is_dir(work_of(dir)) then fail("wrap_long_lines: a finished rewrite should remove its work copy, " .. work_of(dir)) end
  fresh_copies(PLANTS .. "/too_deep")
  local stopped = attempt(rewrite_self_test_dir)
  local named = "still changing after " .. MAX_PASSES .. " passes, so no file was written: " .. dir .. "/too_deep.roc"
  if stopped.ok or not contains(stopped.error, named) then fail("wrap_long_lines: too_deep.roc should stop with `" .. named .. "`") end
  if read(dir .. "/too_deep.roc") ~= read(PLANTS .. "/too_deep/too_deep.roc") then fail("wrap_long_lines: a rewrite that stops should leave too_deep.roc as it was") end
  print("ok   too_deep.roc: stops naming its file, and is left as it was")
  remove_tree(work_of(dir))
  remove_tree(SELF_TEST_DIR)
  print("PASS: the rewrite ends, every plant comes out as its .want, no group is left to stack or to unstack, the lines left wide are listed or counted, and a rewrite past its passes stops naming its file and changes none")
end

-- The hidden work folder, when there is no `scratch:`, goes once the run
-- has finished.
function remove_work_base()
  if WORK_BASE ~= "scratch:" then remove_tree(WORK_BASE) end
end

if SELF_TEST then
  self_test()
  remove_work_base()
else
  local report = fresh_report()
  for dir in dirs_of(DIRS_ARG) do
    local r = rewrite_in_work(dir)
    if WRITE then
      write_back(dir, r.work, r.paths)
      report_wide_lines(report, dir, dir, r.paths)
    else
      report_wide_lines(report, dir, r.work, r.paths)
    end
    remove_tree(r.work)
  end
  remove_work_base()
  print_findings((WRITE and "" or "report, nothing written: ") .. report_summary(report), report.long)
  fail_if_refused("wrap_long_lines", report.refused)
end