Skip to content

Commit

Permalink
Fixes #463 (no info if port in use)
Browse files Browse the repository at this point in the history
We're now checking to see if the port is in use and exiting with an error if it is.
  • Loading branch information
LightGuard committed Apr 21, 2015
1 parent 402581a commit bb9b78b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
21 changes: 19 additions & 2 deletions lib/awestruct/cli/server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
require 'rack/server'
require 'awestruct/rack/app'
require 'awestruct/rack/generate'
require 'awestruct/cli/options'

module Awestruct
module CLI
Expand All @@ -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
Expand All @@ -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
end
14 changes: 14 additions & 0 deletions spec/awestruct/cli/server_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit bb9b78b

Please sign in to comment.