#!/usr/bin/env ruby current_branch = `git symbolic-ref --short HEAD`.strip target_branch = ARGV[0] if current_branch != target_branch repository_path = Dir.getwd worktree_name = repository_path + "-worktree-#{target_branch.gsub('/', '_')}" worktree_folder = File.expand_path(worktree_name) worktree_workspace_file = Dir.glob(worktree_folder + "/*.xcworkspace").first worktree_workspace_file_exists = worktree_workspace_file != nil xed_command = "xed #{worktree_workspace_file}" make_project_command = "make project" change_worktree_command = "cd #{worktree_folder} && #{worktree_workspace_file_exists ? xed_command : make_project_command}" # create worktree if !Dir.exist?(worktree_folder) `git worktree add --checkout #{worktree_name} #{target_branch} && #{change_worktree_command}` else `#{change_worktree_command}` end # cleanup previous worktrees child_pid = fork { project_root_path = File.expand_path("..", repository_path) project_folder_name = repository_path.split("/").last all_worktree_folders = Dir.entries(project_root_path).select {|f| !File.directory? f and f.start_with?(project_folder_name) and f != project_folder_name} if all_worktree_folders.length > 2 oldest_worktree_folder_name = all_worktree_folders.sort_by! {|f| File.mtime(File.join(project_root_path, f)) }.first if !oldest_worktree_folder_name.empty? oldest_folder_path = File.join(project_root_path, oldest_worktree_folder_name) oldest_xcodeproj_file = File.join(oldest_folder_path, "*.xcodeproj") build_dir = `xcodebuild -project #{oldest_xcodeproj_file} -showBuildSettings | grep -m 1 "BUILD_DIR" | awk '{print $3}'` oldest_project_derived_data_dir = build_dir.empty? ? "" : File.expand_path("../..", build_dir) `rm -r #{oldest_folder_path} #{oldest_project_derived_data_dir} && git worktree remove #{oldest_folder_path}` end end exit } Process.detach(child_pid) end exit 0