Class: Ace::Git::Worktree::Molecules::WorktreeCreator

Inherits:
Object
  • Object
show all
Defined in:
lib/ace/git/worktree/molecules/worktree_creator.rb

Overview

Worktree creator molecule

Creates git worktrees with proper validation, naming, and error handling. Integrates with git commands and provides task-aware creation capabilities.

Examples:

Create a task-aware worktree

creator = WorktreeCreator.new
task_data = fetch_task_data("081")
config = WorktreeConfig.new
result = creator.create_for_task(task_data, config)

Create a traditional worktree

result = creator.create_traditional("feature-branch", "/path/to/worktree")

Constant Summary collapse

DEFAULT_TIMEOUT =

Default timeout for git commands

60

Instance Method Summary collapse

Constructor Details

#initialize(config: nil, timeout: DEFAULT_TIMEOUT) ⇒ WorktreeCreator

Initialize a new WorktreeCreator

Parameters:

  • config (WorktreeConfig, nil) (defaults to: nil) —

    Worktree configuration

  • timeout (Integer) (defaults to: DEFAULT_TIMEOUT) —

    Command timeout in seconds



30
31
32
33
# File 'lib/ace/git/worktree/molecules/worktree_creator.rb', line 30

def initialize(config: nil, timeout: DEFAULT_TIMEOUT)
  @config = config
  @timeout = timeout
end

Instance Method Details

#create_for_branch(branch_name, config, git_root: nil) ⇒ Hash

Create a worktree for a specific branch (local or remote)

Examples:

Remote branch

result = creator.create_for_branch("origin/feature/auth", config)
# => { success: true, worktree_path: "/project/.ace-wt/feature-auth", branch: "feature/auth", tracking: "origin/feature/auth" }

Local branch

result = creator.create_for_branch("local-feature", config)
# => { success: true, worktree_path: "/project/.ace-wt/local-feature", branch: "local-feature", tracking: nil }

Parameters:

  • branch_name (String) —

    Branch name (e.g., "feature" or "origin/feature")

  • config (WorktreeConfig) —

    Worktree configuration

  • git_root (String, nil) (defaults to: nil) —

    Git repository root (auto-detected if nil)

Returns:

  • (Hash) —

    Result with :success, :worktree_path, :branch, :error



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/ace/git/worktree/molecules/worktree_creator.rb', line 196

def create_for_branch(branch_name, config, git_root: nil)
  return error_result("Branch name is required") if branch_name.nil? || branch_name.empty?
  return error_result("Configuration is required") unless config

  begin
    # Determine git repository root
    git_root ||= detect_git_root
    return error_result("Not in a git repository") unless git_root

    # Detect if this is a remote branch
    remote_info = detect_remote_branch(branch_name)

    if remote_info
      # Remote branch - create with tracking
      create_for_remote_branch(branch_name, remote_info, config, git_root)
    else
      # Local branch - create without tracking
      create_for_local_branch(branch_name, config, git_root)
    end
  rescue => e
    error_result("Unexpected error: #{e.message}")
  end
end

#create_for_pr(pr_data, config, git_root: nil, source_ref: nil, remote_tracking: nil) ⇒ Hash

Create a worktree for a Pull Request from an already-verified source ref (see PullRequestCheckoutPreparer).

Examples:

pr_data = { number: 26, title: "Add feature", head_branch: "feature/auth", base_branch: "main" }
result = creator.create_for_pr(pr_data, config, source_ref: "FETCH_HEAD")
# => { success: true, worktree_path: ".../ace-pr-26", branch: "pr-26-add-feature", tracking: nil }

Parameters:

  • pr_data (Hash) —

    normalized PR data: :number, :title, :head_branch, :base_branch

  • config (WorktreeConfig) —

    Worktree configuration

  • git_root (String, nil) (defaults to: nil) —

    Git repository root (auto-detected if nil)

  • source_ref (String, nil) (defaults to: nil) —

    verified local ref (e.g. FETCH_HEAD) the PR head was proven against; required

  • remote_tracking (String, nil) (defaults to: nil) —

    "remote/branch" tracking ref when the source is reachable via a configured local remote

Returns:

  • (Hash) —

    Result with :success, :worktree_path, :branch, :error



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/ace/git/worktree/molecules/worktree_creator.rb', line 123

def create_for_pr(pr_data, config, git_root: nil, source_ref: nil, remote_tracking: nil)
  return error_result("PR data is required") unless pr_data
  return error_result("Configuration is required") unless config
  return error_result("Verified source ref is required for PR checkout") if source_ref.nil? || source_ref.empty?

  begin
    # Determine git repository root
    git_root ||= detect_git_root
    return error_result("Not in a git repository") unless git_root

    # Get PR-specific configuration (fallback to defaults)
    pr_config = config.pr_config || {}
    directory_format = pr_config[:directory_format] || "ace-pr-{number}"
    branch_format = pr_config[:branch_format] || "pr-{number}-{slug}"

    # Format directory and branch names
    directory_name = format_pr_name(directory_format, pr_data)
    local_branch_name = format_pr_name(branch_format, pr_data)

    # Build full path
    worktree_path = File.join(config.absolute_root_path, directory_name)

    # Validate worktree path
    validation = validate_worktree_path(worktree_path, git_root)
    return error_result(validation[:error]) unless validation[:valid]

    # Create the worktree from the proven source ref
    result = create_worktree(worktree_path, local_branch_name, git_root, start_point: source_ref)
    return result unless result[:success]

    # Configure push behavior when tracking a differently-named branch
    if remote_tracking && local_branch_name != extract_remote_branch_name(remote_tracking)
      configure_push_for_worktree(worktree_path, local_branch_name, remote_tracking)
    end

    # Bind the reported tracking ref as the branch's real upstream so
    # `@{upstream}` resolves; advisory when the tracking ref is not a
    # local remote-tracking ref (fork URL fetches).
    upstream = remote_tracking ? set_and_verify_upstream(local_branch_name, remote_tracking) : nil

    # Success - return worktree information
    {
      success: true,
      worktree_path: worktree_path,
      branch: local_branch_name,
      tracking: remote_tracking,
      upstream: upstream,
      warnings: remote_tracking && !upstream ? ["Could not set upstream to #{remote_tracking}"] : nil,
      directory_name: directory_name,
      pr_number: pr_data[:number],
      pr_title: pr_data[:title],
      git_root: git_root,
      error: nil
    }
  rescue => e
    error_result("Unexpected error: #{e.message}")
  end
end

#create_for_task(task_data, config, counter: nil, git_root: nil, source: nil, target_branch: nil) ⇒ Hash

Create a worktree for a specific task

Examples:

creator = WorktreeCreator.new
task_data = fetch_task_data("081")
config = ConfigLoader.new.load
result = creator.create_for_task(task_data, config)
# => { success: true, worktree_path: "/project/.ace-wt/task.081", branch: "081-fix-auth", error: nil }

With explicit source

result = creator.create_for_task(task_data, config, source: "main")
# => Creates branch based on 'main' instead of current branch

Subtask with target branch

result = creator.create_for_task(subtask_data, config, target_branch: "202-orchestrator")
# => { success: true, target_branch: "202-orchestrator", ... }

Parameters:

  • task_data (Hash) —

    Task data hash from ace-task

  • config (WorktreeConfig) —

    Worktree configuration

  • counter (Integer, nil) (defaults to: nil) —

    Counter for multiple worktrees of same task

  • git_root (String, nil) (defaults to: nil) —

    Git repository root (auto-detected if nil)

  • source (String, nil) (defaults to: nil) —

    Git ref to use as start-point for the new branch If nil, uses current branch (default behavior - fixes the branch source bug)

  • target_branch (String, nil) (defaults to: nil) —

    PR target branch (for subtasks)

Returns:

  • (Hash) —

    Result with :success, :worktree_path, :branch, :error



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/ace/git/worktree/molecules/worktree_creator.rb', line 60

def create_for_task(task_data, config, counter: nil, git_root: nil, source: nil, target_branch: nil)
  return error_result("Task data is required") unless task_data
  return error_result("Configuration is required") unless config

  begin
    # Determine git repository root
    git_root ||= detect_git_root
    return error_result("Not in a git repository") unless git_root

    # Generate names based on configuration
    directory_name = config.format_directory(task_data, counter)
    branch_name = config.format_branch(task_data)

    # Build full path
    worktree_path = File.join(config.absolute_root_path, directory_name)

    # Ensure parent directory exists before validation
    # (PathExpander rejects paths whose parent doesn't exist yet)
    parent_dir = File.dirname(worktree_path)
    FileUtils.mkdir_p(parent_dir) unless File.exist?(parent_dir)

    # Validate worktree path
    validation = validate_worktree_path(worktree_path, git_root)
    return error_result(validation[:error]) unless validation[:valid]

    # Create the worktree with source as start-point
    result = create_worktree(worktree_path, branch_name, git_root, start_point: source)
    return result unless result[:success]

    # Success - return worktree information
    {
      success: true,
      worktree_path: worktree_path,
      branch: branch_name,
      start_point: result[:start_point],
      directory_name: directory_name,
      task_id: extract_task_id_from_data(task_data),
      git_root: git_root,
      target_branch: target_branch,
      error: nil
    }
  rescue => e
    error_result("Unexpected error: #{e.message}")
  end
end

#create_traditional(branch_name, worktree_path = nil, git_root: nil, source: nil) ⇒ Hash

Create a traditional worktree (not task-aware)

Examples:

result = creator.create_traditional("feature-branch", "/tmp/worktree")

With explicit source

result = creator.create_traditional("feature-branch", nil, source: "main")

Parameters:

  • branch_name (String) —

    Branch name

  • worktree_path (String, nil) (defaults to: nil) —

    Worktree path (auto-generated if nil)

  • git_root (String, nil) (defaults to: nil) —

    Git repository root (auto-detected if nil)

  • source (String, nil) (defaults to: nil) —

    Git ref to use as start-point for the new branch If nil, uses current branch (default behavior)

Returns:

  • (Hash) —

    Result with :success, :worktree_path, :branch, :error



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/ace/git/worktree/molecules/worktree_creator.rb', line 234

def create_traditional(branch_name, worktree_path = nil, git_root: nil, source: nil)
  return error_result("Branch name is required") if branch_name.nil? || branch_name.empty?

  begin
    # Determine git repository root
    git_root ||= detect_git_root
    return error_result("Not in a git repository") unless git_root

    # Auto-generate worktree path if not provided
    if worktree_path.nil?
      worktree_path = generate_default_worktree_path(branch_name, git_root)
    end

    # Validate worktree path
    validation = validate_worktree_path(worktree_path, git_root)
    return error_result(validation[:error]) unless validation[:valid]

    # Validate branch name
    return error_result("Invalid branch name") unless valid_branch_name?(branch_name)

    # Check if branch already exists (locally or remotely)
    if branch_exists?(branch_name)
      # Branch exists - create worktree for existing branch
      create_worktree_for_existing_branch(worktree_path, branch_name, git_root)
    else
      # Branch doesn't exist - create new branch with worktree
      create_worktree(worktree_path, branch_name, git_root, start_point: source)
    end
  rescue => e
    error_result("Unexpected error: #{e.message}")
  end
end

#generate_unique_path(task_data, config, git_root) ⇒ String

Generate a unique worktree path for a task (handles conflicts)

Examples:

path = creator.generate_unique_path(task_data, config, git_root)
# => "/project/.ace-wt/task.081-2"

Parameters:

  • task_data (Hash) —

    Task data hash from ace-task

  • config (WorktreeConfig) —

    Worktree configuration

  • git_root (String) —

    Git repository root

Returns:

  • (String) —

    Unique worktree path



315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/ace/git/worktree/molecules/worktree_creator.rb', line 315

def generate_unique_path(task_data, config, git_root)
  counter = 1
  loop do
    directory_name = config.format_directory(task_data, (counter > 1) ? counter : nil)
    worktree_path = File.join(config.absolute_root_path, directory_name)

    # Check if path already exists
    existing = worktree_exists?(worktree_path: worktree_path)
    break worktree_path unless existing

    counter += 1
  end
end

#validate_worktree_path(worktree_path, git_root) ⇒ Hash

Validate a worktree path for creation

Examples:

validation = creator.validate_worktree_path("/tmp/worktree", "/project")
# => { valid: true, error: nil, expanded_path: "/tmp/worktree" }

Parameters:

  • worktree_path (String) —

    Path to validate

  • git_root (String) —

    Git repository root

Returns:

  • (Hash) —

    Validation result with :valid, :error, :expanded_path



338
339
340
341
# File 'lib/ace/git/worktree/molecules/worktree_creator.rb', line 338

def validate_worktree_path(worktree_path, git_root)
  require_relative "../atoms/path_expander"
  Atoms::PathExpander.validate_for_worktree(worktree_path, git_root)
end

#worktree_exists?(task_data: nil, branch_name: nil, worktree_path: nil) ⇒ WorktreeInfo?

Check if a worktree already exists for the given criteria

Examples:

existing = creator.worktree_exists_for_task?(task_data)
existing = creator.worktree_exists_for_branch?("feature-branch")

Parameters:

  • task_data (Hash, nil) (defaults to: nil) —

    Task data hash from ace-task

  • branch_name (String, nil) (defaults to: nil) —

    Branch name

  • worktree_path (String, nil) (defaults to: nil) —

    Worktree path

Returns:

  • (WorktreeInfo, nil) —

    Existing worktree info or nil



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/ace/git/worktree/molecules/worktree_creator.rb', line 277

def worktree_exists?(task_data: nil, branch_name: nil, worktree_path: nil)
  require_relative "worktree_lister"
  lister = WorktreeLister.new
  worktrees = lister.list_all

  # Check by task ID
  if task_data
    task_id = extract_task_id_from_data(task_data)
    existing = Models::WorktreeInfo.find_by_task_id(worktrees, task_id)
    return existing if existing
  end

  # Check by branch name
  if branch_name
    existing = Models::WorktreeInfo.find_by_branch(worktrees, branch_name)
    return existing if existing
  end

  # Check by path
  if worktree_path
    expanded_path = File.expand_path(worktree_path)
    existing = worktrees.find { |wt| File.expand_path(wt.path) == expanded_path }
    return existing if existing
  end

  nil
end