From 1a23ab39384b9222f9a73e4e6c49ab26485d2f70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dennis=20G=C3=BCnnewig?= Date: Thu, 7 May 2015 09:21:47 +0200 Subject: [PATCH] Iterate over 4 ports before giving up and let the user choose a port to listen on --- .../lib/middleman-core/preview_server.rb | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/middleman-core/lib/middleman-core/preview_server.rb b/middleman-core/lib/middleman-core/preview_server.rb index 897c3f0f..3f2a99e7 100644 --- a/middleman-core/lib/middleman-core/preview_server.rb +++ b/middleman-core/lib/middleman-core/preview_server.rb @@ -207,9 +207,26 @@ module Middleman end begin + tries ||= 4 + tried_ports ||= [] + ::WEBrick::HTTPServer.new(http_opts) rescue Errno::EADDRINUSE - logger.error "== Port #{port} is unavailable. Either close the instance of Middleman already running on #{port} or start this Middleman on a new port with: --port=#{port.to_i + 1}" + tries -= 1 + + tried_ports << port + + if tries > 0 + logger.error %(== Port #{port} is unavailable. Trying port #{port + 1} next.) + + @port += 1 + http_opts[:Port] = @port + + retry + end + + logger.error %(== Ports #{tried_ports.to_sentence} are unavailable. Either close the instances of "Middleman" already running on Ports #{tried_ports.to_sentence} or start this "Middleman"-instance on a another port with: "middleman server --port=#{port + 1}".) + exit(1) end end