Module: GemRadar::CLI
- Defined in:
- lib/gem_radar/cli.rb
Constant Summary collapse
- USER_AGENT =
"gem_radar/#{VERSION} (https://github.com/laurajaime/gem_radar)"- RAILS_FAMILY =
%w[ rails railties actionpack actionview activerecord activesupport activejob activemodel actioncable activestorage actionmailer actionmailbox actiontext ].freeze
- MAX_RAILS_CHECKS =
12- DEPRECATION_NOTICE =
Matches an actual deprecation notice ("DEPRECATED: ...", "this gem is deprecated", "no longer maintained"), not just any mention of the word — a gem about deprecation (like this one) can otherwise flag itself.
/ (?:\A|[.!]\s*) \W* (?: this \s gem \s (?:is|has \s been) \s deprecated | deprecated \s*[:-] | \[deprecated\] | no \s longer \s maintained | unmaintained ) /ix.freeze
- CATEGORY_ORDER =
--- Classification -----------------------------------------------------------
%i[mandatory compatible deprecated updatable_safe updatable_breaking not_found].freeze
- CATEGORY_TITLES =
{ mandatory: "❗ Mandatory update (installed version is no longer compatible with your Ruby/Rails)", compatible: "✅ Compatible with Ruby and Rails", deprecated: "🗑️ Deprecated / archived", updatable_safe: "⬆️ Safely updatable (same major version line)", updatable_breaking: "⚠️ Updatable with changes (major version bump, or requires a newer Ruby/Rails)", not_found: "❔ No data (not found on rubygems.org)" }.freeze
Class Method Summary collapse
- .build_report(project, ruby_version, rails_version, results, _options) ⇒ Object
- .classify(result) ⇒ Object
- .depends_on_rails_family?(runtime_deps) ⇒ Boolean
- .deprecated?(info, repo_info) ⇒ Boolean
- .detect_rails_version(options, lockfile_data) ⇒ Object
- .detect_ruby_version(options, lockfile_data) ⇒ Object
-
.format_gem_line(result) ⇒ Object
--- Report -------------------------------------------------------------------.
- .gem_version(str) ⇒ Object
- .github_api(path) ⇒ Object
-
.github_repo(url) ⇒ Object
--- Repository / deprecation status -----------------------------------------.
- .github_token ⇒ Object
-
.http_get(url, headers = {}, limit = 5) ⇒ Object
--- HTTP -----------------------------------------------------------------.
-
.latest_compatible(name, versions, ruby_version, rails_version, latest_runtime_deps) ⇒ Object
Latest stable version compatible with the project's Ruby and, if the gem depends on any Rails component, also with the project's Rails version.
-
.mandatory_update_reasons(name, installed, versions, ruby_version, rails_version, latest_runtime_deps) ⇒ Object
Reasons why the ALREADY INSTALLED version fails to meet the project's current Ruby/Rails: if any are found, this gem must be updated — it's not just a recommendation (unlike the "updatable" categories).
-
.parse_lockfile(path) ⇒ Object
Returns { dependencies: [names], specs: => version, ruby: "x.y.z" or nil }.
- .parse_options(argv) ⇒ Object
-
.process_gem(name, installed_str, ruby_version, rails_version) ⇒ Object
--- Per-gem processing ------------------------------------------------------.
- .rails_requirement_satisfied?(runtime_deps, rails_version) ⇒ Boolean
- .repo_url_for(info) ⇒ Object
- .requirement_satisfied?(requirement_str, version) ⇒ Boolean
-
.rubygems_info(name) ⇒ Object
--- rubygems.org -----------------------------------------------------------.
- .rubygems_versions(name) ⇒ Object
- .run(argv) ⇒ Object
-
.same_compat_line?(installed, candidate) ⇒ Boolean
In SemVer, when major is 0 it's the minor that marks breaking changes (0.MAJOR.MINOR), as is common across the Rails gem ecosystem.
- .version_runtime_dependencies(name, version) ⇒ Object
Class Method Details
.build_report(project, ruby_version, rails_version, results, _options) ⇒ Object
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
# File 'lib/gem_radar/cli.rb', line 403 def build_report(project, ruby_version, rails_version, results, ) grouped = results.group_by { |result| classify(result) } lines = [] lines << "# Gems in #{project}" lines << "" lines << "Generated: #{Time.now.strftime('%Y-%m-%d %H:%M')} · Ruby: #{ruby_version || 'unknown'} · " \ "Rails: #{rails_version || 'unknown'} · #{results.size} direct gems" lines << "" lines << "## Summary" lines << "" lines << "| Category | Gems |" lines << "|---|---|" CATEGORY_ORDER.each do |cat| count = grouped[cat]&.size || 0 lines << "| #{CATEGORY_TITLES[cat]} | #{count} |" end lines << "" lines << "---" CATEGORY_ORDER.each do |cat| items = grouped[cat] next if items.nil? || items.empty? lines << "" lines << "## #{CATEGORY_TITLES[cat]}" lines << "" items.each { |result| lines << format_gem_line(result) } end "#{lines.join("\n")}\n" end |
.classify(result) ⇒ Object
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
# File 'lib/gem_radar/cli.rb', line 366 def classify(result) return :not_found unless result[:found] return :mandatory if result[:mandatory_reasons] && !result[:mandatory_reasons].empty? return :deprecated if result[:deprecated] return :compatible unless result[:installed] && result[:latest] no_compatible_update = result[:compatible].nil? || result[:compatible] <= result[:installed] if result[:compatible] && result[:compatible] > result[:installed] same_compat_line?(result[:installed], result[:compatible]) ? :updatable_safe : :updatable_breaking elsif result[:latest] > result[:installed] && no_compatible_update # A newer version exists, but none was found compatible with the # current Ruby/Rails: updating means upgrading the framework too. :updatable_breaking else :compatible end end |
.depends_on_rails_family?(runtime_deps) ⇒ Boolean
229 230 231 |
# File 'lib/gem_radar/cli.rb', line 229 def depends_on_rails_family?(runtime_deps) Array(runtime_deps).any? { |d| RAILS_FAMILY.include?(d["name"]) } end |
.deprecated?(info, repo_info) ⇒ Boolean
336 337 338 339 340 341 |
# File 'lib/gem_radar/cli.rb', line 336 def deprecated?(info, repo_info) return true if repo_info && repo_info["archived"] text = "#{info['info']} #{info['description']}" !!(text =~ DEPRECATION_NOTICE) end |
.detect_rails_version(options, lockfile_data) ⇒ Object
177 178 179 |
# File 'lib/gem_radar/cli.rb', line 177 def detect_rails_version(, lockfile_data) [:rails] || lockfile_data[:specs]["rails"] end |
.detect_ruby_version(options, lockfile_data) ⇒ Object
167 168 169 170 171 172 173 174 175 |
# File 'lib/gem_radar/cli.rb', line 167 def detect_ruby_version(, lockfile_data) return [:ruby] if [:ruby] if File.file?(".ruby-version") v = File.read(".ruby-version").strip.sub(/\Aruby-/, "") return v unless v.empty? end lockfile_data[:ruby] end |
.format_gem_line(result) ⇒ Object
--- Report -------------------------------------------------------------------
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
# File 'lib/gem_radar/cli.rb', line 387 def format_gem_line(result) parts = ["**#{result[:name]}**"] parts << "installed `#{result[:installed]}`" if result[:installed] if result[:compatible] && result[:installed] && result[:compatible] > result[:installed] parts << "recommended `#{result[:compatible]}`" end if result[:latest] && (result[:compatible].nil? || result[:latest] > result[:compatible]) parts << "latest published `#{result[:latest]}`" end line = "- #{parts.join(' · ')}" line += " — [repository](#{result[:repo_url]})" if result[:repo_url] line += "\n\n > #{result[:error]}" if result[:error] Array(result[:mandatory_reasons]).each { |reason| line += "\n\n > #{reason}" } line end |
.gem_version(str) ⇒ Object
215 216 217 218 219 |
# File 'lib/gem_radar/cli.rb', line 215 def gem_version(str) Gem::Version.new(str.to_s.sub(/\Av/i, "").gsub("-", ".")) rescue ArgumentError nil end |
.github_api(path) ⇒ Object
130 131 132 133 134 135 136 137 138 139 |
# File 'lib/gem_radar/cli.rb', line 130 def github_api(path) headers = { "Accept" => "application/vnd.github+json" } headers["Authorization"] = "Bearer #{github_token}" if github_token res = http_get("https://api.github.com#{path}", headers) return nil unless res.is_a?(Net::HTTPSuccess) JSON.parse(res.body) rescue JSON::ParserError nil end |
.github_repo(url) ⇒ Object
--- Repository / deprecation status -----------------------------------------
306 307 308 309 310 311 |
# File 'lib/gem_radar/cli.rb', line 306 def github_repo(url) return nil unless url && !url.empty? m = url.match(%r{github\.com/([^/]+)/([^/#?]+)}) m && "#{m[1]}/#{m[2].sub(/\.git\z/, '')}" end |
.github_token ⇒ Object
117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'lib/gem_radar/cli.rb', line 117 def github_token return @github_token if defined?(@github_token) token = ENV["GITHUB_TOKEN"] || ENV.fetch("GH_TOKEN", nil) token ||= begin out = `gh auth token 2>/dev/null`.strip out.empty? ? nil : out rescue StandardError nil end @github_token = token end |
.http_get(url, headers = {}, limit = 5) ⇒ Object
--- HTTP -----------------------------------------------------------------
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
# File 'lib/gem_radar/cli.rb', line 98 def http_get(url, headers = {}, limit = 5) return nil if limit.zero? uri = URI(url) req = Net::HTTP::Get.new(uri) req["User-Agent"] = USER_AGENT headers.each { |k, v| req[k] = v } res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 10, read_timeout: 30) { |h| h.request(req) } if res.is_a?(Net::HTTPRedirection) && res["location"] http_get(URI.join(url, res["location"]).to_s, headers, limit - 1) else res end rescue StandardError => e warn " warning: HTTP request failed for #{url}: #{e.class}: #{e.}" nil end |
.latest_compatible(name, versions, ruby_version, rails_version, latest_runtime_deps) ⇒ Object
Latest stable version compatible with the project's Ruby and, if the gem depends on any Rails component, also with the project's Rails version. Returns nil if none of the latest MAX_RAILS_CHECKS ruby-compatible versions satisfies the Rails requirement.
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
# File 'lib/gem_radar/cli.rb', line 246 def latest_compatible(name, versions, ruby_version, rails_version, latest_runtime_deps) ruby = ruby_version && gem_version(ruby_version) rails = rails_version && gem_version(rails_version) candidates = versions.reject { |v| v["prerelease"] } .select { |v| v["platform"].nil? || v["platform"] == "ruby" } candidates = candidates.select do |v| ruby.nil? || requirement_satisfied?(v["ruby_version"], ruby) end candidates = candidates.map { |v| [gem_version(v["number"]), v["number"]] } .select { |gv, _| gv } .sort_by { |gv, _| gv } .reverse return candidates.first&.first unless rails && depends_on_rails_family?(latest_runtime_deps) candidates.first(MAX_RAILS_CHECKS).each do |gv, number| deps = version_runtime_dependencies(name, number) next if deps.nil? return gv if rails_requirement_satisfied?(deps, rails) end nil end |
.mandatory_update_reasons(name, installed, versions, ruby_version, rails_version, latest_runtime_deps) ⇒ Object
Reasons why the ALREADY INSTALLED version fails to meet the project's current Ruby/Rails: if any are found, this gem must be updated — it's not just a recommendation (unlike the "updatable" categories).
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
# File 'lib/gem_radar/cli.rb', line 273 def mandatory_update_reasons(name, installed, versions, ruby_version, rails_version, latest_runtime_deps) return [] unless installed entry = versions.find { |v| gem_version(v["number"]) == installed } return [] unless entry # installed version not indexed on rubygems.org (yanked, etc.) reasons = [] if ruby_version ruby = gem_version(ruby_version) req = entry["ruby_version"] unless req.nil? || req.to_s.empty? || requirement_satisfied?(req, ruby) reasons << "requires Ruby #{req}, project uses #{ruby_version}" end end if rails_version && depends_on_rails_family?(latest_runtime_deps) deps = version_runtime_dependencies(name, entry["number"]) if deps rails = gem_version(rails_version) Array(deps).select { |d| RAILS_FAMILY.include?(d["name"]) }.each do |d| unless requirement_satisfied?(d["requirements"], rails) reasons << "#{d['name']} requires #{d['requirements']}, project uses Rails #{rails_version}" end end end end reasons end |
.parse_lockfile(path) ⇒ Object
Returns { dependencies: [names], specs: => version, ruby: "x.y.z" or nil }
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/gem_radar/cli.rb', line 144 def parse_lockfile(path) abort "Can't find #{path}. Run this from the project root (or use --lockfile)." unless File.file?(path) deps = [] specs = {} ruby = nil section = nil File.read(path).each_line do |line| if line =~ /\A[A-Z][A-Z ]*\s*\z/ section = line.strip next end case section when "GEM", "GIT", "PATH" specs[::Regexp.last_match(1)] = ::Regexp.last_match(2) if line =~ /\A (\S+) \(([^)\s]+)\)/ when "DEPENDENCIES" deps << ::Regexp.last_match(1) if line =~ /\A ([^\s!(]+)/ when "RUBY VERSION" ruby = ::Regexp.last_match(1) if line =~ /ruby (\d+\.\d+\.\d+)/ end end { dependencies: deps.uniq.sort, specs: specs, ruby: ruby } end |
.parse_options(argv) ⇒ Object
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/gem_radar/cli.rb', line 72 def (argv) = { output: "gem_radar.md", lockfile: "Gemfile.lock" } OptionParser.new do |o| o. = "Usage: gem_radar [options] (run from inside the project directory)" o.on("--ruby VERSION", "Project's Ruby version (default: .ruby-version or Gemfile.lock)") do |v| [:ruby] = v end o.on("--rails VERSION", "Project's Rails version (default: the one in Gemfile.lock)") do |v| [:rails] = v end o.on("--lockfile PATH", "Path to Gemfile.lock (default: ./Gemfile.lock)") { |v| [:lockfile] = v } o.on("-o", "--output PATH", "Output file (default: gem_radar.md)") { |v| [:output] = v } o.on("-h", "--help", "Shows this help") do puts o exit end o.on("--version", "Shows the version") do puts "gem_radar #{VERSION} (\"#{CODENAME}\")" exit end end.parse!(argv) end |
.process_gem(name, installed_str, ruby_version, rails_version) ⇒ Object
--- Per-gem processing ------------------------------------------------------
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 |
# File 'lib/gem_radar/cli.rb', line 437 def process_gem(name, installed_str, ruby_version, rails_version) installed = gem_version(installed_str) info = rubygems_info(name) unless info return { name: name, installed: installed, found: false, error: "Couldn't find `#{name}` on rubygems.org (private gem, or installed from git/path?)." } end latest = gem_version(info["version"]) versions = rubygems_versions(name) latest_runtime_deps = info.dig("dependencies", "runtime") || [] compatible = latest_compatible(name, versions, ruby_version, rails_version, latest_runtime_deps) mandatory_reasons = mandatory_update_reasons(name, installed, versions, ruby_version, rails_version, latest_runtime_deps) url, repo = repo_url_for(info) repo_info = repo && github_api("/repos/#{repo}") { name: name, found: true, installed: installed, latest: latest, compatible: compatible, repo_url: url, deprecated: deprecated?(info, repo_info), mandatory_reasons: mandatory_reasons } end |
.rails_requirement_satisfied?(runtime_deps, rails_version) ⇒ Boolean
233 234 235 236 237 238 239 240 |
# File 'lib/gem_radar/cli.rb', line 233 def rails_requirement_satisfied?(runtime_deps, rails_version) return true unless rails_version rails_deps = Array(runtime_deps).select { |d| RAILS_FAMILY.include?(d["name"]) } return true if rails_deps.empty? rails_deps.all? { |d| requirement_satisfied?(d["requirements"], rails_version) } end |
.repo_url_for(info) ⇒ Object
313 314 315 316 317 318 319 320 321 |
# File 'lib/gem_radar/cli.rb', line 313 def repo_url_for(info) repo = github_repo(info["source_code_uri"]) || github_repo(info.dig("metadata", "source_code_uri")) || github_repo(info["homepage_uri"]) || github_repo(info["changelog_uri"]) return ["https://github.com/#{repo}", repo] if repo [info["source_code_uri"] || info["homepage_uri"], nil] end |
.requirement_satisfied?(requirement_str, version) ⇒ Boolean
221 222 223 224 225 226 227 |
# File 'lib/gem_radar/cli.rb', line 221 def requirement_satisfied?(requirement_str, version) return true if requirement_str.nil? || requirement_str.to_s.empty? Gem::Requirement.new(*requirement_str.split(",").map(&:strip)).satisfied_by?(version) rescue StandardError true end |
.rubygems_info(name) ⇒ Object
--- rubygems.org -----------------------------------------------------------
183 184 185 186 187 188 189 190 |
# File 'lib/gem_radar/cli.rb', line 183 def rubygems_info(name) res = http_get("https://rubygems.org/api/v1/gems/#{name}.json") return nil unless res.is_a?(Net::HTTPSuccess) JSON.parse(res.body) rescue JSON::ParserError nil end |
.rubygems_versions(name) ⇒ Object
192 193 194 195 196 197 198 199 |
# File 'lib/gem_radar/cli.rb', line 192 def rubygems_versions(name) res = http_get("https://rubygems.org/api/v1/versions/#{name}.json") return [] unless res.is_a?(Net::HTTPSuccess) JSON.parse(res.body) rescue JSON::ParserError [] end |
.run(argv) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/gem_radar/cli.rb', line 44 def run(argv) = (argv) lock = parse_lockfile([:lockfile]) ruby_version = detect_ruby_version(, lock) rails_version = detect_rails_version(, lock) lockfile_dir = File.dirname([:lockfile]) project = File.basename(File.(lockfile_dir == "." ? Dir.pwd : lockfile_dir)) warn "Project: #{project} · Ruby: #{ruby_version || 'not detected (use --ruby)'} · " \ "Rails: #{rails_version || 'not detected (use --rails)'} · #{lock[:dependencies].size} direct gems" unless github_token warn "Warning: no GITHUB_TOKEN and no authenticated `gh`; GitHub's API is limited to 60 requests/hour." end results = lock[:dependencies].each_with_index.map do |name, i| warn format(" [%<index>d/%<total>d] %<name>s…", index: i + 1, total: lock[:dependencies].size, name: name) process_gem(name, lock[:specs][name], ruby_version, rails_version) end File.write([:output], build_report(project, ruby_version, rails_version, results, )) by_category = results.group_by { |r| classify(r) } warn "Done: #{[:output]} (#{results.size} gems · " \ "#{by_category[:mandatory]&.size || 0} mandatory update · " \ "#{by_category[:updatable_safe]&.size || 0} safely updatable · " \ "#{by_category[:updatable_breaking]&.size || 0} updatable with changes · " \ "#{by_category[:deprecated]&.size || 0} deprecated)" end |
.same_compat_line?(installed, candidate) ⇒ Boolean
In SemVer, when major is 0 it's the minor that marks breaking changes (0.MAJOR.MINOR), as is common across the Rails gem ecosystem.
358 359 360 361 362 363 364 |
# File 'lib/gem_radar/cli.rb', line 358 def same_compat_line?(installed, candidate) if installed.segments.first.zero? && candidate.segments.first.zero? installed.segments[1] == candidate.segments[1] else installed.segments.first == candidate.segments.first end end |
.version_runtime_dependencies(name, version) ⇒ Object
201 202 203 204 205 206 207 208 209 210 211 212 213 |
# File 'lib/gem_radar/cli.rb', line 201 def version_runtime_dependencies(name, version) @version_deps_cache ||= {} key = "#{name}@#{version}" return @version_deps_cache[key] if @version_deps_cache.key?(key) res = http_get("https://rubygems.org/api/v2/rubygems/#{name}/versions/#{version}.json") @version_deps_cache[key] = begin res.is_a?(Net::HTTPSuccess) ? (JSON.parse(res.body).dig("dependencies", "runtime") || []) : nil rescue JSON::ParserError nil end end |