class SourceFile

Updates Ruby source headers without removing documentation comments.

Definitions

def self.update(path, copyrights:)

Replace the license and copyright header for a Ruby source file.

Signature

parameter path String

The source file path.

parameter copyrights Array(String)

The copyright statements to write.

Implementation

def self.update(path, copyrights:)
	input = File.readlines(path)
	prefix = []
	
	prefix << input.shift if input.first&.start_with?("#!")
	while input.first&.match?(MAGIC_COMMENT)
		prefix << input.shift
	end
	
	# Keep the complete leading comment block, removing only known license metadata.
	documentation = []
	while line = input.first
		break unless line.match?(/\A\s*#/) || line.strip.empty?
		
		input.shift
		next if line.match?(LICENSE_COMMENT)
		
		documentation << line
	end
	
	while documentation.first&.strip&.empty?
		documentation.shift
	end
	while documentation.last&.strip&.empty?
		documentation.pop
	end
	
	output = prefix.dup
	output << "\n" if output.any?
	output << "# Released under the MIT License.\n"
	copyrights.each do |copyright|
		output << "# #{copyright}\n"
	end
	output << "\n"
	output.concat(documentation)
	output.concat(input)
	
	File.write(path, output.join)
end