diff --git a/.github/workflows/batch_release_pr.yml b/.github/workflows/batch_release_pr.yml index fa7f5d70f785..a1b60fe16ad1 100644 --- a/.github/workflows/batch_release_pr.yml +++ b/.github/workflows/batch_release_pr.yml @@ -105,8 +105,9 @@ jobs: cut until the version bump and changelog on `${{ needs.create_batch_release_branch.outputs.blocking_branch }}` are on `main`. That release is already published, so these changes have to - land. If this PR can't be landed as-is, apply the same version bump and - changelog to `main` by hand. + land. If this PR can't be landed as-is, apply the same version bump, + changelog, and `{{NEXT_VERSION}}` placeholder replacements to `main` by + hand. secrets: BOT_TOKEN: ${{ secrets.FLUTTERGITHUBBOT_TOKEN }} diff --git a/script/tool/CHANGELOG.md b/script/tool/CHANGELOG.md index 2bd48caa8955..2150c3e17c4f 100644 --- a/script/tool/CHANGELOG.md +++ b/script/tool/CHANGELOG.md @@ -1,11 +1,15 @@ -## NEXT +## 0.14.4+4 * Exempts `test_apps/` from requiring version and changelog changes. * Fixes `dart-test --package-tags` not matching any packages when the repository is checked out into a directory named `packages`, as it is in CI. - -## 0.14.4+4 - +* Updates `branches-for-batch-release` to replace `{{NEXT_VERSION}}` + placeholders in Dart files in `lib/` with the new release version. +* Updates `validate` to fail if `{{NEXT_VERSION}}` placeholders are present in + packages that don't use batch release, in packages without pending changelog + entries, or in files other than Dart files in `lib/`. +* Updates `publish` to refuse to publish packages containing `{{NEXT_VERSION}}` + placeholders. * Uses `flutter pub` instead of `dart pub` for non-Flutter packages that depend on `jni`. diff --git a/script/tool/lib/src/branches_for_batch_release_command.dart b/script/tool/lib/src/branches_for_batch_release_command.dart index aa8ee9b429f6..7235df4474e7 100644 --- a/script/tool/lib/src/branches_for_batch_release_command.dart +++ b/script/tool/lib/src/branches_for_batch_release_command.dart @@ -11,12 +11,16 @@ import 'package:pub_semver/pub_semver.dart'; import 'package:yaml_edit/yaml_edit.dart'; import 'common/core.dart'; +import 'common/file_utils.dart'; import 'common/output_utils.dart'; import 'common/package_command.dart'; +import 'common/pub_utils.dart'; import 'common/repository_package.dart'; +import 'common/version_placeholder.dart'; const int _kExitPackageMalformed = 3; const int _kGitFailedToPush = 4; +const int _kFormatFailed = 5; /// A command to create remote branches with release changes for a single package. class BranchesForBatchReleaseCommand extends PackageCommand { @@ -211,10 +215,70 @@ class BranchesForBatchReleaseCommand extends PackageCommand { _updatePubspec(package, releaseInfo.newVersion!); _updateChangelog(package, releaseInfo); - await _stageAndCommitChanges(git, package, pendingChangelogFiles); + final List filesWithPlaceholders = await _replaceVersionPlaceholders( + package, + releaseInfo.newVersion!, + ); + await _stageAndCommitChanges( + git, + package, + pendingChangelogFiles, + additionalFiles: filesWithPlaceholders, + ); await _pushBranch(git, remoteName, branchName); } + /// Replaces every occurrence of [nextVersionPlaceholder] in the Dart files in + /// `lib/` of [package] with [newVersion], returning the list of modified + /// files. + /// + /// This allows contributors to reference the not-yet-known release version + /// (e.g., in deprecation messages) before the batch release determines it. + Future> _replaceVersionPlaceholders( + RepositoryPackage package, + Version newVersion, + ) async { + final modifiedFiles = []; + for (final (:File file, :String content) in await findVersionPlaceholderFiles( + package.directory, + getFilesForPackage(package), + scope: VersionPlaceholderScope.replaceable, + )) { + file.writeAsStringSync(content.replaceAll(nextVersionPlaceholder, newVersion.toString())); + modifiedFiles.add(file); + } + if (modifiedFiles.isNotEmpty) { + print(' Replaced $nextVersionPlaceholder with $newVersion in:'); + for (final file in modifiedFiles) { + print(' ${relativePosixPath(file, from: package.directory, platformContext: path)}'); + } + await _formatDartFiles(package, modifiedFiles); + } + return modifiedFiles; + } + + /// Runs `dart format` on [files] in [package]. + /// + /// Replacing [nextVersionPlaceholder] with a (shorter) version can allow + /// lines that were previously split to fit on one line, which would fail the + /// format check on the release PR. + Future _formatDartFiles(RepositoryPackage package, List files) async { + // The formatter's behavior depends on the package's language version, so + // make sure it has been resolved. + if (!await runPubGet(package, processRunner, platform)) { + printError('Unable to fetch dependencies for ${package.displayName}.'); + throw ToolExit(_kFormatFailed); + } + final io.ProcessResult formatResult = await processRunner.run('dart', [ + 'format', + ...files.map((File f) => f.path), + ], workingDir: package.directory); + if (formatResult.exitCode != 0) { + printError('Failed to format files: ${formatResult.stderr}'); + throw ToolExit(_kFormatFailed); + } + } + void _updatePubspec(RepositoryPackage package, Version newVersion) { final editablePubspec = YamlEditor(package.pubspecFile.readAsStringSync()); editablePubspec.update(['version'], newVersion.toString()); @@ -250,8 +314,9 @@ class BranchesForBatchReleaseCommand extends PackageCommand { Future _stageAndCommitChanges( GitDir git, RepositoryPackage package, - List pendingChangelogFiles, - ) async { + List pendingChangelogFiles, { + List additionalFiles = const [], + }) async { final List paths = pendingChangelogFiles.map((File f) => f.path).toList(); final io.ProcessResult rmResult = await git.runCommand(['rm', ...paths]); if (rmResult.exitCode != 0) { @@ -263,6 +328,7 @@ class BranchesForBatchReleaseCommand extends PackageCommand { 'add', package.pubspecFile.path, package.changelogFile.path, + ...additionalFiles.map((File f) => f.path), ]); if (addResult.exitCode != 0) { printError('Failed to git add: ${addResult.stderr}'); diff --git a/script/tool/lib/src/common/version_placeholder.dart b/script/tool/lib/src/common/version_placeholder.dart new file mode 100644 index 000000000000..cbf24505d0d5 --- /dev/null +++ b/script/tool/lib/src/common/version_placeholder.dart @@ -0,0 +1,78 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:convert'; + +import 'package:file/file.dart'; +import 'package:path/path.dart' as path; + +/// Placeholder text that is replaced with the new release version in a batch +/// release package's Dart files in `lib/` when creating a batch release. +/// +/// For example, a deprecation message can use +/// `'This feature was deprecated in v{{NEXT_VERSION}}.'`. +const String nextVersionPlaceholder = '{{NEXT_VERSION}}'; + +/// A text file containing [nextVersionPlaceholder]. +typedef VersionPlaceholderFile = ({File file, String content}); + +/// The set of files to search for [nextVersionPlaceholder]. +enum VersionPlaceholderScope { + /// Files in which the batch release tooling replaces placeholders: Dart files + /// in `lib/`. + replaceable, + + /// All text files in the package, other than those in build output or tool + /// state directories. Used to find placeholders that won't be replaced. + all; + + /// Whether the file at [relativePath], relative to the package root, is in + /// this scope. + bool includes(String relativePath, path.Context pathContext) { + final List components = pathContext.split(relativePath); + switch (this) { + case VersionPlaceholderScope.replaceable: + return components.first == 'lib' && pathContext.extension(relativePath) == '.dart'; + case VersionPlaceholderScope.all: + final List directories = components.sublist(0, components.length - 1); + return !directories.any((String name) => name.startsWith('.') || name == 'build'); + } + } +} + +/// Returns the files in [files] that are in [scope] and contain +/// [nextVersionPlaceholder], along with their contents, in path order. +/// +/// [files] should be the files of the package rooted at [packageDirectory], +/// as returned by `PackageCommand.getFilesForPackage`. +Future> findVersionPlaceholderFiles( + Directory packageDirectory, + Stream files, { + required VersionPlaceholderScope scope, +}) async { + final path.Context pathContext = packageDirectory.fileSystem.path; + final List candidates = + await files + .where( + (File file) => scope.includes( + pathContext.relative(file.path, from: packageDirectory.path), + pathContext, + ), + ) + .toList() + ..sort((File a, File b) => a.path.compareTo(b.path)); + return [ + for (final File file in candidates) + if (_readUtf8(file) case final String content when content.contains(nextVersionPlaceholder)) + (file: file, content: content), + ]; +} + +String? _readUtf8(File file) { + try { + return utf8.decode(file.readAsBytesSync()); + } on FormatException { + return null; + } +} diff --git a/script/tool/lib/src/publish_command.dart b/script/tool/lib/src/publish_command.dart index 4d2f8917a450..71d46ace98b7 100644 --- a/script/tool/lib/src/publish_command.dart +++ b/script/tool/lib/src/publish_command.dart @@ -23,6 +23,7 @@ import 'common/package_looping_command.dart'; import 'common/pub_utils.dart'; import 'common/pub_version_finder.dart'; import 'common/repository_package.dart'; +import 'common/version_placeholder.dart'; @immutable class _RemoteInfo { @@ -256,6 +257,10 @@ class PublishCommand extends PackageLoopingCommand { return PackageResult.fail(['uncommitted changes']); } + if (!await _checkForVersionPlaceholders(package)) { + return PackageResult.fail(['unreplaced $nextVersionPlaceholder placeholder']); + } + final bool tagOnly = getBoolArg(_tagForAutoPublishFlag); if (!tagOnly) { if (!await _publish(package)) { @@ -411,6 +416,25 @@ Safe to ignore if the package is deleted in this commit. return statusOutput.isEmpty; } + /// Returns false, printing the offending files, if [package] contains any + /// [nextVersionPlaceholder]s. + Future _checkForVersionPlaceholders(RepositoryPackage package) async { + final List placeholderFiles = await findVersionPlaceholderFiles( + package.directory, + getFilesForPackage(package), + scope: VersionPlaceholderScope.all, + ); + if (placeholderFiles.isEmpty) { + return true; + } + printError( + 'Refusing to publish a package containing $nextVersionPlaceholder ' + 'placeholders. Replace them with the release version:\n' + '${placeholderFiles.map((VersionPlaceholderFile f) => ' ${getRelativePosixPath(f.file, from: package.directory)}').join('\n')}', + ); + return false; + } + Future _verifyRemote(String remote) async { final io.ProcessResult getRemoteUrlResult = await (await gitDir).runCommand([ 'remote', diff --git a/script/tool/lib/src/validate_command.dart b/script/tool/lib/src/validate_command.dart index 78ac7cacf18a..a12fc9cdaf5e 100644 --- a/script/tool/lib/src/validate_command.dart +++ b/script/tool/lib/src/validate_command.dart @@ -297,6 +297,7 @@ class ValidateCommand extends PackageLoopingCommand { return validator.validateChangelogAndVersion( package, + packageFiles: getFilesForPackage(package), checkForMissingChanges: getBoolArg(_checkForMissingChanges), ignorePlatformInterfaceBreaks: getBoolArg(_ignorePlatformInterfaceBreaks), ); diff --git a/script/tool/lib/src/validators/version_and_changelog_validator.dart b/script/tool/lib/src/validators/version_and_changelog_validator.dart index 58e79a15b722..a0cc6b56edbc 100644 --- a/script/tool/lib/src/validators/version_and_changelog_validator.dart +++ b/script/tool/lib/src/validators/version_and_changelog_validator.dart @@ -13,6 +13,7 @@ import '../common/git_version_finder.dart'; import '../common/output_utils.dart'; import '../common/package_state_utils.dart'; import '../common/repository_package.dart'; +import '../common/version_placeholder.dart'; /// Categories of version change types. enum NextVersionType { @@ -112,9 +113,13 @@ class VersionAndChangelogValidator { /// and match the policy for the files changed, returning a list of resulting /// error strings. /// + /// [packageFiles] should be all of the files in [package], and is used to + /// check for version placeholders. + /// /// If no errors are found, an empty list is returned. Future> validateChangelogAndVersion( RepositoryPackage package, { + required Stream packageFiles, required bool checkForMissingChanges, required bool ignorePlatformInterfaceBreaks, }) async { @@ -159,6 +164,15 @@ class VersionAndChangelogValidator { } } + final String? placeholderError = await _checkForVersionPlaceholders( + package, + packageFiles, + usesBatchRelease: usesBatchRelease, + ); + if (placeholderError != null) { + errors.add(placeholderError); + } + final _CurrentVersionState versionState = await _getVersionState( package, pubspec: pubspec, @@ -649,6 +663,82 @@ ${_indentation}The first version listed in CHANGELOG.md is $fromChangeLog. return versionChanged; } + /// Returns an error string if any of [packageFiles] contain a + /// [nextVersionPlaceholder] that won't be replaced automatically, printing + /// the offending files. + /// + /// Placeholders are only replaced by the batch release tooling, and only in + /// [VersionPlaceholderScope.replaceable] files, so they are not allowed in + /// packages that don't use batch release, in PRs without a pending changelog + /// entry, or in any other files. + Future _checkForVersionPlaceholders( + RepositoryPackage package, + Stream packageFiles, { + required bool usesBatchRelease, + }) async { + final bool hasPendingChangelogs = usesBatchRelease && _hasPendingChangelogs(package); + final path.Context fsPath = package.directory.fileSystem.path; + final placeholderPaths = [ + for (final VersionPlaceholderFile f in await findVersionPlaceholderFiles( + package.directory, + packageFiles, + scope: VersionPlaceholderScope.all, + )) + if (!hasPendingChangelogs || + !VersionPlaceholderScope.replaceable.includes( + fsPath.relative(f.file.path, from: package.directory.path), + fsPath, + )) + relativePosixPath(f.file, from: package.directory, platformContext: _path), + ]; + if (placeholderPaths.isEmpty) { + return null; + } + final String reason = _versionPlaceholderErrorMessage( + usesBatchRelease: usesBatchRelease, + hasPendingChangelogs: hasPendingChangelogs, + ); + printError( + '$_indentation$reason\n' + '${_indentation}Found $nextVersionPlaceholder in:\n' + '${placeholderPaths.map((String p) => '$_indentation $p').join('\n')}', + ); + return 'Unreplaced $nextVersionPlaceholder placeholder.'; + } + + /// Returns the explanation for why unreplaced [nextVersionPlaceholder]s are + /// not allowed. + String _versionPlaceholderErrorMessage({ + required bool usesBatchRelease, + required bool hasPendingChangelogs, + }) { + if (!usesBatchRelease) { + return 'This package does not use batch release, so $nextVersionPlaceholder ' + 'placeholders will not be replaced automatically. Use the actual ' + 'version instead.'; + } else if (!hasPendingChangelogs) { + return 'Using $nextVersionPlaceholder is only allowed in PRs with a ' + 'pending changelog entry. To resolve, create a pending changelog entry ' + 'or remove $nextVersionPlaceholder instead.'; + } else { + return '$nextVersionPlaceholder placeholders are only supported ' + 'in Dart files in lib/.'; + } + } + + /// Returns true if [package] has at least one valid pending changelog entry. + /// + /// Entries with `version: skip` count, since their placeholders will be + /// replaced by the next release that does change the version. + bool _hasPendingChangelogs(RepositoryPackage package) { + try { + return package.getPendingChangelogs().isNotEmpty; + } on FormatException { + // Invalid pending changelogs are reported separately. + return false; + } + } + Future _getRelativePackagePath(RepositoryPackage package) async { return relativePosixPath(package.directory, from: _repoRoot, platformContext: _path); } diff --git a/script/tool/test/branches_for_batch_release_command_test.dart b/script/tool/test/branches_for_batch_release_command_test.dart index d5b165e84e73..70ffef310c4e 100644 --- a/script/tool/test/branches_for_batch_release_command_test.dart +++ b/script/tool/test/branches_for_batch_release_command_test.dart @@ -593,9 +593,137 @@ A new feature - Existing unreleased change '''); }); + + test('replaces version placeholder in package files', () async { + final RepositoryPackage package = createTestPackage(); + addTearDown(() { + package.directory.deleteSync(recursive: true); + }); + final File libFile = package.libDirectory.childFile('a_package.dart') + ..createSync(recursive: true) + ..writeAsStringSync(''' +@Deprecated( + 'Use bar instead. ' + 'This feature was deprecated in v{{NEXT_VERSION}}.', +) +void foo() {} +'''); + final File libSubdirectoryFile = + package.libDirectory.childDirectory('src').childFile('impl.dart') + ..createSync(recursive: true) + ..writeAsStringSync('// Since {{NEXT_VERSION}}, and again {{NEXT_VERSION}}.\n'); + final File exampleFile = + package.directory.childDirectory('example').childDirectory('lib').childFile('main.dart') + ..createSync(recursive: true) + ..writeAsStringSync('// Since {{NEXT_VERSION}}.\n'); + final File nonDartLibFile = package.libDirectory.childFile('notes.txt') + ..writeAsStringSync('{{NEXT_VERSION}}'); + final File readmeFile = package.directory.childFile('README.md') + ..writeAsStringSync('Since {{NEXT_VERSION}}.'); + final File untouchedFile = package.libDirectory.childFile('other.dart') + ..writeAsStringSync('void bar() {}\n'); + createPendingChangelogFile(package, 'a.yaml', ''' +changelog: Deprecates foo. +version: minor +'''); + + final List output = await runBatchCommand(); + + expect( + output, + containsAllInOrder([ + ' Replaced {{NEXT_VERSION}} with 1.1.0 in:', + ' lib/a_package.dart', + ' lib/src/impl.dart', + ]), + ); + expect(libFile.readAsStringSync(), ''' +@Deprecated( + 'Use bar instead. ' + 'This feature was deprecated in v1.1.0.', +) +void foo() {} +'''); + expect(libSubdirectoryFile.readAsStringSync(), '// Since 1.1.0, and again 1.1.0.\n'); + expect(exampleFile.readAsStringSync(), '// Since {{NEXT_VERSION}}.\n'); + expect(nonDartLibFile.readAsStringSync(), '{{NEXT_VERSION}}'); + expect(readmeFile.readAsStringSync(), 'Since {{NEXT_VERSION}}.'); + expect(untouchedFile.readAsStringSync(), 'void bar() {}\n'); + expect( + gitProcessRunner.recordedCalls, + contains( + const ProcessCall('git-add', [ + '/packages/a_package/pubspec.yaml', + '/packages/a_package/CHANGELOG.md', + '/packages/a_package/lib/a_package.dart', + '/packages/a_package/lib/src/impl.dart', + ], null), + ), + ); + expect( + processRunner.recordedCalls, + orderedEquals([ + ProcessCall('dart', const ['pub', 'get'], package.path), + ProcessCall('dart', const [ + 'format', + '/packages/a_package/lib/a_package.dart', + '/packages/a_package/lib/src/impl.dart', + ], package.path), + ]), + ); + }); + + test('does not format when there are no version placeholders', () async { + final RepositoryPackage package = createTestPackage(); + addTearDown(() { + package.directory.deleteSync(recursive: true); + }); + package.libDirectory.childFile('a_package.dart') + ..createSync(recursive: true) + ..writeAsStringSync('void foo() {}\n'); + createPendingChangelogFile(package, 'a.yaml', ''' +changelog: A change. +version: minor +'''); + + await runBatchCommand(); + + expect(processRunner.recordedCalls, isEmpty); + }); }); group('error handling', () { + test('throws when formatting fails', () async { + final RepositoryPackage package = createTestPackage(); + addTearDown(() { + package.directory.deleteSync(recursive: true); + }); + package.libDirectory.childFile('a_package.dart') + ..createSync(recursive: true) + ..writeAsStringSync('// Since {{NEXT_VERSION}}.\n'); + createPendingChangelogFile(package, 'a.yaml', ''' +changelog: A change. +version: minor +'''); + processRunner.mockProcessesForExecutable['dart'] = [ + FakeProcessInfo(MockProcess(), ['pub', 'get']), + FakeProcessInfo(MockProcess(exitCode: 1, stderr: 'format error'), ['format']), + ]; + + Error? commandError; + final List output = await runBatchCommand( + errorHandler: (Error e) { + commandError = e; + }, + ); + + expect(commandError, isA()); + expect( + output, + containsAllInOrder([contains('Failed to format files: format error')]), + ); + }); + test('throw when git-checkout fails', () async { final RepositoryPackage package = createTestPackage(); addTearDown(() { diff --git a/script/tool/test/publish_command_test.dart b/script/tool/test/publish_command_test.dart index 422a40ed2307..86c0e13c80a7 100644 --- a/script/tool/test/publish_command_test.dart +++ b/script/tool/test/publish_command_test.dart @@ -106,6 +106,42 @@ void main() { ); }); + test('refuses to publish packages containing version placeholders', () async { + final RepositoryPackage plugin = createFakePlugin('foo', packagesDir, examples: []); + plugin.libDirectory.childFile('foo.dart').writeAsStringSync(''' +@Deprecated('Deprecated in v{{NEXT_VERSION}}.') +void foo() {} +'''); + plugin.directory.childFile('README.md').writeAsStringSync('Since {{NEXT_VERSION}}.'); + + Error? commandError; + final List output = await runCapturingPrint( + commandRunner, + ['publish', '--packages=foo'], + errorHandler: (Error e) { + commandError = e; + }, + ); + + expect(commandError, isA()); + expect( + output, + containsAllInOrder([ + contains( + 'Refusing to publish a package containing {{NEXT_VERSION}} ' + 'placeholders. Replace them with the release version:\n' + ' README.md\n' + ' lib/foo.dart', + ), + contains( + 'foo:\n' + ' unreplaced {{NEXT_VERSION}} placeholder', + ), + ]), + ); + expect(output, isNot(contains('Publishing...'))); + }); + test("fails immediately if the remote doesn't exist", () async { createFakePlugin('foo', packagesDir, examples: []); diff --git a/script/tool/test/validate_command_version_test.dart b/script/tool/test/validate_command_version_test.dart index ac41eb76ea39..6a80def8dc0a 100644 --- a/script/tool/test/validate_command_version_test.dart +++ b/script/tool/test/validate_command_version_test.dart @@ -1631,6 +1631,274 @@ packages/package/pubspec.yaml }, ); + test('fails for version placeholders in non-batch release package', () async { + final RepositoryPackage package = createFakePackage( + 'package', + packagesDir, + version: '1.0.0', + ); + package.libDirectory.childFile('package.dart').writeAsStringSync(''' +@Deprecated('Deprecated in v{{NEXT_VERSION}}.') +void foo() {} +'''); + gitProcessRunner.mockProcessesForExecutable['git-show'] = [ + FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')), + ]; + + Error? commandError; + final List output = await runCapturingPrint( + runner, + ['validate', '--base-sha=main'], + errorHandler: (Error e) { + commandError = e; + }, + ); + + expect(commandError, isA()); + expect( + output, + containsAllInOrder([ + allOf( + contains( + 'This package does not use batch release, so {{NEXT_VERSION}} ' + 'placeholders will not be replaced automatically.', + ), + contains('lib/package.dart'), + ), + contains('Unreplaced {{NEXT_VERSION}} placeholder.'), + ]), + ); + }); + + test('allows version placeholders in batch release package', () async { + final RepositoryPackage package = createFakePackage( + 'package', + packagesDir, + version: '1.0.0', + ); + package.ciConfigFile.writeAsStringSync(''' +release: + batch: true +'''); + package.pendingChangelogsDirectory.createSync(); + package.pendingChangelogsDirectory.childFile('a.yaml').writeAsStringSync(''' +changelog: Deprecates foo. +version: minor +'''); + package.libDirectory.childFile('package.dart').writeAsStringSync(''' +@Deprecated('Deprecated in v{{NEXT_VERSION}}.') +void foo() {} +'''); + gitProcessRunner.mockProcessesForExecutable['git-show'] = [ + FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')), + ]; + + final List output = await runCapturingPrint(runner, [ + 'validate', + '--base-sha=main', + ]); + + expect( + output, + containsAllInOrder([ + contains('Running for package'), + contains('No issues found!'), + ]), + ); + }); + + test('fails for version placeholders outside lib/ in batch release package', () async { + final RepositoryPackage package = createFakePackage( + 'package', + packagesDir, + version: '1.0.0', + ); + package.ciConfigFile.writeAsStringSync(''' +release: + batch: true +'''); + package.pendingChangelogsDirectory.createSync(); + package.pendingChangelogsDirectory.childFile('a.yaml').writeAsStringSync(''' +changelog: Deprecates foo in {{NEXT_VERSION}}. +version: minor +'''); + package.libDirectory.childFile('package.dart').writeAsStringSync(''' +@Deprecated('Deprecated in v{{NEXT_VERSION}}.') +void foo() {} +'''); + package.directory.childFile('README.md').writeAsStringSync('Since {{NEXT_VERSION}}.'); + package.directory.childDirectory('example').childDirectory('lib').childFile('main.dart') + ..createSync(recursive: true) + ..writeAsStringSync('// Since {{NEXT_VERSION}}.'); + gitProcessRunner.mockProcessesForExecutable['git-show'] = [ + FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')), + ]; + + Error? commandError; + final List output = await runCapturingPrint( + runner, + ['validate', '--base-sha=main'], + errorHandler: (Error e) { + commandError = e; + }, + ); + + expect(commandError, isA()); + expect( + output, + containsAllInOrder([ + allOf( + contains('{{NEXT_VERSION}} placeholders are only supported in Dart files in lib/.'), + contains('README.md'), + contains('example/lib/main.dart'), + contains('pending_changelogs/a.yaml'), + isNot(contains(' lib/package.dart')), + ), + contains('Unreplaced {{NEXT_VERSION}} placeholder.'), + ]), + ); + }); + + test('ignores version placeholders in build output, tool state, and binary files', () async { + final RepositoryPackage package = createFakePackage( + 'package', + packagesDir, + version: '1.0.0', + ); + package.directory.childDirectory('build').childFile('output.txt') + ..createSync(recursive: true) + ..writeAsStringSync('{{NEXT_VERSION}}'); + package.directory.childDirectory('.dart_tool').childFile('state.txt') + ..createSync(recursive: true) + ..writeAsStringSync('{{NEXT_VERSION}}'); + package.directory.childFile('binary.bin').writeAsBytesSync([0xff, 0xfe, 0x00, 0xc3]); + gitProcessRunner.mockProcessesForExecutable['git-show'] = [ + FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')), + ]; + + final List output = await runCapturingPrint(runner, [ + 'validate', + '--base-sha=main', + ]); + + expect(output, containsAllInOrder([contains('No issues found!')])); + }); + + test('fails for version placeholders in lib/ in batch release PR', () async { + final RepositoryPackage package = createFakePackage( + 'package', + packagesDir, + version: '1.1.0', + ); + package.ciConfigFile.writeAsStringSync(''' +release: + batch: true +'''); + package.pendingChangelogsDirectory.createSync(); + package.changelogFile.writeAsStringSync(''' +## 1.1.0 + +* Deprecates foo. +'''); + package.libDirectory.childFile('package.dart').writeAsStringSync(''' +@Deprecated('Deprecated in v{{NEXT_VERSION}}.') +void foo() {} +'''); + gitProcessRunner.mockProcessesForExecutable['git-diff'] = [ + FakeProcessInfo( + MockProcess( + stdout: ''' +packages/package/CHANGELOG.md +packages/package/pubspec.yaml +''', + ), + ), + ]; + gitProcessRunner.mockProcessesForExecutable['git-show'] = [ + FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')), + ]; + + Error? commandError; + final List output = await runCapturingPrint( + runner, + ['validate', '--base-sha=main', '--pr-labels=override: batch-package'], + errorHandler: (Error e) { + commandError = e; + }, + ); + + expect(commandError, isA()); + expect( + output, + containsAllInOrder([ + allOf( + contains( + 'Using {{NEXT_VERSION}} is only allowed in PRs with a pending changelog entry.', + ), + contains(' lib/package.dart'), + ), + contains('Unreplaced {{NEXT_VERSION}} placeholder.'), + ]), + ); + }); + + test('allows version placeholders in lib/ in batch release sync PR with pending ' + 'changelogs', () async { + // The PR syncing a release branch back to main also uses the + // override: batch- label, and may contain placeholders added + // to main since the release, along with their pending changelogs. + final RepositoryPackage package = createFakePackage( + 'package', + packagesDir, + version: '1.1.0', + ); + package.ciConfigFile.writeAsStringSync(''' +release: + batch: true +'''); + package.pendingChangelogsDirectory.createSync(); + package.pendingChangelogsDirectory.childFile('a.yaml').writeAsStringSync(''' +changelog: Deprecates foo. +version: minor +'''); + package.changelogFile.writeAsStringSync(''' +## 1.1.0 + +* Adds bar. +'''); + package.libDirectory.childFile('package.dart').writeAsStringSync(''' +@Deprecated('Deprecated in v{{NEXT_VERSION}}.') +void foo() {} +'''); + gitProcessRunner.mockProcessesForExecutable['git-diff'] = [ + FakeProcessInfo( + MockProcess( + stdout: ''' +packages/package/CHANGELOG.md +packages/package/pubspec.yaml +''', + ), + ), + ]; + gitProcessRunner.mockProcessesForExecutable['git-show'] = [ + FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')), + ]; + + final List output = await runCapturingPrint(runner, [ + 'validate', + '--base-sha=main', + '--pr-labels=override: batch-package', + ]); + + expect( + output, + containsAllInOrder([ + contains('Running for package'), + contains('No issues found!'), + ]), + ); + }); + test('fails when there is changelog modifications', () async { final RepositoryPackage package = createFakePackage( 'package',