# frozen_string_literal: false
require_relative 'base'

class TestMkmfDepend < TestMkmf
  def test_update_extension_dependencies
    Dir.mktmpdir('mkmf-depend') do |root|
      FileUtils.mkdir_p(File.join(root, '.git'))
      source_dir = File.join(root, 'ext/example')
      FileUtils.mkdir_p(source_dir)
      File.write(File.join(root, 'ext/shared.h'), '')
      File.write(File.join(source_dir, 'local.h'), '')
      File.write(File.join(source_dir, 'example.c'), <<~SOURCE)
        #include "../shared.h"
        #include "local.h"
      SOURCE
      File.write(File.join(source_dir, 'extconf.rb'), <<~RUBY)
        require "mkmf"
        $headers << "local.h"
        create_makefile("example")
      RUBY
      depend = File.join(source_dir, 'depend')
      File.write(depend, <<~DEPEND)
        example.o: $(LOCAL_HDRS)

        # AUTOGENERATED DEPENDENCIES START
        stale.o: stale.c
        # AUTOGENERATED DEPENDENCIES END
      DEPEND

      command = [
        RbConfig.ruby, "--disable-gems",
        "-I#{File.expand_path('../../lib', __dir__)}",
        "extconf.rb", "--update-depend",
      ]
      output = IO.popen(
        command, chdir: source_dir, err: [:child, :out], &:read
      )
      assert_predicate($?, :success?, output)
      assert_equal(<<~DEPEND, File.read(depend))
        example.o: $(LOCAL_HDRS)

        # AUTOGENERATED DEPENDENCIES START
        example.o: $(srcdir)/../shared.h
        example.o: example.c
        # AUTOGENERATED DEPENDENCIES END
      DEPEND
    end
  end
end
