Skip to content

git pr create --dry-run works with remote branch but actual command does not #9201

Open

Description

@findepi

Describe the bug

I have a branch that I pushed and deleted locally. I can reference it using origin/branch-name.
gh pr create --dry-run works with origin/branch-name reference, but same invocation without --dry-run does not.

$ gh --version
gh version 2.50.0 (2024-05-29)
https://github.com/cli/cli/releases/tag/v2.50.0
master$ gh pr create --base master --head origin/findepi/sample-branch --fill --dry-run

Dry Running pull request for origin/findepi/sample-branch into master in xxx/xxx

Would have created a Pull Request with:
Title: My sample commit
Draft: false
Base: master
Head: origin/findepi/sample-branch
MaintainerCanModify: true
Body:

  My commit description.
master$ gh pr create --base master --head origin/findepi/sample-branch --fill

Creating pull request for origin/findepi/sample-branch into master in xxx/xxx

pull request create failed: GraphQL: Head sha can't be blank, Base sha can't be blank, No commits between master and origin/findepi/sample-branch, Head ref must be a branch (createPullRequest)

Steps to reproduce the behavior

  1. Create a branch, push it, and delete locally
  2. Use gh pr create --dry-run to dry-run creation of a PR from that branch
  3. Use gh pr create to finalize creation of a PR from that branch

Expected vs actual behavior

If --dry-run works, the call without --dry-run should work too.
If origin/... references are not accepted, --dry-run should not accept them either.

Activity

  1. added
    bug
    on Jun 12, 2024
  2. added
    needs-triage
    on Jun 12, 2024
  3. Talkinghawk commented on Jun 17, 2024

    @Talkinghawk
  4. andyfeller commented on Aug 1, 2024

    @andyfeller
    Contributor

    Thank you for opening this issue, @findepi, and apologies for any frustration this might have caused! 🙇

    If --dry-run works, the call without --dry-run should work too.
    If origin/... references are not accepted, --dry-run should not accept them either.

    I generally agree with the overall spirit of what you're saying — "If this won't work, then tell me about it during --dry-run — so let's put a fine point on exactly what should happen here.

    Let's dig into the code

    This is the bulk of code involved in creating PRs:

    func createRun(opts *CreateOptions) (err error) {
    ctx, err := NewCreateContext(opts)
    if err != nil {
    return
    }
    client := ctx.Client
    state, err := NewIssueState(*ctx, *opts)
    if err != nil {
    return
    }
    var openURL string
    if opts.WebMode {
    if !(opts.Autofill || opts.FillFirst) {
    state.Title = opts.Title
    state.Body = opts.Body
    }
    err = handlePush(*opts, *ctx)
    if err != nil {
    return
    }
    openURL, err = generateCompareURL(*ctx, *state)
    if err != nil {
    return
    }
    if !shared.ValidURL(openURL) {
    err = fmt.Errorf("cannot open in browser: maximum URL length exceeded")
    return
    }
    return previewPR(*opts, openURL)
    }
    if opts.TitleProvided {
    state.Title = opts.Title
    }
    if opts.BodyProvided {
    state.Body = opts.Body
    }
    existingPR, _, err := opts.Finder.Find(shared.FindOptions{
    Selector: ctx.HeadBranchLabel,
    BaseBranch: ctx.BaseBranch,
    States: []string{"OPEN"},
    Fields: []string{"url"},
    })
    var notFound *shared.NotFoundError
    if err != nil && !errors.As(err, &notFound) {
    return fmt.Errorf("error checking for existing pull request: %w", err)
    }
    if err == nil {
    return fmt.Errorf("a pull request for branch %q into branch %q already exists:\n%s",
    ctx.HeadBranchLabel, ctx.BaseBranch, existingPR.URL)
    }
    message := "\nCreating pull request for %s into %s in %s\n\n"
    if state.Draft {
    message = "\nCreating draft pull request for %s into %s in %s\n\n"
    }
    if opts.DryRun {
    message = "\nDry Running pull request for %s into %s in %s\n\n"
    }
    cs := opts.IO.ColorScheme()
    if opts.IO.CanPrompt() {
    fmt.Fprintf(opts.IO.ErrOut, message,
    cs.Cyan(ctx.HeadBranchLabel),
    cs.Cyan(ctx.BaseBranch),
    ghrepo.FullName(ctx.BaseRepo))
    }
    if opts.FillVerbose || opts.Autofill || opts.FillFirst || (opts.TitleProvided && opts.BodyProvided) {
    err = handlePush(*opts, *ctx)
    if err != nil {
    return
    }
    return submitPR(*opts, *ctx, *state)
    }

    func submitPR(opts CreateOptions, ctx CreateContext, state shared.IssueMetadataState) error {
    client := ctx.Client
    params := map[string]interface{}{
    "title": state.Title,
    "body": state.Body,
    "draft": state.Draft,
    "baseRefName": ctx.BaseBranch,
    "headRefName": ctx.HeadBranchLabel,
    "maintainerCanModify": opts.MaintainerCanModify,
    }
    if params["title"] == "" {
    return errors.New("pull request title must not be blank")
    }
    err := shared.AddMetadataToIssueParams(client, ctx.BaseRepo, params, &state)
    if err != nil {
    return err
    }
    if opts.DryRun {
    if opts.IO.IsStdoutTTY() {
    return renderPullRequestTTY(opts.IO, params, &state)
    } else {
    return renderPullRequestPlain(opts.IO.Out, params, &state)
    }
    }
    opts.IO.StartProgressIndicator()
    pr, err := api.CreatePullRequest(client, ctx.BaseRepo, params)
    opts.IO.StopProgressIndicator()
    if pr != nil {
    fmt.Fprintln(opts.IO.Out, pr.URL)
    }
    if err != nil {
    if pr != nil {
    return fmt.Errorf("pull request update failed: %w", err)
    }
    return fmt.Errorf("pull request create failed: %w", err)
    }
    return nil
    }

    Digging a little bit deeper, I think all of the logic for handling user arguments and flags happens when the context for creating the PR here:

    func NewCreateContext(opts *CreateOptions) (*CreateContext, error) {
    httpClient, err := opts.HttpClient()
    if err != nil {
    return nil, err
    }
    client := api.NewClientFromHTTP(httpClient)
    remotes, err := getRemotes(opts)
    if err != nil {
    return nil, err
    }
    repoContext, err := ghContext.ResolveRemotesToRepos(remotes, client, opts.RepoOverride)
    if err != nil {
    return nil, err
    }
    var baseRepo *api.Repository
    if br, err := repoContext.BaseRepo(opts.IO); err == nil {
    if r, ok := br.(*api.Repository); ok {
    baseRepo = r
    } else {
    // TODO: if RepoNetwork is going to be requested anyway in `repoContext.HeadRepos()`,
    // consider piggybacking on that result instead of performing a separate lookup
    baseRepo, err = api.GitHubRepo(client, br)
    if err != nil {
    return nil, err
    }
    }
    } else {
    return nil, err
    }
    isPushEnabled := false
    headBranch := opts.HeadBranch
    headBranchLabel := opts.HeadBranch
    if headBranch == "" {
    headBranch, err = opts.Branch()
    if err != nil {
    return nil, fmt.Errorf("could not determine the current branch: %w", err)
    }
    headBranchLabel = headBranch
    isPushEnabled = true
    } else if idx := strings.IndexRune(headBranch, ':'); idx >= 0 {
    headBranch = headBranch[idx+1:]
    }
    gitClient := opts.GitClient
    if ucc, err := gitClient.UncommittedChangeCount(context.Background()); err == nil && ucc > 0 {
    fmt.Fprintf(opts.IO.ErrOut, "Warning: %s\n", text.Pluralize(ucc, "uncommitted change"))
    }
    var headRepo ghrepo.Interface
    var headRemote *ghContext.Remote
    if isPushEnabled {
    // determine whether the head branch is already pushed to a remote
    if pushedTo := determineTrackingBranch(gitClient, remotes, headBranch); pushedTo != nil {
    isPushEnabled = false
    if r, err := remotes.FindByName(pushedTo.RemoteName); err == nil {
    headRepo = r
    headRemote = r
    headBranchLabel = pushedTo.BranchName
    if !ghrepo.IsSame(baseRepo, headRepo) {
    headBranchLabel = fmt.Sprintf("%s:%s", headRepo.RepoOwner(), pushedTo.BranchName)
    }
    }
    }
    }
    // otherwise, ask the user for the head repository using info obtained from the API
    if headRepo == nil && isPushEnabled && opts.IO.CanPrompt() {
    pushableRepos, err := repoContext.HeadRepos()
    if err != nil {
    return nil, err
    }
    if len(pushableRepos) == 0 {
    pushableRepos, err = api.RepoFindForks(client, baseRepo, 3)
    if err != nil {
    return nil, err
    }
    }
    currentLogin, err := api.CurrentLoginName(client, baseRepo.RepoHost())
    if err != nil {
    return nil, err
    }
    hasOwnFork := false
    var pushOptions []string
    for _, r := range pushableRepos {
    pushOptions = append(pushOptions, ghrepo.FullName(r))
    if r.RepoOwner() == currentLogin {
    hasOwnFork = true
    }
    }
    if !hasOwnFork {
    pushOptions = append(pushOptions, "Create a fork of "+ghrepo.FullName(baseRepo))
    }
    pushOptions = append(pushOptions, "Skip pushing the branch")
    pushOptions = append(pushOptions, "Cancel")
    selectedOption, err := opts.Prompter.Select(fmt.Sprintf("Where should we push the '%s' branch?", headBranch), "", pushOptions)
    if err != nil {
    return nil, err
    }
    if selectedOption < len(pushableRepos) {
    headRepo = pushableRepos[selectedOption]
    if !ghrepo.IsSame(baseRepo, headRepo) {
    headBranchLabel = fmt.Sprintf("%s:%s", headRepo.RepoOwner(), headBranch)
    }
    } else if pushOptions[selectedOption] == "Skip pushing the branch" {
    isPushEnabled = false
    } else if pushOptions[selectedOption] == "Cancel" {
    return nil, cmdutil.CancelError
    } else {
    // "Create a fork of ..."
    headBranchLabel = fmt.Sprintf("%s:%s", currentLogin, headBranch)
    }
    }
    if headRepo == nil && isPushEnabled && !opts.IO.CanPrompt() {
    fmt.Fprintf(opts.IO.ErrOut, "aborted: you must first push the current branch to a remote, or use the --head flag")
    return nil, cmdutil.SilentError
    }
    baseBranch := opts.BaseBranch
    if baseBranch == "" {
    baseBranch = baseRepo.DefaultBranchRef.Name
    }
    if headBranch == baseBranch && headRepo != nil && ghrepo.IsSame(baseRepo, headRepo) {
    return nil, fmt.Errorf("must be on a branch named differently than %q", baseBranch)
    }
    baseTrackingBranch := baseBranch
    if baseRemote, err := remotes.FindByRepo(baseRepo.RepoOwner(), baseRepo.RepoName()); err == nil {
    baseTrackingBranch = fmt.Sprintf("%s/%s", baseRemote.Name, baseBranch)
    }
    return &CreateContext{
    BaseRepo: baseRepo,
    HeadRepo: headRepo,
    BaseBranch: baseBranch,
    BaseTrackingBranch: baseTrackingBranch,
    HeadBranch: headBranch,
    HeadBranchLabel: headBranchLabel,
    HeadRemote: headRemote,
    IsPushEnabled: isPushEnabled,
    RepoContext: repoContext,
    Client: client,
    GitClient: gitClient,
    }, nil
    }

    It is here we see validation for a variety of cases including some checking around the --base and --head arguments:

    baseBranch := opts.BaseBranch
    if baseBranch == "" {
    baseBranch = baseRepo.DefaultBranchRef.Name
    }
    if headBranch == baseBranch && headRepo != nil && ghrepo.IsSame(baseRepo, headRepo) {
    return nil, fmt.Errorf("must be on a branch named differently than %q", baseBranch)
    }
    baseTrackingBranch := baseBranch
    if baseRemote, err := remotes.FindByRepo(baseRepo.RepoOwner(), baseRepo.RepoName()); err == nil {
    baseTrackingBranch = fmt.Sprintf("%s/%s", baseRemote.Name, baseBranch)
    }

    Thoughts

    1. gh passes your head branch argument, which is a local reference to a remote reference, straight to the GitHub API when creating the PR causes this to error
    2. NewCreateContext logic seems like it can be enhanced to detect if --base or --head are remote references which don't make sense in this context
  5. added
    priority-3
    gh-pr
    and removed
    needs-triage
    on Aug 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    buggh-prpriority-3

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions