class Fauxhai::Mocker

def version

def version
  @version ||= begin
    if File.exist?("#{platform_path}/#{@options[:version]}.json")
      # Whole version, use it as-is.
      @options[:version]
    else
      # Check if it's a prefix of an existing version.
      versions = Dir["#{platform_path}/*.json"].map { |path| File.basename(path, ".json") }
      unless @options[:version].to_s == ""
        # If the provided version is nil or '', that means take anything,
        # otherwise run the prefix match with an extra \D to avoid the
        # case where "7.1" matches "7.10.0".
        prefix_re = /^#{Regexp.escape(@options[:version])}\D/
        versions.select! { |ver| ver =~ prefix_re }
      end
      if versions.empty?
        # No versions available, either an unknown platform or nothing matched
        # the prefix check. Pass through the option as given so we can try
        # github fetching.
        @options[:version]
      else
        # Take the highest version available, trying to use rules that should
        # probably mostly work on all OSes. Famous last words. The idea of
        # the regex is to split on any punctuation (the common case) and
        # also any single letter with digit on either side (2012r2). This
        # leaves any long runs of letters intact (4.2-RELEASE). Then convert
        # any run of digits to an integer to get version-ish comparison.
        # This is basically a more flexible version of Gem::Version.
        versions.max_by do |ver|
          ver.split(/[^a-z0-9]|(?<=\d)[a-z](?=\d)/i).map do |part|
            if part =~ /^\d+$/
              part.to_i
            else
              part
            end
          end
        end
      end
    end
  end
end