Skip to content

Commit

Permalink
[Fix #12846] Fix an error for RuboCop::Lockfile
Browse files Browse the repository at this point in the history
Fixes #12846.

This PR fixes an error for `RuboCop::Lockfile`
when there is no Bundler environment.

From a performance perspective as well, resolving through `require 'bundler'` is not optimal.
This PR ensures that the necessary `Bundler::LockfileParser` exists as a constant.
This approach reduces unnecessary loading caused by `require 'bundler'` and
ensures the presence of the essential `Bundler::LockfileParser`.
  • Loading branch information
koic authored and bbatsov committed Apr 16, 2024
1 parent 1deecbd commit 1246c55
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_rubocop_lockfile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12846](https://github.com/rubocop/rubocop/issues/12846): Fix an error for `RuboCop::Lockfile` when there is no Bundler environment. ([@koic][])
16 changes: 7 additions & 9 deletions lib/rubocop/lockfile.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
# frozen_string_literal: true

begin
require 'bundler'
rescue LoadError
nil
end

module RuboCop
# Encapsulation of a lockfile for use when checking for gems.
# Does not actually resolve gems, just parses the lockfile.
# @api private
class Lockfile
# @param [String, Pathname, nil] lockfile_path
def initialize(lockfile_path = nil)
lockfile_path ||= defined?(Bundler) ? Bundler.default_lockfile : nil
lockfile_path ||= Bundler.default_lockfile if bundler_lock_parser_defined?

@lockfile_path = lockfile_path
end
Expand Down Expand Up @@ -66,14 +60,18 @@ def includes_gem?(name)
def parser
return @parser if defined?(@parser)

@parser = if defined?(::Bundler) && @lockfile_path
@parser = if @lockfile_path
begin
lockfile = ::Bundler.read_file(@lockfile_path)
lockfile ? ::Bundler::LockfileParser.new(lockfile) : nil
::Bundler::LockfileParser.new(lockfile) if lockfile
rescue ::Bundler::BundlerError
nil
end
end
end

def bundler_lock_parser_defined?
Object.const_defined?(:Bundler) && Bundler.const_defined?(:LockfileParser)
end
end
end

0 comments on commit 1246c55

Please sign in to comment.