Skip to content

refactor: reduce complexity of execute_impl in create_pr.rs#361

Merged
jamesadevine merged 2 commits into
mainfrom
refactor/reduce-create-pr-execute-impl-complexity-fe4613258f8e8fc3
Apr 30, 2026
Merged

refactor: reduce complexity of execute_impl in create_pr.rs#361
jamesadevine merged 2 commits into
mainfrom
refactor/reduce-create-pr-execute-impl-complexity-fe4613258f8e8fc3

Conversation

@github-actions

Copy link
Copy Markdown
Contributor

What was complex

execute_impl in src/safeoutputs/create_pr.rs was 992 lines — a single async method that handled the entire PR creation pipeline: input validation, ADO config extraction, patch security checks, git worktree setup, patch application (two strategies), change collection, ADO push with collision retry, PR creation, label/work-item wiring, completion options, and reviewer assignment.

Two specific problems stood out:

  1. The patch-application conflict-marker scan (git grep -l -E '^(<<<<<<<\s|>>>>>>>\s)') was copy-pasted in both the git apply path and the git am fallback path.
  2. The tail of the function (~100 lines) mixed PR-completion-options setup and reviewer assignment inline with the main control flow, making the success path hard to read.

What changed

Five focused helper functions extracted, all placed alongside the existing standalone helpers below the impl block:

Function Role
check_for_conflict_markers Runs the git-grep conflict scan; eliminates the duplication
apply_patch_with_exclusions The git apply --3way path (used when excluded-files are set)
apply_patch_without_exclusions The git am --3way + git apply fallback path
apply_patch_to_worktree Thin dispatcher — picks the right strategy, returns Result<bool, ExecutionResult>
set_pr_completion_options Sets delete-source-branch / squash-merge / auto-complete on the new PR
add_reviewers_to_pr Resolves and attaches each configured reviewer

The call sites in execute_impl become:

// Patch application (~130 lines → 4 lines)
let patch_committed = match apply_patch_to_worktree(&worktree_path, &patch_path, &exclude_args).await? {
    Ok(committed) => committed,
    Err(result) => return Ok(result),
};

// PR configuration (~100 lines → 8 lines)
set_pr_completion_options(&client, &config, org_url, project, &repo_id, pr_id,
    pr_data["createdBy"]["id"].as_str(), token).await;
add_reviewers_to_pr(&client, &config, org_url, project, &repo_id, pr_id, organization, token).await;

Before / After

Metric Before After
execute_impl lines 992 789 (-203)
Conflict-marker scan copies 2 1 (in check_for_conflict_markers)
Patch strategy nesting depth 4 levels 2 levels per helper

Verification

  • cargo build — ✅ clean
  • cargo test — ✅ all tests pass
  • cargo clippy --all-targets --all-features — ✅ no new warnings
  • Behaviour is identical: same git commands, same error messages, same return values

Generated by Cyclomatic Complexity Reducer · ● 2.8M ·

Extract five focused helper functions from the 992-line execute_impl:

- check_for_conflict_markers: deduplicates the git-grep conflict scan
  that was copy-pasted in both the git-apply and git-am fallback paths
- apply_patch_with_exclusions: the git-apply --3way path (excluded-files)
- apply_patch_without_exclusions: the git-am --3way + git-apply fallback path
- apply_patch_to_worktree: thin dispatcher selecting the right strategy
- set_pr_completion_options: sets delete-source-branch / squash-merge /
  auto-complete on the newly created PR
- add_reviewers_to_pr: resolves and attaches each configured reviewer

execute_impl shrinks from 992 lines to 789 lines (-203 lines). The
extracted functions are independently documented and testable.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@jamesadevine jamesadevine marked this pull request as ready for review April 30, 2026 05:24
@jamesadevine

Copy link
Copy Markdown
Collaborator

/rust-review

@github-actions

github-actions Bot commented Apr 30, 2026

Copy link
Copy Markdown
Contributor Author

Rust PR Reviewer completed successfully!

@github-actions

Copy link
Copy Markdown
Contributor Author

🔍 Rust PR Review

Summary: Looks good — clean, faithful refactor. One minor observability regression worth noting.

Findings

⚠️ Suggestions

  • set_pr_completion_options — silent skip when createdBy.id is absent
    The call site passes pr_data["createdBy"]["id"].as_str(), which returns None if the field is missing or not a string. The new helper then silently skips setting autoCompleteSetBy with no log output. The old code would have sent "id": null to ADO, received an error response, and emitted a warn! — preserving observability.

    This is low-severity (auto-complete still works correctly when the creator ID is present), but a warn! in the None branch would restore the signal:

    if config.auto_complete && !config.draft {
        if let Some(creator_id) = pr_created_by_id {
            update_body["autoCompleteSetBy"] = serde_json::json!({ "id": creator_id });
        } else {
            warn!("auto_complete requested but creator ID is unavailable; skipping autoCompleteSetBy");
        }
    }

✅ What Looks Good

  • Deduplication is clean: check_for_conflict_markers correctly eliminates the copy-pasted git-grep block; both call sites (with and without exclusions) share identical behavior.
  • Return-type choice is sound: anyhow::Result<Result<bool, ExecutionResult>> correctly distinguishes infrastructure errors (outer Err) from expected domain failures (inner Err); doc comments explain the semantics clearly.
  • &[String] slices: the helpers take &[String] rather than Vec<String> — a good improvement over the original owned parameters.
  • set_pr_completion_options / add_reviewers_to_pr signatures: returning () and handling errors internally via warn! is the right design for best-effort post-creation operations; doc comments document this clearly.
  • No behavioral regressions in the patch-application path: git commands, arguments, error messages, and patch_committed semantics are identical to the original.

Generated by Rust PR Reviewer for issue #361 · ● 319.7K ·

@jamesadevine

Copy link
Copy Markdown
Collaborator

@copilot implement suggestion

…_completion_options

Agent-Logs-Url: https://github.com/githubnext/ado-aw/sessions/1c554779-676a-488c-b5b4-fcf961e2c542

Co-authored-by: jamesadevine <4742697+jamesadevine@users.noreply.github.com>

Copilot AI commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

@copilot implement suggestion

Implemented in ea21a33. Added warn!("auto_complete requested but creator ID is unavailable; skipping autoCompleteSetBy") in the None branch of set_pr_completion_options, restoring the observability that was silently lost in the refactor.

Copilot AI requested a review from jamesadevine April 30, 2026 05:43
@jamesadevine jamesadevine merged commit ebc14d8 into main Apr 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants