process_run tools: which, dart/flutter helpers, stdio
Besides Shell, package:process_run ships small helpers to find
executables the way a shell does, to know which Dart and Flutter SDK are
available, to read the user home/config directories, to prompt on the
terminal and to keep the output of concurrent scripts readable. All of them
need dart:io (Dart VM, Flutter desktop/mobile; not web).
import 'package:process_run/shell.dart';
Future<void> main() async {
print(await which('git')); // /usr/bin/git or null
print(dartExecutable); // running dart VM path
print(flutterExecutablePath); // null when flutter is not installed
print(dartVersion); // 3.12.0
}
Guidelines
Finding executables
whichSync(name) / await which(name) return the absolute path of an
executable or null. Import package:process_run/shell.dart (or the
smaller package:process_run/which.dart). They search the current shell
environment paths: PATH, the user config paths, the running dart SDK
bin directory. On Windows the PATHEXT extensions are tried, so
whichSync('flutter') returns flutter.bat.
name must be a bare name (git, flutter), never a path: any string
containing a directory separator returns null.
whichSync(name, environment: {'PATH': dir}) searches a given map on top
of the current environment; add includeParentEnvironment: false to
search only that map. ShellEnvironment().whichSync(name) does the same
for an environment object.
- Use
which to give a clear error before running a tool
(if (await which('firebase') == null) throw StateError('install firebase'))
rather than catching the ShellException of a failed run.
dartBinFileName (dart or dart.exe) helps building paths by hand.
Dart SDK
dartExecutable (String?) is the running VM (Platform.resolvedExecutable
when it is dart, else which('dart')); dartSdkBinDirPath and
dartSdkDirPath derive from it. Use dartExecutable to spawn another
Dart process with the same SDK, or simply write dart ... in a script:
the SDK bin directory is always first in the shell paths.
dartVersion (a pub_semver Version) and dartChannel ('stable',
'beta', 'dev', 'master', compare with dartChannelStable...) are
parsed from Platform.version and cost nothing. getDartBinVersion()
(package:process_run/cmd_run.dart) runs dart --version and returns
Version?; use it only for a dart found elsewhere.
getPackageVersion({String? dir}) from
package:process_run/package/package.dart reads version: of the
pubspec.yaml in dir (default .) as a Version?, null when absent.
Flutter SDK
flutterExecutablePath (String?) is whichSync('flutter') cached for
the process; isFlutterSupported / isFlutterSupportedSync are
flutterExecutablePath != null. flutterDartExecutablePath is the
dart bundled in that flutter (bin/cache/dart-sdk/bin/dart).
await getFlutterBinVersion() (Version?) and
await getFlutterBinChannel() (String?) run flutter --version once
and cache it; both return null without flutter.
- When the current program runs on the flutter-bundled dart, the flutter
bin directory is prepended to the shell paths, so flutter scripts
work without configuration.
- Skip flutter-specific work with
if (!isFlutterSupported) return; instead
of catching errors.
User directories
userHomePath: HOME (USERPROFILE on Windows), '~' when neither is
set. userAppDataPath: %APPDATA% on Windows, ~/.config elsewhere.
pubCacheBinPath: where dart pub global activate puts its binstubs
(PUB_CACHE, else %LOCALAPPDATA%\Pub\Cache\bin or ~/.pub-cache/bin).
dartInstallBinPath: where dart install puts its executables
(DART_DATA_HOME, else %LOCALAPPDATA%\Dart, ~/Library/Application Support/Dart
or $XDG_STATE_HOME/~/.local/state/Dart, then install/bin). Also
pubCachePath, dartDataHomePath, dartInstallPath, and
DartToolPaths(os: DartToolOs.windows, environment: {...}) to compute them for
another platform or environment (pathIndexOf/isDirOnPath check PATH).
Both honor the TEKARTIK_PROCESS_RUN_USER_HOME_PATH and
TEKARTIK_PROCESS_RUN_USER_APP_DATA_PATH overrides. Use them with
package:path join to locate tool configuration files.
Terminal prompts
await prompt('Enter your name') returns a line, await promptConfirm('Delete it')
returns true for y/Y. Both read sharedStdIn, a shareable wrapper
over stdin that can be listened to several times in sequence.
- Call
await promptTerminate() (or await sharedStdIn.terminate()) once
at the end of main, otherwise the process keeps running.
Shell(stdin: sharedStdIn) forwards the terminal input to child
processes (password prompts, sudo --stdin).
Zone aware stdout/stderr (package:process_run/stdio.dart)
package:process_run/stdio.dart re-exports dart:io but replaces
stdout and stderr with zone-aware getters. Import it instead of
dart:io in scripts and tools; outside a zone they are the regular sinks.
shellStdioLinesGrouper.runZoned(() async { ... }) groups the output
produced inside the callback (by stdout.writeln, stderr.writeln and
verbose Shell runs) so that several concurrent callbacks do not
interleave their lines: one zone is printed at a time, the others are
buffered and flushed in the order the zones were started.
ShellStdio is the interface (out, err sinks); a Shell created
inside the zone with verbose: true and no explicit sinks writes to the
zone sinks automatically.
Legacy command objects (package:process_run/cmd_run.dart)
ProcessCmd(executable, arguments, {workingDirectory, environment, runInShell, ...}),
DartCmd(arguments), PubCmd(arguments), PubRunCmd, PubGlobalRunCmd,
FlutterCmd(arguments) and runCmd(cmd, {verbose, commandVerbose, stdout, stderr, stdin})
predate Shell. runCmd does not throw on a non-zero exit code. Prefer
Shell and ShellCommand in new code; keep DartCmd/PubCmd only for
existing scripts.
ProcessResult gained toDebugString() and command (the
ShellCommand) through package:process_run/shell.dart, and Process
gained outLines/errLines (Stream<String>) for processes you start
yourself with Process.start.
Examples
Check the tools a script needs
import 'package:process_run/shell.dart';
Future<void> requireTools(List<String> names) async {
var missing = <String>[];
for (var name in names) {
if (await which(name) == null) {
missing.add(name);
}
}
if (missing.isNotEmpty) {
throw StateError('Missing executables: ${missing.join(', ')}');
}
}
Future<void> main() async {
await requireTools(['git', 'dart']);
await run('git status');
}
Search in a custom directory only
import 'package:process_run/shell.dart';
String? findTool(String binDir, String name) => whichSync(
name,
environment: {'PATH': binDir},
includeParentEnvironment: false,
);
void main() {
print(findTool('/opt/node/bin', 'node'));
// Same through an environment object
var env = ShellEnvironment.empty()..paths.add('/opt/node/bin');
print(env.whichSync('npm'));
}
Dart and Flutter SDK information
import 'package:process_run/cmd_run.dart';
import 'package:process_run/shell.dart';
Future<void> main() async {
print('dart: $dartExecutable');
print('sdk: $dartSdkDirPath');
print('version: $dartVersion channel: $dartChannel');
if (dartChannel != dartChannelStable) {
print('not on stable');
}
// Runs `dart --version`
print('dart bin version: ${await getDartBinVersion()}');
if (isFlutterSupported) {
print('flutter: $flutterExecutablePath');
print('flutter dart: $flutterDartExecutablePath');
var version = await getFlutterBinVersion();
var channel = await getFlutterBinChannel();
print('flutter $version ($channel)');
}
}
Spawn the same dart VM explicitly
import 'package:process_run/shell.dart';
Future<void> main() async {
var shell = Shell();
// Equivalent to `dart run tool/build.dart` since the SDK bin is first
// in the shell paths; explicit when the script must not depend on PATH.
await shell.runExecutableArguments(dartExecutable!, [
'run',
'tool/build.dart',
]);
}
Version of the current package
import 'package:process_run/package/package.dart';
Future<void> main() async {
var version = await getPackageVersion();
print('building ${version ?? 'unversioned'}');
}
Prompt before a destructive action
import 'package:process_run/shell.dart';
Future<void> main() async {
var name = await prompt('Project name');
if (await promptConfirm('Delete build of $name')) {
await run('dart run tool/clean.dart ${shellArgument(name)}');
}
await promptTerminate();
}
Readable output from concurrent scripts
import 'package:process_run/shell.dart';
import 'package:process_run/stdio.dart';
Future<void> testPackage(String dir) async {
stdout.writeln('# $dir');
await Shell().cd(dir).run('dart test');
stdout.writeln('# $dir done');
}
Future<void> main() async {
var stdio = shellStdioLinesGrouper;
await Future.wait([
stdio.runZoned(() => testPackage('packages/a')),
stdio.runZoned(() => testPackage('packages/b')),
]);
}
User configuration file location
import 'package:path/path.dart';
import 'package:process_run/shell.dart';
String get myToolConfigPath => join(userAppDataPath, 'my_tool', 'config.yaml');
void main() {
print(userHomePath); // /home/me
print(myToolConfigPath); // /home/me/.config/my_tool/config.yaml
}
Common mistakes
whichSync('bin/tool') or whichSync('/usr/bin/git'): only bare names
are searched; a path always returns null. Check the file yourself.
- Forgetting
await promptTerminate() after using prompt,
promptConfirm or sharedStdIn: the program hangs at exit.
- Using
dartExecutable! in a Flutter app: it can be null when the
process is not a dart VM and dart is not in the paths.
- Expecting
getFlutterBinVersion() to refresh after installing flutter in
the same process: the result (including null) is cached.
- Calling
Platform.environment for child processes instead of
platformEnvironment: the child inherits DART_VM_OPTIONS, which can
break dart children started from a debugger.
- Mixing
dart:io stdout with package:process_run/stdio.dart inside
shellStdioLinesGrouper.runZoned: only the zone-aware sinks are grouped.
1---2name: process-run-tools3description: >-4 Use when locating executables or SDK information with package:process_run:5 which/whichSync, dartExecutable, dartSdkBinDirPath, dartSdkDirPath,6 dartVersion, dartChannel, getDartBinVersion, flutterExecutablePath,7 flutterDartExecutablePath, isFlutterSupported, getFlutterBinVersion,8 getFlutterBinChannel, userHomePath, userAppDataPath, pubCacheBinPath,9 dartInstallBinPath, DartToolPaths, getPackageVersion,10 prompt/promptConfirm/promptTerminate, sharedStdIn, the zone aware11 stdout/stderr of package:process_run/stdio.dart and12 shellStdioLinesGrouper, and the legacy ProcessCmd/DartCmd/runCmd API of13 package:process_run/cmd_run.dart.14metadata:15 source: https://skillmd.com/skills/tekartik/process-run-tools16---1718# process_run tools: which, dart/flutter helpers, stdio1920Besides `Shell`, `package:process_run` ships small helpers to find21executables the way a shell does, to know which Dart and Flutter SDK are22available, to read the user home/config directories, to prompt on the23terminal and to keep the output of concurrent scripts readable. All of them24need `dart:io` (Dart VM, Flutter desktop/mobile; not web).2526```dart27import 'package:process_run/shell.dart';2829Future<void> main() async {30 print(await which('git')); // /usr/bin/git or null31 print(dartExecutable); // running dart VM path32 print(flutterExecutablePath); // null when flutter is not installed33 print(dartVersion); // 3.12.034}35```3637## Guidelines3839### Finding executables4041* `whichSync(name)` / `await which(name)` return the absolute path of an42 executable or `null`. Import `package:process_run/shell.dart` (or the43 smaller `package:process_run/which.dart`). They search the current shell44 environment paths: `PATH`, the user config paths, the running dart SDK45 `bin` directory. On Windows the `PATHEXT` extensions are tried, so46 `whichSync('flutter')` returns `flutter.bat`.47* `name` must be a bare name (`git`, `flutter`), never a path: any string48 containing a directory separator returns `null`.49* `whichSync(name, environment: {'PATH': dir})` searches a given map on top50 of the current environment; add `includeParentEnvironment: false` to51 search only that map. `ShellEnvironment().whichSync(name)` does the same52 for an environment object.53* Use `which` to give a clear error before running a tool54 (`if (await which('firebase') == null) throw StateError('install firebase')`)55 rather than catching the `ShellException` of a failed run.56* `dartBinFileName` (`dart` or `dart.exe`) helps building paths by hand.5758### Dart SDK5960* `dartExecutable` (`String?`) is the running VM (`Platform.resolvedExecutable`61 when it is `dart`, else `which('dart')`); `dartSdkBinDirPath` and62 `dartSdkDirPath` derive from it. Use `dartExecutable` to spawn another63 Dart process with the same SDK, or simply write `dart ...` in a script:64 the SDK `bin` directory is always first in the shell paths.65* `dartVersion` (a `pub_semver` `Version`) and `dartChannel` (`'stable'`,66 `'beta'`, `'dev'`, `'master'`, compare with `dartChannelStable`...) are67 parsed from `Platform.version` and cost nothing. `getDartBinVersion()`68 (`package:process_run/cmd_run.dart`) runs `dart --version` and returns69 `Version?`; use it only for a `dart` found elsewhere.70* `getPackageVersion({String? dir})` from71 `package:process_run/package/package.dart` reads `version:` of the72 `pubspec.yaml` in `dir` (default `.`) as a `Version?`, `null` when absent.7374### Flutter SDK7576* `flutterExecutablePath` (`String?`) is `whichSync('flutter')` cached for77 the process; `isFlutterSupported` / `isFlutterSupportedSync` are78 `flutterExecutablePath != null`. `flutterDartExecutablePath` is the79 `dart` bundled in that flutter (`bin/cache/dart-sdk/bin/dart`).80* `await getFlutterBinVersion()` (`Version?`) and81 `await getFlutterBinChannel()` (`String?`) run `flutter --version` once82 and cache it; both return `null` without flutter.83* When the current program runs on the flutter-bundled dart, the flutter84 `bin` directory is prepended to the shell paths, so `flutter` scripts85 work without configuration.86* Skip flutter-specific work with `if (!isFlutterSupported) return;` instead87 of catching errors.8889### User directories9091* `userHomePath`: `HOME` (`USERPROFILE` on Windows), `'~'` when neither is92 set. `userAppDataPath`: `%APPDATA%` on Windows, `~/.config` elsewhere.93* `pubCacheBinPath`: where `dart pub global activate` puts its binstubs94 (`PUB_CACHE`, else `%LOCALAPPDATA%\Pub\Cache\bin` or `~/.pub-cache/bin`).95 `dartInstallBinPath`: where `dart install` puts its executables96 (`DART_DATA_HOME`, else `%LOCALAPPDATA%\Dart`, `~/Library/Application Support/Dart`97 or `$XDG_STATE_HOME`/`~/.local/state/Dart`, then `install/bin`). Also98 `pubCachePath`, `dartDataHomePath`, `dartInstallPath`, and99 `DartToolPaths(os: DartToolOs.windows, environment: {...})` to compute them for100 another platform or environment (`pathIndexOf`/`isDirOnPath` check `PATH`).101 Both honor the `TEKARTIK_PROCESS_RUN_USER_HOME_PATH` and102 `TEKARTIK_PROCESS_RUN_USER_APP_DATA_PATH` overrides. Use them with103 `package:path` `join` to locate tool configuration files.104105### Terminal prompts106107* `await prompt('Enter your name')` returns a line, `await promptConfirm('Delete it')`108 returns `true` for `y`/`Y`. Both read `sharedStdIn`, a shareable wrapper109 over `stdin` that can be listened to several times in sequence.110* Call `await promptTerminate()` (or `await sharedStdIn.terminate()`) once111 at the end of `main`, otherwise the process keeps running.112* `Shell(stdin: sharedStdIn)` forwards the terminal input to child113 processes (password prompts, `sudo --stdin`).114115### Zone aware stdout/stderr (`package:process_run/stdio.dart`)116117* `package:process_run/stdio.dart` re-exports `dart:io` but replaces118 `stdout` and `stderr` with zone-aware getters. Import it instead of119 `dart:io` in scripts and tools; outside a zone they are the regular sinks.120* `shellStdioLinesGrouper.runZoned(() async { ... })` groups the output121 produced inside the callback (by `stdout.writeln`, `stderr.writeln` and122 verbose `Shell` runs) so that several concurrent callbacks do not123 interleave their lines: one zone is printed at a time, the others are124 buffered and flushed in the order the zones were started.125* `ShellStdio` is the interface (`out`, `err` sinks); a `Shell` created126 inside the zone with `verbose: true` and no explicit sinks writes to the127 zone sinks automatically.128129### Legacy command objects (`package:process_run/cmd_run.dart`)130131* `ProcessCmd(executable, arguments, {workingDirectory, environment, runInShell, ...})`,132 `DartCmd(arguments)`, `PubCmd(arguments)`, `PubRunCmd`, `PubGlobalRunCmd`,133 `FlutterCmd(arguments)` and `runCmd(cmd, {verbose, commandVerbose, stdout, stderr, stdin})`134 predate `Shell`. `runCmd` does not throw on a non-zero exit code. Prefer135 `Shell` and `ShellCommand` in new code; keep `DartCmd`/`PubCmd` only for136 existing scripts.137* `ProcessResult` gained `toDebugString()` and `command` (the138 `ShellCommand`) through `package:process_run/shell.dart`, and `Process`139 gained `outLines`/`errLines` (`Stream<String>`) for processes you start140 yourself with `Process.start`.141142## Examples143144### Check the tools a script needs145146```dart147import 'package:process_run/shell.dart';148149Future<void> requireTools(List<String> names) async {150 var missing = <String>[];151 for (var name in names) {152 if (await which(name) == null) {153 missing.add(name);154 }155 }156 if (missing.isNotEmpty) {157 throw StateError('Missing executables: ${missing.join(', ')}');158 }159}160161Future<void> main() async {162 await requireTools(['git', 'dart']);163 await run('git status');164}165```166167### Search in a custom directory only168169```dart170import 'package:process_run/shell.dart';171172String? findTool(String binDir, String name) => whichSync(173 name,174 environment: {'PATH': binDir},175 includeParentEnvironment: false,176 );177178void main() {179 print(findTool('/opt/node/bin', 'node'));180 // Same through an environment object181 var env = ShellEnvironment.empty()..paths.add('/opt/node/bin');182 print(env.whichSync('npm'));183}184```185186### Dart and Flutter SDK information187188```dart189import 'package:process_run/cmd_run.dart';190import 'package:process_run/shell.dart';191192Future<void> main() async {193 print('dart: $dartExecutable');194 print('sdk: $dartSdkDirPath');195 print('version: $dartVersion channel: $dartChannel');196 if (dartChannel != dartChannelStable) {197 print('not on stable');198 }199 // Runs `dart --version`200 print('dart bin version: ${await getDartBinVersion()}');201202 if (isFlutterSupported) {203 print('flutter: $flutterExecutablePath');204 print('flutter dart: $flutterDartExecutablePath');205 var version = await getFlutterBinVersion();206 var channel = await getFlutterBinChannel();207 print('flutter $version ($channel)');208 }209}210```211212### Spawn the same dart VM explicitly213214```dart215import 'package:process_run/shell.dart';216217Future<void> main() async {218 var shell = Shell();219 // Equivalent to `dart run tool/build.dart` since the SDK bin is first220 // in the shell paths; explicit when the script must not depend on PATH.221 await shell.runExecutableArguments(dartExecutable!, [222 'run',223 'tool/build.dart',224 ]);225}226```227228### Version of the current package229230```dart231import 'package:process_run/package/package.dart';232233Future<void> main() async {234 var version = await getPackageVersion();235 print('building ${version ?? 'unversioned'}');236}237```238239### Prompt before a destructive action240241```dart242import 'package:process_run/shell.dart';243244Future<void> main() async {245 var name = await prompt('Project name');246 if (await promptConfirm('Delete build of $name')) {247 await run('dart run tool/clean.dart ${shellArgument(name)}');248 }249 await promptTerminate();250}251```252253### Readable output from concurrent scripts254255```dart256import 'package:process_run/shell.dart';257import 'package:process_run/stdio.dart';258259Future<void> testPackage(String dir) async {260 stdout.writeln('# $dir');261 await Shell().cd(dir).run('dart test');262 stdout.writeln('# $dir done');263}264265Future<void> main() async {266 var stdio = shellStdioLinesGrouper;267 await Future.wait([268 stdio.runZoned(() => testPackage('packages/a')),269 stdio.runZoned(() => testPackage('packages/b')),270 ]);271}272```273274### User configuration file location275276```dart277import 'package:path/path.dart';278import 'package:process_run/shell.dart';279280String get myToolConfigPath => join(userAppDataPath, 'my_tool', 'config.yaml');281282void main() {283 print(userHomePath); // /home/me284 print(myToolConfigPath); // /home/me/.config/my_tool/config.yaml285}286```287288## Common mistakes289290* `whichSync('bin/tool')` or `whichSync('/usr/bin/git')`: only bare names291 are searched; a path always returns `null`. Check the file yourself.292* Forgetting `await promptTerminate()` after using `prompt`,293 `promptConfirm` or `sharedStdIn`: the program hangs at exit.294* Using `dartExecutable!` in a Flutter app: it can be `null` when the295 process is not a dart VM and `dart` is not in the paths.296* Expecting `getFlutterBinVersion()` to refresh after installing flutter in297 the same process: the result (including `null`) is cached.298* Calling `Platform.environment` for child processes instead of299 `platformEnvironment`: the child inherits `DART_VM_OPTIONS`, which can300 break `dart` children started from a debugger.301* Mixing `dart:io` `stdout` with `package:process_run/stdio.dart` inside302 `shellStdioLinesGrouper.runZoned`: only the zone-aware sinks are grouped.