tom_build_base_v2 library

tom_build_base v2 - Unified CLI framework for workspace traversal.

This library provides:

Quick Start

import 'package:tom_build_base/tom_build_base_v2.dart';

void main() async {
  await BuildBase.traverse(
    info: ProjectTraversalInfo(
      scan: '.',
      recursive: true,
      executionRoot: Directory.current.path,
    ),
    run: (ctx) async {
      print('Processing: ${ctx.name}');
      return true;
    },
  );
}

Classes

AnchorWalker
Walks up the directory tree to find "anchor" directories.
AnsiColors
ANSI color codes for terminal output.
BaseTraversalInfo
Base class for traversal configuration.
BoundaryFinding
One finding of a BoundaryReport: a broken boundary or a broken rule.
BoundaryReport
The outcome of checkContextBoundaries.
BoundedContext
One bounded context of a ContextBoundaryRules.
BuildBase
Main entry point for workspace traversal.
BuildkitFolder
Buildkit configuration nature: the project file.
BuildkitMasterFolder
Workspace root nature: the folder holds buildkit_master.yaml.
BuildOrderComputer
Computes build order for Dart projects using topological sort.
BuildOrderCycle
One dependency cycle: a strongly connected group of projects.
BuildOrderEdge
A dependency of one project on another, as the build order sees it.
BuildOrderResult
Outcome of a build-order computation.
BuildRunnerFolder
Build runner (build.yaml) nature.
CallbackExecutor
Callback-based command executor.
CFolder
C project nature: a native build file (NativeBuildSystem) with C sources (.c) and no C++ sources.
CliArgParser
Parser for command-line arguments.
CliArgs
Parsed command-line arguments.
CommandContext
Context provided to commands during execution.
CommandDefinition
Definition of a command within a multi-command tool.
CommandExecutor
Base class for command executors.
CompletionGenerator
Generates shell completion scripts from tool definitions.
ConsoleMarkdownSink
A StringSink that renders console markdown in every string written (renderConsoleMarkdown).
ContextBoundaryRules
The rules of a package, read from its buildkit.yaml.
CppFolder
C++ project nature: a native build file (NativeBuildSystem) with C++ sources (.cpp, .cc, .cxx, .hpp, ...).
DartConsoleFolder
Dart console application nature.
DartDirective
One directive: its kind, the URIs it names (a conditional import names more than one) and the 1-based line of its first URI.
DartExecutor
Executor that invokes a Dart function for each project.
DartPackageFolder
Dart package nature (library).
DartProjectFolder
Base class for Dart project natures.
ExecutePlaceholderContext
Context for resolving execute command placeholders.
ExecutePlaceholderResolver
Resolves placeholders in command strings for execute commands.
FilterPipeline
Applies filters to folder lists based on TraversalInfo configuration.
FlutterProjectFolder
Flutter project nature.
FolderContext
A scanned folder with its detected natures.
FolderScanner
Scans directories and builds a list of FsFolders.
FolderSorter
Sorts folders based on traversal configuration.
FsFolder
Filesystem folder during scanning (minimal info).
GitFolder
Git repository nature.
GitRepoFinder
Finds git repositories under a given root.
GitTraversalInfo
Configuration for git repository traversal.
GoFolder
Go project nature: a go.mod.
HelpGenerator
Generates help text from tool and command definitions.
HelpTopic
A named help topic that can be shown via tool help <name>.
ItemResult
Result for a single processed item (folder/project).
JavaFolder
Java project nature: a pom.xml, build.gradle or build.gradle.kts.
JavaScriptFolder
JavaScript project nature: a package.json without a tsconfig.json.
LanguageDetector
Detects the non-Dart language natures of a folder from its project files (LanguageProjectFolder and its subtypes, TypeScript excepted: the NatureDetector creates that one with the VS Code natures).
LanguageProjectFolder
A project in a language other than Dart, detected by its project file: the SOM runtime languages TypeScript, JavaScript, Python, Java, Go, Rust, C and C++, and Scala (sbt).
ListedProject
The projects of a workspace as every tool built on tom_build_base sees them: the folders a project command visits, with their identity and natures.
ListExecutor
No-op executor that just lists folders.
MessageCatalog
A command's messages, by code.
MessageDefinition
A message, defined once per code: its level, the label of its block, its help text and its options.
MessageOption
One option of a message: how it is written and what it does.
MkLinkExecutor
Generic cross-platform symbolic-link executor.
NativeProjectFolder
A C or C++ project: a make, CMake, Meson, Bazel or Ceedling build file beside the sources that decide the language (CFolder, CppFolder).
NatureDetector
Detects and creates folder natures based on filesystem markers.
NestedToolExecutor
Executor that delegates to an external tool binary.
OptionDefinition
Definition of a CLI option.
OutputSpec
A parsed --output <format>[:<file>] specification.
PerCommandArgs
Per-command arguments for multi-command tools.
PipelineCommandPrefixParser
PipelineCommandSpec
PipelineDefinition
PipelineOptionResolver
PipelineStepConfig
ProcessingResult
Result of a traversal operation.
ProjectTraversalInfo
Configuration for project-based traversal.
ProjectVersionFile
The version field of a project file: read it, and write a new one with the rest of the file as it was.
PubCacheIntegrity
Checks that every hosted package a project has locked is really in the pub cache.
PubCacheProblem
One locked package that the pub cache cannot supply.
PythonFolder
Python project nature: a pyproject.toml, setup.py or setup.cfg.
RepeatCommand
Builds the command line to repeat: the run's arguments plus one option.
RepoEntry
One repository of the tree.
A symlink of the tree: path points to target (relative to its folder).
RepoNames
The names a run gives its repositories (see the library comment).
ReportDone
One repository that changed: what was done (committed 2 files, merged 3 commits, pushed) and the files.
ReportEvidence
One kind of evidence of a message: files, commits, branches, sizes, windows, ... with a label and its items.
ReportExitCode
The exit codes of a run that ends with a RunReport.
ReportMessage
A raised message: the definition and what this case shows.
RepoSelections
The repositories each repository-list option of a run names (--skip core,basics), resolved by RepoNames.
RepoSet
The combined repository set of a Tom root (see the library comment).
RepoSetMember
One repository of a RepoSet.
RepositoryIdLookup
Lookup helper for repository IDs.
ReposManifest
The parsed repos.yaml.
RunFolder
Base class for folder natures detected during execution.
RunReport
The one report a run ends with (see the library comment).
RustFolder
Rust project nature: a Cargo.toml.
ScalaFolder
Scala project nature: an sbt build, build.sbt.
ScanResults
Result of workspace scanning with nature detection.
ShellExecutor
Executor that runs a shell command in each folder.
SyncExecutor
Synchronous callback-based executor.
TomBuildFolder
Tom project configuration nature (tom_project.yaml).
ToolDefinition
Definition of a CLI tool for buildkit and similar applications.
ToolDefinitionSerializer
Serializes a ToolDefinition tree to YAML format.
ToolPipelineConfig
ToolPipelineConfigLoader
ToolPipelineExecutor
ToolResult
Result of running a tool or command.
ToolRunner
Runs tools based on their definitions.
ToolWiringEntry
Describes how a nested tool is wired into a host tool.
TraversalDefaults
Traversal defaults loaded from buildkit_master.yaml navigation section.
TypeScriptFolder
TypeScript project nature.
VsCodeExtensionFolder
VS Code extension nature.
WiringLoader
Loads and resolves nested tool wiring for a host tool.
WiringResult
Result of loading and resolving wired tool definitions.
WorkspaceNavigationArgs
Parsed navigation options for workspace traversal.
WorkspaceScanner
Scans workspace directories and detects folder natures.

Enums

DartDirectiveKind
The kind of a DartDirective.
ExecutionMode
Represents the execution mode for a tool.
GitTraversalMode
Git traversal order mode.
GitTraversalOrder
Git traversal order when both inner-first and outer-first are valid.
JavaBuildTool
The build tool of a JavaFolder.
MessageLevel
How serious a message is; decides where it is listed and the exit code.
NativeBuildSystem
The build system of a C or C++ project.
OptionType
Type of option value.
OutputFormat
Supported CLI output formats.
PipelineCommandPrefix
PubCacheProblemKind
How a locked package fails to be usable from the pub cache.
RepoClass
The class of a repository in a RepoSet (see the library comment).
RepoKind
What an entry is: one of ours, a fork, the AI state, the binaries layer, or a third-party project pinned to a SHA.
ShellType
Shell type for completion scripts.
SpecialCommandResult
Result of checking for special commands.
ToolMode
Mode in which a tool can operate.
WiringMode
Mode for how a nested tool is wired into a host tool.

Extensions

CommandListOps on List<CommandDefinition>
Extension methods for manipulating command lists.
ToolDefinitionCompletion on ToolDefinition
Extension to generate completions.

Constants

bazelWorkspaceFiles → const List<String>
The files that mark the root of a Bazel workspace.
ceedlingProjectFile → const String
The project file of a Ceedling project.
commonOptions → const List<OptionDefinition>
Common options for all tools.
defaultHelpTopics → const List<HelpTopic>
All built-in help topics that apply to every tool.
definesHelpTopic → const HelpTopic
Help topic documenting the defines system.
gitTraversalOptions → const List<OptionDefinition>
Standard options for git traversal.
kAiFolder → const String
The AI state's folder at a Tom root.
kAlwaysSkipDirectories → const Set<String>
Directories that should always be skipped during recursive scanning.
kBoundariesSection → const String
The buildkit.yaml key the rules are read from.
kBuildkitGroupYaml → const String
The file that marks a directory as a project group.
kBuildkitMasterYaml → const String
Filename for the workspace-level buildkit configuration.
kBuildkitSkipYaml → const String
Filename for the buildkit skip marker.
kConsoleMarkdownZoneKey → const Symbol
Zone-local key that indicates console_markdown rendering is active.
kQuestReposFolder → const String
The bare clones of the multi-quest repositories, inside _ai.
kQuestsFolder → const String
The quest folders inside the AI state; a clone there is a quest clone.
kReposManifestFile → const String
The manifest's file name at a Tom root.
kTomCodeWorkspace → const String
Filename of a VS Code workspace file that once marked the workspace root.
kTomSkipYaml → const String
Filename for the global skip marker (all tools).
kWorktreesFolder → const String
The run worktrees' folder (tool-owned clones).
languageProjectFiles → const List<String>
Project files that make a folder a project in one of the non-Dart languages, apart from C / C++ (see isProjectFolder).
macrosHelpTopic → const HelpTopic
Help topic documenting the macro system.
masterYamlHelpTopics → const List<HelpTopic>
Help topics for tools that use a {tool}_master.yaml configuration file.
pipelinesHelpTopic → const HelpTopic
Help topic documenting pipeline configuration.
placeholdersHelpTopic → const HelpTopic
Help topic documenting placeholder and environment variable usage.
projectTraversalOptions → const List<OptionDefinition>
Standard options for project traversal.
wiringHelpTopic → const HelpTopic
Help topic documenting nested tool wiring.

Properties

isConsoleMarkdownActive → bool
Returns true if the current zone already applies console_markdown.
no setter

Functions

addNavigationOptions(ArgParser parser) → void
Add standard navigation options to an ArgParser.
argsForNestedWorkspace(List<String> args) → List<String>
args for a run in a nested workspace (-w): without the scan roots (-s / --scan), which name folders of this run; the nested run scans from its own workspace.
cargoIdentity(String text) → ProjectIdentity
Name and version of a Cargo.toml's [package].
checkContextBoundaries(String projectPath, {ContextBoundaryRules? rules, bool? includeTests}) → BoundaryReport
Checks the package at projectPath against its boundaries: rules (rules when given, else read from its buildkit.yaml). includeTests overrides the rules' tests: flag.
consoleStylingEnabled({required bool hasTerminal, Map<String, String>? environment}) → bool
Whether console markdown becomes ANSI styling on a stream: NO_COLOR set to a non-empty value turns it off (no-color.org), also over FORCE_COLOR; FORCE_COLOR set to anything but 0 / false turns it on through a pipe; otherwise the stream must be a terminal (hasTerminal). Logs, | grep, files written with > and tests that capture stdout get no escape codes.
currentToolOriginLine() → String
toolOriginLine for the process running now.
decodeProcessOutput(Object? raw) → String
Decode raw process output as UTF-8, tolerating malformed byte sequences.
describeUnmatchedGroups(List<String> groups, {required String scanRoot}) → String
The error message for ProcessingResult.unmatchedGroups, worded like describeUnmatchedProjectPatterns.
describeUnmatchedProjectPatterns(List<String> patterns, {required String scanRoot}) → String
The error message for ProcessingResult.unmatchedProjectPatterns.
enableUtf8Console() → void
Switch the process to UTF-8 console output so non-ASCII tool output renders correctly.
expandMacros(List<String> args, Map<String, String> macros) → List<String>
Expand macros in argument list.
findReposRoot(String start) → String?
The folder holding repos.yaml at or above start (absolute), or null.
findWorkspaceRoot(String startPath) → String
The workspace root of startPath (findWorkspaceRootOrNull), or startPath itself when it is not inside a workspace.
findWorkspaceRootOrNull(String startPath) → String?
The workspace root: the nearest directory at or above startPath that holds buildkit_master.yaml, or null when there is none.
formatDuration(Duration d) → String
d as 0.3s, 12.4s or 2m 05.4s: tenths of a second, minutes from one minute on.
generatePlainCommandHelp(ToolDefinition tool, CommandDefinition cmd) → String
Generate plain-text help for a command (no ANSI colors).
generatePlainToolHelp(ToolDefinition tool) → String
Generate plain-text tool help (no ANSI colors).
getExecutionModesHelpLines() → List<String>
Returns execution modes explanation lines.
getRequiredArgCount(String macroValue) → int
Get the number of required arguments for a macro.
goModulePath(String text) → String?
The module path of a go.mod.
handleSpecialCommands(List<String> args, ToolDefinition tool, {void printer(String)?, String toolHelpGenerator(ToolDefinition)?, String commandHelpGenerator(ToolDefinition, CommandDefinition)?, String versionGenerator(ToolDefinition)?}) → SpecialCommandResult
Check for and handle special commands (help, version).
hasNoRunWithoutTraversal(ToolResult result) → bool
Whether result is what CommandExecutor.executeWithoutTraversal returns when the executor does not implement it: the executor has no run of its own without traversal.
isBinaryOnPath(String binary) → bool
Check if a binary is available on the system PATH.
isBrokenPipe(Object error) → bool
Whether error says the reader of a pipe went away: tool | head -1, grep -m1, a pager quit early. EPIPE (32) on macOS and Linux; ERROR_BROKEN_PIPE (109) and ERROR_NO_DATA (232) on Windows.
isCeedlingProjectFile(String path) → bool
Whether path is a Ceedling project.yml: it holds Ceedling's top-level :project: section.
isFlutterPackage(String directory) → bool
Whether the package in directory is a Flutter package (pubspecDeclaresFlutterSdk on its pubspec.yaml). A missing or unreadable pubspec is not one.
isHelpCommand(List<String> args) → bool
Check if the first argument is a help command.
isMesonProjectFile(String path) → bool
Whether path is a meson.build that declares a project (the top file of a Meson build; the meson.build of a subdir() does not).
isProjectFolder(String dir) → bool
Whether dir is a project folder of any language the build tools know: a pubspec.yaml, one of languageProjectFiles, or a make, CMake, Meson, Bazel or Ceedling file beside C or C++ sources.
isSkippedFolderName(String name) → bool
Whether a walk from above leaves out a folder named name, whatever else it skips: a hidden folder (.…), or a feature worktree beside its main clone (<main clone folder>@<branch>, any name with @), which is a second copy of that clone's projects and holds links to the clones inside it. Every walk of tom_build_base shares this rule (the folder scanner, the git repository finder, the Dart project scan, the nested-workspace walk, the package search, the repository set), each with its own list of skipped names on top (kAlwaysSkipDirectories, ...). --no-skip does not change it. A walk started inside such a folder works normally: the rule is for the folders it enters, not the one it starts in.
isVersionCommand(List<String> args) → bool
Check if the first argument is a version command.
isWorkspaceBoundary(String dirPath) → bool
Check if a directory is a workspace boundary (contains buildkit_master.yaml).
killProcessTree(int pid) → Future<void>
Kills the process pid and every process it started, children before parents, with SIGKILL (taskkill /T /F on Windows).
listProjects(ProjectTraversalInfo info) → Future<List<ListedProject>>
Every project the traversal info selects, in its order (build order by default): exactly the folders a command working on Dart and other language projects visits (BuildBase.traverse), as ListedProjects.
listProjectsFor(CliArgs args, {required String executionRoot, bool navigationDefaults = true}) → Future<List<ListedProject>>
listProjects for args as a tool parsed them, rooted at executionRoot, with the navigation: defaults of the workspace's buildkit_master.yaml (TraversalDefaults.load) — the selection a project command given the same arguments would make.
nativeSourceLanguages(String dir) → Set<String>
The native languages whose sources lie in dir or up to three levels below it: c for .c files, cpp for C++ sources and headers. A .h header says neither.
natureName(RunFolder nature) → String
The short name of a nature in machine-readable output: flutter, dart_console, dart_package, dart, the language of a LanguageProjectFolder (typescript, python, ...), git, buildkit, build_runner, vscode_extension, workspace_root; any other nature by its type name.
packageScripts(Map<String, dynamic> json) → Map<String, String>
The scripts of a package.json object.
parseNavigationArgs(ArgResults results, {bool bareRoot = false}) → WorkspaceNavigationArgs
Parse navigation options from ArgResults.
pomIdentity(String text) → ProjectIdentity
The project's own <artifactId> and <version> of a pom.xml.
preprocessRootFlag(List<String> args) → (List<String>, bool)
Preprocess command-line arguments to handle special -R behavior.
primaryProjectNature(List<RunFolder> natures) → RunFolder?
The nature that decides a project's language and defaults when it has several: Flutter, Dart, then TypeScript, JavaScript, Python, Java, Go, Rust, C++, C. Null when the folder has no project nature.
printExecutionModesHelp() → void
Prints execution modes explanation to stdout.
projectGroupsOf(String projectPath, String executionRoot) → Set<String>
The names of the groups the project at projectPath belongs to.
pubspecDeclaresFlutterSdk(Object? pubspec) → bool
Whether a parsed pubspec.yaml pubspec declares the Flutter SDK as a dependency:
pyprojectIdentity(String text) → ProjectIdentity
Name and version of a pyproject.toml: [project], else [tool.poetry].
readPackageJson(File file) → Map<String, dynamic>
The JSON object of a package.json, or an empty map when it does not parse.
renderConsoleMarkdown(String text, {required bool styled}) → String
text with its console markdown rendered: as ANSI styling when styled, else as plain text, the markers removed and any escape code dropped.
reposHostId(String root) → String
This host's fleet id, which hosts: of an entry names: TOM_REPOS_HOST, else <root>/.tom/machine_id, else derived from the host name (mbp, bomber, bigbeast, legiondary01, else the host name's first label).
requiredFolderLinkNote(String path, {bool? windows, String readTarget(String link)?}) → String?
A note for a required folder at path that is not there as a folder: null unless path is a link; else its target, whether that target is there, and the command that recreates the link.
resolveBinary(String binary) → String
Platform-aware binary resolution and checking utilities.
resolveDartExecutable({String? resolvedExecutable, Map<String, String>? environment, bool exists(String path)?}) → String
The dart executable to use when a tool needs to spawn an SDK command.
resolveExecutionRoot(WorkspaceNavigationArgs navArgs, {required String currentDir}) → String
Determine the execution root based on navigation args.
runBinary(String binary, List<String> args, String workingDirectory) → Future<ProcessResult>
Run a binary with the given arguments in a working directory.
runBinaryStreaming(String binary, List<String> args, String workingDirectory) → Future<int>
Run a binary with streaming output directly to stdout/stderr.
runSelf(String binary, List<String> args, String workingDirectory) → Future<ProcessResult>
Runs this program again with args in workingDirectory (selfInvocation): the same binary or script, so a run it hands on (a sub-workspace of -w, a delegated pipeline) has the same version and needs nothing on the PATH. Falls back to binary on the PATH (runBinary) when the program cannot name itself.
runWithConsoleMarkdown<T>(Future<T> body(), {void onError(Object error, StackTrace stack)?}) → Future<T>
Run body inside a Dart zone that automatically renders console_markdown syntax in every print() call.
runWithConsoleMarkdownSync<T>(T body(), {void onError(Object error, StackTrace stack)?}) → T
Synchronous variant of runWithConsoleMarkdown for tools that don't need async (rarely used — prefer the async version).
sbtIdentity(String text) → ProjectIdentity
Name and version of a build.sbt: its top-level name := "..." and version := "..." settings (also ThisBuild / version).
scanDartDirectives(String source) → List<DartDirective>
The directives of source, in order.
scanForDartProjects(String dir, {bool recursive = false, bool includeTestProjects = false, bool verbose = false}) → List<String>
Scan a directory for Dart projects (directories containing pubspec.yaml).
selfInvocation({String? resolvedExecutable, Uri? script, List<String>? executableArguments}) → ({String executable, List<String> leading})?
How to start the running program again, with arguments of its own: a compiled binary is its resolvedExecutable; under the Dart VM (dart run, dart bin/x.dart) or the AOT runtime it is that executable with its executableArguments and the script. Null when the script is no file (the caller then falls back to the tool's name on the PATH).
shellQuote(String arg) → String
arg as a POSIX shell reads it back: plain when it holds only safe characters, else in double quotes with ", \, $ and ` escaped.
streamStylingEnabled(Stdout stream) → bool
consoleStylingEnabled for stream (stdout or stderr) in this process. A terminal is what stdioType reports: Stdout.hasTerminal is false in some pseudo-terminals (e.g. under script) where the stream is one.
tomlTableStrings(String text, String table) → Map<String, String>
The string values of one table of a TOML document ([project], [package], [tool.poetry]): key = "value" / key = 'value' lines, comments and other value types ignored. Enough for a project file's name and version; not a TOML parser.
toolOriginLine({required String resolvedExecutable, required Uri script}) → String
The origin line for a run whose executable is resolvedExecutable and whose entry point is script.
unmatchedGroups(Iterable<String> projectPaths, List<String> groups, String executionRoot) → List<String>
The groups that no project in projectPaths belongs to, in the order given and each once.
upstreamPaths(String start) → Set<String>
The absolute paths of every kind: upstream entry of the repos.yaml at or above start: project mode (builds) skips them without a marker file. Empty without a repos.yaml, and when it does not parse (a build does not fail over the manifest; git mode reports it).
validateProjectPathsExist(List<String> projectPatterns, String executionRoot) → String?
Validate that every path-style, non-glob --project pattern resolves to an existing directory under executionRoot.
validateProjectPathsWithinRoot(List<String> projectPatterns, String executionRoot) → String?
Validate that no absolute --project pattern points outside executionRoot.
validateScanPathWithinRoot(String scan, String executionRoot) → String?
Validate that the --scan path does not point outside executionRoot.
validateScanRootsWithinRoot(List<String> roots, String executionRoot) → String?
validateScanPathWithinRoot for every root of a --scan a,b list: the first root outside the workspace, or null when all are inside.

Typedefs

ProjectIdentity = ({String? name, String? version})
A project's name and version as its project file states them.
RepoSetScope = ({List<RepoSetMember> members, List<String> nestedWorkspaces})
The repositories a git-mode run in one folder works on: members (the ones the git commands take, on disk), and nestedWorkspaces, the repositories holding a workspace of their own that the run stops at (-w runs the command there).
TomBuildMasterFolder = BuildkitMasterFolder
The former name of BuildkitMasterFolder.

Exceptions / Errors

MacroExpansionException
Exception thrown when macro expansion fails.
RepoNameException
A repository name that is unknown or names more than one repository: a usage error (exit 2).
ReposManifestException
A repos.yaml that breaks the format; problems says where.
UnresolvedPlaceholderException
Exception thrown when a placeholder cannot be resolved.