Skip to content

Instantly share code, notes, and snippets.

@bensheldon
Last active February 25, 2026 01:31
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.exclude?("/.git/worktrees/")
# 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.normalize(text)
text.gsub(/[^a-zA-Z0-9_]/, "_").squeeze("_").downcase
end
private_class_method :normalize
def self.db_suffix
value = name
return "" if value.blank?
"_#{value.first(30)}"
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