bin/guard

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby
# frozen_string_literal: true

require "pathname"

class GuardReloader
  class Config
    def using_rubygems?
      ENV["RUBYGEMS_GEMDEPS"]
    end

    def setup_rubygems_for_deps
      require "rubygems"
    end

    def current_bundler_gemfile
      ENV["BUNDLE_GEMFILE"]
    end
    alias_method :using_bundler?, :current_bundler_gemfile

    def setup_bundler_env(gemfile)
      ENV["BUNDLE_GEMFILE"] = gemfile
    end

    def setup_bundler
      require "rubygems"
      require "bundler/setup"
    end

    def program_path
      Pathname(__FILE__)
    end

    def program_arguments
      ARGV
    end

    def windows?
      Gem.win_platform?
    end

    def wait_ignoring_interrupts(pid)
      Process.wait2(pid)[1].exitstatus
    rescue Interrupt
      retry
    rescue Errno::ECHILD
      1
    end

    def exist?(path)
      path.exist?
    end

    def guard_core_path
      Gem.bin_path("guard", "_guard-core")
    end
  end

  attr_reader :config

  def initialize(config)
    @config = config
  end

  def setup
    return config.setup_bundler if config.using_bundler?
    return config.setup_rubygems_for_deps if config.using_rubygems?

    # No dependency management detected - check if binstubbed by bundler
    relative_to_binstub = config.program_path + "../../Gemfile"
    if config.exist?(relative_to_binstub)
      config.setup_bundler_env(relative_to_binstub.to_s)
      config.setup_bundler
    end
  end

  def auto_restart
    args = [Gem.ruby, config.guard_core_path] + config.program_arguments

    loop do
      exitcode = config.wait_ignoring_interrupts(spawn(*args))
      exit(exitcode) if exitcode != 2
    end
  end
end

return if ENV["GUARD_SPECS_RUNNING"]

config = GuardReloader::Config.new
reloader = GuardReloader.new(config)
reloader.setup
reloader.auto_restart