A platform for community discussion. Free, open, simple.
DEV: Automatic upcoming change status report and PR creation (#40291)
Martin Brennand9359c12561c
diff --git a/.github/workflows/upcoming-change-status-bump.yml b/.github/workflows/upcoming-change-status-bump.ymlnew file mode 100644index 00000000000..afc56bf5be3--- /dev/null+++ b/.github/workflows/upcoming-change-status-bump.yml@@ -0,0 +1,92 @@+name: Upcoming change status bump++on:+ schedule:+ - cron: "0 2 * * 1"+ workflow_dispatch:+ inputs:+ dry_run:+ description: "Print commands without creating pull requests"+ required: false+ default: true+ type: boolean+ stale_after_days:+ description: "Minimum days since the status last changed"+ required: false+ default: "14"+ type: string++permissions:+ contents: write+ issues: write+ pull-requests: write++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: false++jobs:+ create-prs:+ name: Create status bump PRs+ runs-on: ubuntu-latest+ container: discourse/discourse_test:slim+ timeout-minutes: 15++ env:+ GH_TOKEN: ${{ secrets.GH_PUSH_TOKEN || github.token }}+ SKIP_DB_AND_REDIS: "1"+ RAILS_DB: nonexistent++ steps:+ - uses: actions/checkout@v6+ with:+ fetch-depth: 0+ token: ${{ secrets.GH_PUSH_TOKEN || github.token }}++ - uses: ./.github/actions/setup-release-environment++ - name: Configure run mode+ id: config+ env:+ INPUT_DRY_RUN: ${{ inputs.dry_run }}+ INPUT_STALE_AFTER_DAYS: ${{ inputs.stale_after_days }}+ run: |+ if [ "${GITHUB_EVENT_NAME}" = "schedule" ]; then+ dry_run=false+ else+ dry_run="${INPUT_DRY_RUN:-true}"+ fi++ echo "dry_run=${dry_run}" >> "${GITHUB_OUTPUT}"+ echo "stale_after_days=${INPUT_STALE_AFTER_DAYS:-14}" >> "${GITHUB_OUTPUT}"++ - name: Generate status report+ id: report+ run: |+ bin/rails runner script/upcoming_changes_status_report -- \+ --stale-after-days "${{ steps.config.outputs.stale_after_days }}" \+ --pretty > /tmp/upcoming_changes_status_report.json++ cat /tmp/upcoming_changes_status_report.json++ eligible_count="$(jq '[.[] | select(.eligible)] | length' /tmp/upcoming_changes_status_report.json)"+ echo "eligible_count=${eligible_count}" >> "${GITHUB_OUTPUT}"++ {+ echo "### Upcoming change status report"+ echo+ echo "- Dry run: \`${{ steps.config.outputs.dry_run }}\`"+ echo "- Stale after days: \`${{ steps.config.outputs.stale_after_days }}\`"+ echo "- Eligible changes: \`${eligible_count}\`"+ echo+ jq -r '.[] | select(.eligible) | "- `\(.name)`: `\(.current_status)` -> `\(.next_status)` in `\(.settings_path)`; last changed \(.days_since_status_change) days ago"' /tmp/upcoming_changes_status_report.json+ } >> "${GITHUB_STEP_SUMMARY}"++ - name: Create or print pull requests+ if: steps.report.outputs.eligible_count != '0'+ env:+ REPORT_FILE: /tmp/upcoming_changes_status_report.json+ BASE_BRANCH: ${{ github.event.repository.default_branch }}+ DRY_RUN: ${{ steps.config.outputs.dry_run }}+ STALE_AFTER_DAYS: ${{ steps.config.outputs.stale_after_days }}+ run: script/create_upcoming_change_status_prsdiff --git a/lib/upcoming_changes.rb b/lib/upcoming_changes.rbindex 2a843cf1245..1d310050aef 100644--- a/lib/upcoming_changes.rb+++ b/lib/upcoming_changes.rb@@ -73,6 +73,16 @@ module UpcomingChangesstatuses.keys.select { |key| statuses[key] < statuses[status.to_sym] }.last || :conceptualend+ def self.next_status(status)+ status = status&.to_sym+ status_value = statuses[status]++ return if status_value.nil?+ return if status_value < statuses[:experimental] || status_value >= statuses[:stable]++ statuses.keys.find { |key| statuses[key] > status_value }+ end+def self.image_exists?(change_setting_name)File.exist?(File.join(Rails.public_path, image_path(change_setting_name)))enddiff --git a/lib/upcoming_changes/status_report.rb b/lib/upcoming_changes/status_report.rbnew file mode 100644index 00000000000..609a46bf7b0--- /dev/null+++ b/lib/upcoming_changes/status_report.rb@@ -0,0 +1,486 @@+# frozen_string_literal: true++require "json"+require "open3"+require "optparse"+require "pathname"+require "psych"+require "tempfile"++module UpcomingChanges+ class StatusReport+ SETTINGS_PATH = "config/site_settings.yml"+ PLUGIN_SETTINGS_PATH_PATTERN = "plugins/*/config/settings.yml"+ STATUS_PATTERN = /\A(\s*)status:\s*(["']?)([^"'\s#]+)\2([^\n]*)(\n?)\z/++ Commit = Struct.new(:sha, :date, :author_name, :author_email, :subject, keyword_init: true)+ HistoryEntry = Struct.new(:commit, :status, keyword_init: true)++ class Git+ def initialize(repo_path:)+ @repo_path = repo_path+ end++ def commits_for(path)+ output = capture("log", "--format=%H%x00%aI%x00%an%x00%ae%x00%s", "--", path)++ output.lines.filter_map do |line|+ sha, date, author_name, author_email, subject = line.chomp.split("\0", 5)+ next if sha.blank?++ Commit.new(sha:, date:, author_name:, author_email:, subject:)+ end+ end++ def show_file(commit_sha, path)+ capture("show", "#{commit_sha}:#{path}")+ end++ private++ def capture(*args)+ stdout, stderr, status = Open3.capture3("git", "-C", @repo_path, *args)+ return stdout if status.success?++ raise "git #{args.join(" ")} failed: #{stderr}"+ end+ end++ class MetadataLoader+ def self.from_content(content)+ return {} if content.blank?++ Tempfile.create(%w[upcoming-change-settings .yml]) do |file|+ file.write(content)+ file.close++ from_file(file.path, strict: false)+ end+ end++ def self.from_file(path, strict:)+ site_settings = Class.new { extend SiteSettingExtension }+ site_settings.load_settings(path)+ site_settings.upcoming_change_metadata+ rescue => error+ raise if strict++ Rails.logger.warn("Failed to parse historical site settings from #{path}: #{error.message}")+ {}+ end+ end++ class SourceIndex+ def initialize(repo_path:, settings_path:, settings_paths:)+ @repo_path = repo_path+ @settings_path = settings_path+ @configured_settings_paths = settings_paths+ end++ def changes+ @changes ||=+ settings_paths+ .each_with_object({}) do |settings_path, result|+ MetadataLoader+ .from_file(File.join(@repo_path, settings_path), strict: true)+ .each { |name, metadata| result[name.to_sym] = metadata.merge(settings_path:) }+ end+ .sort+ .to_h+ end++ def change_names+ changes.keys+ end++ def explicit_paths?+ @configured_settings_paths.present?+ end++ def metadata_for(change_name)+ changes[change_name.to_sym]+ end++ def settings_path_for(change_name)+ metadata_for(change_name)&.fetch(:settings_path) || plugin_settings_path_for(change_name) ||+ @settings_path+ end++ private++ def settings_paths+ @settings_paths ||=+ normalize_paths(@configured_settings_paths.presence || default_settings_paths)+ end++ def default_settings_paths+ [@settings_path, *Dir.glob(File.join(@repo_path, PLUGIN_SETTINGS_PATH_PATTERN)).sort]+ end++ def normalize_paths(paths)+ paths+ .map { |path| File.expand_path(path, @repo_path) }+ .map { |path| Pathname.new(path).relative_path_from(Pathname.new(@repo_path)).to_s }+ .uniq+ end++ def plugin_settings_path_for(change_name)+ plugin_name = SiteSetting.plugins[change_name.to_sym]+ return if plugin_name.blank?++ "plugins/#{plugin_name}/config/settings.yml"+ end+ end++ class CurrentChanges+ def initialize(repo_path:, source_index:)+ @repo_path = repo_path+ @source_index = source_index+ end++ def call+ current_change_names+ .each_with_object({}) do |change_name, result|+ metadata = source_metadata_for(change_name).merge(core_metadata_for(change_name))+ result[change_name] = metadata.merge(settings_path: settings_path_for(change_name))+ end+ .sort+ .to_h+ end++ private++ def current_change_names+ return @source_index.change_names.sort if source_only?++ (@source_index.change_names + SiteSetting.upcoming_change_site_settings)+ .map(&:to_sym)+ .uniq+ .sort+ end++ def source_only?+ @source_index.explicit_paths? ||+ File.expand_path(@repo_path) != File.expand_path(Rails.root.to_s)+ end++ def source_metadata_for(change_name)+ @source_index.metadata_for(change_name) || {}+ end++ def core_metadata_for(change_name)+ return {} if source_only?++ SiteSetting.upcoming_change_metadata[change_name.to_sym] || {}+ end++ def settings_path_for(change_name)+ source_metadata_for(change_name)[:settings_path] ||+ @source_index.settings_path_for(change_name)+ end+ end++ class GitHistory+ def initialize(git:)+ @git = git+ end++ def by_change(changes)+ changes+ .group_by { |_, metadata| metadata[:settings_path] }+ .each_with_object(+ Hash.new { |hash, key| hash[key] = [] },+ ) do |(settings_path, entries), result|+ add_history_for_settings_file(result, settings_path, entries.map(&:first))+ end+ end++ private++ def add_history_for_settings_file(result, settings_path, change_names)+ @git+ .commits_for(settings_path)+ .reverse_each do |commit|+ statuses = statuses_at(commit, settings_path)++ change_names.each do |change_name|+ next if !statuses.key?(change_name)++ result[change_name] << HistoryEntry.new(commit:, status: statuses[change_name])+ end+ end+ end++ def statuses_at(commit, settings_path)+ MetadataLoader+ .from_content(@git.show_file(commit.sha, settings_path))+ .transform_values { |metadata| metadata[:status]&.to_s }+ end+ end++ class PullRequestPlan+ BRANCH_PREFIX = "dev/upcoming-change-status-bump"+ LABEL = "upcoming-change"++ def self.add_to(record, stale_after_days:)+ return record if !record[:eligible]++ record.merge(+ branch: "#{BRANCH_PREFIX}/#{record[:name]}",+ title: "FEATURE: Bump #{record[:name]} upcoming change to #{record[:next_status]}",+ pr_label: LABEL,+ pr_body: body_for(record, stale_after_days:),+ )+ end++ def self.body_for(record, stale_after_days:)+ <<~MD.chomp+ <!-- upcoming-change-status-pr:#{record[:name]} -->++ This automated PR moves `#{record[:name]}` from `#{record[:current_status]}` to `#{record[:next_status]}` after #{stale_after_days}+ days without a status change.++ - Last status change commit: #{commit_link(record[:last_status_change_commit])}+ - Last status change date: `#{record[:last_status_change_date]}`+ - Settings file: `#{record[:settings_path]}`+ - Original author: #{original_author(record)}+ - Original PR: #{original_pr(record)}+ MD+ end++ def self.commit_link(commit_sha)+ return "N/A" if commit_sha.blank?++ "[`#{commit_sha}`](https://github.com/discourse/discourse/commit/#{commit_sha})"+ end++ def self.original_author(record)+ return "N/A" if record[:original_author_name].blank?++ "#{record[:original_author_name]} (<#{record[:original_author_email]}>)"+ end++ def self.original_pr(record)+ return "N/A" if record[:original_pr_number].blank?++ "##{record[:original_pr_number]}"+ end+ end++ class SourceStatusUpdater+ def initialize(settings_file:)+ @settings_file = settings_file+ end++ def update!(change_name:, next_status:)+ lines = File.readlines(@settings_file)+ status_line = status_line_for(change_name)+ raise "Could not locate status line for upcoming change: #{change_name}" if status_line.nil?++ original_line = lines.fetch(status_line)+ lines[status_line] = updated_status_line(original_line, next_status)+ if original_line == lines[status_line]+ raise "Status line for upcoming change #{change_name} did not change"+ end++ File.write(@settings_file, lines.join)+ end++ private++ def updated_status_line(line, next_status)+ match = STATUS_PATTERN.match(line)+ raise "Could not parse status line: #{line.strip}" if match.nil?++ indentation, quote, _old_status, suffix, newline = match.captures+ "#{indentation}status: #{quote}#{next_status}#{quote}#{suffix}#{newline}"+ end++ def status_line_for(change_name)+ root = Psych.parse_file(@settings_file).root+ return if !root.is_a?(Psych::Nodes::Mapping)++ each_pair(root) do |_category_key, category_value|+ next if !category_value.is_a?(Psych::Nodes::Mapping)++ each_pair(category_value) do |setting_key, setting_value|+ next if setting_key.value != change_name+ next if !setting_value.is_a?(Psych::Nodes::Mapping)++ return status_line_in(setting_value)+ end+ end++ nil+ end++ def status_line_in(setting_node)+ each_pair(setting_node) do |setting_key, setting_value|+ next if setting_key.value != "upcoming_change"+ next if !setting_value.is_a?(Psych::Nodes::Mapping)++ each_pair(setting_value) do |metadata_key, metadata_value|+ return metadata_value.start_line if metadata_key.value == "status"+ end+ end++ nil+ end++ def each_pair(mapping)+ mapping.children.each_slice(2) { |key, value| yield key, value }+ end+ end++ def initialize(+ repo_path: Rails.root.to_s,+ settings_path: SETTINGS_PATH,+ settings_paths: nil,+ stale_after_days: 14,+ now: Time.current+ )+ @repo_path = repo_path+ @settings_path = settings_path+ @stale_after_days = stale_after_days.to_i+ @now = now+ @source_index = SourceIndex.new(repo_path:, settings_path:, settings_paths:)+ @git = Git.new(repo_path:)+ end++ def report+ current_changes.map do |name, metadata|+ build_record(name, metadata, history_by_change.fetch(name, []))+ end+ end++ def apply(change_name)+ record = report.find { |change| change[:name] == change_name.to_s }+ raise "Unknown upcoming change: #{change_name}" if record.nil?+ raise "Upcoming change is not eligible: #{record[:eligibility_reason]}" if !record[:eligible]++ SourceStatusUpdater.new(settings_file: File.join(@repo_path, record[:settings_path])).update!(+ change_name: change_name.to_s,+ next_status: record[:next_status],+ )++ record.merge(applied: true)+ end++ private++ def build_record(name, metadata, history)+ original_commit = history.first+ last_status_change = last_status_change_for(history)+ current_status = metadata[:status]&.to_s+ next_status = UpcomingChanges.next_status(current_status)&.to_s+ eligible, reason = eligibility_for(current_status:, next_status:, last_status_change:)++ PullRequestPlan.add_to(+ {+ name: name.to_s,+ settings_path: metadata[:settings_path],+ current_status:,+ next_status:,+ eligible:,+ eligibility_reason: reason,+ days_since_status_change: days_since(last_status_change),+ last_status_change_commit: last_status_change&.commit&.sha,+ last_status_change_date: last_status_change&.commit&.date,+ original_commit: original_commit&.commit&.sha,+ original_commit_date: original_commit&.commit&.date,+ original_author_name: original_commit&.commit&.author_name,+ original_author_email: original_commit&.commit&.author_email,+ original_pr_number: original_pr_number(original_commit),+ },+ stale_after_days: @stale_after_days,+ )+ end++ def current_changes+ @current_changes ||=+ CurrentChanges.new(repo_path: @repo_path, source_index: @source_index).call+ end++ def changes_needing_history+ current_changes.select do |_, metadata|+ UpcomingChanges.next_status(metadata[:status]).present?+ end+ end++ def history_by_change+ @history_by_change ||= GitHistory.new(git: @git).by_change(changes_needing_history)+ end++ def last_status_change_for(history)+ history+ .each_cons(2)+ .reduce(history.first) do |last_change, (previous, current)|+ previous.status == current.status ? last_change : current+ end+ end++ def eligibility_for(current_status:, next_status:, last_status_change:)+ return false, "missing_status" if current_status.blank?+ return false, "unknown_status" if UpcomingChanges.statuses[current_status.to_sym].nil?+ return false, "terminal_status" if next_status.blank?+ return false, "missing_git_history" if last_status_change.nil?++ return false, "status_changed_recently" if days_since(last_status_change) < @stale_after_days++ [true, "status_unchanged_for_#{@stale_after_days}_days"]+ end++ def days_since(history_entry)+ return nil if history_entry.nil?++ (@now - Time.iso8601(history_entry.commit.date)).to_i / 1.day+ end++ def original_pr_number(history_entry)+ subject = history_entry&.commit&.subject+ subject&.match(/\(#(\d+)\)\z/)&.[](1) || subject&.match(/#(\d+)/)&.[](1)+ end++ class CLI+ def self.run(args)+ options = {+ repo_path: Rails.root.to_s,+ settings_paths: nil,+ stale_after_days: 14,+ pretty: false,+ }++ parser =+ OptionParser.new do |opts|+ opts.banner =+ "Usage: bin/rails runner script/upcoming_changes_status_report -- [options]"++ opts.on(+ "--apply NAME",+ "Apply the next status for one eligible upcoming change",+ ) { |name| options[:apply] = name }++ opts.on("--repo PATH", "Git repository path") { |path| options[:repo_path] = path }+ opts.on(+ "--settings-path PATH",+ "Only inspect one settings YAML path; defaults to core and plugin settings",+ ) { |path| options[:settings_paths] = [path] }+ opts.on("--stale-after-days DAYS", Integer, "Minimum unchanged age") do |days|+ options[:stale_after_days] = days+ end+ opts.on("--pretty", "Pretty-print JSON output") { options[:pretty] = true }+ end++ parser.parse!(args)++ status_report =+ StatusReport.new(+ repo_path: options[:repo_path],+ settings_paths: options[:settings_paths],+ stale_after_days: options[:stale_after_days],+ )+ output = options[:apply] ? status_report.apply(options[:apply]) : status_report.report+ puts(options[:pretty] ? JSON.pretty_generate(output) : JSON.generate(output))+ end+ end+ end+enddiff --git a/script/create_upcoming_change_status_prs b/script/create_upcoming_change_status_prsnew file mode 100755index 00000000000..d01c40c3da3--- /dev/null+++ b/script/create_upcoming_change_status_prs@@ -0,0 +1,182 @@+#!/usr/bin/env ruby+# frozen_string_literal: true++require "json"+require "open3"+require "shellwords"++class UpcomingChangeStatusPRs+ def initialize(env: ENV)+ @report_file = env.fetch("REPORT_FILE") { abort "REPORT_FILE is required" }+ @base_branch = env.fetch("BASE_BRANCH") { abort "BASE_BRANCH is required" }+ @dry_run = env.fetch("DRY_RUN", "true") == "true"+ @stale_after_days = env.fetch("STALE_AFTER_DAYS", "14")+ @github_repository = env.fetch("GITHUB_REPOSITORY", "")+ @github_step_summary = env.fetch("GITHUB_STEP_SUMMARY", "/dev/stdout")+ @rails_command = env.fetch("RAILS_COMMAND", "bin/rails")+ end++ def run+ if !@dry_run && @github_repository != "discourse/discourse"+ abort "Refusing to create pull requests outside discourse/discourse."+ end++ run!("git", "fetch", "origin", @base_branch)++ eligible_changes.each { |change| process(change) }+ end++ private++ def eligible_changes+ JSON.parse(File.read(@report_file)).select { |change| change["eligible"] }+ end++ def process(change)+ name = change["name"]+ settings_path = change["settings_path"]+ original_pr_number = change["original_pr_number"]+ branch = change["branch"]+ title = change["title"]+ pr_label = change["pr_label"]+ body_file = "/tmp/upcoming-change-#{name}-body.md"+ assignee = resolve_assignee(original_pr_number)++ File.write(body_file, change["pr_body"])++ if @dry_run+ write_dry_run_summary(+ name:,+ branch:,+ title:,+ body_file:,+ assignee:,+ settings_path:,+ pr_label:,+ )+ return+ end++ if open_pr_exists?(branch)+ puts "Open PR already exists for #{branch}; skipping."+ return+ end++ run!("git", "checkout", "-B", branch, "origin/#{@base_branch}")+ rails_runner(+ "script/upcoming_changes_status_report",+ "--",+ "--stale-after-days",+ @stale_after_days,+ "--apply",+ name,+ )+ run!("git", "add", settings_path)+ run!("git", "commit", "-m", title)+ run!("git", "push", "-f", "origin", branch)++ create_pr(branch:, title:, body_file:, pr_label:, assignee:)+ end++ def resolve_assignee(original_pr_number)+ return if original_pr_number.nil? || original_pr_number.to_s.empty?++ login, status =+ Open3.capture2(+ "gh",+ "pr",+ "view",+ original_pr_number.to_s,+ "--json",+ "author",+ "--jq",+ ".author.login",+ )+ status.success? ? login.strip : nil+ end++ def open_pr_exists?(branch)+ count =+ capture!(+ "gh",+ "pr",+ "list",+ "--head",+ branch,+ "--state",+ "open",+ "--json",+ "number",+ "--jq",+ "length",+ ).strip+ count != "0"+ end++ def create_pr(branch:, title:, body_file:, pr_label:, assignee:)+ args = [+ "gh",+ "pr",+ "create",+ "--base",+ @base_branch,+ "--head",+ branch,+ "--title",+ title,+ "--body-file",+ body_file,+ "--label",+ pr_label,+ ]+ args.push("--assignee", assignee) if assignee && !assignee.empty?+ run!(*args)+ end++ def rails_runner(*args)+ run!(@rails_command, "runner", *args, env: { "SKIP_DB_AND_REDIS" => "1", "RAILS_DB" => "nonexistent" })+ end++ def write_dry_run_summary(name:, branch:, title:, body_file:, assignee:, settings_path:, pr_label:)+ create_pr_line =+ if assignee && !assignee.empty?+ "gh pr create --base #{@base_branch} --head #{branch} --title \"#{title}\" --body-file #{body_file} --label #{pr_label} --assignee #{assignee}"+ else+ "gh pr create --base #{@base_branch} --head #{branch} --title \"#{title}\" --body-file #{body_file} --label #{pr_label}"+ end++ summary = <<~SUMMARY+ ### #{name}++ ```bash+ git checkout -B #{branch} origin/#{@base_branch}+ SKIP_DB_AND_REDIS=1 RAILS_DB=nonexistent bin/rails runner script/upcoming_changes_status_report -- --stale-after-days #{@stale_after_days} --apply #{name}+ git add #{settings_path}+ git commit -m "#{title}"+ git push -f origin #{branch}+ #{create_pr_line}+ ```++ SUMMARY++ File.open(@github_step_summary, "a") { |file| file.write(summary) }+ end++ # Runs a command, streaming output, and aborts on failure (set -e equivalent).+ def run!(*args, env: {})+ args = args.map(&:to_s)+ unless system(env, *args)+ abort "Command failed (#{$?.exitstatus}): #{args.shelljoin}"+ end+ end++ # Runs a command and returns its stdout, aborting on failure (set -e + pipefail).+ def capture!(*args)+ args = args.map(&:to_s)+ stdout, status = Open3.capture2(*args)+ abort "Command failed (#{status.exitstatus}): #{args.shelljoin}" unless status.success?+ stdout+ end+end++UpcomingChangeStatusPRs.new.run if $PROGRAM_NAME == __FILE__diff --git a/script/upcoming_changes_status_report b/script/upcoming_changes_status_reportnew file mode 100755index 00000000000..d9fefcb4945--- /dev/null+++ b/script/upcoming_changes_status_report@@ -0,0 +1,9 @@+#!/usr/bin/env ruby++# frozen_string_literal: true++if !defined?(Rails)+ abort "Run this script with bin/rails runner: SKIP_DB_AND_REDIS=1 RAILS_DB=nonexistent bin/rails runner script/upcoming_changes_status_report -- [options]"+end++UpcomingChanges::StatusReport::CLI.run(ARGV)diff --git a/spec/lib/upcoming_changes_spec.rb b/spec/lib/upcoming_changes_spec.rbindex d03646e312b..9a6a2b5d893 100644--- a/spec/lib/upcoming_changes_spec.rb+++ b/spec/lib/upcoming_changes_spec.rb@@ -295,6 +295,24 @@ RSpec.describe UpcomingChanges doendend+ describe ".next_status" do+ it "returns the next automatically promoted status", :aggregate_failures do+ expect(described_class.next_status(:experimental)).to eq(:alpha)+ expect(described_class.next_status(:alpha)).to eq(:beta)+ expect(described_class.next_status(:beta)).to eq(:stable)+ expect(described_class.next_status("beta")).to eq(:stable)+ end++ it "returns nil for statuses outside automatic promotion", :aggregate_failures do+ expect(described_class.next_status(:conceptual)).to be_nil+ expect(described_class.next_status(:stable)).to be_nil+ expect(described_class.next_status(:permanent)).to be_nil+ expect(described_class.next_status(:never)).to be_nil+ expect(described_class.next_status(:unknown)).to be_nil+ expect(described_class.next_status(nil)).to be_nil+ end+ end+describe ".history_for" dofab!(:admin)diff --git a/spec/script/create_upcoming_change_status_prs_spec.rb b/spec/script/create_upcoming_change_status_prs_spec.rbnew file mode 100644index 00000000000..bf3f84e4780--- /dev/null+++ b/spec/script/create_upcoming_change_status_prs_spec.rb@@ -0,0 +1,150 @@+# frozen_string_literal: true++require "fileutils"+require "json"+require "open3"+require "tmpdir"++RSpec.describe "script/create_upcoming_change_status_prs" do # rubocop:disable RSpec/DescribeClass+ let(:tmpdir) { Dir.mktmpdir("upcoming-change-status-prs") }+ let(:report_file) { File.join(tmpdir, "report.json") }+ let(:summary_file) { File.join(tmpdir, "summary.md") }+ let(:command_log) { File.join(tmpdir, "commands.log") }+ let(:fake_bin) { File.join(tmpdir, "bin") }+ let(:fake_rails) { File.join(fake_bin, "rails") }++ before do+ FileUtils.mkdir_p(fake_bin)+ write_fake_executable("git", <<~BASH)+ #!/usr/bin/env bash+ echo "git $*" >> "${COMMAND_LOG}"+ BASH+ write_fake_executable("gh", <<~BASH)+ #!/usr/bin/env bash+ echo "gh $*" >> "${COMMAND_LOG}"++ if [ "$1" = "pr" ] && [ "$2" = "view" ]; then+ echo original-author+ elif [ "$1" = "pr" ] && [ "$2" = "list" ]; then+ echo "${EXISTING_PR_COUNT:-0}"+ fi+ BASH+ write_fake_executable("rails", <<~BASH)+ #!/usr/bin/env bash+ echo "rails $*" >> "${COMMAND_LOG}"+ BASH+ write_fake_executable("jq", <<~'RUBY')+ #!/usr/bin/env ruby+ require "json"++ args = ARGV.dup+ args.delete("-r")+ args.delete("-c")+ filter = args.shift+ input = args.empty? ? STDIN.read : File.read(args.shift)+ data = JSON.parse(input)++ if filter == ".[] | select(.eligible)"+ data.select { |record| record["eligible"] }.each { |record| puts JSON.generate(record) }+ elsif filter.match?(/\A\.[a-z_]+( \/\/ empty)?\z/)+ field = filter.delete_prefix(".").delete_suffix(" // empty")+ print(data[field] || "")+ else+ warn "Unsupported jq filter: #{filter}"+ exit 1+ end+ RUBY+ File.write(report_file, JSON.generate(report_records))+ end++ after { FileUtils.remove_entry(tmpdir) }++ it "prints dry-run PR commands for eligible changes" do+ stdout, stderr, status = run_script("DRY_RUN" => "true")++ expect(status).to be_success, stderr.presence || stdout+ expect(File.read(summary_file)).to include(+ "SKIP_DB_AND_REDIS=1 RAILS_DB=nonexistent bin/rails runner script/upcoming_changes_status_report -- --stale-after-days 14 --apply alpha_change",+ "git add plugins/chat/config/settings.yml",+ "gh pr create --base main --head dev/upcoming-change-status-bump/alpha_change",+ "--label upcoming-change",+ "--assignee original-author",+ )+ expect(File.read(summary_file)).not_to include("stable_change")+ end++ it "creates a pull request for each eligible change" do+ stdout, stderr, status = run_script("DRY_RUN" => "false")++ expect(status).to be_success, stderr.presence || stdout+ expect(File.read(command_log)).to include(+ "git fetch origin main",+ "gh pr list --head dev/upcoming-change-status-bump/alpha_change --state open --json number --jq length",+ "git checkout -B dev/upcoming-change-status-bump/alpha_change origin/main",+ "rails runner script/upcoming_changes_status_report -- --stale-after-days 14 --apply alpha_change",+ "git add plugins/chat/config/settings.yml",+ "git commit -m FEATURE: Bump alpha_change upcoming change to beta",+ "git push -f origin dev/upcoming-change-status-bump/alpha_change",+ "gh pr create --base main --head dev/upcoming-change-status-bump/alpha_change --title FEATURE: Bump alpha_change upcoming change to beta --body-file /tmp/upcoming-change-alpha_change-body.md --label upcoming-change --assignee original-author",+ )+ expect(File.read("/tmp/upcoming-change-alpha_change-body.md")).to include(+ "<!-- upcoming-change-status-pr:alpha_change -->",+ "This automated PR moves `alpha_change` from `alpha` to `beta`",+ )+ end++ it "skips branches that already have open pull requests" do+ stdout, stderr, status = run_script("DRY_RUN" => "false", "EXISTING_PR_COUNT" => "1")++ expect(status).to be_success, stderr.presence || stdout+ expect(File.read(command_log)).to include(+ "gh pr list --head dev/upcoming-change-status-bump/alpha_change --state open --json number --jq length",+ )+ expect(File.read(command_log)).not_to include(+ "git checkout -B dev/upcoming-change-status-bump/alpha_change origin/main",+ )+ end++ def report_records+ [+ {+ name: "alpha_change",+ settings_path: "plugins/chat/config/settings.yml",+ current_status: "alpha",+ next_status: "beta",+ eligible: true,+ original_pr_number: "123",+ branch: "dev/upcoming-change-status-bump/alpha_change",+ title: "FEATURE: Bump alpha_change upcoming change to beta",+ pr_label: "upcoming-change",+ pr_body:+ "<!-- upcoming-change-status-pr:alpha_change -->\n\nThis automated PR moves `alpha_change` from `alpha` to `beta`.",+ },+ { name: "stable_change", current_status: "stable", next_status: nil, eligible: false },+ ]+ end++ def run_script(env)+ Open3.capture3(+ {+ "PATH" => "#{fake_bin}:#{ENV["PATH"]}",+ "COMMAND_LOG" => command_log,+ "REPORT_FILE" => report_file,+ "BASE_BRANCH" => "main",+ "STALE_AFTER_DAYS" => "14",+ "GITHUB_REPOSITORY" => "discourse/discourse",+ "GITHUB_STEP_SUMMARY" => summary_file,+ "RAILS_COMMAND" => fake_rails,+ **env,+ },+ "script/create_upcoming_change_status_prs",+ chdir: Rails.root.to_s,+ )+ end++ def write_fake_executable(name, content)+ path = File.join(fake_bin, name)+ File.write(path, content)+ FileUtils.chmod("+x", path)+ end+enddiff --git a/spec/script/upcoming_changes_status_report_spec.rb b/spec/script/upcoming_changes_status_report_spec.rbnew file mode 100644index 00000000000..5e01f815d41--- /dev/null+++ b/spec/script/upcoming_changes_status_report_spec.rb@@ -0,0 +1,233 @@+# frozen_string_literal: true++require "fileutils"+require "open3"+require "tmpdir"++RSpec.describe UpcomingChanges::StatusReport do+ subject(:report) do+ described_class.new(repo_path:, stale_after_days: 14, now: Time.iso8601("2026-05-26T00:00:00Z"))+ end++ let(:repo_path) { Dir.mktmpdir("upcoming-changes-status-report") }+ let(:commit_shas) { {} }++ before do+ git("init")+ git("config", "user.name", "Discourse CI")+ git("config", "user.email", "[email protected]")++ write_settings(+ "experimental_change" => "experimental",+ "alpha_change" => "alpha",+ "beta_change" => "beta",+ "recent_change" => "alpha",+ "stable_change" => "stable",+ "conceptual_change" => "conceptual",+ "permanent_change" => "permanent",+ "never_change" => "never",+ )+ write_plugin_settings("plugin_alpha_change" => "alpha")+ commit_shas[:original] = commit(+ "FEATURE: Add upcoming changes (#123)",+ date: "2026-04-01T12:00:00Z",+ author_name: "Alice Example",+ author_email: "[email protected]",+ )++ write_settings(+ "experimental_change" => "experimental",+ "alpha_change" => "alpha",+ "beta_change" => "beta",+ "recent_change" => "beta",+ "stable_change" => "stable",+ "conceptual_change" => "conceptual",+ "permanent_change" => "permanent",+ "never_change" => "never",+ )+ write_plugin_settings("plugin_alpha_change" => "alpha")+ commit_shas[:recent] = commit(+ "DEV: Bump recent upcoming change (#456)",+ date: "2026-05-20T12:00:00Z",+ author_name: "Bob Example",+ author_email: "[email protected]",+ )+ end++ after { FileUtils.remove_entry(repo_path) }++ describe "#report" do+ it "reports eligibility and git metadata", :aggregate_failures do+ records = report.report.index_by { |record| record.fetch(:name) }++ expect(records.fetch("experimental_change")).to include(+ settings_path: "config/site_settings.yml",+ current_status: "experimental",+ next_status: "alpha",+ eligible: true,+ eligibility_reason: "status_unchanged_for_14_days",+ last_status_change_commit: commit_shas[:original],+ original_commit: commit_shas[:original],+ original_author_name: "Alice Example",+ original_author_email: "[email protected]",+ original_pr_number: "123",+ branch: "dev/upcoming-change-status-bump/experimental_change",+ title: "FEATURE: Bump experimental_change upcoming change to alpha",+ pr_label: "upcoming-change",+ )+ expect(records.fetch("experimental_change").fetch(:pr_body)).to include(+ "<!-- upcoming-change-status-pr:experimental_change -->",+ "This automated PR moves `experimental_change` from `experimental` to `alpha`",+ "Original PR: #123",+ )+ expect(records.fetch("alpha_change")).to include(+ current_status: "alpha",+ next_status: "beta",+ eligible: true,+ )+ expect(records.fetch("beta_change")).to include(+ current_status: "beta",+ next_status: "stable",+ eligible: true,+ )+ recent_change = records.fetch("recent_change")+ expect(recent_change).to include(+ current_status: "beta",+ next_status: "stable",+ eligible: false,+ eligibility_reason: "status_changed_recently",+ last_status_change_commit: commit_shas[:recent],+ days_since_status_change: 5,+ )+ expect(Time.iso8601(recent_change.fetch(:last_status_change_date))).to eq(+ Time.iso8601("2026-05-20T12:00:00Z"),+ )+ expect(records.fetch("stable_change")).to include(+ current_status: "stable",+ next_status: nil,+ eligible: false,+ eligibility_reason: "terminal_status",+ )+ expect(records.fetch("conceptual_change")).to include(+ current_status: "conceptual",+ eligible: false,+ eligibility_reason: "terminal_status",+ )+ expect(records.fetch("permanent_change")).to include(+ current_status: "permanent",+ eligible: false,+ eligibility_reason: "terminal_status",+ )+ expect(records.fetch("never_change")).to include(+ current_status: "never",+ eligible: false,+ eligibility_reason: "terminal_status",+ )+ expect(records.fetch("plugin_alpha_change")).to include(+ settings_path: "plugins/chat/config/settings.yml",+ current_status: "alpha",+ next_status: "beta",+ eligible: true,+ original_commit: commit_shas[:original],+ )+ end+ end++ describe "#apply" do+ it "updates only the target setting file" do+ report.apply("plugin_alpha_change")++ metadata =+ described_class::MetadataLoader.from_file(+ File.join(repo_path, "plugins/chat/config/settings.yml"),+ strict: true,+ )++ expect(metadata.transform_values { |value| value[:status].to_s }).to include(+ plugin_alpha_change: "beta",+ )+ expect(File.read(File.join(repo_path, "config/site_settings.yml"))).to include(+ " alpha_change:\n default: false\n client: true\n hidden: true\n upcoming_change:\n status: alpha\n",+ )+ end+ end++ describe described_class::SourceStatusUpdater do+ it "raises when the status line cannot be edited" do+ settings_file = File.join(repo_path, "config/site_settings.yml")+ File.write(settings_file, <<~YAML)+ experimental:+ malformed_change:+ upcoming_change:+ status: "alpha beta"+ YAML++ updater = described_class.new(settings_file:)++ expect {+ updater.update!(change_name: "malformed_change", next_status: "beta")+ }.to raise_error(RuntimeError, /Could not parse status line/)+ end+ end++ def git(*args, env: {})+ stdout, stderr, status = Open3.capture3(env, "git", "-C", repo_path, *args)+ raise "git #{args.join(" ")} failed: #{stderr}" if !status.success?++ stdout+ end++ def commit(message, date:, author_name:, author_email:)+ git("add", ".")+ git(+ "commit",+ "-m",+ message,+ env: {+ "GIT_AUTHOR_DATE" => date,+ "GIT_COMMITTER_DATE" => date,+ "GIT_AUTHOR_NAME" => author_name,+ "GIT_AUTHOR_EMAIL" => author_email,+ "GIT_COMMITTER_NAME" => "Discourse CI",+ "GIT_COMMITTER_EMAIL" => "[email protected]",+ },+ )+ git("rev-parse", "HEAD").strip+ end++ def write_settings(statuses)+ FileUtils.mkdir_p(File.join(repo_path, "config"))+ File.write(File.join(repo_path, "config/site_settings.yml"), "experimental:\n")++ File.open(File.join(repo_path, "config/site_settings.yml"), "a") do |file|+ statuses.each do |name, status|+ file.write(" #{name}:\n")+ file.write(" default: false\n")+ file.write(" client: true\n")+ file.write(" hidden: true\n")+ file.write(" upcoming_change:\n")+ file.write(" status: #{status}\n")+ file.write(" impact: \"feature,all_members\"\n")+ file.write(" learn_more_url: \"https://meta.discourse.org/t/-/123\"\n")+ end+ end+ end++ def write_plugin_settings(statuses)+ FileUtils.mkdir_p(File.join(repo_path, "plugins/chat/config"))+ File.write(File.join(repo_path, "plugins/chat/config/settings.yml"), "chat:\n")++ File.open(File.join(repo_path, "plugins/chat/config/settings.yml"), "a") do |file|+ statuses.each do |name, status|+ file.write(" #{name}:\n")+ file.write(" default: false\n")+ file.write(" client: true\n")+ file.write(" hidden: true\n")+ file.write(" upcoming_change:\n")+ file.write(" status: #{status}\n")+ file.write(" impact: \"feature,all_members\"\n")+ file.write(" learn_more_url: \"https://meta.discourse.org/t/-/123\"\n")+ end+ end+ end+end