brew/Library/Homebrew/cmd/rbenv-sync.rb

80 lines
2.4 KiB
Ruby
Raw Permalink Normal View History

2024-04-01 10:02:09 -07:00
# typed: strict
# frozen_string_literal: true
2024-04-01 10:02:09 -07:00
require "abstract_command"
require "formula"
module Homebrew
2024-04-01 10:02:09 -07:00
module Cmd
class RbenvSync < AbstractCommand
cmd_args do
description <<~EOS
Create symlinks for Homebrew's installed Ruby versions in `~/.rbenv/versions`.
2024-04-01 10:02:09 -07:00
Note that older version symlinks will also be created so e.g. Ruby 3.2.1 will
also be symlinked to 3.2.0.
EOS
2024-04-01 10:02:09 -07:00
named_args :none
end
2024-04-01 10:02:09 -07:00
sig { override.void }
def run
rbenv_root = Pathname(ENV.fetch("HOMEBREW_RBENV_ROOT", Pathname(Dir.home)/".rbenv"))
2024-04-01 10:02:09 -07:00
# Don't run multiple times at once.
rbenv_sync_running = rbenv_root/".rbenv_sync_running"
return if rbenv_sync_running.exist?
2024-04-01 10:02:09 -07:00
begin
rbenv_versions = rbenv_root/"versions"
rbenv_versions.mkpath
FileUtils.touch rbenv_sync_running
2024-04-01 10:02:09 -07:00
HOMEBREW_CELLAR.glob("ruby{,@*}")
.flat_map(&:children)
.each { |path| link_rbenv_versions(path, rbenv_versions) }
2024-04-01 10:02:09 -07:00
rbenv_versions.children
.select(&:symlink?)
.reject(&:exist?)
.each { |path| FileUtils.rm_f path }
ensure
rbenv_sync_running.unlink if rbenv_sync_running.exist?
end
end
2024-04-01 10:02:09 -07:00
private
2024-04-01 10:02:09 -07:00
sig { params(path: Pathname, rbenv_versions: Pathname).void }
def link_rbenv_versions(path, rbenv_versions)
rbenv_versions.mkpath
2024-04-01 10:02:09 -07:00
version = Keg.new(path).version
major_version = version.major.to_i
minor_version = version.minor.to_i
patch_version = version.patch.to_i || 0
patch_version_range = if Homebrew::EnvConfig.env_sync_strict?
# Only create symlinks for the exact installed patch version.
# e.g. 3.4.0 => 3.4.0
[patch_version]
else
# Create folder symlinks for all patch versions to the latest patch version
# e.g. 3.4.0 => 3.4.2
0..patch_version
end
patch_version_range.each do |patch|
2024-04-01 10:02:09 -07:00
link_path = rbenv_versions/"#{major_version}.#{minor_version}.#{patch}"
# Don't clobber existing user installations.
next if link_path.exist? && !link_path.symlink?
2024-04-01 10:02:09 -07:00
FileUtils.rm_f link_path
FileUtils.ln_s path, link_path
2024-04-01 10:02:09 -07:00
end
end
end
end
end