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

Ci/docs #157

Merged
merged 3 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
19 changes: 19 additions & 0 deletions .github/workflows/build-docs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: "Build documentation"
on:
pull_request:
branches:
- gh-pages-source
jobs:
test-docs:
permissions:
id-token: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
- name: Install dependencies
run: npm install
- name: Build docs
run: npm run build
44 changes: 44 additions & 0 deletions .github/workflows/release-docs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Deploy Documentation

on:
push:
branches:
- gh-pages-source
jobs:
build:
name: Build Docusaurus
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 18

- name: Install dependencies
run: npm install
- name: Build website
run: npm run build

- name: Upload Build Artifact
uses: actions/upload-pages-artifact@v3
with:
path: build

deploy:
name: Deploy to GitHub Pages
needs: build

permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}

runs-on: ubuntu-latest
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
47 changes: 30 additions & 17 deletions lib/src/analyzers/lint_analyzer/lint_analyzer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ class LintAnalyzer {
LintConfig config, {
String? sdkPath,
}) async {
final collection = createAnalysisContextCollection(folders, rootFolder, sdkPath);
final collection =
createAnalysisContextCollection(folders, rootFolder, sdkPath);
final analyzerResult = <LintFileReport>[];

for (final context in collection.contexts) {
Expand Down Expand Up @@ -125,7 +126,8 @@ class LintAnalyzer {
LintConfig config, {
String? sdkPath,
}) async {
final collection = createAnalysisContextCollection(folders, rootFolder, sdkPath);
final collection =
createAnalysisContextCollection(folders, rootFolder, sdkPath);

for (final context in collection.contexts) {
final (lintAnalysisConfig, analyzedFiles, _) = prepareLintAnalysis(
Expand Down Expand Up @@ -191,7 +193,8 @@ class LintAnalyzer {
rootFolder,
lintAnalysisConfig.globalExcludes,
);
final analyzedFiles = filePaths.intersection(context.contextRoot.analyzedFiles().toSet());
final analyzedFiles =
filePaths.intersection(context.contextRoot.analyzedFiles().toSet());

final contextsLength = collection.contexts.length;
final filesLength = analyzedFiles.length;
Expand Down Expand Up @@ -266,12 +269,14 @@ 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 @@ -284,9 +289,11 @@ 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 @@ -329,7 +336,8 @@ 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 Expand Up @@ -377,10 +385,11 @@ class LintAnalyzer {
createAbsolutePatterns(rule.excludes, config.rootFolder),
))
.expand(
(rule) => rule.check(source).where((issue) => !ignores.isSuppressedAt(
issue.ruleId,
issue.location.start.line,
)),
(rule) =>
rule.check(source).where((issue) => !ignores.isSuppressedAt(
issue.ruleId,
issue.location.start.line,
)),
)
.toList();

Expand All @@ -398,10 +407,12 @@ class LintAnalyzer {
source.path,
createAbsolutePatterns(pattern.excludes, config.rootFolder),
))
.expand((pattern) => pattern.check(source, classMetrics, functionMetrics).where((issue) => !ignores.isSuppressedAt(
issue.ruleId,
issue.location.start.line,
)))
.expand((pattern) => pattern
.check(source, classMetrics, functionMetrics)
.where((issue) => !ignores.isSuppressedAt(
issue.ruleId,
issue.location.start.line,
)))
.toList();

Map<ScopedClassDeclaration, Report> _checkClassMetrics(
Expand Down Expand Up @@ -518,5 +529,7 @@ class LintAnalyzer {
}

bool _isSupported(FileResult result) =>
result.path.endsWith('.dart') && !result.path.endsWith('.g.dart') && !result.path.endsWith('.freezed.dart');
result.path.endsWith('.dart') &&
!result.path.endsWith('.g.dart') &&
!result.path.endsWith('.freezed.dart');
}
3 changes: 2 additions & 1 deletion lib/src/analyzers/lint_analyzer/rules/rules_factory.dart
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ final _implementedRules = <String, Rule Function(Map<String, Object>)>{
MemberOrderingRule.ruleId: MemberOrderingRule.new,
MissingTestAssertionRule.ruleId: MissingTestAssertionRule.new,
NewlineBeforeReturnRule.ruleId: NewlineBeforeReturnRule.new,
NoBlankLineBeforeSingleReturnRule.ruleId: NoBlankLineBeforeSingleReturnRule.new,
NoBlankLineBeforeSingleReturnRule.ruleId:
NoBlankLineBeforeSingleReturnRule.new,
PreferFirstOrNullRule.ruleId: PreferFirstOrNullRule.new,
PreferSingleQuotesRule.ruleId: PreferSingleQuotesRule.new,
NoBooleanLiteralCompareRule.ruleId: NoBooleanLiteralCompareRule.new,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ part 'visitor.dart';
class NoBlankLineBeforeSingleReturnRule extends DartRule {
static const String ruleId = 'no-blank-line-before-single-return';

static const warning = 'Remove blank line before single return statement in a block.';
static const warning =
'Remove blank line before single return statement in a block.';

NoBlankLineBeforeSingleReturnRule([Map<String, Object> config = const {}])
: super(
Expand Down Expand Up @@ -72,10 +73,13 @@ Token _optimalToken(Token token, LineInfo lineInfo) {
var commentToken = _latestCommentToken(token);

while (commentToken != null) {
final commentTokenLineNumber = lineInfo.getLocation(commentToken.end).lineNumber;
final optimalTokenLineNumber = lineInfo.getLocation(optimalToken.offset).lineNumber;
final commentTokenLineNumber =
lineInfo.getLocation(commentToken.end).lineNumber;
final optimalTokenLineNumber =
lineInfo.getLocation(optimalToken.offset).lineNumber;

final isDirectlyPrecedingComment = commentTokenLineNumber + 1 >= optimalTokenLineNumber;
final isDirectlyPrecedingComment =
commentTokenLineNumber + 1 >= optimalTokenLineNumber;

if (!isDirectlyPrecedingComment) {
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ part 'visitor.dart';

class PreferFirstOrNullRule extends DartRule {
static const ruleId = 'prefer-first-or-null';
static const warningMessage = 'Use firstOrNull instead of accessing the element at zero index or using first.';
static const warningMessage =
'Use firstOrNull instead of accessing the element at zero index or using first.';
static const replaceComment = "Replace with 'firstOrNull'.";

PreferFirstOrNullRule([Map<String, Object> config = const {}])
Expand Down Expand Up @@ -48,9 +49,13 @@ class PreferFirstOrNullRule extends DartRule {
String replacement;

if (expression is MethodInvocation) {
replacement = expression.isCascaded ? '..firstOrNull' : '${expression.target ?? ''}.firstOrNull';
replacement = expression.isCascaded
? '..firstOrNull'
: '${expression.target ?? ''}.firstOrNull';
} else if (expression is IndexExpression) {
replacement = expression.isCascaded ? '..firstOrNull' : '${expression.target ?? ''}.firstOrNull';
replacement = expression.isCascaded
? '..firstOrNull'
: '${expression.target ?? ''}.firstOrNull';
} else if (expression is PrefixedIdentifier) {
replacement = '${expression.prefix.token.lexeme}.firstOrNull';
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ class _Visitor extends RecursiveAstVisitor<void> {

final targetType = node.prefix.staticType;

if (node.identifier.name == 'first' && targetType is InterfaceType && isIterableOrSubclass(targetType)) {
if (node.identifier.name == 'first' &&
targetType is InterfaceType &&
isIterableOrSubclass(targetType)) {
_expressions.add(node);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ part 'visitor.dart';

class PreferSingleQuotesRule extends DartRule {
static const ruleId = 'prefer-single-quotes';
static const _warningMessage = 'Use single quotation marks instead of double quotations.';
static const _warningMessage =
'Use single quotation marks instead of double quotations.';
static const _replaceComment = "Replace with ''.";

PreferSingleQuotesRule([Map<String, Object> config = const {}])
Expand Down
5 changes: 3 additions & 2 deletions lib/src/cli/commands/fix_lints_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ class FixCommand extends BaseCommand {
sdkPath: findSdkPath(),
);

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

void _addFlags() {
Expand Down Expand Up @@ -95,7 +96,7 @@ class FixCommand extends BaseCommand {
allowed: ['noted', 'warning', 'alarm'],
valueHelp: 'warning',
help:
'Set exit code 2 if code violations same or higher level than selected are detected.',
'Set exit code 2 if code violations same or higher level than selected are detected.',
)
..addFlag(
FlagNames.fatalStyle,
Expand Down
3 changes: 2 additions & 1 deletion lib/src/cli/models/parsed_arguments.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ class ParsedArguments {
},
);

factory ParsedArguments.fromArgsNoMetrics(ArgResults argResults) => ParsedArguments(
factory ParsedArguments.fromArgsNoMetrics(ArgResults argResults) =>
ParsedArguments(
excludePath: argResults[FlagNames.exclude] as String,
rootFolder: argResults[FlagNames.rootFolder] as String,
jsonReportPath: argResults[FlagNames.jsonReportPath] as String?,
Expand Down
38 changes: 28 additions & 10 deletions test/src/analyzers/lint_analyzer/lint_analyzer_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ void main() {
config,
);

final report = reportForFile(result, 'lint_analyzer_exclude_example.dart').functions.values.first;
final report =
reportForFile(result, 'lint_analyzer_exclude_example.dart')
.functions
.values
.first;
final metrics = {for (final m in report.metrics) m.metricsId: m.level};

expect(metrics, {
Expand All @@ -79,7 +83,11 @@ void main() {
config,
);

final report = reportForFile(result, 'lint_analyzer_exclude_example.dart').functions.values.first;
final report =
reportForFile(result, 'lint_analyzer_exclude_example.dart')
.functions
.values
.first;
final metrics = {for (final m in report.metrics) m.metricsId: m.level};

expect(metrics, {
Expand All @@ -104,7 +112,10 @@ void main() {
config,
);

final report = reportForFile(result, 'lint_analyzer_exclude_example.dart').functions.values;
final report =
reportForFile(result, 'lint_analyzer_exclude_example.dart')
.functions
.values;

expect(report, isEmpty);
});
Expand All @@ -118,7 +129,8 @@ void main() {
config,
);

final issues = reportForFile(result, 'lint_analyzer_exclude_example.dart').issues;
final issues =
reportForFile(result, 'lint_analyzer_exclude_example.dart').issues;

expect(
issues.map((issue) => issue.ruleId),
Expand All @@ -138,7 +150,8 @@ void main() {
config,
);

final report = reportForFile(result, 'lint_analyzer_exclude_example.dart').issues;
final report =
reportForFile(result, 'lint_analyzer_exclude_example.dart').issues;
expect(report, isEmpty);
});

Expand Down Expand Up @@ -204,10 +217,12 @@ void main() {
});

test('should not fix files', () async {
final basePath = '${Directory.current.path}/test/resources/lint_analyzer';
final basePath =
'${Directory.current.path}/test/resources/lint_analyzer';
final fixedExamplePath = '$basePath/lint_fix_fixed_example.dart';

final originalFixedExampleContent = await File(fixedExamplePath).readAsString();
final originalFixedExampleContent =
await File(fixedExamplePath).readAsString();

final config = _createConfig(
excludePatterns: [
Expand Down Expand Up @@ -235,11 +250,13 @@ void main() {
});

test('should fix files', () async {
final basePath = '${Directory.current.path}/test/resources/lint_analyzer';
final basePath =
'${Directory.current.path}/test/resources/lint_analyzer';
final originalExamplePath = '$basePath/lint_fix_original_example.dart';
final fixedExamplePath = '$basePath/lint_fix_fixed_example.dart';

final originalExampleContent = await File(originalExamplePath).readAsString();
final originalExampleContent =
await File(originalExamplePath).readAsString();

final config = _createConfig(
rules: {
Expand All @@ -253,7 +270,8 @@ void main() {
config,
);

final modifiedExampleContent = await File(originalExamplePath).readAsString();
final modifiedExampleContent =
await File(originalExamplePath).readAsString();
final fixedExampleContent = await File(fixedExamplePath).readAsString();

expect(
Expand Down
Loading
Loading