Bundler 모듈
Bundler 모듈
Bundler 는 프로젝트에 필요한 정확한 젬과 그 버전을 추적하고 설치해서, Ruby 프로젝트에 일관된 환경을 제공해요. Ruby 표준 라이브러리의 일부예요.
출처: Ruby 4.0 API
본문
Bundler 는 필요한 정확한 젬과 버전을 추적·설치해 Ruby 프로젝트에 일관된 환경을 제공해요. Ruby 표준 라이브러리의 일부예요.
Bundler 는 프로젝트 의존성 전체와 (선택적으로) 버전을 적어 둔 gemfile 을 만들고, 그다음 환경을 설정해서 사용해요:
require 'bundler/setup'
또는 Bundler.setup 으로, 지정한 젬과 그 지정 버전만 쓸 수 있는 환경을 설정해요. gemfile 작성과 Bundler 사용에 대한 방대한 문서는 Bundler 문서를 보세요.
프로젝트 안의 표준 라이브러리로서 Bundler 는 로드·요구된 모듈의 내부(심층 점검)에도 쓸 수 있어요.
모듈 함수
이 페이지는 편의상 모듈 메서드를 모두 소개할게요. 대부분은 코드가 곧 설명인 간단한 getter/setter예요.
app_cache(custom_path = nil)
앱 캐시 경로를 돌려줘요. custom_path 를 주면 그 경로, 아니면 root 에 Bundler.settings.app_cache_path 를 이어 붙인 Pathname 을 돌려줘요.
# File lib/bundler.rb, line 342
def app_cache(custom_path = nil)
path = custom_path || root
Pathname.new(path).join(Bundler.settings.app_cache_path)
end
app_config_path()
앱 설정 경로를 돌려줘요. 환경 변수 BUNDLE_APP_CONFIG 가 있으면 그 경로(상대 경로면 root 기준으로 확장)를, 없으면 root.join(".bundle") 을 돌려줘요.
# File lib/bundler.rb, line 328
def app_config_path
if app_config = ENV["BUNDLE_APP_CONFIG"]
app_config_pathname = Pathname.new(app_config)
if app_config_pathname.absolute?
app_config_pathname
else
app_config_pathname.expand_path(root)
end
else
root.join(".bundle")
end
end
auto_install()
settings[:auto_install] 이 존재하면 의존성을 자동으로 설치해요. 이는 설정 명령 bundle config set –global auto_install 1 으로 설정돼요.
이 메서드는 전역 Definition 객체를 nil로 만들므로, 오래된 것을 참조하게 될 Installer 같은 것을 인스턴스화하기 전에 먼저 호출해야 한다는 점에 주의하세요.
# File lib/bundler.rb, line 182
def auto_install
return unless Bundler.settings[:auto_install]
begin
definition.specs
rescue GemNotFound, GitError
ui.info "Automatically installing missing gems."
reset!
CLI::Install.new({}).run
reset!
end
end
auto_switch()
필요하면 잠긴 Bundler로 셀프 매니저가 재시작하도록 해요.
# File lib/bundler.rb, line 172
def auto_switch
self_manager.restart_with_locked_bundler_if_needed
end
bin_path()
binstub이 설치되는 절대 위치를 돌려줘요. 기본은 settings[:bin] 또는 "bin" 이에요.
# File lib/bundler.rb, line 119
def bin_path
@bin_path ||= begin
path = Bundler.settings[:bin] || "bin"
path = Pathname.new(path).expand_path(root).expand_path
mkdir_p(path)
path
end
end
bundle_path()
젬이 파일시스템에 설치되는 절대 경로를 돌려줘요.
# File lib/bundler.rb, line 101
def bundle_path
@bundle_path ||= Pathname.new(configured_bundle_path.path).expand_path(root)
end
clean_env()
Bundler.clean_env는 Bundler.unbundled_env 로 대체되어 제거됐어요. Bundler가 로드되기 전의 환경을 원한다면 Bundler.original_env 을 쓰세요.
# File lib/bundler.rb, line 367
def clean_env
removed_message =
"`Bundler.clean_env` has been removed in favor of `Bundler.unbundled_env`. " \
"If you instead want the environment before bundler was originally loaded, use `Bundler.original_env`"
Bundler::SharedHelpers.feature_removed!(removed_message)
end
clean_exec(*args)
Bundler.clean_exec는 Bundler.unbundled_exec 로 대체되어 제거됐어요. Bundler가 로드되기 전의 환경에서 명령을 exec하려면 Bundler.original_exec 을 쓰세요.
# File lib/bundler.rb, line 423
def clean_exec(*args)
removed_message =
"`Bundler.clean_exec` has been removed in favor of `Bundler.unbundled_exec`. " \
"If you instead want to exec to a command in the environment before bundler was originally loaded, use `Bundler.original_exec`"
Bundler::SharedHelpers.feature_removed!(removed_message)
end
clean_system(*args)
Bundler.clean_system은 Bundler.unbundled_system 으로 대체되어 제거됐어요. Bundler가 로드되기 전의 환경에서 명령을 실행하려면 Bundler.original_system 을 쓰세요.
# File lib/bundler.rb, line 406
def clean_system(*args)
removed_message =
"`Bundler.clean_system` has been removed in favor of `Bundler.unbundled_system`. " \
"If you instead want to run the command in the environment before bundler was originally loaded, use `Bundler.original_system`"
Bundler::SharedHelpers.feature_removed!(removed_message)
end
clear_gemspec_cache()
gemspec 캐시를 비워요. @gemspec_cache = {} 로 초기화해요.
# File lib/bundler.rb, line 539
def clear_gemspec_cache
@gemspec_cache = {}
end
configure()
gem home과 path를 설정한 결과를 돌려줘요. configure_gem_home_and_path 의 결과를 캐시해 둬요.
# File lib/bundler.rb, line 87
def configure
@configure ||= configure_gem_home_and_path
end
configure_custom_gemfile(custom_gemfile = nil)
커스텀 Gemfile을 환경 변수 BUNDLE_GEMFILE 로 설정하고 설정·루트를 리셋해요.
# File lib/bundler.rb, line 590
def configure_custom_gemfile(custom_gemfile = nil)
custom_gemfile ||= Bundler.settings[:gemfile]
if custom_gemfile && !custom_gemfile.empty?
Bundler::SharedHelpers.set_env "BUNDLE_GEMFILE", File.expand_path(custom_gemfile)
reset_settings_and_root!
end
end
configure_gem_home_and_path(path = bundle_path)
gem path 설정, gem home 설정, RubyGems 경로 정리를 순서대로 수행해요.
# File lib/bundler.rb, line 584
def configure_gem_home_and_path(path = bundle_path)
configure_gem_path
configure_gem_home(path)
Bundler.rubygems.clear_paths
end
configured_bundle_path()
설정된 bundle path를 돌려줘요. Bundler.settings.path 를 검증하며 캐시해 둬요.
# File lib/bundler.rb, line 114
def configured_bundle_path
@configured_bundle_path ||= Bundler.settings.path.tap(&:validate!)
end
create_bundle_path()
없으면 bundle path 디렉토리를 만들고 realpath를 돌려줘요. 해당 경로에 파일이 이미 있으면 PathError 를 발생시켜요.
# File lib/bundler.rb, line 105
def create_bundle_path
mkdir_p(bundle_path) unless bundle_path.exist?
@bundle_path = bundle_path.realpath
rescue Errno::EEXIST
raise PathError, "Could not install to path `#{bundle_path}` " \
"because a file already exists at that path. Either remove or rename the file so the directory can be created."
end
default_bundle_dir()
표준 번들 디렉토리(SharedHelpers.default_bundle_dir)를 돌려줘요.
# File lib/bundler.rb, line 452
def default_bundle_dir
SharedHelpers.default_bundle_dir
end
default_gemfile()
기본 Gemfile 경로(SharedHelpers.default_gemfile)를 돌려줘요.
# File lib/bundler.rb, line 444
def default_gemfile
SharedHelpers.default_gemfile
end
default_lockfile()
기본 Gemfile.lock 경로(SharedHelpers.default_lockfile)를 돌려줘요.
# File lib/bundler.rb, line 448
def default_lockfile
SharedHelpers.default_lockfile
end
definition(unlock = nil, lockfile = default_lockfile)
주어진 Gemfile과 lockfile에 대한 Bundler::Definition 인스턴스를 돌려줘요.
unlock[Hash, Boolean, nil] - 업데이트를 요청받은 젬, 또는 모든 젬을 업데이트하려면true.lockfile[Pathname] - Gemfile.lock 경로.- 반환 [Bundler::Definition]
# File lib/bundler.rb, line 231
def definition(unlock = nil, lockfile = default_lockfile)
@definition = nil if unlock
@definition ||= begin
configure
Definition.build(default_gemfile, lockfile, unlock)
end
end
environment()
Bundler.environment 은 Bundler.load 로 대체되어 제거됐어요.
# File lib/bundler.rb, line 221
def environment
SharedHelpers.feature_removed! "Bundler.environment has been removed in favor of Bundler.load"
end
feature_flag()
FeatureFlag 인스턴스를 돌려줘요. Bundler.settings[:simulate_version] 또는 VERSION으로 만들어요.
# File lib/bundler.rb, line 548
def feature_flag
@feature_flag ||= FeatureFlag.new(Bundler.settings[:simulate_version] || VERSION)
end
find_executable(path)
주어진 경로에 해당하는 실행 가능한 파일을 찾아 돌려줘요. 시스템의 EXECUTABLE_EXTS(또는 EXEEXT) 확장자를 붙인 후보 중 파일이면서 실행 가능한 첫 것을 찾아요.
# File lib/bundler.rb, line 493
def find_executable(path)
extensions = RbConfig::CONFIG["EXECUTABLE_EXTS"]&.split
extensions = [RbConfig::CONFIG["EXEEXT"]] unless extensions&.any?
candidates = extensions.map {|ext| "#{path}#{ext}" }
candidates.find {|candidate| File.file?(candidate) && File.executable?(candidate) }
end
frozen_bundle?
settings[:frozen] 이 있으면 그 값을, 없으면 settings[:deployment] 을 돌려줘요. 즉 frozen 모드 여부를 나타내요.
# File lib/bundler.rb, line 239
def frozen_bundle?
frozen = Bundler.settings[:frozen]
return frozen unless frozen.nil?
Bundler.settings[:deployment]
end
generic_local_platform()
로컬 플랫폼의 제네릭 플랫폼 버전을 돌려줘요. Gem::Platform.generic(local_platform).
# File lib/bundler.rb, line 440
def generic_local_platform
Gem::Platform.generic(local_platform)
end
git_present?
git 실행 파일이 있으면 그 경로를, 없으면 nil 을 돌려줘요(한 번만 계산해 캐시).
# File lib/bundler.rb, line 543
def git_present?
return @git_present if defined?(@git_present)
@git_present = Bundler.which("git")
end
home()
bundle_path.join("bundler") 을 돌려줘요.
# File lib/bundler.rb, line 306
def home
bundle_path.join("bundler")
end
install_path()
home.join("gems") 을 돌려줘요.
# File lib/bundler.rb, line 310
def install_path
home.join("gems")
end
load()
Runtime.new(root, definition) 을 돌려줘요(캐시). Runtime 인스턴스로 번들 로드·러타임 동작을 처리해요.
# File lib/bundler.rb, line 217
def load
@load ||= Runtime.new(root, definition)
end
load_gemspec(file, validate = false)
gemspec 파일을 로드해서 반환해요. 결과를 캐시하고, 매번 새 인스턴스를 돌려줘서 부수효과가 있는 gemspec이 캐시로부터 영향받지 않게 해요.
# File lib/bundler.rb, line 520
def load_gemspec(file, validate = false)
@gemspec_cache ||= {}
key = File.expand_path(file)
@gemspec_cache[key] ||= load_gemspec_uncached(file, validate)
# Protect against caching side-effected gemspecs by returning a
# new instance each time.
@gemspec_cache[key]&.dup
end
load_gemspec_uncached(file, validate = false)
gemspec을 캐시 없이 로드해 반환해요. validate 가 참이면 RubyGems 검증을 수행해요.
# File lib/bundler.rb, line 529
def load_gemspec_uncached(file, validate = false)
path = Pathname.new(file).expand_path
contents = read_file(path.to_s)
spec = eval_gemspec(path, contents)
return unless spec
spec.loaded_from = path.to_s
Bundler.rubygems.validate(spec) if validate
spec
end
local_platform()
settings[:force_ruby_platform] 이면 Gem::Platform::RUBY 를, 아니면 Gem::Platform.local 을 돌려줘요.
# File lib/bundler.rb, line 435
def local_platform
return Gem::Platform::RUBY if Bundler.settings[:force_ruby_platform]
Gem::Platform.local
end
locked_gems()
잠긴 젬 정보를 돌려줘요. 정의된 @definition 이 있으면 그 lock, 아니면 기본 lockfile을 LockfileParser 로 파싱한 결과예요.
# File lib/bundler.rb, line 246
def locked_gems
@locked_gems ||=
if defined?(@definition) && @definition
definition.locked_gems
elsif Bundler.default_lockfile.file?
lock = Bundler.read_file(Bundler.default_lockfile)
LockfileParser.new(lock)
end
end
mkdir_p(path)
파일시스템 접근 보호를 적용해 디렉토리를 만드는 헬퍼예요.
# File lib/bundler.rb, line 473
def mkdir_p(path)
SharedHelpers.filesystem_access(path, :create) do |p|
FileUtils.mkdir_p(p)
end
end
original_env()
Bundler 가 활성화되기 전에 존재했던 환경을 돌려줘요. ORIGINAL_ENV.clone 이에요.
# File lib/bundler.rb, line 363
def original_env
ORIGINAL_ENV.clone
end
original_exec(*args)
Bundler 가 활성화되기 전의 환경으로 서브커맨드에 Kernel.exec 을 실행해요.
# File lib/bundler.rb, line 419
def original_exec(*args)
with_original_env { Kernel.exec(*args) }
end
original_system(*args)
Bundler 가 활성화되기 전의 환경으로 서브커맨드를 실행해요.
# File lib/bundler.rb, line 402
def original_system(*args)
with_original_env { Kernel.system(*args) }
end
preferred_gemfile_name()
settings[:init_gems_rb] 이면 "gems.rb", 아니면 "Gemfile" 을 돌려줘요.
# File lib/bundler.rb, line 465
def preferred_gemfile_name
Bundler.settings[:init_gems_rb] ? "gems.rb" : "Gemfile"
end
read_file(file)
파일을 UTF-8로 안전하게 읽어 돌려줘요.
# File lib/bundler.rb, line 501
def read_file(file)
SharedHelpers.filesystem_access(file, :read) do
File.open(file, "r:UTF-8", &:read)
end
end
require(*groups)
아직 설정되지 않았다면 Bundler 환경을 설정(Bundler.setup 참고)하고, 지정된 그룹의 모든 젬을 로드해요. ::setup 과 달리, 서로 다른 그룹으로 여러 번 호출할 수 있어요(setup이 허용했을 경우).
Gemfile이 이렇다고 해볼게요:
gem 'first_gem', '= 1.0'
group :test do
gem 'second_gem', '= 1.0'
end
코드는 이렇게 동작해요:
Bundler.setup # allow all groups
Bundler.require(:default) # requires only first_gem
# ...later
Bundler.require(:test) # requires second_gem
# File lib/bundler.rb, line 213
def require(*groups)
setup(*groups).require(*groups)
end
reset!()
경로, 플러그인, RubyGems 상태를 모두 리셋해요.
# File lib/bundler.rb, line 552
def reset!
reset_paths!
Plugin.reset!
reset_rubygems!
end
reset_paths!()
캐시된 경로·설정 관련 인스턴스 변수들을 모두 nil로 비워요.
# File lib/bundler.rb, line 563
def reset_paths!
@bin_path = nil
@bundle_path = nil
@configure = nil
@configured_bundle_path = nil
@definition = nil
@load = nil
@locked_gems = nil
@root = nil
@settings = nil
@setup = nil
@user_home = nil
end
reset_rubygems!
RubyGems 대체(replacements)를 되돌리고 리셋해요.
# File lib/bundler.rb, line 577
def reset_rubygems!
return unless defined?(@rubygems) && @rubygems
rubygems.undo_replacements
rubygems.reset
@rubygems = nil
end
reset_settings_and_root!()
설정과 루트 캐시를 비워요.
# File lib/bundler.rb, line 558
def reset_settings_and_root!
@settings = nil
@root = nil
end
rm_rf(path)
경로가 존재하면 FileUtils.remove_entry_secure 로 안전하게 제거해요.
# File lib/bundler.rb, line 352
def rm_rf(path)
FileUtils.remove_entry_secure(path) if path && File.exist?(path)
end
root()
현재 프로젝트 루트를 돌려줘요. Gemfile이나 .bundle/ 를 못 찾으면 GemfileNotFound 를 발생시켜요.
# File lib/bundler.rb, line 318
def root
@root ||= begin
SharedHelpers.root
rescue GemfileNotFound
bundle_dir = default_bundle_dir
raise GemfileNotFound, "Could not locate Gemfile or .bundle/ directory" unless bundle_dir
Pathname.new(File.expand_path("..", bundle_dir))
end
end
ruby_scope()
Ruby 엔진과 버전을 합친 문자열을 돌려줘요.
# File lib/bundler.rb, line 256
def ruby_scope
"#{Bundler.rubygems.ruby_engine}/#{RbConfig::CONFIG["ruby_version"]}"
end
safe_load_marshal(data)
Marshal 데이터를 안전하게 로드해요. 가능하면 Gem::SafeMarshal, 아니면 SafeMarshal.proc 을 적용한 로드를 사용해요.
# File lib/bundler.rb, line 507
def safe_load_marshal(data)
if Gem.respond_to?(:load_safe_marshal)
Gem.load_safe_marshal
begin
Gem::SafeMarshal.safe_load(data)
rescue Gem::SafeMarshal::Reader::Error, Gem::SafeMarshal::Visitors::ToRuby::Error => e
raise MarshalError, "#{e.class}: #{e.message}"
end
else
load_marshal(data, marshal_proc: SafeMarshal.proc)
end
end
self_manager()
Bundler::SelfManager 인스턴스를 돌려줘요(캐시). 셀프 매니지먼트(자신을 갱신·재시작)를 담당해요.
# File lib/bundler.rb, line 599
def self_manager
@self_manager ||= begin
require_relative "bundler/self_manager"
Bundler::SelfManager.new
end
end
settings()
앱 설정을 돌려줘요. app_config_path 기반 Settings 인스턴스(캐시)이고, Gemfile을 못 찾으면 빈 Settings 로 폴백해요.
# File lib/bundler.rb, line 356
def settings
@settings ||= Settings.new(app_config_path)
rescue GemfileNotFound
@settings = Settings.new
end
setup(*groups)
Bundler 러타임을 켜요. Bundler.setup 호출 뒤에는, 젬의 load 나 require 가 Gemfile의 일부이거나 Ruby 표준 라이브러리일 때만 허용돼요. Gemfile에 버전이 명시되어 있으면 그 버전만 로드돼요.
Gemfile이 이렇다고 해볼게요:
gem 'first_gem', '= 1.0'
group :test do
gem 'second_gem', '= 1.0'
end
Bundler.setup 을 쓴 코드는 이렇게 동작해요:
require 'third_gem' # allowed, required from global gems
require 'first_gem' # allowed, loads the last installed version
Bundler.setup
require 'fourth_gem' # fails with LoadError
require 'second_gem' # loads exactly version 1.0
Bundler.setup 은 한 번만 호출할 수 있고, 이후 호출은 모두 no-op이에요.
groups 목록을 주면 지정된 그룹의 젬만 허용돼요(그룹 밖에 지정된 젬은 특별한 :default 그룹에 속해요).
Gemfile의 모든 젬(또는 일부 그룹)을 require하려면 Bundler.require 를 보세요.
# File lib/bundler.rb, line 155
def setup(*groups)
# Return if all groups are already loaded
return @setup if defined?(@setup) && @setup
configure_custom_gemfile
definition.validate_runtime!
SharedHelpers.print_major_deprecations!
if groups.empty?
# Load all groups, but only once
@setup = load.setup
else
load.setup(*groups)
end
end
specs_path()
bundle_path.join("specifications") 을 돌려줘요.
# File lib/bundler.rb, line 314
def specs_path
bundle_path.join("specifications")
end
system_bindir()
시스템 바이너리가 설치되는 디렉토리를 돌려줘요. settings[:system_bindir] 이 있으면 그 값, 아니면 RubyGems의 gem bindir을 돌려줘요.
# File lib/bundler.rb, line 456
def system_bindir
Bundler.settings[:system_bindir] || Bundler.rubygems.gem_bindir
end
tmp(name = Process.pid.to_s)
임시 디렉토리를 만들어 돌려줘요. Dir.mktmpdir(["bundler", name]) 의 Pathname 이에요.
# File lib/bundler.rb, line 347
def tmp(name = Process.pid.to_s)
Kernel.send(:require, "tmpdir")
Pathname.new(Dir.mktmpdir(["bundler", name]))
end
ui()
현재 UI 객체를 돌려줘요. 없으면 UI::Shell.new 로 새로 만들어 설정해요.
# File lib/bundler.rb, line 91
def ui
(defined?(@ui) && @ui) || (self.ui = UI::Shell.new)
end