class Spring::Client::Binstub::Item

def add

def add
  if existing
    if existing.include?(OLD_BINSTUB)
      fallback = existing.match(/#{Regexp.escape OLD_BINSTUB}\n(.*)else/m)[1]
      fallback.gsub!(/^  /, "")
      fallback = nil if fallback.include?("exec")
      generate(fallback)
      status "upgraded"
    elsif existing =~ /load .*spring/
      status "spring already present"
    else
      head, shebang, tail = existing.partition(SHEBANG)
      if shebang.include?("ruby")
        unless command.binstub.exist?
          FileUtils.touch command.binstub
          command.binstub.chmod 0755
        end
        File.write(command.binstub, "#{head}#{shebang}#{LOADER}#{tail}")
        status "spring inserted"
      else
        status "doesn't appear to be ruby, so cannot use spring", $stderr
        exit 1
      end
    end
  else
    generate
    status "generated with spring"
  end
end

def generate(fallback = nil)

def generate(fallback = nil)
  unless fallback
    fallback = "require 'bundler/setup'\n" \
               "load Gem.bin_path('#{command.gem_name}', '#{command.exec_name}')\n"
  end
  File.write(command.binstub, "#!/usr/bin/env ruby\n#{LOADER}#{fallback}")
  command.binstub.chmod 0755
end

def initialize(command)

def initialize(command)
  @command = command
  if command.binstub.exist?
    @existing = command.binstub.read
  elsif command.name == "rails"
    scriptfile = Spring.application_root_path.join("script/rails")
    @existing = scriptfile.read if scriptfile.exist?
  end
end

def remove

def remove
  if existing
    File.write(command.binstub, existing.sub(LOADER, ""))
    status "spring removed"
  end
end

def status(text, stream = $stdout)

def status(text, stream = $stdout)
  stream.puts "* #{command.binstub_name}: #{text}"
end