Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
35 changes: 33 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,36 @@ _\* Learn more at [Flutter Starter App: Very Good Core & CLI][very_good_cli_blog

---

### `$ very_good packages get`

Get packages in a Dart or Flutter project.

```sh
# Install packages in the current directory
$ very_good packages get

# Install packages in ./some/other/directory
$ very_good packages get ./some/other/directory

# Install packages recursively
$ very_good packages get --recursive

# Install packages recursively (shorthand)
$ very_good packages get -r
```

#### Complete Usage

```sh
Get packages in a Dart or Flutter project.

Usage: very_good packages get [arguments]
-h, --help Print this usage information.
-r, --recursive Install dependencies recursively for all nested packages.

Run "very_good help" to see global options.
```

### `$ very_good --help`

See the complete list of commands and usage information.
Expand All @@ -96,8 +126,9 @@ Global options:
[true] Enable anonymous usage statistics

Available commands:
create very_good create <output directory>
Creates a new very good flutter project in the specified directory.
create very_good create <output directory>
Creates a new very good project in the specified directory.
packages Command for managing packages.

Run "very_good help <command>" for more information about a command.
```
Expand Down
5 changes: 5 additions & 0 deletions lib/src/cli/cli.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,12 @@ class _Cmd {
}
}

final _ignoredDirectories = RegExp(
'ios|android|windows|linux|macos|.symlinks|.plugin_symlinks|.dart_tool|build',
);

bool _isPubspec(FileSystemEntity entity) {
if (entity.path.contains(_ignoredDirectories)) return false;
if (entity is! File) return false;
return p.basename(entity.path) == 'pubspec.yaml';
}
1 change: 1 addition & 0 deletions lib/src/command_runner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class VeryGoodCommandRunner extends CommandRunner<int> {
},
);
addCommand(CreateCommand(analytics: _analytics, logger: logger));
addCommand(PackagesCommand(logger: logger));
}

/// Standard timeout duration for the CLI.
Expand Down
1 change: 1 addition & 0 deletions lib/src/commands/commands.dart
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export 'create.dart';
export 'packages.dart';
84 changes: 84 additions & 0 deletions lib/src/commands/packages.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:io/io.dart';
import 'package:mason/mason.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'package:universal_io/io.dart';
import 'package:very_good_cli/src/cli/cli.dart';

/// {@template packages_command}
/// `very_good packages` command for managing packages.
/// {@endtemplate}
class PackagesCommand extends Command<int> {
/// {@macro packages_command}
PackagesCommand({Logger? logger}) {
addSubcommand(PackagesGetCommand(logger: logger));
}

@override
String get description => 'Command for managing packages.';

@override
String get name => 'packages';
}

/// {@template packages_get_command}
/// `very_good packages` command for installing packages.
/// {@endtemplate}
class PackagesGetCommand extends Command<int> {
/// {@macro packages_get_command}
PackagesGetCommand({Logger? logger}) : _logger = logger ?? Logger() {
argParser.addFlag(
'recursive',
abbr: 'r',
help: 'Install dependencies recursively for all nested packages.',
negatable: false,
);
}

final Logger _logger;

@override
String get description => 'Get packages in a Dart or Flutter project.';

@override
String get name => 'get';

/// [ArgResults] which can be overridden for testing.
@visibleForTesting
ArgResults? argResultOverrides;

ArgResults get _argResults => argResultOverrides ?? argResults!;

@override
Future<int> run() async {
if (_argResults.rest.length > 1) {
throw UsageException('Too many arguments', usage);
}

final recursive = _argResults['recursive'] as bool;
final target = _argResults.rest.length == 1 ? _argResults.rest[0] : '.';
final targetDir = Directory(target);
final targetPath = path.normalize(targetDir.absolute.path);
final isFlutterInstalled = await Flutter.installed();
if (isFlutterInstalled) {
final installDependenciesDone = _logger.progress(
'Running "flutter packages get" in $targetPath',
);
try {
await Flutter.packagesGet(cwd: targetDir.path, recursive: recursive);
installDependenciesDone();
} on PubspecNotFound catch (_) {
installDependenciesDone();
_logger.err('Could not find a pubspec.yaml in $targetPath');
return ExitCode.noInput.code;
} catch (error) {
installDependenciesDone();
_logger.err('$error');
return ExitCode.unavailable.code;
}
}
return ExitCode.success.code;
}
}
5 changes: 3 additions & 2 deletions test/src/command_runner_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ const expectedUsage = [
' [true] Enable anonymous usage statistics\n'
'\n'
'Available commands:\n'
' create very_good create <output directory>\n'
''' Creates a new very good project in the specified directory.\n'''
' create very_good create <output directory>\n'
''' Creates a new very good project in the specified directory.\n'''
' packages Command for managing packages.\n'
'\n'
'Run "very_good help <command>" for more information about a command.'
];
Expand Down
2 changes: 1 addition & 1 deletion test/src/commands/create_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class FakeDirectoryGeneratorTarget extends Fake
implements DirectoryGeneratorTarget {}

void main() {
group('Create', () {
group('create', () {
late List<String> progressLogs;
late List<String> printLogs;
late Analytics analytics;
Expand Down
188 changes: 188 additions & 0 deletions test/src/commands/packages_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import 'dart:async';

import 'package:io/io.dart';
import 'package:mason/mason.dart';
import 'package:mocktail/mocktail.dart';
import 'package:path/path.dart' as path;
import 'package:pub_updater/pub_updater.dart';
import 'package:test/test.dart';
import 'package:universal_io/io.dart';
import 'package:usage/usage.dart';
import 'package:very_good_cli/src/command_runner.dart';

class MockAnalytics extends Mock implements Analytics {}

class MockLogger extends Mock implements Logger {}

class MockPubUpdater extends Mock implements PubUpdater {}

const expectedPackagesUsage = [
// ignore: no_adjacent_strings_in_list
'Command for managing packages.\n'
'\n'
'Usage: very_good packages <subcommand> [arguments]\n'
'-h, --help Print this usage information.\n'
'\n'
'Available subcommands:\n'
' get Get packages in a Dart or Flutter project.\n'
'\n'
'Run "very_good help" to see global options.'
];

const expectedPackagesGetUsage = [
// ignore: no_adjacent_strings_in_list
'Get packages in a Dart or Flutter project.\n'
'\n'
'Usage: very_good packages get [arguments]\n'
'-h, --help Print this usage information.\n'
'''-r, --recursive Install dependencies recursively for all nested packages.\n'''
'\n'
'Run "very_good help" to see global options.'
];

void main() {
group('packages', () {
late Analytics analytics;
late Logger logger;
late PubUpdater pubUpdater;
late List<String> printLogs;
late List<String> progressLogs;
late VeryGoodCommandRunner commandRunner;

void Function() overridePrint(void Function() fn) {
return () {
final spec = ZoneSpecification(print: (_, __, ___, String msg) {
printLogs.add(msg);
});
return Zone.current.fork(specification: spec).run<void>(fn);
};
}

setUp(() {
analytics = MockAnalytics();
logger = MockLogger();
pubUpdater = MockPubUpdater();
printLogs = [];
progressLogs = [];
commandRunner = VeryGoodCommandRunner(
analytics: analytics,
logger: logger,
pubUpdater: pubUpdater,
);

when(() => analytics.firstRun).thenReturn(false);
when(() => analytics.enabled).thenReturn(false);
when(
() => analytics.sendEvent(any(), any(), label: any(named: 'label')),
).thenAnswer((_) async {});
when(
() => analytics.waitForLastPing(timeout: any(named: 'timeout')),
).thenAnswer((_) async {});

when(() => logger.progress(any())).thenReturn(
([_]) {
if (_ != null) progressLogs.add(_);
},
);

when(
() => pubUpdater.isUpToDate(
packageName: any(named: 'packageName'),
currentVersion: any(named: 'currentVersion'),
),
).thenAnswer((_) => Future.value(true));
});

test('help', overridePrint(() async {
final result = await commandRunner.run(['packages', '--help']);
expect(printLogs, equals(expectedPackagesUsage));
expect(result, equals(ExitCode.success.code));

printLogs.clear();

final resultAbbr = await commandRunner.run(['packages', '-h']);
expect(printLogs, equals(expectedPackagesUsage));
expect(resultAbbr, equals(ExitCode.success.code));
}));

group('get', () {
test('help', overridePrint(() async {
final result = await commandRunner.run(['packages', 'get', '--help']);
expect(printLogs, equals(expectedPackagesGetUsage));
expect(result, equals(ExitCode.success.code));

printLogs.clear();

final resultAbbr = await commandRunner.run(['packages', 'get', '-h']);
expect(printLogs, equals(expectedPackagesGetUsage));
expect(resultAbbr, equals(ExitCode.success.code));
}));

test(
'throws usage exception '
'when too many arguments are provided', () async {
final result = await commandRunner.run(
['packages', 'get', 'arg1', 'arg2'],
);
expect(result, equals(ExitCode.usage.code));
});

test(
'throws pubspec not found exception '
'when no pubspec.yaml exists', () async {
final result = await commandRunner.run(['packages', 'get', 'test']);
expect(result, equals(ExitCode.noInput.code));
verify(() {
logger.err(any(that: contains('Could not find a pubspec.yaml in')));
}).called(1);
});

test(
'throws pubspec not found exception '
'when no pubspec.yaml exists (recursive)', () async {
final result = await commandRunner.run(
['packages', 'get', '-r', 'test'],
);
expect(result, equals(ExitCode.noInput.code));
verify(() {
logger.err(any(that: contains('Could not find a pubspec.yaml in')));
}).called(1);
});

test('throws when installation fails', () async {
final directory = Directory.systemTemp.createTempSync();
File(path.join(directory.path, 'pubspec.yaml')).writeAsStringSync('');
final result = await commandRunner.run(
['packages', 'get', directory.path],
);
expect(result, equals(ExitCode.unavailable.code));
});

test(
'completes normally '
'when pubspec.yaml exists', () async {
final result = await commandRunner.run(['packages', 'get']);
expect(result, equals(ExitCode.success.code));
verify(() {
logger.progress(
any(that: contains('Running "flutter packages get" in')),
);
}).called(1);
});

test(
'completes normally '
'when pubspec.yaml exists (recursive)', () async {
final result = await commandRunner.run(
['packages', 'get', '--recursive'],
);
expect(result, equals(ExitCode.success.code));
verify(() {
logger.progress(
any(that: contains('Running "flutter packages get" in')),
);
}).called(1);
});
});
});
}