class Spring::Env

def app_name

def app_name
  root.basename
end

def application_id

def application_id
  Digest::MD5.hexdigest(RUBY_VERSION + project_root.to_s)
end

def initialize(root = nil)

def initialize(root = nil)
  @root         = root
  @project_root = root
  @log_file     = File.open(ENV["SPRING_LOG"] || File::NULL, "a")
end

def kill(sig)

def kill(sig)
  pid = self.pid
  Process.kill(sig, pid) if pid
rescue Errno::ESRCH
  # already dead
end

def log(message)

def log(message)
  log_file.puts "[#{Time.now}] [#{Process.pid}] #{message}"
  log_file.flush
end

def pid

def pid
  pidfile_path.exist? ? pidfile_path.read.to_i : nil
rescue Errno::ENOENT
  # This can happen if the pidfile is removed after we check it
  # exists
end

def pidfile_path

def pidfile_path
  tmp_path.join("#{application_id}.pid")
end

def project_root

def project_root
  @project_root ||= Spring.project_root_path
end

def root

def root
  @root ||= Spring.application_root_path
end

def server_running?

def server_running?
  pidfile = pidfile_path.open('r+')
  !pidfile.flock(File::LOCK_EX | File::LOCK_NB)
rescue Errno::ENOENT
  false
ensure
  if pidfile
    pidfile.flock(File::LOCK_UN)
    pidfile.close
  end
end

def socket_name

def socket_name
  socket_path.to_s
end

def socket_path

def socket_path
  tmp_path.join(application_id)
end

def stop

def stop
  if server_running?
    timeout = Time.now + STOP_TIMEOUT
    kill 'TERM'
    sleep 0.1 until !server_running? || Time.now >= timeout
    if server_running?
      kill 'KILL'
      :killed
    else
      :stopped
    end
  else
    :not_running
  end
end

def tmp_path

def tmp_path
  path = Pathname.new(File.join(ENV['XDG_RUNTIME_DIR'] || Dir.tmpdir, "spring"))
  FileUtils.mkdir_p(path) unless path.exist?
  path
end

def version

def version
  Spring::VERSION
end