Skip to content

Instantly share code, notes, and snippets.

@bensheldon
Last active April 16, 2026 02:43
Show Gist options
  • Select an option

  • Save bensheldon/f475a2669d72256545df5e2fcd1a4dae to your computer and use it in GitHub Desktop.

Select an option

Save bensheldon/f475a2669d72256545df5e2fcd1a4dae to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# Helper for Git worktree-aware behavior
module GitWorktree
PROJECT_ROOT = File.expand_path("..", __dir__)
def self.name
return @_name if defined?(@_name)
git_dir = `git rev-parse --git-dir 2>/dev/null`.strip
return @_name = nil if git_dir.empty? || !git_dir.include?("/.git/worktrees/") # rubocop:disable Rails/NegateInclude
# Conductor renames the branch after setup runs, so use the worktree directory
# name (set at worktree creation) for a stable identifier during setup.
@_name = normalize(File.basename(git_dir))
end
def self.worktree?
!name.nil?
end
def self.normalize(text)
text.gsub(/[^a-zA-Z0-9_]/, "_").squeeze("_").downcase
end
private_class_method :normalize
def self.db_suffix
value = name
return "" if value.nil?
"_#{value[0, 30]}"
end
# When in a worktree, copies each +relative_path+ from the main repo into this
# worktree if the file is missing here but present in the main repo.
# Safe to call without Rails loaded.
def self.copy_from_main_worktree(*relative_paths, overwrite: false)
git_dir = `git rev-parse --git-dir 2>/dev/null`.strip
git_common_dir = `git rev-parse --git-common-dir 2>/dev/null`.strip
return if git_dir.empty? || git_dir == git_common_dir
main_root = File.expand_path("..", git_common_dir)
require "fileutils"
relative_paths.each do |relative_path|
dest = File.join(PROJECT_ROOT, relative_path)
next if File.exist?(dest) && !overwrite
source = File.join(main_root, relative_path)
next unless File.exist?(source)
FileUtils.mkdir_p(File.dirname(dest))
FileUtils.cp(source, dest)
end
end
# Returns a deterministic integer from +range+ based on the current worktree branch name.
# Returns +range.first+ when not in a worktree (e.g. main branch).
#
# +stride+ reserves a block of consecutive integers per worktree so callers can add an
# offset without colliding with adjacent worktrees. For example, Capybara system tests
# use stride equal to PARALLEL_TEST_GROUPS and add TEST_ENV_NUMBER on top:
#
# GitWorktree.integer(4000..4990, stride: ENV.fetch("PARALLEL_TEST_GROUPS", 1).to_i) + ENV.fetch("TEST_ENV_NUMBER", 0).to_i
# # worktree A (PARALLEL_TEST_GROUPS=4) => 4000, 4001, 4002, 4003
# # worktree B (PARALLEL_TEST_GROUPS=4) => 4020, 4021, 4022, 4023 (never overlaps A)
def self.integer(range, stride: 1)
value = name
return range.first if value.nil?
require "zlib"
slots = range.size / stride
range.first + ((Zlib.crc32(value) % slots) * stride)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment