class InvocaGems::Gemfile def initialize(path) @path = path @lines = File.readlines(path).map(&:chomp) end def find(gem_name, allow_missing: false) if index = @lines.find_index { |l| l =~ /\A\s*gem\s+.*[\'\"]#{gem_name}[\'\"]/ } InvocaGems::GemfileLine.new(self, @lines[index], index) else allow_missing or InvocaGems::Presenter.stop_with_message "could not find gem #{gem_name}" nil end end def append(gem_name) InvocaGems::GemfileLine.new(self, "gem '#{gem_name}'", -1) end def save!(gemspec) update_gemspec(gemspec) File.open(@path, "w") { |f| f.write(@lines.join("\n") + "\n") } end private def update_gemspec(gemspec) if gemspec.index == -1 @lines << gemspec.line else @lines = @lines[0, gemspec.index] + [gemspec.line] + @lines[gemspec.index+1..-1] end end end