Class: SemverDialects::Commands::SortVersions

Inherits:
SemverDialects::Command show all
Defined in:
lib/semver_dialects/commands/sort_versions.rb

Overview

The sort command implementation

Instance Method Summary collapse

Methods inherited from SemverDialects::Command

#command, #cursor, #editor, #exec_exist?, #generator, #pager, #platform, #prompt, #screen, #which

Constructor Details

#initialize(type, versions, options) ⇒ SortVersions

rubocop:disable Lint/MissingSuper



11
12
13
14
15
# File 'lib/semver_dialects/commands/sort_versions.rb', line 11

def initialize(type, versions, options) # rubocop:disable Lint/MissingSuper
  @type = type.downcase
  @versions = versions
  @options = options
end

Instance Method Details

#execute(_input: $stdin, output: $stdout) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/semver_dialects/commands/sort_versions.rb', line 17

def execute(_input: $stdin, output: $stdout)
  sorted_versions = []
  invalid_versions = []

  @versions.each do |version|
    parsed_version = SemverDialects.parse_version(@type, version)
    sorted_versions << parsed_version
  rescue SemverDialects::InvalidVersionError, SemverDialects::UnsupportedVersionError => e
    invalid_versions << { version: version, error: e.message }
  end

  sorted_versions.sort!

  if @options[:json]
    result = {
      versions: sorted_versions.map(&:to_s),
      invalid: invalid_versions.map { |v| v[:version] }
    }
    output.puts JSON.generate(result)
  else
    invalid_versions.each do |invalid|
      output.puts "Warning: Invalid version '#{invalid[:version]}' - #{invalid[:error]}"
    end
    output.puts "Sorted versions: #{sorted_versions.map(&:to_s).join(', ')}"
  end

  0
end