Skip to content

Add WithHead option to prcreator for App-auth PR creation#4974

Open
jmguzik wants to merge 3 commits intoopenshift:mainfrom
jmguzik:prcreation
Open

Add WithHead option to prcreator for App-auth PR creation#4974
jmguzik wants to merge 3 commits intoopenshift:mainfrom
jmguzik:prcreation

Conversation

@jmguzik
Copy link
Contributor

@jmguzik jmguzik commented Feb 27, 2026

Allow prcreator to skip git operations (fork, commit, push) and only create/update the PR when --head is provided. This enables a split workflow where fork+push is handled externally (e.g. via bash with PAT) and prcreator only does PR creation using GitHub App auth.

Summary by CodeRabbit

  • New Features

    • Support for both token-based fork PRs and App-authenticated same-repo PRs
    • Automatic branch name generation from PR title and configurable commit message selection
    • Local git user configuration when creating/updating PR branches
    • Added option to provide an existing head branch for PR creation
  • Bug Fixes / Improvements

    • Improved issue lookups with organization-aware behavior and correct bot author handling
    • PR bodies now append formatted CC mentions and labels are applied during upsert

Allow prcreator to skip git operations (fork, commit, push) and only
create/update the PR when --head is provided. This enables a split
workflow where fork+push is handled externally (e.g. via bash with PAT)
and prcreator only does PR creation using GitHub App auth.

Signed-off-by: Jakub Guzik <jguzik@redhat.com>
@openshift-ci-robot
Copy link
Contributor

Pipeline controller notification
This repo is configured to use the pipeline controller. Second-stage tests will be triggered either automatically or after lgtm label is added, depending on the repository configuration. The pipeline controller will automatically detect which contexts are required and will utilize /test Prow commands to trigger the second stage.

For optional jobs, comment /test ? to see a list of all defined jobs. To trigger manually all jobs from second stage use /pipeline required command.

This repository is configured in: automatic mode

@coderabbitai
Copy link

coderabbitai bot commented Feb 27, 2026

Walkthrough

Refactors PR option passing in the CLI to build a variadic prOpts slice and call UpsertPR with prOpts...; adds an OrgAwareClient wrapper; and significantly expands PR creation logic to support PAT vs GitHub App auth, new helpers, and git/branch management for upstream vs forked PRs.

Changes

Cohort / File(s) Summary
CLI invocation
cmd/prcreator/main.go
Builds a prOpts slice and appends PrBody, PrAssignee, and GitCommitMessage options; calls UpsertPR using variadic expansion (prOpts...) instead of passing individual option arguments.
Organization-aware client
pkg/github/prcreation/orgaware.go
New OrgAwareClient type wrapping github.Client with Org and IsAppAuth fields; overrides FindIssues to call FindIssuesWithOrg, and BotUser to append "[bot]" to logins when App auth is enabled.
PR creation flow
pkg/github/prcreation/prcreation.go
Major expansion: adds GithubClient github.Client to PRCreationOptions; splits UpsertPR into PAT-based (upsertWithPAT) and App-auth upstream (upsertWithAppAuth) paths; introduces branch name, commit message, git user configuration, ensurePR, formatAssigneeCC, and other helpers; centralizes PR creation/update and label application; conditional token handling.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add WithHead option to prcreator for App-auth PR creation' directly corresponds to the PR's main objective of adding a WithHead option that enables App-auth PR creation without local git operations, as evidenced by the file changes introducing App-auth support infrastructure and the new option logic in main.go.
Stable And Deterministic Test Names ✅ Passed This pull request does not add or modify any test files. The three files changed contain only implementation code with no test declarations or Ginkgo/testing syntax, so the custom check for stable test names is not applicable and passes by default.
Test Structure And Quality ✅ Passed PR contains only source code changes with no test code modifications. No test files exist in affected packages, making this check not applicable.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


Comment @coderabbitai help to get the list of available commands and usage tips.

@openshift-ci
Copy link
Contributor

openshift-ci bot commented Feb 27, 2026

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: jmguzik

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ci openshift-ci bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Feb 27, 2026
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/github/prcreation/prcreation.go`:
- Around line 124-126: Before calling upsertPR, add fast-fail validation of
inputs: if prArgs.head != "" validate the head value format (e.g., non-empty and
matches expected "user:branch" or "owner/branch" pattern) and return a clear
error if malformed; otherwise (when prArgs.head == "") ensure a token path is
provided (e.g., prArgs.tokenPath is non-empty) and return an error if missing.
Place these checks immediately before the existing conditional that calls
o.upsertPR(org, repo, branch, prTitle, prArgs) so invalid inputs are rejected
early.

ℹ️ Review info

Configuration used: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 27060f7 and d2b6d11.

📒 Files selected for processing (3)
  • cmd/prcreator/main.go
  • pkg/github/prcreation/orgaware.go
  • pkg/github/prcreation/prcreation.go

Comment on lines +124 to +126
if prArgs.head != "" {
return o.upsertPR(org, repo, branch, prTitle, prArgs)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Validate execution mode inputs before branching.

This branch should fail fast for malformed --head and for non-head mode without a token path; otherwise failures happen later during API/git operations and are harder to diagnose.

Suggested fix
 	if prArgs.head != "" {
+		parts := strings.SplitN(prArgs.head, ":", 2)
+		if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
+			return fmt.Errorf("invalid --head value %q, expected <owner>:<branch>", prArgs.head)
+		}
 		return o.upsertPR(org, repo, branch, prTitle, prArgs)
 	}
+
+	if o.TokenPath == "" {
+		return fmt.Errorf("token path is required when --head is not set")
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if prArgs.head != "" {
return o.upsertPR(org, repo, branch, prTitle, prArgs)
}
if prArgs.head != "" {
parts := strings.SplitN(prArgs.head, ":", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return fmt.Errorf("invalid --head value %q, expected <owner>:<branch>", prArgs.head)
}
return o.upsertPR(org, repo, branch, prTitle, prArgs)
}
if o.TokenPath == "" {
return fmt.Errorf("token path is required when --head is not set")
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/github/prcreation/prcreation.go` around lines 124 - 126, Before calling
upsertPR, add fast-fail validation of inputs: if prArgs.head != "" validate the
head value format (e.g., non-empty and matches expected "user:branch" or
"owner/branch" pattern) and return a clear error if malformed; otherwise (when
prArgs.head == "") ensure a token path is provided (e.g., prArgs.tokenPath is
non-empty) and return an error if missing. Place these checks immediately before
the existing conditional that calls o.upsertPR(org, repo, branch, prTitle,
prArgs) so invalid inputs are rejected early.

hbhushan3 and others added 2 commits March 3, 2026 18:13
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/github/prcreation/prcreation.go`:
- Around line 167-170: The functions that call os.Chdir (notably upsertWithPAT)
change the global working directory and never restore it; capture the original
working directory with os.Getwd() before calling os.Chdir, then defer restoring
it (e.g., defer func() { _ = os.Chdir(origWd) }()) so the process cwd is always
reset even on early returns; apply the same pattern to the other function(s) in
this file that perform os.Chdir so all paths restore the original directory and
wrap or return an error if Getwd fails.
- Around line 322-326: prArgs.additionalLabels is being aliased by labelsToAdd
so appending self-approval labels can mutate the caller's slice; change the
assignment in the PR creation flow to make a copy (e.g. create a new slice and
copy contents of prArgs.additionalLabels into labelsToAdd) before the
SelfApprove branch, then append labels.Approved and labels.LGTM when
o.SelfApprove is true so callers' slices are not modified.
- Around line 136-139: branchNameFromTitle currently only replaces spaces and
colons and can still produce invalid git ref characters; update
branchNameFromTitle to fully sanitize the title by lowercasing it then replacing
any character that is not a lowercase letter, digit, hyphen, underscore, dot or
slash with a hyphen, collapse consecutive hyphens into one, trim
leading/trailing hyphens, dots and slashes, and ensure the result is non-empty
(fallback to a safe default like "branch") before returning; reference the
branchNameFromTitle function to locate and implement these transformations.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 59fe509d-1f9a-4db3-a7b2-cb6259a3db2d

📥 Commits

Reviewing files that changed from the base of the PR and between d2b6d11 and cefc785.

📒 Files selected for processing (3)
  • cmd/prcreator/main.go
  • pkg/github/prcreation/orgaware.go
  • pkg/github/prcreation/prcreation.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/prcreator/main.go

Comment on lines +136 to +139
func branchNameFromTitle(title string) string {
name := strings.ReplaceAll(strings.ToLower(title), " ", "-")
name = strings.ReplaceAll(name, ":", "-")
return name
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Harden branch name derivation against invalid git ref characters.

Current replacement handles only spaces and :, so some titles can still produce invalid refs and fail at checkout/push time.

Proposed fix
 import (
 	"flag"
 	"fmt"
 	"io"
 	"os"
+	"regexp"
 	"strings"
 	"time"
@@
+var invalidBranchRunes = regexp.MustCompile(`[^a-z0-9._/-]+`)
+
 func branchNameFromTitle(title string) string {
-	name := strings.ReplaceAll(strings.ToLower(title), " ", "-")
+	name := strings.ReplaceAll(strings.ToLower(strings.TrimSpace(title)), " ", "-")
 	name = strings.ReplaceAll(name, ":", "-")
+	name = invalidBranchRunes.ReplaceAllString(name, "-")
+	name = strings.Trim(name, "./-")
+	if name == "" {
+		name = "autobump"
+	}
 	return name
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/github/prcreation/prcreation.go` around lines 136 - 139,
branchNameFromTitle currently only replaces spaces and colons and can still
produce invalid git ref characters; update branchNameFromTitle to fully sanitize
the title by lowercasing it then replacing any character that is not a lowercase
letter, digit, hyphen, underscore, dot or slash with a hyphen, collapse
consecutive hyphens into one, trim leading/trailing hyphens, dots and slashes,
and ensure the result is non-empty (fallback to a safe default like "branch")
before returning; reference the branchNameFromTitle function to locate and
implement these transformations.

Comment on lines +167 to 170
func (o *PRCreationOptions) upsertWithPAT(localSourceDir, org, repo, branch, prTitle string, prArgs *PrOptions) error {
if err := os.Chdir(localSourceDir); err != nil {
return fmt.Errorf("failed to chdir into %s: %w", localSourceDir, err)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Restore the original working directory after os.Chdir.

Both paths mutate process-global cwd and never restore it. In long-lived callers, later file/git ops can run in the wrong directory.

Proposed fix
 func (o *PRCreationOptions) upsertWithPAT(localSourceDir, org, repo, branch, prTitle string, prArgs *PrOptions) error {
+	cwd, err := os.Getwd()
+	if err != nil {
+		return fmt.Errorf("failed to get current working directory: %w", err)
+	}
 	if err := os.Chdir(localSourceDir); err != nil {
 		return fmt.Errorf("failed to chdir into %s: %w", localSourceDir, err)
 	}
+	defer func() {
+		_ = os.Chdir(cwd)
+	}()
-	changed, err := bumper.HasChanges()
+	changed, err := bumper.HasChanges()
 	if err != nil {
 		return fmt.Errorf("failed to check for changes: %w", err)
 	}
 func (o *PRCreationOptions) upsertWithAppAuth(localSourceDir, org, repo, branch, prTitle string, prArgs *PrOptions) error {
+	cwd, err := os.Getwd()
+	if err != nil {
+		return fmt.Errorf("failed to get current working directory: %w", err)
+	}
 	if err := os.Chdir(localSourceDir); err != nil {
 		return fmt.Errorf("failed to chdir into %s: %w", localSourceDir, err)
 	}
+	defer func() {
+		_ = os.Chdir(cwd)
+	}()
-	changed, err := bumper.HasChanges()
+	changed, err := bumper.HasChanges()
 	if err != nil {
 		return fmt.Errorf("failed to check for changes: %w", err)
 	}

Also applies to: 244-246

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/github/prcreation/prcreation.go` around lines 167 - 170, The functions
that call os.Chdir (notably upsertWithPAT) change the global working directory
and never restore it; capture the original working directory with os.Getwd()
before calling os.Chdir, then defer restoring it (e.g., defer func() { _ =
os.Chdir(origWd) }()) so the process cwd is always reset even on early returns;
apply the same pattern to the other function(s) in this file that perform
os.Chdir so all paths restore the original directory and wrap or return an error
if Getwd fails.

Comment on lines 322 to 326
labelsToAdd := prArgs.additionalLabels
if o.SelfApprove {
l.Infof("Self-aproving PR by adding the %q and %q labels", labels.Approved, labels.LGTM)
logrus.Infof("Self-approving PR by adding the %q and %q labels", labels.Approved, labels.LGTM)
labelsToAdd = append(labelsToAdd, labels.Approved, labels.LGTM)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Copy additionalLabels before appending self-approval labels.

labelsToAdd := prArgs.additionalLabels aliases the caller slice; append may mutate caller-owned data when capacity allows.

Proposed fix
-	labelsToAdd := prArgs.additionalLabels
+	labelsToAdd := append([]string(nil), prArgs.additionalLabels...)
 	if o.SelfApprove {
 		logrus.Infof("Self-approving PR by adding the %q and %q labels", labels.Approved, labels.LGTM)
 		labelsToAdd = append(labelsToAdd, labels.Approved, labels.LGTM)
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
labelsToAdd := prArgs.additionalLabels
if o.SelfApprove {
l.Infof("Self-aproving PR by adding the %q and %q labels", labels.Approved, labels.LGTM)
logrus.Infof("Self-approving PR by adding the %q and %q labels", labels.Approved, labels.LGTM)
labelsToAdd = append(labelsToAdd, labels.Approved, labels.LGTM)
}
labelsToAdd := append([]string(nil), prArgs.additionalLabels...)
if o.SelfApprove {
logrus.Infof("Self-approving PR by adding the %q and %q labels", labels.Approved, labels.LGTM)
labelsToAdd = append(labelsToAdd, labels.Approved, labels.LGTM)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/github/prcreation/prcreation.go` around lines 322 - 326,
prArgs.additionalLabels is being aliased by labelsToAdd so appending
self-approval labels can mutate the caller's slice; change the assignment in the
PR creation flow to make a copy (e.g. create a new slice and copy contents of
prArgs.additionalLabels into labelsToAdd) before the SelfApprove branch, then
append labels.Approved and labels.LGTM when o.SelfApprove is true so callers'
slices are not modified.

@openshift-ci
Copy link
Contributor

openshift-ci bot commented Mar 4, 2026

@jmguzik: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
ci/prow/breaking-changes cefc785 link false /test breaking-changes
ci/prow/images cefc785 link true /test images
ci/prow/lint cefc785 link true /test lint
ci/prow/integration cefc785 link true /test integration

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants