diff --git a/tool/dash_site/lib/src/commands/stage_preview.dart b/tool/dash_site/lib/src/commands/stage_preview.dart index da5e4959bc..efafdc2cee 100644 --- a/tool/dash_site/lib/src/commands/stage_preview.dart +++ b/tool/dash_site/lib/src/commands/stage_preview.dart @@ -6,11 +6,11 @@ import 'dart:convert'; import 'dart:io'; import 'package:args/command_runner.dart'; -import 'package:github/github.dart' as github; import 'package:path/path.dart' as path; import '../firebase.dart'; import '../preview_changes.dart'; +import '../preview_comments.dart'; import '../sites.dart'; import '../utils.dart'; import 'build.dart'; @@ -164,13 +164,39 @@ final class StagePreviewCommand extends Command { return 0; } + /// Records [status] for the selected site in + /// the pull request's preview comment. + /// + /// Does nothing and returns `0` if there's no pull request context. + Future updatePreviewComment( + PreviewStatus status, { + String? stagingUrl, + }) async { + if (prContext case final context?) { + return await updatePreviewCommentOnGitHub( + site: selectedSite, + status: status, + stagingUrl: stagingUrl, + prNumber: context.prNumber, + repoFullName: context.repoFullName, + commitSha: context.commitSha, + githubToken: context.githubToken, + ); + } + return 0; + } + + await updatePreviewComment(PreviewStatus.pending); + final firebaseToolsVersion = await validateFirebaseCli(); if (firebaseToolsVersion == null) { + await updatePreviewComment(PreviewStatus.failed); return 1; } if (await buildSite(selectedSite, productionRelease: false) case final buildResult when buildResult != 0) { + await updatePreviewComment(PreviewStatus.failed); return buildResult; } @@ -189,6 +215,7 @@ final class StagePreviewCommand extends Command { expires: expires, ); if (stagingUrl == null) { + await updatePreviewComment(PreviewStatus.failed); return 1; } @@ -198,10 +225,9 @@ final class StagePreviewCommand extends Command { return 0; } - return await _commentStagingUrlOnGitHub( - site: selectedSite, + return await updatePreviewComment( + PreviewStatus.ready, stagingUrl: stagingUrl, - context: prContext, ); } } @@ -270,81 +296,6 @@ String? _extractDeployedUrl(String firebaseJsonOutput) { return null; } -/// Posts a new preview comment on the pull request, -/// or updates the existing one identified by an HTML marker that -/// includes the [site]'s name. -/// -/// Returns `0` on success or `1` if the GitHub API call fails. -Future _commentStagingUrlOnGitHub({ - required Site site, - required String stagingUrl, - required _PullRequestContext context, -}) async { - final commentMarker = ''; - final commentBody = - ''' -$commentMarker -Staged preview of the updated ${site.host} site (updated for commit ${context.commitSha}): - -$stagingUrl'''; - - print('Commenting ${site.host} staging URL on the PR...'); - final gitHub = github.GitHub( - auth: github.Authentication.withToken(context.githubToken), - ); - try { - final repository = github.RepositorySlug.full(context.repoFullName); - final existingCommentId = await _findExistingPreviewCommentId( - gitHub: gitHub, - repository: repository, - issueNumber: context.prNumber, - commentMarker: commentMarker, - ); - - if (existingCommentId == null) { - await gitHub.issues.createComment( - repository, - context.prNumber, - commentBody, - ); - } else { - await gitHub.issues.updateComment( - repository, - existingCommentId, - commentBody, - ); - } - } on github.GitHubError catch (error) { - stderr.writeln('Error: Failed to comment on the pull request: $error'); - return 1; - } finally { - gitHub.dispose(); - } - - return 0; -} - -/// Returns the id of the first comment on the issue whose body -/// contains the specified [commentMarker]. -/// -/// Returns `null` if no matching comment exists. -Future _findExistingPreviewCommentId({ - required github.GitHub gitHub, - required github.RepositorySlug repository, - required int issueNumber, - required String commentMarker, -}) async { - await for (final comment in gitHub.issues.listCommentsByIssue( - repository, - issueNumber, - )) { - if (comment.body?.contains(commentMarker) ?? false) { - return comment.id; - } - } - return null; -} - /// Builds a Firebase Hosting channel name for [site] that /// incorporates [branchOrSha] and if specified, [prNumber], /// and satisfies Firebase's naming constraints: diff --git a/tool/dash_site/lib/src/preview_comments.dart b/tool/dash_site/lib/src/preview_comments.dart new file mode 100644 index 0000000000..1896ea18d6 --- /dev/null +++ b/tool/dash_site/lib/src/preview_comments.dart @@ -0,0 +1,285 @@ +// Copyright 2026 The Flutter Authors. 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:convert'; +import 'dart:io'; + +import 'package:github/github.dart' as github; + +import 'sites.dart'; + +/// The hidden HTML comment that identifies +/// the combined preview comment on a pull request. +const String previewCommentMarker = ''; + +/// The state of a site's staged preview. +enum PreviewStatus { + /// Building and deploying, with no earlier preview to link to. + pending('⏳ Building'), + + /// Building and deploying, with an earlier preview still available. + rebuilding('⏳ Rebuilding'), + + /// Deployed and available to visit. + ready('✅ Ready'), + + /// The latest build or deployment failed. + failed('❌ Failed'); + + const PreviewStatus(this.label); + + /// The text shown for this status in the preview comment. + final String label; +} + +/// The state of one [Site]'s staged preview, +/// as tracked in the combined preview comment. +final class PreviewEntry { + /// Creates an entry for a preview with the specified state. + const PreviewEntry({required this.status, this.url, required this.commitSha}); + + /// The status of the latest build and deployment. + final PreviewStatus status; + + /// The URL of the most recent successful deployment, + /// or `null` if there hasn't been one. + /// + /// Kept while a newer commit builds or after it fails, + /// so it might serve an older commit than [commitSha]. + final String? url; + + /// The SHA of the commit that [status] describes. + final String commitSha; + + /// Converts this entry to a JSON-encodable map + /// that [fromJson] can parse. + Map toJson() => { + 'status': status.name, + 'url': ?url, + 'commitSha': commitSha, + }; + + /// Parses an entry from decoded [json] in the format produced by [toJson]. + /// + /// Treats an unrecognized `status` as [PreviewStatus.ready] and + /// also accepts the legacy format that has a `url` but no `status`. + /// + /// Returns `null` if [json] isn't a valid entry. + static PreviewEntry? fromJson(Object? json) { + if (json + case final Map map && + { + 'status': final String statusName, + 'commitSha': final String commitSha, + } + when commitSha.isNotEmpty) { + final status = + PreviewStatus.values.asNameMap()[statusName] ?? PreviewStatus.ready; + final url = map['url'] as String?; + return PreviewEntry(status: status, url: url, commitSha: commitSha); + } + + if (json + case { + 'url': final String url, + 'commitSha': final String commitSha, + } + when url.isNotEmpty && commitSha.isNotEmpty) { + return PreviewEntry( + status: PreviewStatus.ready, + url: url, + commitSha: commitSha, + ); + } + + return null; + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is PreviewEntry && + other.status == status && + other.url == url && + other.commitSha == commitSha; + + @override + int get hashCode => Object.hash(status, url, commitSha); + + @override + String toString() => + 'PreviewEntry(status: $status, url: $url, commitSha: $commitSha)'; +} + +/// Parses the entry for each site from a preview [commentBody]. +/// +/// Reads the hidden metadata written by [buildPreviewCommentBody], +/// skipping unknown sites and invalid entries. +/// +/// Returns an empty map if the metadata is missing or isn't valid JSON. +Map parsePreviewCommentEntries(String commentBody) { + final entries = {}; + + final jsonStr = RegExp(r'') + .firstMatch(commentBody) + ?.group(1); + if (jsonStr == null) return entries; + + try { + final decoded = jsonDecode(jsonStr) as Object?; + if (decoded is! Map) return entries; + + final siteMap = Site.values.asNameMap(); + for (final MapEntry(:key, :value) in decoded.entries) { + final site = siteMap[key]; + if (site == null) continue; + if (PreviewEntry.fromJson(value) case final entry?) { + entries[site] = entry; + } + } + } catch (_) { + // Ignore malformed JSON metadata. + } + + return entries; +} + +/// Builds the Markdown body of the combined preview comment for [previews]. +/// +/// The body is a table with a row for each site in [Site.values] order, +/// preceded by hidden metadata that [parsePreviewCommentEntries] reads back. +/// +/// If [repoFullName] is specified, +/// each commit SHA links to its commit on GitHub. +String buildPreviewCommentBody( + Map previews, { + String? repoFullName, +}) { + final buffer = StringBuffer(); + buffer.writeln(previewCommentMarker); + + final data = { + for (final MapEntry(:key, :value) in previews.entries) + key.name: value.toJson(), + }; + buffer.writeln(''); + buffer.writeln('### 🚀 Staged previews'); + buffer.writeln(); + buffer.writeln('| Site | Status | Preview link | Commit |'); + buffer.writeln('| :--- | :--- | :--- | :--- |'); + + // Iterate over all sites rather than the map's keys + // so the rows are always in declaration order. + for (final site in Site.values) { + final entry = previews[site]; + if (entry == null) continue; + + final shortSha = entry.commitSha.length > 7 + ? entry.commitSha.substring(0, 7) + : entry.commitSha; + + final commitDisplay = repoFullName != null + ? '[`$shortSha`]' + '(https://github.com/$repoFullName/commit/${entry.commitSha})' + : '`$shortSha`'; + + final previewLink = switch (entry) { + PreviewEntry(:final url?) => '[Visit preview ↗]($url)', + PreviewEntry(status: .pending || .rebuilding) => '_Deploying..._', + PreviewEntry(status: .failed) => '_Failed_', + PreviewEntry(status: .ready) => '—', + }; + + buffer.writeln( + '| **${site.host}** | ${entry.status.label} | ' + '$previewLink | $commitDisplay |', + ); + } + + return buffer.toString().trimRight(); +} + +/// Returns the first comment on [issueNumber] in [repository] that +/// contains the [previewCommentMarker], or `null` if there isn't one. +Future _findExistingPreviewComment({ + required github.GitHub gitHub, + required github.RepositorySlug repository, + required int issueNumber, +}) async { + await for (final comment in gitHub.issues.listCommentsByIssue( + repository, + issueNumber, + )) { + final body = comment.body; + if (body != null && body.contains(previewCommentMarker)) { + return comment; + } + } + return null; +} + +/// Records [status] for [site] in the pull request's preview comment, +/// creating the comment if it doesn't exist yet. +/// +/// Entries for other sites are left unchanged. +/// If [stagingUrl] is `null`, the site's previous URL is kept. +/// A [PreviewStatus.pending] update for a site that already has a URL +/// is recorded as [PreviewStatus.rebuilding]. +/// +/// Returns `0` on success or `1` if a GitHub API call fails. +Future updatePreviewCommentOnGitHub({ + required Site site, + required PreviewStatus status, + String? stagingUrl, + required int prNumber, + required String repoFullName, + required String commitSha, + required String githubToken, +}) async { + final gitHub = github.GitHub( + auth: github.Authentication.withToken(githubToken), + ); + try { + final repository = github.RepositorySlug.full(repoFullName); + + final existingComment = await _findExistingPreviewComment( + gitHub: gitHub, + repository: repository, + issueNumber: prNumber, + ); + + final previews = parsePreviewCommentEntries(existingComment?.body ?? ''); + + final existingEntry = previews[site]; + final resolvedStatus = + status == PreviewStatus.pending && existingEntry?.url != null + ? PreviewStatus.rebuilding + : status; + final resolvedUrl = stagingUrl ?? existingEntry?.url; + + previews[site] = PreviewEntry( + status: resolvedStatus, + url: resolvedUrl, + commitSha: commitSha, + ); + + final commentBody = buildPreviewCommentBody( + previews, + repoFullName: repoFullName, + ); + + if (existingComment?.id case final commentId?) { + await gitHub.issues.updateComment(repository, commentId, commentBody); + } else { + await gitHub.issues.createComment(repository, prNumber, commentBody); + } + } on Exception catch (error) { + stderr.writeln('Error: Failed to comment on the pull request: $error'); + return 1; + } finally { + gitHub.dispose(); + } + + return 0; +} diff --git a/tool/dash_site/test/preview_comments_test.dart b/tool/dash_site/test/preview_comments_test.dart new file mode 100644 index 0000000000..ead3958c9d --- /dev/null +++ b/tool/dash_site/test/preview_comments_test.dart @@ -0,0 +1,228 @@ +// Copyright 2026 The Flutter Authors. 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:dash_site/src/preview_comments.dart'; +import 'package:dash_site/src/sites.dart'; +import 'package:test/test.dart'; + +void main() { + group('PreviewEntry', () { + test('serializes and deserializes ready status', () { + const entry = PreviewEntry( + status: PreviewStatus.ready, + url: 'https://flutter-docs-prod--pr100.web.app', + commitSha: '4977bb96d8ac0d94e8954c0682c80adce95b810e', + ); + + final json = entry.toJson(); + expect(PreviewEntry.fromJson(json), equals(entry)); + }); + + test('serializes and deserializes pending status without url', () { + const entry = PreviewEntry( + status: PreviewStatus.pending, + commitSha: '4977bb96d8ac0d94e8954c0682c80adce95b810e', + ); + + final json = entry.toJson(); + expect(json.containsKey('url'), isFalse); + expect(PreviewEntry.fromJson(json), equals(entry)); + }); + + test('serializes and deserializes rebuilding status with url', () { + const entry = PreviewEntry( + status: PreviewStatus.rebuilding, + url: 'https://flutter-docs-prod--pr100.web.app', + commitSha: '4977bb96d8ac0d94e8954c0682c80adce95b810e', + ); + + final json = entry.toJson(); + expect(PreviewEntry.fromJson(json), equals(entry)); + }); + + test('serializes and deserializes failed status', () { + const entry = PreviewEntry( + status: PreviewStatus.failed, + commitSha: '4977bb96d8ac0d94e8954c0682c80adce95b810e', + ); + + final json = entry.toJson(); + expect(PreviewEntry.fromJson(json), equals(entry)); + }); + + test('returns null on invalid JSON', () { + expect(PreviewEntry.fromJson(null), isNull); + expect(PreviewEntry.fromJson({}), isNull); + expect(PreviewEntry.fromJson({'status': 'ready'}), isNull); + }); + }); + + group('buildPreviewCommentBody', () { + test('formats a single pending site table cleanly', () { + final previews = { + Site.docs: const PreviewEntry( + status: PreviewStatus.pending, + commitSha: '4977bb96d8ac0d94e8954c0682c80adce95b810e', + ), + }; + + final body = buildPreviewCommentBody( + previews, + repoFullName: 'flutter/website', + ); + + expect(body, contains(previewCommentMarker)); + expect(body, contains(' + +### 🚀 Staged previews +'''; + + expect(parsePreviewCommentEntries(corruptBody), isEmpty); + }); + + test('returns empty map for unrelated comment', () { + expect(parsePreviewCommentEntries('Hello world! LGTM!'), isEmpty); + }); + }); +}