cmd/watchflakes: post new issues to GitHub at the end

Currently, if -post is set, when we encounter a new issue, it
immediately creates an issue on GitHub. This CL changes it to post
at end. This gives us a chance to modify the new issue before
posting. This also makes posting actions together.

Change-Id: I8252b0fde0373134378e61c440b5b62c3cdc514d
Reviewed-on: https://go-review.googlesource.com/c/build/+/602375
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
diff --git a/cmd/watchflakes/github.go b/cmd/watchflakes/github.go
index 938b0f8..3314ebe 100644
--- a/cmd/watchflakes/github.go
+++ b/cmd/watchflakes/github.go
@@ -237,9 +237,10 @@
 	return b.String()
 }
 
-// reportNew creates and returns a new issue for reporting the failure.
-// If *post is false, reportNew returns a fake issue with number 0.
-func reportNew(fp *FailurePost) (*Issue, error) {
+// prepareNew creates and returns a new issue for reporting the failure.
+// It doesn't post the issue to GitHub. If *post is true, one needs to
+// call postNew to post.
+func prepareNew(fp *FailurePost) (*Issue, error) {
 	var pattern, title string
 	if fp.Pkg != "" {
 		pattern = fmt.Sprintf("pkg == %q && test == %q", fp.Pkg, fp.Test)
@@ -272,11 +273,7 @@
 	}
 
 	issue := new(Issue)
-	if *post {
-		issue.Issue = newIssue(title, msg.String())
-	} else {
-		issue.Issue = &github.Issue{Title: title, Body: msg.String()}
-	}
+	issue.Issue = &github.Issue{Title: title, Body: msg.String()}
 	findScript(issue)
 	if issue.Error != "" {
 		return nil, fmt.Errorf("cannot find script in generated issue:\nBody:\n%s\n\nError:\n%s", issue.Body, issue.Error)
@@ -333,11 +330,11 @@
 	issue.Stale = false
 }
 
-// newIssue creates a new issue with the given title and body,
+// postNew creates a new issue with the given title and body,
 // setting the NeedsInvestigation label and placing the issue int
 // the Test Flakes project.
 // It automatically adds signature to the body.
-func newIssue(title, body string) *github.Issue {
+func postNew(title, body string) *github.Issue {
 	var args []any
 	if lab := labels["NeedsInvestigation"]; lab != nil {
 		args = append(args, lab)
diff --git a/cmd/watchflakes/main.go b/cmd/watchflakes/main.go
index 23e36a5..7257db4 100644
--- a/cmd/watchflakes/main.go
+++ b/cmd/watchflakes/main.go
@@ -201,7 +201,7 @@
 					if *verbose {
 						fmt.Printf("%s: new issue\n", fp.URL)
 					}
-					issue, err := reportNew(fp)
+					issue, err := prepareNew(fp)
 					if err != nil {
 						log.Fatal(err)
 					}
@@ -249,6 +249,9 @@
 	posts := 0
 	for _, issue := range issues {
 		if len(issue.Post) > 0 {
+			if *post && issue.Number == 0 {
+				issue.Issue = postNew(issue.Title, issue.Body)
+			}
 			fmt.Printf(" - new for #%d %s\n", issue.Number, issue.Title)
 			for _, fp := range issue.Post {
 				fmt.Printf("    - %s\n      %s\n", fp, fp.URL)