Skip to content

Commit

Permalink
add some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
renancaraujo committed Jan 18, 2024
1 parent a4f2d0b commit 805f367
Show file tree
Hide file tree
Showing 17 changed files with 625 additions and 72 deletions.
1 change: 1 addition & 0 deletions .github/cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@
],
"useGitignore": true,
"words": [
"depgen"
]
}
1 change: 1 addition & 0 deletions lib/src/commands/commands.dart
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export 'create_command.dart';
export 'mixins.dart';
export 'update_command.dart';
13 changes: 8 additions & 5 deletions lib/src/commands/create_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,16 @@ Will keep existing entries and add new ones if needed.

@override
Future<int> run() async {
logger.level = logLevel;
super.run();

final repoRoot = await getRepositoryRoot();

final dependabotFile = getDependabotFile(repositoryRoot: repoRoot);
final dependabotFile = DependabotFile.fromRepositoryRoot(repoRoot);

logger.info(
'Creating dependabot.yaml in ${dependabotFile.path}}',
);


final newEntries = ecosystems.fold(
<UpdateEntry>[],
(previousValue, element) {
Expand Down Expand Up @@ -100,13 +100,16 @@ Entry for ${newEntry.ecosystem} already exists for ${newEntry.directory}''',
continue;
}

dependabotFile.removeUpdateEntry(entry);
dependabotFile.removeUpdateEntry(
ecosystem: entry.ecosystem,
directory: entry.directory,
);
logger.info(
yellow.wrap('Removed ${entry.ecosystem} entry for ${entry.directory}'),
);
}

dependabotFile.commitChanges();
dependabotFile.saveToFile();

logger.info('Finished creating dependabot.yaml in $repoRoot');

Expand Down
17 changes: 16 additions & 1 deletion lib/src/commands/mixins.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:async';

import 'dart:io';

import 'package:args/command_runner.dart';
Expand Down Expand Up @@ -28,6 +30,12 @@ abstract class MixinsCommand<T> extends Command<T> {

/// The [Logger] for this command.
Logger get logger => _logger;

@mustCallSuper
@override
FutureOr<T>? run() {
return null;
}
}

/// Adds the `--silent` and `--verbose` options to the command.
Expand Down Expand Up @@ -72,6 +80,14 @@ mixin LoggerLevelOption<T> on MixinsCommand<T> {

return Level.info;
}

@mustCallSuper
@override
FutureOr<T>? run() {
super.run();
logger.level = logLevel;
return null;
}
}

/// Adds the `--schedule-interval` option to the command.
Expand Down Expand Up @@ -188,7 +204,6 @@ mixin MilestoneOption<T> on MixinsCommand<T> {
}
}


/// Adds the `--ecosystems` option to the command.
mixin EcosystemsOption<T> on MixinsCommand<T> {
@override
Expand Down
23 changes: 11 additions & 12 deletions lib/src/commands/update_command.dart
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
import 'dart:io';

import 'package:args/command_runner.dart';
import 'package:dependabot_gen/src/command_runner.dart';
import 'package:dependabot_gen/src/commands/mixins.dart';
import 'package:dependabot_gen/src/version.dart';
import 'package:mason_logger/mason_logger.dart';
import 'package:pub_updater/pub_updater.dart';

/// {@template update_command}
/// A command which updates the CLI.
/// {@endtemplate}
class UpdateCommand extends Command<int> {
class UpdateCommand extends MixinsCommand<int> with LoggerLevelOption {
/// {@macro update_command}
UpdateCommand({
required Logger logger,
required super.logger,
PubUpdater? pubUpdater,
}) : _logger = logger,
_pubUpdater = pubUpdater ?? PubUpdater();
}) : _pubUpdater = pubUpdater ?? PubUpdater();

final Logger _logger;
final PubUpdater _pubUpdater;

@override
Expand All @@ -31,24 +29,25 @@ class UpdateCommand extends Command<int> {

@override
Future<int> run() async {
final updateCheckProgress = _logger.progress('Checking for updates');
super.run();
final updateCheckProgress = logger.progress('Checking for updates');
late final String latestVersion;
try {
latestVersion = await _pubUpdater.getLatestVersion(packageName);
} catch (error) {
updateCheckProgress.fail();
_logger.err('$error');
logger.err('$error');
return ExitCode.software.code;
}
updateCheckProgress.complete('Checked for updates');

final isUpToDate = packageVersion == latestVersion;
if (isUpToDate) {
_logger.info('CLI is already at the latest version.');
logger.info('CLI is already at the latest version.');
return ExitCode.success.code;
}

final updateProgress = _logger.progress('Updating to $latestVersion');
final updateProgress = logger.progress('Updating to $latestVersion');

late final ProcessResult result;
try {
Expand All @@ -58,13 +57,13 @@ class UpdateCommand extends Command<int> {
);
} catch (error) {
updateProgress.fail();
_logger.err('$error');
logger.err('$error');
return ExitCode.software.code;
}

if (result.exitCode != ExitCode.success.code) {
updateProgress.fail();
_logger.err('Error updating CLI: ${result.stderr}');
logger.err('Error updating CLI: ${result.stderr}');
return ExitCode.software.code;
}

Expand Down
87 changes: 49 additions & 38 deletions lib/src/dependabot_yaml/file.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,10 @@ import 'dart:io';
import 'package:checked_yaml/checked_yaml.dart';
import 'package:dependabot_gen/src/dependabot_yaml/dependabot_yaml.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
import 'package:yaml_edit/yaml_edit.dart';

/// Retrieves the [DependabotFile] for the given [repositoryRoot].
///
/// If the file does not exist, it will be created.
DependabotFile getDependabotFile({required Directory repositoryRoot}) {
final filePath = p.join(repositoryRoot.path, '.github', 'dependabot.yaml');
final filePath2 = p.join(repositoryRoot.path, '.github', 'dependabot.yml');
var file = File(filePath);

if (!file.existsSync()) {
file = File(filePath2);
}

if (!file.existsSync()) {
file = File(filePath)..createSync(recursive: true);
}

return DependabotFile.fromFile(file);
}
import 'package:yaml_writer/yaml_writer.dart';

/// Represents a dependabot.yaml file with its [path].
class DependabotFile {
Expand All @@ -36,15 +19,17 @@ class DependabotFile {
/// Creates a new [DependabotFile] from the given [file].
///
/// If the file is empty, a default [DependabotSpec] will be created.
@visibleForTesting
factory DependabotFile.fromFile(File file) {
final contents = file.readAsStringSync();
var contents = file.existsSync() ? file.readAsStringSync() : '';

DependabotSpec content;
if (contents.isEmpty) {
content = const DependabotSpec(
version: DependabotVersion.v2,
updates: [],
);
contents = YAMLWriter().write(content);
} else {
content = checkedYamlDecode(
contents,
Expand All @@ -62,11 +47,31 @@ class DependabotFile {
sourceUrl: file.uri,
);
}

final editor = YamlEditor(contents);

return DependabotFile._(file.path, content, editor);
}

/// Retrieves the [DependabotFile] for the given [repositoryRoot].
///
/// If the file does not exist, it will be created.
factory DependabotFile.fromRepositoryRoot(Directory repositoryRoot) {
final filePath = p.join(repositoryRoot.path, '.github', 'dependabot.yml');
final filePath2 = p.join(repositoryRoot.path, '.github', 'dependabot.yaml');
var file = File(filePath);

if (!file.existsSync()) {
file = File(filePath2);
}

if (!file.existsSync()) {
file = File(filePath);
}

return DependabotFile.fromFile(file);
}

/// The path to the dependabot.yaml file.
final String path;

Expand All @@ -81,7 +86,7 @@ class DependabotFile {
/// Adds a new [UpdateEntry] to the dependabot.yaml file.
///
/// Does not immediately save the changes to the file.
/// For that, call [commitChanges].
/// For that, call [saveToFile].
void addUpdateEntry(UpdateEntry newEntry) {
_content = _content.copyWith(
updates: [
Expand All @@ -95,30 +100,36 @@ class DependabotFile {
/// Removes an [UpdateEntry] from the dependabot.yaml file.
///
/// Does not immediately save the changes to the file.
/// For that, call [commitChanges].
void removeUpdateEntry(UpdateEntry entry) {
final index = _content.updates.indexWhere(
(element) =>
element.directory == entry.directory &&
element.ecosystem == entry.ecosystem,
);

if (index == -1) {
/// For that, call [saveToFile].
void removeUpdateEntry({
required String directory,
required String ecosystem,
}) {
final matchingEntries = [..._content.updates].indexed.where(
(e) => e.$2.directory == directory && e.$2.ecosystem == ecosystem,
);

if (matchingEntries.isEmpty) {
return;
}

_content = _content.copyWith(
updates: [
..._content.updates.take(index),
..._content.updates.skip(index + 1),
],
_content.updates.removeWhere(
(e) => e.directory == directory && e.ecosystem == ecosystem,
);

_editor.remove(['updates', index]);
for (final (index, _) in matchingEntries) {
_editor.remove(['updates', index]);
}
}

/// Saves the changes to the actual dependabot.yaml file.
void commitChanges() {
File(path).writeAsStringSync(_editor.toString());
void saveToFile() {
final file = File(path);

if (!file.existsSync()) {
file.createSync(recursive: true);
}

file.writeAsStringSync(_editor.toString());
}
}
Loading

0 comments on commit 805f367

Please sign in to comment.