diff --git a/lib/awestruct/cli/server.rb b/lib/awestruct/cli/server.rb index 4c891b7b..ff616c24 100644 --- a/lib/awestruct/cli/server.rb +++ b/lib/awestruct/cli/server.rb @@ -3,6 +3,7 @@ require 'rack/server' require 'awestruct/rack/app' require 'awestruct/rack/generate' +require 'awestruct/cli/options' module Awestruct module CLI @@ -17,9 +18,13 @@ def initialize(path, bind_addr=Options::DEFAULT_BIND_ADDR, port=Options::DEFAULT end def run + unless port_open? (Options::LOCAL_HOSTS[@bind_addr] || @bind_addr), @port + $LOG.error "#{Options::LOCAL_HOSTS[@bind_addr] || @bind_addr}:#{@port} not available for server" if $LOG.error? + abort + end url = %(http://#{Options::LOCAL_HOSTS[@bind_addr] || @bind_addr}:#{@port}) msg = %(Starting preview server at #{url} (Press Ctrl-C to shutdown)) - puts %(#{'*' * msg.length}\n#{msg}\n#{'*' * msg.length}\n) + $LOG.info %(#{'*' * msg.length}\n#{msg}\n#{'*' * msg.length}\n) if $LOG.info? path = @path generate_on_access = @generate_on_access @@ -35,6 +40,18 @@ def run :Host => @bind_addr ) end + + private + # Private. Checks to see if the port is open. + def port_open?(addr, port) + begin + s = TCPServer.new(addr, port) + s.close + true + rescue + false + end + end end end -end \ No newline at end of file +end diff --git a/spec/awestruct/cli/server_spec.rb b/spec/awestruct/cli/server_spec.rb new file mode 100644 index 00000000..76e1d912 --- /dev/null +++ b/spec/awestruct/cli/server_spec.rb @@ -0,0 +1,14 @@ +require 'awestruct/cli/server' +require 'awestruct/cli/options' +require 'socket' + +describe Awestruct::CLI::Server do + + let(:subject) { Awestruct::CLI::Server.new('./')} + + it 'should abort if the port is already in use' do + server = TCPServer.new(Awestruct::CLI::Options::DEFAULT_BIND_ADDR, Awestruct::CLI::Options::DEFAULT_PORT) + expect(lambda {subject.run} ).to raise_error(SystemExit) + server.close + end +end \ No newline at end of file