Debian Codegraph @

internal/gapicgen/cmd/genbot/bot.go

raw
1 // Copyright 2021 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //go:build !windows
16 // +build !windows
17
18 package main
19
20 import (
21 "context"
22 "flag"
23 "log"
24 "time"
25
26 "cloud.google.com/go/internal/gapicgen/git"
27 )
28
29 type botConfig struct {
30 githubAccessToken string
31 githubUsername string
32 githubName string
33 githubEmail string
34 forceAll bool
35 }
36
37 func genBot(ctx context.Context, c botConfig) error {
38 for k, v := range map[string]string{
39 "githubAccessToken": c.githubAccessToken,
40 "githubUsername": c.githubUsername,
41 "githubName": c.githubName,
42 "githubEmail": c.githubEmail,
43 } {
44 if v == "" {
45 log.Printf("missing or empty value for required flag --%s\n", k)
46 flag.PrintDefaults()
47 }
48 }
49
50 // Setup the client and git environment.
51 githubClient, err := git.NewGithubClient(ctx, c.githubUsername, c.githubName, c.githubEmail, c.githubAccessToken)
52 if err != nil {
53 return err
54 }
55
56 // Check current regen status.
57 if pr, err := githubClient.GetRegenPR(ctx, "go-genproto", "open"); err != nil {
58 return err
59 } else if pr != nil {
60 log.Println("there is already a re-generation in progress")
61 return nil
62 }
63
64 log.Println("checking if a pull request was already opened and merged today")
65 if pr, err := githubClient.GetRegenPR(ctx, "go-genproto", "closed"); err != nil {
66 return err
67 } else if pr != nil && hasCreatedPRToday(pr.Created) {
68 log.Println("skipping generation, already created and merged a go-genproto PR today")
69 return nil
70 }
71 return generate(ctx, githubClient, c.forceAll)
72 }
73
74 // hasCreatedPRToday checks if the created time of a PR is from today.
75 func hasCreatedPRToday(created time.Time) bool {
76 now := time.Now()
77 today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
78 log.Printf("Times -- Now: %v\tToday: %v\tPR Created: %v", now, today, created)
79 return created.After(today)
80 }