From 4aa7f839543d36873348d8b5ab0011a32fbd86d9 Mon Sep 17 00:00:00 2001 From: Mike McQuaid Date: Wed, 21 May 2025 17:02:18 +0100 Subject: [PATCH] dev-cmd/bump-formula-pr: use `Formatter.truncate`. Add new `Formatter.truncate` method, tests and use it. --- Library/Homebrew/dev-cmd/bump-formula-pr.rb | 2 +- Library/Homebrew/test/formatter_spec.rb | 14 ++++++++++++++ Library/Homebrew/utils/formatter.rb | 13 +++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Library/Homebrew/dev-cmd/bump-formula-pr.rb b/Library/Homebrew/dev-cmd/bump-formula-pr.rb index adfb59ab07..c3a0646c15 100644 --- a/Library/Homebrew/dev-cmd/bump-formula-pr.rb +++ b/Library/Homebrew/dev-cmd/bump-formula-pr.rb @@ -400,7 +400,7 @@ module Homebrew if github_release_data.present? pre = "pre" if github_release_data["prerelease"].present? # maximum length of PR body is 65,536 characters so let's truncate release notes to half of that. - body = github_release_data["body"].truncate(32_768) + body = Formatter.truncate(github_release_data["body"], max: 32_768) formula_pr_message += <<~XML
diff --git a/Library/Homebrew/test/formatter_spec.rb b/Library/Homebrew/test/formatter_spec.rb index e02451a594..ba866ee8f5 100644 --- a/Library/Homebrew/test/formatter_spec.rb +++ b/Library/Homebrew/test/formatter_spec.rb @@ -110,4 +110,18 @@ RSpec.describe Formatter do expect(described_class.format_help_text(text, width: 80)).to eq expected end end + + describe "::truncate" do + it "returns the original string if it's shorter than max length" do + expect(described_class.truncate("short", max: 10)).to eq("short") + end + + it "truncates strings longer than max length" do + expect(described_class.truncate("this is a long string", max: 10)).to eq("this is...") + end + + it "uses custom omission string" do + expect(described_class.truncate("this is a long string", max: 10, omission: " [...]")).to eq("this [...]") + end + end end diff --git a/Library/Homebrew/utils/formatter.rb b/Library/Homebrew/utils/formatter.rb index 9815425204..3e7428c80e 100644 --- a/Library/Homebrew/utils/formatter.rb +++ b/Library/Homebrew/utils/formatter.rb @@ -54,6 +54,19 @@ module Formatter label(label, string, :red) end + # Truncate a string to a specific length. + # + # @api internal + sig { params(string: String, max: Integer, omission: String).returns(String) } + def self.truncate(string, max: 30, omission: "...") + return string if string.length <= max + + length_with_room_for_omission = max - omission.length + truncated = string[0, length_with_room_for_omission] + + "#{truncated}#{omission}" + end + # Wraps text to fit within a given number of columns using regular expressions that: # # 1. convert hard-wrapped paragraphs to a single line