github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/review/git-codereview/submit.go (about)

     1  // Copyright 2014 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"os"
    11  	"strings"
    12  	"time"
    13  )
    14  
    15  // TODO(rsc): Add -tbr, along with standard exceptions (doc/go1.5.txt)
    16  
    17  func cmdSubmit(args []string) {
    18  	var interactive bool
    19  	flags.BoolVar(&interactive, "i", false, "interactively select commits to submit")
    20  	flags.Usage = func() {
    21  		fmt.Fprintf(stderr(), "Usage: %s submit %s [-i | commit-hash...]\n", os.Args[0], globalFlags)
    22  	}
    23  	flags.Parse(args)
    24  	if interactive && flags.NArg() > 0 {
    25  		flags.Usage()
    26  		os.Exit(2)
    27  	}
    28  
    29  	b := CurrentBranch()
    30  	var cs []*Commit
    31  	if interactive {
    32  		hashes := submitHashes(b)
    33  		if len(hashes) == 0 {
    34  			printf("nothing to submit")
    35  			return
    36  		}
    37  		for _, hash := range hashes {
    38  			cs = append(cs, b.CommitByHash("submit", hash))
    39  		}
    40  	} else if args := flags.Args(); len(args) >= 1 {
    41  		for _, arg := range args {
    42  			cs = append(cs, b.CommitByHash("submit", arg))
    43  		}
    44  	} else {
    45  		cs = append(cs, b.DefaultCommit("submit"))
    46  	}
    47  
    48  	// No staged changes.
    49  	// Also, no unstaged changes, at least for now.
    50  	// This makes sure the sync at the end will work well.
    51  	// We can relax this later if there is a good reason.
    52  	checkStaged("submit")
    53  	checkUnstaged("submit")
    54  
    55  	// Submit the changes.
    56  	var g *GerritChange
    57  	for _, c := range cs {
    58  		printf("submitting %s %s", c.ShortHash, c.Subject)
    59  		g = submit(b, c)
    60  	}
    61  
    62  	// Sync client to revision that Gerrit committed, but only if we can do it cleanly.
    63  	// Otherwise require user to run 'git sync' themselves (if they care).
    64  	run("git", "fetch", "-q")
    65  	if len(cs) == 1 && len(b.Pending()) == 1 {
    66  		if err := runErr("git", "checkout", "-q", "-B", b.Name, g.CurrentRevision, "--"); err != nil {
    67  			dief("submit succeeded, but cannot sync local branch\n"+
    68  				"\trun 'git sync' to sync, or\n"+
    69  				"\trun 'git branch -D %s; git change master; git sync' to discard local branch", b.Name)
    70  		}
    71  	} else {
    72  		printf("submit succeeded; run 'git sync' to sync")
    73  	}
    74  
    75  	// Done! Change is submitted, branch is up to date, ready for new work.
    76  }
    77  
    78  // submit submits a single commit c on branch b and returns the
    79  // GerritChange for the submitted change. It dies if the submit fails.
    80  func submit(b *Branch, c *Commit) *GerritChange {
    81  	// Fetch Gerrit information about this change.
    82  	g, err := b.GerritChange(c, "LABELS", "CURRENT_REVISION")
    83  	if err != nil {
    84  		dief("%v", err)
    85  	}
    86  
    87  	// Pre-check that this change appears submittable.
    88  	// The final submit will check this too, but it is better to fail now.
    89  	if err = submitCheck(g); err != nil {
    90  		dief("cannot submit: %v", err)
    91  	}
    92  
    93  	// Upload most recent revision if not already on server.
    94  
    95  	if c.Hash != g.CurrentRevision {
    96  		run("git", "push", "-q", "origin", b.PushSpec(c))
    97  
    98  		// Refetch change information, especially mergeable.
    99  		g, err = b.GerritChange(c, "LABELS", "CURRENT_REVISION")
   100  		if err != nil {
   101  			dief("%v", err)
   102  		}
   103  	}
   104  
   105  	// Don't bother if the server can't merge the changes.
   106  	if !g.Mergeable {
   107  		// Server cannot merge; explicit sync is needed.
   108  		dief("cannot submit: conflicting changes submitted, run 'git sync'")
   109  	}
   110  
   111  	if *noRun {
   112  		printf("stopped before submit")
   113  		return g
   114  	}
   115  
   116  	// Otherwise, try the submit. Sends back updated GerritChange,
   117  	// but we need extended information and the reply is in the
   118  	// "SUBMITTED" state anyway, so ignore the GerritChange
   119  	// in the response and fetch a new one below.
   120  	if err := gerritAPI("/a/changes/"+fullChangeID(b, c)+"/submit", []byte(`{"wait_for_merge": true}`), nil); err != nil {
   121  		dief("cannot submit: %v", err)
   122  	}
   123  
   124  	// It is common to get back "SUBMITTED" for a split second after the
   125  	// request is made. That indicates that the change has been queued for submit,
   126  	// but the first merge (the one wait_for_merge waited for)
   127  	// failed, possibly due to a spurious condition. We see this often, and the
   128  	// status usually changes to MERGED shortly thereafter.
   129  	// Wait a little while to see if we can get to a different state.
   130  	const steps = 6
   131  	const max = 2 * time.Second
   132  	for i := 0; i < steps; i++ {
   133  		time.Sleep(max * (1 << uint(i+1)) / (1 << steps))
   134  		g, err = b.GerritChange(c, "LABELS", "CURRENT_REVISION")
   135  		if err != nil {
   136  			dief("waiting for merge: %v", err)
   137  		}
   138  		if g.Status != "SUBMITTED" {
   139  			break
   140  		}
   141  	}
   142  
   143  	switch g.Status {
   144  	default:
   145  		dief("submit error: unexpected post-submit Gerrit change status %q", g.Status)
   146  
   147  	case "MERGED":
   148  		// good
   149  
   150  	case "SUBMITTED":
   151  		// see above
   152  		dief("cannot submit: timed out waiting for change to be submitted by Gerrit")
   153  	}
   154  
   155  	return g
   156  }
   157  
   158  // submitCheck checks that g should be submittable. This is
   159  // necessarily a best-effort check.
   160  //
   161  // g must have the "LABELS" option.
   162  func submitCheck(g *GerritChange) error {
   163  	// Check Gerrit change status.
   164  	switch g.Status {
   165  	default:
   166  		return fmt.Errorf("unexpected Gerrit change status %q", g.Status)
   167  
   168  	case "NEW", "SUBMITTED":
   169  		// Not yet "MERGED", so try the submit.
   170  		// "SUBMITTED" is a weird state. It means that Submit has been clicked once,
   171  		// but it hasn't happened yet, usually because of a merge failure.
   172  		// The user may have done git sync and may now have a mergable
   173  		// copy waiting to be uploaded, so continue on as if it were "NEW".
   174  
   175  	case "MERGED":
   176  		// Can happen if moving between different clients.
   177  		return fmt.Errorf("change already submitted, run 'git sync'")
   178  
   179  	case "ABANDONED":
   180  		return fmt.Errorf("change abandoned")
   181  	}
   182  
   183  	// Check for label approvals (like CodeReview+2).
   184  	for _, name := range g.LabelNames() {
   185  		label := g.Labels[name]
   186  		if label.Optional {
   187  			continue
   188  		}
   189  		if label.Rejected != nil {
   190  			return fmt.Errorf("change has %s rejection", name)
   191  		}
   192  		if label.Approved == nil {
   193  			return fmt.Errorf("change missing %s approval", name)
   194  		}
   195  	}
   196  
   197  	return nil
   198  }
   199  
   200  // submitHashes interactively prompts for commits to submit.
   201  func submitHashes(b *Branch) []string {
   202  	// Get pending commits on b.
   203  	pending := b.Pending()
   204  	for _, c := range pending {
   205  		// Note that DETAILED_LABELS does not imply LABELS.
   206  		c.g, c.gerr = b.GerritChange(c, "CURRENT_REVISION", "LABELS", "DETAILED_LABELS")
   207  		if c.g == nil {
   208  			c.g = new(GerritChange)
   209  		}
   210  	}
   211  
   212  	// Construct submit script.
   213  	var script bytes.Buffer
   214  	for i := len(pending) - 1; i >= 0; i-- {
   215  		c := pending[i]
   216  
   217  		if c.g.ID == "" {
   218  			fmt.Fprintf(&script, "# change not on Gerrit:\n#")
   219  		} else if err := submitCheck(c.g); err != nil {
   220  			fmt.Fprintf(&script, "# %v:\n#", err)
   221  		}
   222  
   223  		formatCommit(&script, c, true)
   224  	}
   225  
   226  	fmt.Fprintf(&script, `
   227  # The above commits will be submitted in order from top to bottom
   228  # when you exit the editor.
   229  #
   230  # These lines can be re-ordered, removed, and commented out.
   231  #
   232  # If you remove all lines, the submit will be aborted.
   233  `)
   234  
   235  	// Edit the script.
   236  	final := editor(script.String())
   237  
   238  	// Parse the final script.
   239  	var hashes []string
   240  	for _, line := range lines(final) {
   241  		line := strings.TrimSpace(line)
   242  		if len(line) == 0 || line[0] == '#' {
   243  			continue
   244  		}
   245  		if i := strings.Index(line, " "); i >= 0 {
   246  			line = line[:i]
   247  		}
   248  		hashes = append(hashes, line)
   249  	}
   250  
   251  	return hashes
   252  }