Files
codex-proxy-rs/.github/scripts/release-notes.rb
T

180 lines
8.3 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
require_relative 'release-metadata'
# 预检与发布共用日志范围;生成结果随版本提交保存,构建时不再查询可变的 PR 信息
module ReleaseNotes
START = '<!-- cpr-release:generated -->'
FINISH = '<!-- /cpr-release:generated -->'
def self.manual_body(document)
body = document.lines.drop(1).join.strip
return body unless body.include?(START) || body.include?(FINISH)
unless body.scan(START).length == 1 && body.scan(FINISH).length == 1 && body.end_with?(FINISH) &&
body.index(START) < body.index(FINISH)
raise 'Invalid generated release notes block; keep the complete block at the end or remove it'
end
body.split(START, 2).first.rstrip
end
def self.body(value)
ReleaseMetadata.validate_notes(value)
document = File.read('release/notes.md')
manual_body(document)
unless value.include?('-exp.') || document.include?(START)
raise 'Release notes are not prepared; use release/publish to generate and commit the final body'
end
document.lines.drop(1).join.strip + "\n"
end
# 只选已公开且属于目标历史的发行;首次实验版可以以同号正式版为基线
def self.previous_tag(value, releases, reachable)
core, stage = value.split('-', 2)
candidates = releases.select do |release|
tag = release.fetch('tag_name')
raw = tag.delete_prefix('v')
tag == "v#{raw}" && raw.match?(ReleaseMetadata::SEMVER) && !raw.include?('+') &&
!release.fetch('draft') && release.fetch('prerelease') == ReleaseMetadata.prerelease?(raw) &&
reachable.include?(tag)
end.map { |release| release.fetch('tag_name') }
lower = candidates.select { |tag| ReleaseMetadata.sort_key(tag) < ReleaseMetadata.sort_key(value) }
if stage
same_line = lower.select do |tag|
previous_core, previous_stage = tag.delete_prefix('v').split('-', 2)
previous_core == core && previous_stage &&
previous_stage.start_with?('exp.') == stage.start_with?('exp.')
end
return same_line.max_by { |tag| ReleaseMetadata.sort_key(tag) } unless same_line.empty?
return candidates.find { |tag| tag == "v#{core}" } if stage.start_with?('exp.')
end
lower.reject { |tag| ReleaseMetadata.prerelease?(tag) }.max_by { |tag| ReleaseMetadata.sort_key(tag) }
end
class Generator
def initialize(repository)
raise 'Invalid GitHub repository' unless repository.match?(%r{\A[\w.-]+/[\w.-]+\z})
@repository = repository
@endpoint = "repos/#{repository}"
@url = "https://github.com/#{repository}"
end
def api(path, data: nil, paginate: false)
args = ['gh', 'api', "#{@endpoint}/#{path}"]
args.concat(['--method', 'POST', '--input', '-']) if data
args.concat(['--paginate', '--jq', '.[] | @json']) if paginate
output, error, status = Open3.capture3(*args, stdin_data: data ? JSON.generate(data) : '')
raise "Cannot read release information: #{error.strip}" unless status.success?
paginate ? output.lines.map { |line| JSON.parse(line) } : JSON.parse(output)
end
def commits(base, head)
range = base ? "#{base}..#{head}" : head
ReleaseMetadata.git('log', '--first-parent', '--reverse', '--format=%H %s', range, '--').lines.map do |line|
sha, subject = line.strip.split(' ', 2)
[sha, subject]
end.reject do |sha, _|
paths = ReleaseMetadata.git('diff-tree', '--root', '--no-commit-id', '--name-only', '-r', sha).lines.map(&:strip)
!paths.empty? && (paths - %w[release/version.yaml release/notes.md]).empty?
end
end
def markdown(text)
text.gsub(/[\\`*_\[\]<>]/) { |character| "\\#{character}" }
end
def changelog(base, head, value, github_head)
# 没有前序发行时从仓库起点列举,不让 GitHub 自动猜测另一条发行线
# 未推送的提交由本地历史补齐,避免要求预检先写远端
github_range = base && ReleaseMetadata.git('merge-base', base, github_head) == ReleaseMetadata.git('rev-parse', "#{base}^{commit}")
generated = if github_range
api('releases/generate-notes', data: {
tag_name: "v#{value}", target_commitish: github_head, previous_tag_name: base
}).fetch('body').gsub("\r\n", "\n").strip
else
''
end
listed = generated.scan(%r{#{Regexp.escape(@url)}/pull/(\d+)\b}).flatten.map(&:to_i).uniq
missing = []
direct = []
commits(base, head).each do |sha, subject|
# 只识别合并提交格式,不把正文中的 Issue 引用猜成 PR
number = subject[/\(#(\d+)\)\z/, 1] || subject[/\AMerge pull request #(\d+)\b/, 1]
unless number
direct << "* #{markdown(subject)} ([#{sha[0, 9]}](#{@url}/commit/#{sha}))"
next
end
number = number.to_i
next if listed.include?(number)
pull = api("pulls/#{number}")
raise "Referenced PR ##{number} is not merged" unless pull.fetch('merged')
missing << "* #{markdown(pull.fetch('title'))} by @#{pull.fetch('user').fetch('login')} in #{@url}/pull/#{number}"
listed << number
end
unless missing.empty?
heading = "## What's Changed"
generated = if generated.include?(heading)
generated.sub(heading, "#{heading}\n#{missing.join("\n")}")
else
["#{heading}\n#{missing.join("\n")}", generated].reject(&:empty?).join("\n\n")
end
end
# 直接提交也有明确链接,不能把 PR 列表当成完整变更范围
generated += "\n\n## 其他提交\n#{direct.join("\n")}" unless direct.empty?
link = base ? "#{@url}/compare/#{base}...v#{value}" : "#{@url}/commits/#{head}"
generated += "\n\n**Full Changelog**: #{link}" unless generated.include?(link)
warn "日志范围:#{base || '仓库起点'} → #{head};#{listed.length} 个 PR,#{direct.length} 个直接提交"
warn "已补齐自动列表遗漏:#{missing.join("\n")}" unless missing.empty?
generated.strip
end
def prepare(value, head: 'HEAD', github_head: head)
value = ReleaseMetadata.release_version(value)
ReleaseMetadata.validate_notes(value)
head = ReleaseMetadata.git('rev-parse', '--verify', "#{head}^{commit}")
github_head = ReleaseMetadata.git('rev-parse', '--verify', "#{github_head}^{commit}")
unless ReleaseMetadata.git('merge-base', head, github_head) == github_head
raise 'GitHub source commit must be an ancestor of the release source'
end
reachable = ReleaseMetadata.git('tag', '--list', 'v*', '--merged', head).lines.map(&:strip)
releases = api('releases?per_page=100', paginate: true)
unknown = releases.map { |release| release.fetch('tag_name') } - ReleaseMetadata.git('tag', '--list', 'v*').lines.map(&:strip)
base = ReleaseNotes.previous_tag(value, releases, reachable + unknown)
raise "Published baseline tag #{base} is missing locally; fetch remote tags before preparing notes" if unknown.include?(base)
manual = ReleaseNotes.manual_body(File.read('release/notes.md'))
raise 'Release notes must contain a handwritten description' if manual.empty?
warn "发布基线:#{base || '仓库起点'};目标:v#{value};源码:#{head}"
return "# v#{value}\n\n#{manual}\n" if value.include?('-exp.')
installation = <<~MARKDOWN.strip
## Linux 一键安装(Docker Compose)
```bash
curl -fsSLO #{@url.sub('github.com', 'raw.githubusercontent.com')}/v#{value}/deploy/install.sh && CPR_RELEASE_TAG=v#{value} bash install.sh
```
## 📚 文档
- [GitHub 仓库](#{@url})
- [部署指南](#{@url}/blob/v#{value}/deploy/README.md)
MARKDOWN
"# v#{value}\n\n#{manual}\n\n#{START}\n#{installation}\n\n#{changelog(base, head, value, github_head)}\n#{FINISH}\n"
end
end
end
if $PROGRAM_NAME == __FILE__
begin
command, value, repository, github_head = ARGV
case command
when 'prepare'
raise 'prepare requires VERSION REPOSITORY GITHUB_HEAD' unless ARGV.length == 4
puts ReleaseNotes::Generator.new(repository).prepare(value, github_head: github_head)
when 'body'
raise 'body requires VERSION' unless ARGV.length == 2
puts ReleaseNotes.body(value)
else
raise 'usage: release-notes.rb prepare VERSION REPOSITORY GITHUB_HEAD | body VERSION'
end
rescue StandardError => error
warn "error: #{error.message}"
exit 1
end
end