|
| 1 | +require 'rbconfig' |
| 2 | + |
| 3 | +bindir = RbConfig::CONFIG["bindir"] |
| 4 | + |
| 5 | +FIRST_LINE = "#!/bin/sh\n" |
| 6 | +RUBY_SHEBANG = %r{^#!/usr/bin/env ruby$} |
| 7 | +RUBYGEMS_LINE = /This file was generated by RubyGems/ |
| 8 | + |
| 9 | +Dir.glob("#{bindir}/*") do |file| |
| 10 | + exe = "bin/#{File.basename(file)}" |
| 11 | + |
| 12 | + if File.binread(file, FIRST_LINE.bytesize) == FIRST_LINE |
| 13 | + puts "\nFound load-relative prolog in #{exe}" |
| 14 | + contents = File.binread(file) |
| 15 | + rubygems_line = contents.lines.index { |line| RUBYGEMS_LINE =~ line } |
| 16 | + |
| 17 | + if !rubygems_line |
| 18 | + puts "No RubyGems line in #{exe}, skipping it" |
| 19 | + elsif rubygems_line == 2 |
| 20 | + # RubyGems expects RUBYGEMS_LINE to match the 3rd line |
| 21 | + # https://github.com/rubygems/rubygems/blob/6d7fe84753/lib/rubygems/installer.rb#L220 |
| 22 | + # Otherwise, it will consider the executable to be conflicting and ask whether to override, |
| 23 | + # and that results in an error when STDIN is not interactive |
| 24 | + else |
| 25 | + puts "The RubyGems line in #{exe} is not the 3rd line (but line #{rubygems_line+1}), fixing it" |
| 26 | + |
| 27 | + index = contents =~ RUBY_SHEBANG |
| 28 | + raise "Could not find ruby shebang in:\n#{contents}" unless index |
| 29 | + contents = contents[index..-1] |
| 30 | + |
| 31 | + rubygems_line = contents.lines.index { |line| RUBYGEMS_LINE =~ line } |
| 32 | + unless rubygems_line == 2 |
| 33 | + raise "The RubyGems line is still not 3rd in #{exe}:\n#{contents}" |
| 34 | + end |
| 35 | + |
| 36 | + File.binwrite(file, contents) |
| 37 | + end |
| 38 | + end |
| 39 | +end |
0 commit comments