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

Add fix command #152

Merged
merged 8 commits into from
Nov 7, 2024
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
114 changes: 104 additions & 10 deletions lib/src/analyzers/lint_analyzer/lint_analyzer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,105 @@ class LintAnalyzer {
return analyzerResult;
}

Future<void> runCliFix(
Iterable<String> folders,
String rootFolder,
LintConfig config, {
String? sdkPath,
}) async {
final collection = createAnalysisContextCollection(folders, rootFolder, sdkPath);

for (final context in collection.contexts) {
final lintAnalysisConfig = _getAnalysisConfig(context, rootFolder, config);

if (config.shouldPrintConfig) {
_logger?.printConfig(lintAnalysisConfig.toJson());
}

final filePaths = getFilePaths(
folders,
context,
rootFolder,
lintAnalysisConfig.globalExcludes,
);

final analyzedFiles = filePaths.intersection(context.contextRoot.analyzedFiles().toSet());

final contextsLength = collection.contexts.length;
final filesLength = analyzedFiles.length;
final updateMessage = contextsLength == 1
? 'Fixing $filesLength file(s)'
: 'Fixing ${collection.contexts.indexOf(context) + 1}/$contextsLength contexts with $filesLength file(s)';
_logger?.progress.update(updateMessage);

for (final filePath in analyzedFiles) {
_logger?.infoVerbose('Fixing $filePath\n');

final unit = await context.currentSession.getResolvedUnit(filePath);
if (unit is ResolvedUnitResult) {
santitigaga marked this conversation as resolved.
Show resolved Hide resolved
final (issuesNo, fixesNo) = _analyzeAndFixFile(
unit,
lintAnalysisConfig,
rootFolder,
filePath: filePath,
);

if (issuesNo != 0) {
_logger?.write(
'\nFix result: fixed $fixesNo out of $issuesNo issues\n',
);
} else {
_logger?.infoVerbose(
'No issues found',
);
}
}
}
}

return;
}

(int issuesNo, int fixesNo) _analyzeAndFixFile(
ResolvedUnitResult unit,
LintAnalysisConfig config,
String rootFolder, {
required String filePath,
}) {
final result = _analyzeFile(unit, config, rootFolder, filePath: filePath);

if (result == null || result.issues.isEmpty) {
return (0, 0);
}

final originalContent = StringBuffer(unit.content);
var fixedContent = originalContent.toString();
final fixedIssues = <Issue>[];

for (final issue in result.issues) {
final fix = issue.suggestion;

if (fix != null) {
fixedContent = fixedContent.replaceRange(
issue.location.start.offset,
issue.location.end.offset,
fix.replacement,
);

fixedIssues.add(issue);
}
}

_applyFixesToFile(fixedContent, filePath);

return (result.issues.length, fixedIssues.length);
}

Future<void> _applyFixesToFile(String fixedContent, String filePath) async {
final file = File(filePath);
await file.writeAsString(fixedContent);
}

Iterable<SummaryLintReportRecord<Object>> getSummary(
Iterable<LintFileReport> records,
) =>
Expand All @@ -164,14 +263,12 @@ class LintAnalyzer {
SummaryLintReportRecord<num>(
title: 'Average Cyclomatic Number per line of code',
value: averageCYCLO(records),
violations:
metricViolations(records, CyclomaticComplexityMetric.metricId),
violations: metricViolations(records, CyclomaticComplexityMetric.metricId),
),
SummaryLintReportRecord<int>(
title: 'Average Source Lines of Code per method',
value: averageSLOC(records),
violations:
metricViolations(records, SourceLinesOfCodeMetric.metricId),
violations: metricViolations(records, SourceLinesOfCodeMetric.metricId),
),
SummaryLintReportRecord<String>(
title: 'Total tech debt',
Expand All @@ -184,11 +281,9 @@ class LintAnalyzer {
String rootFolder,
LintConfig config,
) {
final analysisOptions = analysisOptionsFromContext(context) ??
analysisOptionsFromFilePath(rootFolder, context);
final analysisOptions = analysisOptionsFromContext(context) ?? analysisOptionsFromFilePath(rootFolder, context);

final contextConfig =
ConfigBuilder.getLintConfigFromOptions(analysisOptions).merge(config);
final contextConfig = ConfigBuilder.getLintConfigFromOptions(analysisOptions).merge(config);

return ConfigBuilder.getLintAnalysisConfig(
contextConfig,
Expand Down Expand Up @@ -231,8 +326,7 @@ class LintAnalyzer {

final classMetrics = _checkClassMetrics(visitor, internalResult, config);
final fileMetrics = _checkFileMetrics(visitor, internalResult, config);
final functionMetrics =
_checkFunctionMetrics(visitor, internalResult, config);
final functionMetrics = _checkFunctionMetrics(visitor, internalResult, config);
final antiPatterns = _checkOnAntiPatterns(
ignores,
internalResult,
Expand Down
2 changes: 2 additions & 0 deletions lib/src/cli/cli_runner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import 'commands/check_unnecessary_nullable_command.dart';
import 'commands/check_unused_code_command.dart';
import 'commands/check_unused_files_command.dart';
import 'commands/check_unused_l10n_command.dart';
import 'commands/fix_lints_command.dart';
import 'models/flag_names.dart';

/// Represents a cli runner responsible
Expand All @@ -29,6 +30,7 @@ class CliRunner extends CommandRunner<void> {
CheckUnusedL10nCommand(_logger),
CheckUnusedCodeCommand(_logger),
CheckUnnecessaryNullableCommand(_logger),
FixCommand(_logger),
].forEach(addCommand);

_usesVersionOption();
Expand Down
78 changes: 78 additions & 0 deletions lib/src/cli/commands/fix_lints_command.dart
santitigaga marked this conversation as resolved.
Show resolved Hide resolved
santitigaga marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// ignore_for_file: public_member_api_docs

import '../../../config.dart';
import '../../../lint_analyzer.dart';
import '../../logger/logger.dart';
import '../models/flag_names.dart';
import 'base_command.dart';

class FixCommand extends BaseCommand {
final LintAnalyzer _analyzer;
final Logger _logger;

@override
String get name => 'fix';

@override
String get description =>
'Automatically fix code issues based on lint rules and metrics.';

@override
String get invocation =>
'${runner?.executableName} $name [arguments] <directories>';

FixCommand(this._logger) : _analyzer = LintAnalyzer(_logger) {
_addFlags();
}

@override
Future<void> runCommand() async {
_logger
..isSilent = isNoCongratulate
..isVerbose = isVerbose
..progress.start('Applying fixes');

final parsedArgs = ParsedArguments.fromArgsNoMetrics(argResults);
final config = ConfigBuilder.getLintConfigFromArgs(parsedArgs);

// Run the analysis and apply fixes
await _analyzer.runCliFix(
argResults.rest,
parsedArgs.rootFolder,
config,
sdkPath: findSdkPath(),
);

_logger.progress.complete('Fixes have been applied. Preparing the results:');
}

void _addFlags() {
addCommonFlags();
_usesExitOption();
}

void _usesExitOption() {
argParser
..addSeparator('')
..addOption(
FlagNames.setExitOnViolationLevel,
allowed: ['noted', 'warning', 'alarm'],
valueHelp: 'warning',
help:
'Set exit code 2 if code violations same or higher level than selected are detected.',
)
..addFlag(
FlagNames.fatalStyle,
help: 'Treat style level issues as fatal.',
)
..addFlag(
FlagNames.fatalPerformance,
help: 'Treat performance level issues as fatal.',
)
..addFlag(
FlagNames.fatalWarnings,
help: 'Treat warning level issues as fatal.',
defaultsTo: true,
);
}
}
7 changes: 7 additions & 0 deletions lib/src/cli/models/parsed_arguments.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,11 @@ class ParsedArguments {
metric.id: argResults[metric.id] as Object,
},
);

factory ParsedArguments.fromArgsNoMetrics(ArgResults argResults) => ParsedArguments(
excludePath: argResults[FlagNames.exclude] as String,
rootFolder: argResults[FlagNames.rootFolder] as String,
santitigaga marked this conversation as resolved.
Show resolved Hide resolved
shouldPrintConfig: argResults[FlagNames.printConfig] as bool,
metricsConfig: {},
);
}