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

Warn when publishing breaking release with deprecated members #3959

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/src/validator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import 'entrypoint.dart';
import 'log.dart' as log;
import 'sdk.dart';
import 'validator/analyze.dart';
import 'validator/breaking_with_deprecated.dart';
import 'validator/changelog.dart';
import 'validator/compiled_dartdoc.dart';
import 'validator/dependency.dart';
Expand Down Expand Up @@ -159,6 +160,7 @@ abstract class Validator {
PubspecTypoValidator(),
LeakDetectionValidator(),
SizeValidator(),
RemoveDeprecatedOnBreakingReleaseValidator(),
];

final context = ValidationContext(
Expand Down
106 changes: 106 additions & 0 deletions lib/src/validator/breaking_with_deprecated.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

import 'package:analyzer/dart/ast/ast.dart';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:path/path.dart' as p;
import 'package:pub_semver/pub_semver.dart';
import 'package:source_span/source_span.dart';

import '../dart.dart';
import '../exceptions.dart';
import '../io.dart';
import '../package_name.dart';
import '../validator.dart';

/// Gives a warning when releasing a breaking version containing @Deprecated
/// annotations.
class RemoveDeprecatedOnBreakingReleaseValidator extends Validator {
@override
Future<void> validate() async {
final hostedSource = entrypoint.cache.hosted;
List<PackageId> existingVersions;
try {
existingVersions = await entrypoint.cache.getVersions(
hostedSource.refFor(entrypoint.root.name, url: serverUrl.toString()),
);
} on PackageNotFoundException {
existingVersions = [];
}
existingVersions.sort((a, b) => a.version.compareTo(b.version));

final currentVersion = entrypoint.root.pubspec.version;

final previousRelease = existingVersions
.lastWhereOrNull((id) => id.version < entrypoint.root.version);

if (previousRelease != null &&
!VersionConstraint.compatibleWith(previousRelease.version)
.allows(currentVersion)) {
// A breaking release.
final packagePath = p.normalize(p.absolute(entrypoint.rootDir));
final analysisContextManager = AnalysisContextManager(packagePath);
for (var file in filesBeneath('lib', recursive: true).where(
(file) =>
p.extension(file) == '.dart' &&
!p.isWithin(p.join(entrypoint.root.dir, 'lib', 'src'), file),
)) {
final unit = analysisContextManager.parse(file);
for (final declaration in unit.declarations) {
warnIfDeprecated(declaration, file);
if (declaration is ClassOrAugmentationDeclaration) {
for (final member in declaration.members) {
warnIfDeprecated(member, file);
}
}
if (declaration is MixinOrAugmentationDeclaration) {
for (final member in declaration.members) {
warnIfDeprecated(member, file);
}
}
if (declaration is EnumDeclaration) {
for (final member in declaration.members) {
warnIfDeprecated(member, file);
}
}
}
}
}
}

/// Warn if [declaration] has a This is a syntactic check only, and therefore
/// imprecise but much faster than doing resolution.
///
/// Cases where this will break down:
/// ```
/// const d = Deprecated('Please don't use');
/// @d class P {} // False negative.
/// ```
///
/// ```
/// import 'dart:core as core';
/// import 'mylib.dart' show Deprecated;
///
/// @Deprecated() class A {} // False positive
/// ```
void warnIfDeprecated(Declaration declaration, String file) {
for (final commentOrAnnotation in declaration.sortedCommentAndAnnotations) {
if (commentOrAnnotation
case Annotation(name: SimpleIdentifier(name: 'Deprecated'))) {
warnings.add(
SourceFile.fromString(readTextFile(file), url: file)
.span(
commentOrAnnotation.offset,
commentOrAnnotation.offset + commentOrAnnotation.length,
)
.message(
'You are about to publish a breaking release. Consider removing this deprecated declaration.',
),
);
}
}
}
}
43 changes: 43 additions & 0 deletions test/validator/breaking_with_deprecated_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:test/test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';
import 'utils.dart';

void main() {
test('should only warn when publishing a breaking release ', () async {
final server = await servePackages();
await d.dir(appPath, [
d.validPubspec(extras: {'version': '2.0.0'}),
d.file('LICENSE', 'Eh, do what you want.'),
d.file('README.md', "This package isn't real."),
d.file('CHANGELOG.md', '# 2.0.0\nFirst version\n'),
d.dir('lib', [
d.file(
'test_pkg.dart',
"@Deprecated('Stop using this please') int i = 1;",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why should this be a problem?

Yes, in theory a major version bump is a good opportunity to remove deprecated stuff.

But it's also entirely possible that my package contains multiple kinds of deprecated stuff, what if I want to keep sonme of the deprecated stuffs and remove other deprecated stuff.

In general, unless there is a pressing reason to remove something that's been deprecated, I would suggest not doing so.
You could do things like /// @nodoc in dartdoc documentation comments, to exclude the deprecated bits from documentation, so it doesn't pollute.

Would be nice if there was also a way to hide it from auto-completion.


Yes, in many cases it makes sense to cleanup when doing a major version bump, such that deprecated stuff disappears. But for large complex packages it's entirely possible that some deprecated stuff sticks around because it's low cost to keep, and removing it only causes friction.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah - good points...

Maybe we can lower this to a "hint"... I still think there is some value to extract here (the associated issue seems quite popular)...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WDYT @jonasfj ? Should we make this a hint or close the issue as wontfix?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't mind shipping it as a hint.

Are we sure this shouldn't just be a "lint" or diagnostic in the analyzer?
We run an analyzes run before publishing, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm - maybe that would work...

@pq what do you say? Would we like to be linted not to have deprecated members if the version is x.0.0 ?

),
d.dir('src', [
d.file(
'support.dart',
"@Deprecated('Stop using this please') class B {}",
),
]),
]),
]).create();
// No earlier versions, so not a breaking release.
await expectValidation();
server.serve('test_pkg', '1.0.0');
await expectValidationWarning(
allOf(
contains('Consider removing this deprecated declaration.'),
contains('int i'),
isNot(contains('class B')),
),
);
});
}