Sha256: 44f2878e6853c893b7bf36b0fd996aacd46531b342c9cf0c316a5ea2d2b2bc17

Contents?: true

Size: 829 Bytes

Versions: 1

Compression:

Stored size: 829 Bytes

Contents

# frozen_string_literal: true
require "shopify_cli"
require "socket"

module Extension
  module Tasks
    class ChooseNextAvailablePort
      include ShopifyCli::MethodObject

      property! :from
      property! :to, default: -> { from + 10 }
      property! :host, default: "127.0.0.1"

      def call
        available_port = port_range(from: from, to: to).find { |p| available?(host, p) }
        raise ArgumentError, "Ports between #{from} and #{to} are unavailable" if available_port.nil?
        available_port
      end

      private

      def port_range(from:, to:)
        (from..to)
      end

      def available?(host, port)
        Socket.tcp(host, port, connect_timeout: 1) do |socket|
          socket.close
          false
        end
      rescue Errno::ECONNREFUSED
        true
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
shopify-cli-2.4.0 lib/project_types/extension/tasks/choose_next_available_port.rb