Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add thank you message #814

Merged
merged 6 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions e2e/helpers/command_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ void Function() withRunner(
final commandRunner = VeryGoodCommandRunner(
logger: logger,
pubUpdater: pubUpdater,
environment: {'CI': 'true'},
);

when(() => progress.complete(any())).thenAnswer((_) {
Expand Down
51 changes: 51 additions & 0 deletions lib/src/command_runner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:cli_completion/cli_completion.dart';
import 'package:mason/mason.dart' hide packageVersion;
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'package:pub_updater/pub_updater.dart';
import 'package:universal_io/io.dart';
import 'package:very_good_cli/src/commands/commands.dart';
import 'package:very_good_cli/src/logger_extension.dart';
import 'package:very_good_cli/src/version.dart';

/// The package name.
Expand All @@ -17,8 +21,10 @@ class VeryGoodCommandRunner extends CompletionCommandRunner<int> {
VeryGoodCommandRunner({
Logger? logger,
PubUpdater? pubUpdater,
Map<String, String>? environment,
}) : _logger = logger ?? Logger(),
_pubUpdater = pubUpdater ?? PubUpdater(),
_environment = environment ?? Platform.environment,
super('very_good', '🦄 A Very Good Command-Line Interface') {
argParser
..addFlag(
Expand All @@ -42,6 +48,16 @@ class VeryGoodCommandRunner extends CompletionCommandRunner<int> {
final Logger _logger;
final PubUpdater _pubUpdater;

/// Map of environments information.
Map<String, String> get environment => environmentOverride ?? _environment;
final Map<String, String> _environment;

/// Boolean for checking if windows, which can be overridden for
/// testing purposes.
@visibleForTesting
bool? isWindowsOverride;
bool get _isWindows => isWindowsOverride ?? Platform.isWindows;

@override
void printUsage() => _logger.info(usage);

Expand Down Expand Up @@ -112,6 +128,7 @@ class VeryGoodCommandRunner extends CompletionCommandRunner<int> {
if (topLevelResults.command?.name != UpdateCommand.commandName) {
await _checkForUpdates();
}
_showThankYou();
return exitCode;
}

Expand All @@ -131,4 +148,38 @@ Run ${lightCyan.wrap('very_good update')} to update''',
}
} catch (_) {}
}

void _showThankYou() {
if (environment.containsKey('CI')) return;

final versionFile = File(
path.join(_configDir.path, 'version'),
)..createSync(recursive: true);

if (versionFile.readAsStringSync() == packageVersion) return;
versionFile.writeAsStringSync(packageVersion);

_logger.wrap(
lightMagenta.wrap('''

Thank you for using Very Good CLI from Very Good Ventures. If you want to stay in touch with us and get information on future updates please go join our newsletter: ${lightBlue.wrap(link(uri: Uri.parse('https://verygood.ventures/#newsletter')))}'''),
wolfenrain marked this conversation as resolved.
Show resolved Hide resolved
print: _logger.info,
);
}

Directory get _configDir {
if (_isWindows) {
// Use localappdata on windows
final localAppData = environment['LOCALAPPDATA']!;
return Directory(path.join(localAppData, 'VeryGoodCLI'));
} else {
// Try using XDG config folder
var dirPath = environment['XDG_CONFIG_HOME'];
// Fallback to $HOME if not following XDG specification
if (dirPath == null || dirPath.isEmpty) {
dirPath = environment['HOME'];
}
return Directory(path.join(dirPath!, '.very_good_cli'));
wolfenrain marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
32 changes: 32 additions & 0 deletions lib/src/logger_extension.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,41 @@
import 'package:mason_logger/mason_logger.dart';
import 'package:universal_io/io.dart';

/// Extension on the Logger class for custom styled logging.
extension LoggerX on Logger {
/// Log a message in the "created" style of the CLI.
void created(String message) {
info(lightCyan.wrap(styleBold.wrap(message)));
}

/// Wrap the [text] to fit perfectly within the width of the terminal when
/// [print]ed.
///
/// To overwrite the width you can use [length].
void wrap(
alestiago marked this conversation as resolved.
Show resolved Hide resolved
String? text, {
wolfenrain marked this conversation as resolved.
Show resolved Hide resolved
required void Function(String?) print,
int? length,
}) {
final maxLength = length ?? stdout.terminalColumns;
for (final sentence in text?.split('/n') ?? <String>[]) {
final words = sentence.split(' ');

final currentLine = StringBuffer();
for (final word in words) {
// Replace all ANSI sequences so we can get the true character length.
final charLength = word
.replaceAll(RegExp('\x1B(?:[@-Z\\-_]|[[0-?]*[ -/]*[@-~])'), '')
.length;

if (currentLine.length + charLength > maxLength) {
print(currentLine.toString());
currentLine.clear();
}
currentLine.write('$word ');
}

print(currentLine.toString());
}
}
}
1 change: 1 addition & 0 deletions test/helpers/command_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ void Function() withRunner(
final commandRunner = VeryGoodCommandRunner(
logger: logger,
pubUpdater: pubUpdater,
environment: {'CI': 'true'},
);

when(() => progress.complete(any())).thenAnswer((_) {
Expand Down
113 changes: 113 additions & 0 deletions test/src/command_runner_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ class MockPubUpdater extends Mock implements PubUpdater {}

class MockProgress extends Mock implements Progress {}

class MockDirectory extends Mock implements Directory {}

class MockFile extends Mock implements File {}

class MockStdout extends Mock implements Stdout {}
wolfenrain marked this conversation as resolved.
Show resolved Hide resolved

const expectedUsage = [
'🦄 A Very Good Command-Line Interface\n'
'\n'
Expand Down Expand Up @@ -71,6 +77,7 @@ void main() {
commandRunner = VeryGoodCommandRunner(
logger: logger,
pubUpdater: pubUpdater,
environment: {'CI': 'true'},
);
});

Expand Down Expand Up @@ -179,6 +186,112 @@ void main() {
expect(result, equals(ExitCode.success.code));
});

group('_showThankYou', () {
late Directory cliCache;
late File versionFile;
late Stdout stdout;

setUp(() {
cliCache = MockDirectory();
when(() => cliCache.path).thenReturn('/users/test');

versionFile = MockFile();
when(() => versionFile.readAsStringSync()).thenReturn('0.0.0');

stdout = MockStdout();
when(() => stdout.supportsAnsiEscapes).thenReturn(true);
when(() => stdout.terminalColumns).thenReturn(30);
});

test('shows message when version changed', () async {
commandRunner.environmentOverride = {
'HOME': '/users/test',
};

await IOOverrides.runZoned(
() async {
final result = await commandRunner.run([]);
expect(result, equals(ExitCode.success.code));

verifyInOrder([
() => logger.info('\nThank you for using Very Good '),
() => logger.info('CLI from Very Good Ventures. '),
() => logger.info('If you want to stay in touch '),
() => logger.info('with us and get information on '),
() => logger.info('future updates please go join '),
() => logger.info('our newsletter: '),
() => logger.info(
any(
that: contains('https://verygood.ventures/#newsletter'),
),
),
]);

verify(
() => versionFile.createSync(
recursive: any(that: isTrue, named: 'recursive'),
),
).called(1);
verify(() => versionFile.readAsStringSync()).called(1);
verify(
() => versionFile
.writeAsStringSync(any(that: equals(packageVersion))),
).called(1);
},
createDirectory: (path) => cliCache,
createFile: (path) => versionFile,
stdout: () => stdout,
);
});

test('cache inside XDG directory', () async {
commandRunner.environmentOverride = {
'HOME': '/users/test',
'XDG_CONFIG_HOME': '/users/test/.xdg',
};

final xdgCache = MockDirectory();
when(() => xdgCache.path).thenReturn('/users/test/.xdg');

await IOOverrides.runZoned(
() async {
final result = await commandRunner.run([]);
expect(result, equals(ExitCode.success.code));

verifyNever(() => cliCache.path);
verify(() => xdgCache.path).called(1);
},
createDirectory: (path) =>
path.contains('.xdg') ? xdgCache : cliCache,
createFile: (path) => versionFile,
stdout: () => stdout,
);
});

test('cache inside local APP_DATA on windows', () async {
commandRunner
..environmentOverride = {'LOCALAPPDATA': '/C/Users/test'}
..isWindowsOverride = true;

final windowsCache = MockDirectory();
when(() => windowsCache.path).thenReturn('/C/Users/test');

await IOOverrides.runZoned(
() async {
final result = await commandRunner.run([]);
expect(result, equals(ExitCode.success.code));

verifyNever(() => cliCache.path);
verify(() => windowsCache.path).called(1);
},
createDirectory: (path) =>
path.startsWith('/C/') ? windowsCache : cliCache,
createFile: (path) => versionFile,
stdout: () => stdout,
);
});
});

group('--help', () {
test('outputs usage', () async {
final result = await commandRunner.run(['--help']);
Expand Down
50 changes: 50 additions & 0 deletions test/src/logger_extension_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import 'package:mason/mason.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import 'package:very_good_cli/src/logger_extension.dart';

class _MockLogger extends Mock implements Logger {}

void main() {
group('LoggerX', () {
late Logger logger;

setUp(() {
logger = _MockLogger();
});

test('created', () {
logger.created('test');

verify(
() => logger.info(
any(that: equals(lightCyan.wrap(styleBold.wrap('test')))),
),
).called(1);
});

group('wrap', () {
test('normally across two separate prints', () {
logger.wrap('1 2 3 4 5 1 2 3 4 5', print: logger.info, length: 10);

verifyInOrder([
() => logger.info(any(that: equals('1 2 3 4 5 '))),
() => logger.info(any(that: equals('1 2 3 4 5 '))),
]);
});

test('across two separate prints while not adding in ANSI encoding', () {
logger.wrap(
'${lightCyan.wrap('1 2 3 4 5')} 1 2 3 4 5',
print: logger.info,
length: 10,
);

verifyInOrder([
() => logger.info(any(that: equals(lightCyan.wrap('1 2 3 4 5 ')))),
() => logger.info(any(that: equals('1 2 3 4 5 '))),
]);
});
});
});
}