summaryrefslogtreecommitdiff
path: root/spec/bundler/support/build_metadata.rb
blob: 5898e7f3bd191305e327931e1329c49f92c075a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# frozen_string_literal: true

require_relative "path"
require_relative "helpers"

module Spec
  module BuildMetadata
    include Spec::Path
    include Spec::Helpers

    def write_build_metadata(dir: source_root)
      build_metadata = {
        git_commit_sha: git_commit_sha,
        built_at: loaded_gemspec.date.utc.strftime("%Y-%m-%d"),
        release: true,
      }

      replace_build_metadata(build_metadata, dir: dir)
    end

    def reset_build_metadata(dir: source_root)
      build_metadata = {
        release: false,
      }

      replace_build_metadata(build_metadata, dir: dir)
    end

    private

    def replace_build_metadata(build_metadata, dir:)
      build_metadata_file = File.expand_path("lib/bundler/build_metadata.rb", dir)

      ivars = build_metadata.sort.map do |k, v|
        "    @#{k} = #{loaded_gemspec.send(:ruby_code, v)}"
      end.join("\n")

      contents = File.read(build_metadata_file)
      contents.sub!(/^(\s+# begin ivars).+(^\s+# end ivars)/m, "\\1\n#{ivars}\n\\2")
      File.open(build_metadata_file, "w") {|f| f << contents }
    end

    def git_commit_sha
      ruby_core_tarball? ? "unknown" : sys_exec("git rev-parse --short HEAD", dir: source_root).strip
    end

    extend self
  end
end