Guides/Migrating from mason_logger, interact or prompts

Migrating from mason_logger, interact or prompts

package:dart_tui/cli.dart has a Logger shaped like mason_logger's. This guide maps each call of mason_logger, interact and prompts to its dart_tui equivalent, lists every difference, and says where there is no equivalent.

migrating from mason_logger, interact or prompts · dart_tui
Migrating from mason_logger, interact or prompts demo

The short version

package:dart_tui/cli.dart exports Logger, Level, Progress and ProgressOptions. They are shaped like the ones in mason_logger 0.3.6. For most CLIs you change the import and then either add await before each prompt, or rename it to its Sync twin (promptSync, confirmSync, chooseOneSync) and keep the code synchronous. The library is not exported from dart_tui.dart, so a plain import 'package:dart_tui/dart_tui.dart' does not add these names.

diff
-import 'package:mason_logger/mason_logger.dart';
+import 'package:dart_tui/cli.dart';

 final logger = Logger();
-final name = logger.prompt('Project name?', defaultValue: 'my_app');
+final name = await logger.prompt('Project name?', defaultValue: 'my_app');
+// Or stay synchronous: logger.promptSync('Project name?', defaultValue: 'my_app')

Add the package with dart pub add dart_tui. On a terminal, prompts are a small TUI. In pipes, CI and with ACCESSIBLE=1, they ask plain numbered line questions.

From mason_logger

mason_loggerdart_tuiNote
Logger(), logger.level = Level.verboseSameLevel has the same values.
info, detail, success, writeSameThey write to stdout.
warn(msg, tag: 'WARN'), err, alertSameThey write to stderr. warn writes [WARN] msg.
delayed(msg), flush()Same
info(msg, style: (m) => ...)Samestyle is String? Function(String?). Use dart_tui Style inside it.
progress(msg), update, complete, fail, cancelSameSee difference 5.
ProgressOptions(animation: ProgressAnimation(frames: f, interval: i))ProgressOptions(animation: Spinner(f, i))Any Spinner preset works, for example Spinner.dot.
logger.prompt(msg, defaultValue:, hidden:)logger.promptSync(...) (or await logger.prompt(...))promptSync is a rename with no await. Same parameters and return type as mason_logger. prompt returns a Future<String>.
logger.promptAny(msg, separator:)logger.promptAnySync(...) (or await logger.promptAny(...))promptAnySync is a rename with no await. Same parameters and return type as mason_logger. promptAny returns a Future<List<String>>.
logger.confirm(msg, defaultValue:)logger.confirmSync(...) (or await logger.confirm(...))confirmSync is a rename with no await. Same parameters and return type as mason_logger. confirm returns a Future<bool>.
logger.chooseOne(msg, choices:, defaultValue:, display:)logger.chooseOneSync(...) (or await logger.chooseOne(...))chooseOneSync is a rename with no await. Same parameters and return type as mason_logger. chooseOne returns a Future<T>.
logger.chooseAny(msg, choices:, defaultValues:, display:)logger.chooseAnySync(...) (or await logger.chooseAny(...))chooseAnySync is a rename with no await. Same parameters and return type as mason_logger. chooseAny returns a Future<List<T>>.
Logger(theme: LogTheme(...))No equivalentPass style: per call, or colour the text with dart_tui Style.
lightCyan.wrap('x'), styleBold.wrap('x'), link(uri: ...)No equivalentmason's ansi helpers are not copied. Use Style(foreground256: 14, isBold: true).render('x').

What stays the same

The Level enum has the same values. info, detail, success and write go to stdout. warn, err and alert go to stderr. warn writes [WARN] msg, and tag: '' writes the message alone. delayed and flush work the same. A finished progress shows the elapsed time as (42ms) below 100 ms and (1.2s) above. An answered prompt collapses to one line: message answer.

Differences from mason_logger

These are on purpose. Each one is checked against the mason_logger source.

#Topicmason_loggerdart_tui
1PromptsSynchronous.Async: they return a Future, so write await logger.prompt(...). The sync twins promptSync, promptAnySync, confirmSync, chooseOneSync and chooseAnySync have the same parameters and return types as mason_logger, so migrating is a rename. They only read the process stdin: a Logger built with a custom stdin: stream throws StateError from them. They throw StateError too while a Program or an async prompt is reading stdin.
2Cancel and end of inputCtrl+C exits with code 130. Esc does nothing. On end of input, only prompt and confirm return the default. chooseOne, chooseAny and promptAny throw NoTerminalAttachedError without a terminal.In the TUI, Esc or Ctrl+C exits the process with code 130. In plain mode, when input ends (for example cli < /dev/null), every prompt returns its default: prompt returns defaultValue or '', confirm returns defaultValue, chooseOne returns defaultValue or the first choice, chooseAny returns defaultValues or [], promptAny returns []. dart_tui never throws NoTerminalAttachedError. Without a terminal (pipes, CI, ACCESSIBLE=1), prompts ask plain numbered line questions.
3Theme and ansi helpersLogTheme, theme:, lightCyan.wrap, styleBold, link.None of them. The per-call style: stays. Use dart_tui Style for colours.
4Progress animationProgressAnimation(frames:, interval:).ProgressOptions.animation is a Spinner(frames, interval). The default frames, interval and trailing text (...) are the same as mason's.
5Progress outputWaits one interval before the first frame. Turns line wrap off (\x1b[?7l). Without a terminal it writes the frame with no newline, then \r✓ ....Draws at once. Never turns line wrap off: it cuts the message to the width instead. Never hides the cursor, reads stdin, enters raw mode or installs signal handlers, so Ctrl+C stops the CLI as usual and the terminal stays intact. A Logger write during a progress clears the line, prints, then draws the progress again. Without a terminal it writes one start line (message...) and one end line (✓ message (0.9s)).
6confirmAlso accepts yea, yeah, yep, yup and nope. An unknown answer returns the default.TUI keys: y, n, Enter (the default). Plain mode accepts y, yes, n and no, and asks again on anything else.
7promptAnyInserts <separator> as you type.Only splits the answer on the separator. Items are trimmed and empty ones are dropped.
8chooseOne and chooseAnyEmpty choices in chooseOne throws ArgumentError. Space does not confirm. chooseAny returns the picks in list order, not in the order you toggled them. The a key toggles all.
9Hidden promptShows nothing while you type.Shows • for each character while you type. The answered line shows ******, as in mason.
10Colourmason's own checks.Follows dart_tui's detectColorProfile: NO_COLOR, FORCE_COLOR, CLICOLOR_FORCE, TERM=dumb and pipes. With no colour and no terminal, the output has no escape codes at all.
11Test parametersNone.The constructor also takes stdout, stderr (an IOSink), stdin (a Stream<List<int>>), environment and exit. The defaults are the real ones.
A custom stdin is listened to once per prompt. To answer several prompts from one stream, pass a broadcast stream.

Show colour with Style

mason's lightCyan.wrap(...) becomes a dart_tui Style. The per-call style: parameter keeps its shape.

dart
import 'package:dart_tui/cli.dart';
import 'package:dart_tui/dart_tui.dart' show Style;

const accent = Style(foreground256: 14, isBold: true);

logger.info('Ready', style: (m) => accent.render(m ?? ''));

A full flow

This is the create-project flow from example/cli_logger.dart. On a terminal each prompt is a TUI. Piped through cat, the same code asks numbered questions and the progress writes two lines.

dart
import 'package:dart_tui/cli.dart';

Future<void> main() async {
  final logger = Logger();
  final name = await logger.prompt('Project name?', defaultValue: 'my_app');
  final template = await logger.chooseOne(
    'Template?',
    choices: const ['cli', 'server', 'package'],
    defaultValue: 'cli',
  );
  final features = await logger.chooseAny(
    'Features?',
    choices: const ['tests', 'lints', 'ci', 'docker'],
    defaultValues: const ['tests', 'lints'],
  );
  if (!await logger.confirm('Create $name?', defaultValue: true)) {
    logger.warn('Cancelled.');
    return;
  }
  final files = logger.progress('Writing $template files');
  // ... do the work ...
  files.complete('Wrote ${3 + features.length} files');
  logger.success('Created $name.');
}

From interact 2.2.0

interact components are objects with a synchronous interact() method. dart_tui has one-shot functions that return a Future. They return null when the user cancels with Esc or Ctrl+C. They do not exit the process. (Logger exits with code 130 instead.) If your code is synchronous, use the sync twins (promptInputSync, promptConfirmSync, promptSelectSync, promptMultiSelectSync) and keep the call chain as it is. See Sync prompts.

dart
import 'package:dart_tui/dart_tui.dart';

// A fvm-style helper that wrapped Confirm(...).interact().
bool confirm(String prompt, {bool defaultValue = false}) =>
    promptConfirmSync(prompt, defaultValue: defaultValue) ?? defaultValue;

// Select(...).interact() returned an index.
int select(String prompt, List<String> options) {
  final answer = promptSelectSync(options, title: prompt);
  return answer == null ? -1 : options.indexOf(answer);
}
interactdart_tuiNote
Input(prompt:, defaultValue:).interact()await promptInput(prompt, defaultValue: ...)Empty input returns defaultValue.
Input(initialText:)No equivalentpromptInput starts empty.
Input(validator:) with ValidationErrorNo equivalent in promptInputAsk again in a loop, or use Field.input(validate:) in a Form.
Confirm(prompt:, defaultValue:).interact()await promptConfirm(prompt, defaultValue: ...), or promptConfirmSync(...) with no awaitdefaultValue is false unless set. There is no "no default" mode, so Enter always answers.
Confirm(waitForNewLine:)No equivalentIn the TUI, y and n answer at once.
Select(prompt:, options:, initialIndex:).interact()await promptSelect(options, title: prompt, initial: index)interact returns the index. promptSelect returns the chosen string: use options.indexOf(answer) if you need the index. The cursor does not wrap. An empty list returns null.
MultiSelect(prompt:, options:, defaults:).interact()await promptMultiSelect(options, title: prompt, initial: {0, 2})defaults is a List<bool>. initial is a Set<int> of indexes. The result is a list of strings in list order, not indexes.
Password(prompt:).interact()await promptInput(prompt, hidden: true)Shows • for each character.
Password(confirmation: true)No equivalentCall promptInput(hidden: true) twice and compare the answers.
Sort(prompt:, options:)No equivalentdart_tui has no one-shot sort prompt.
Spinner(icon:).interact() and state.done()await spin(task, label: ...), or logger.progress(...)spin takes a Future and stops by itself when it ends. Logger.progress stops with complete, fail or cancel.
Progress(length:).interact() with increaseNo one-shot equivalentLogger.progress is a spinner with a message, not a bar. For a bar, use the ProgressModel component inside a Program.
MultiSpinner, MultiProgressNo equivalentLogger keeps one progress at a time: a new one takes over the line.
Theme, Theme.colorfulThemeNo equivalentColour your text with dart_tui Style.

From prompts 2.0.0

The prompts package reads lines from stdin with readLineSync. Its functions are synchronous. If your code wraps them in helpers, such as melos does, keep the helpers synchronous and change only their bodies to the sync functions of dart_tui. No caller needs async. See Sync prompts for what they can and cannot do.

dart
import 'package:dart_tui/dart_tui.dart';

// A melos-style helper. Callers stay as they are.
bool promptBool(String message, {bool defaultsTo = false}) =>
    promptConfirmSync(message, defaultValue: defaultsTo) ?? defaultsTo;

String promptString(String message, {String? defaultsTo}) =>
    promptInputSync(message, defaultValue: defaultsTo) ?? defaultsTo ?? '';
promptsdart_tuiNote
get(message, defaultsTo:)await promptInput(message, defaultValue: ...)Or await logger.prompt(...).
get(conceal: true)await promptInput(message, hidden: true)
get(validate:)No equivalent in promptInputAsk again in a loop, or use Field.input(validate:) in a Form.
get(allowMultiline: true)No equivalentpromptInput reads one line.
get(chevron:, color:, inputColor:)No equivalentdart_tui draws its own prompt. Colour follows the colour profile.
getBool(message, defaultsTo:)await promptConfirm(message, defaultValue: ...), or promptConfirmSync(...) with no awaitdart_tui adds the [y/N] or (y/N) hint itself. There is no appendYesNo.
getInt(message), getDouble(message)No equivalentUse int.tryParse(await promptInput(...) ?? '') and ask again if it is null.
choose(message, options, defaultsTo:)await promptSelect(strings, title: message, initial: index)For other types use await logger.chooseOne(message, choices: options, defaultValue: ..., display: ...).
choose(names:)No equivalentThe numbered list in plain mode uses numbers only.
choose(interactive: false)Plain modePass withPlainMode() in options. A Logger uses plain mode in pipes and CI.
chooseShorthand(...)No equivalentUse promptSelect or filter.

Plain mode and CI

You do not configure anything for CI. When stdin or stdout is not a terminal, when TERM=dumb, or when ACCESSIBLE=1 (or DART_TUI_ACCESSIBLE=1) is set, prompts ask plain line questions and write no escape codes. The plain mode guide lists all the rules.

bash
printf 'demo\n2\n1,3\ny\n' | dart run example/cli_logger.dart   # answers from a pipe
dart run example/cli_logger.dart < /dev/null               # every prompt returns its default
ACCESSIBLE=1 dart run example/cli_logger.dart              # plain questions on a terminal
SituationWhat happens
Esc or Ctrl+C in the TUIThe process exits with code 130.
Input ends in plain modeEvery prompt returns its default. No exit, no error.
No terminalNumbered line questions. NoTerminalAttachedError is never thrown.
NO_COLOR set, or output is a pipeNo colour. With no colour and no terminal, there are no escape codes at all.
FORCE_COLOR or CLICOLOR_FORCE setColour is on.
progress without a terminalOne start line (message...) and one end line (✓ message (0.9s)).

Test your CLI

Pass stdout and stderr as CaptureSink objects from package:dart_tui/testing.dart, and read what the logger wrote with .text. To answer a prompt in the TUI, build the logger with fake output and run the call inside TuiTester.run. See the testing guide for the tester.

dart
import 'dart:convert';

import 'package:dart_tui/cli.dart';
import 'package:dart_tui/testing.dart';
import 'package:test/test.dart';

void main() {
  test('writes to stdout and stderr', () {
    final out = CaptureSink(), err = CaptureSink();
    Logger(stdout: out, stderr: err, environment: const {})
      ..info('hello')
      ..warn('careful');
    expect(out.text, 'hello\n');
    expect(err.text, '[WARN] careful\n');
  });

  test('prompt in the TUI', () async {
    final logger = Logger(
      stdout: CaptureSink(),
      stderr: CaptureSink(),
      environment: const {},
    );
    final t = TuiTester.run(() => logger.prompt('Name?', defaultValue: 'app'));
    addTearDown(t.dispose);
    await t.type('demo');
    await t.press('enter');
    expect((await t.done()).value, 'demo');
  });

  test('plain mode reads answers from stdin', () async {
    final logger = Logger(
      stdout: CaptureSink(),
      stderr: CaptureSink(),
      stdin: Stream.value(utf8.encode('2\n')),
      environment: const {'ACCESSIBLE': '1'},
    );
    expect(await logger.chooseOne('Pick', choices: ['a', 'b']), 'b');
  });
}
To test the cancel path, pass exit: (code) => throw MyExit(code) and expect the throw. The default exit ends the process.

New one-shot options

The Logger is built on the one-shot prompts, and they gained options you can use directly. promptMultiSelect(choices, title:, initial:) is new: Space or x toggles, a toggles all, Enter confirms, and it returns the checked strings in list order. promptSelect takes initial:, promptConfirm takes defaultValue:, and promptInput takes hidden: and defaultValue:.

Related