Remix.run Logo
tcoff91 3 days ago

  #!ruby
  
  if ARGV.size < 1
    puts "Usage: wz path"
    exit
  end
  
  # Get current working directory
  current_dir = "#{Dir.pwd}/"
  # puts "Current directory: #{current_dir}"
  
  # Run git worktree list and capture the output
  worktree_output = `git worktree list`
  
  # Split output into lines and process
  worktrees = worktree_output.split("\n")
  
  # Extract all worktree paths
  worktree_paths = worktrees.map { |wt| "#{wt.split.first}/" }
  # puts "Worktree paths: #{worktree_paths}"
  
  # First path is always the root worktree
  root_wt_path = worktree_paths[0]
  
  # Find current worktree by comparing with pwd
  current_wt_path = worktree_paths.find do |path|
    # puts "Path: #{path}"
    current_dir.start_with?(path) 
  end
  
  if current_wt_path == root_wt_path
    zoxide_destination = `zoxide query --exclude "#{Dir.pwd}" "#{ARGV[0]}"`.strip
    puts zoxide_destination
    exit 0
  end
  
  current_dir_in_root_wt = current_dir.sub(current_wt_path, root_wt_path)
  Dir.chdir(current_dir_in_root_wt)
  current_dir = "#{Dir.pwd}/"
  # puts "Current directory: #{current_dir}"
  
  # puts "Querying zoxide for #{ARGV[0]}"
  zoxide_destination = `zoxide query --exclude "#{Dir.pwd}" "#{ARGV[0]}"`.strip
  # puts "zoxide destination: #{zoxide_destination}"
  Dir.chdir(zoxide_destination)
  current_dir = "#{Dir.pwd}/"
  
  if current_dir.start_with?(root_wt_path)
    target_dir = current_dir.sub(root_wt_path, current_wt_path)
    puts target_dir
    exit 0
  end
  
  puts Dir.pwd
  exit 0
  
  

Then put this function in your .zshrc:

  # Worktree aware form of zoxide's z command.
  function w() {
   cd $(wz $@)
  }