Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert logging to slog #25

Merged
merged 7 commits into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions cmd/labelPRs.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package cmd

import (
"log"
"time"

"github.com/chia-network/go-modules/pkg/slogs"
"github.com/google/go-github/v60/github"
"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -17,26 +17,27 @@ var labelPRsCmd = &cobra.Command{
Use: "label-prs",
Short: "Adds community and internal labels to pull requests in designated repos",
Run: func(cmd *cobra.Command, args []string) {
slogs.Init("info")
cfg, err := config.LoadConfig(viper.GetString("config"))
if err != nil {
log.Fatalf("error loading config: %s\n", err.Error())
slogs.Logr.Fatal("Error loading config", "error", err)
}
client := github.NewClient(nil).WithAuthToken(cfg.GithubToken)

loop := viper.GetBool("loop")
loopDuration := viper.GetDuration("loop-time")
for {
log.Println("Labeling Pull Requests")
slogs.Logr.Info("Labeling Pull Requests")
err = label.PullRequests(client, cfg)
if err != nil {
log.Fatalln(err.Error())
slogs.Logr.Fatal("Error labeling pull requests", "error", err)
}

if !loop {
break
}

log.Printf("Waiting %s for next iteration\n", loopDuration.String())
slogs.Logr.Info("Waiting for next iteration", "duration", loopDuration.String())
time.Sleep(loopDuration)
}
},
Expand Down
32 changes: 17 additions & 15 deletions cmd/notifyPendingCI.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cmd
import (
"context"
"fmt"
"log"
"time"

"github.com/google/go-github/v60/github"
Expand All @@ -14,15 +13,18 @@ import (
"github.com/chia-network/github-bot/internal/database"
github2 "github.com/chia-network/github-bot/internal/github"
"github.com/chia-network/github-bot/internal/keybase"

"github.com/chia-network/go-modules/pkg/slogs"
)

var notifyPendingCICmd = &cobra.Command{
Use: "notify-pendingci",
Short: "Sends a Keybase message to a channel, alerting that a community PR is ready for CI to run",
Run: func(cmd *cobra.Command, args []string) {
slogs.Init("info")
cfg, err := config.LoadConfig(viper.GetString("config"))
if err != nil {
log.Fatalf("error loading config: %s\n", err.Error())
slogs.Logr.Fatal("Error loading config", "error", err)
}
client := github.NewClient(nil).WithAuthToken(cfg.GithubToken)

Expand All @@ -36,7 +38,7 @@ var notifyPendingCICmd = &cobra.Command{
)

if err != nil {
log.Printf("[ERROR] Could not initialize mysql connection: %s", err.Error())
slogs.Logr.Error("Could not initialize mysql connection", "error", err)
return
}

Expand All @@ -47,57 +49,57 @@ var notifyPendingCICmd = &cobra.Command{
sendMsgDuration := 24 * time.Hour

for {
log.Println("Checking for community PRs that are waiting for CI to run")
slogs.Logr.Info("Checking for community PRs that are waiting for CI to run")
listPendingPRs, err := github2.CheckForPendingCI(ctx, client, cfg)
if err != nil {
log.Printf("The following error occurred while obtaining a list of pending PRs: %s", err)
slogs.Logr.Error("Error obtaining a list of pending PRs", "error", err)
time.Sleep(loopDuration)
continue
}

for _, pr := range listPendingPRs {
prInfo, err := datastore.GetPRData(pr.Repo, int64(pr.PRNumber))
if err != nil {
log.Printf("Error checking PR info in database: %v", err)
slogs.Logr.Error("Error checking PR info in database", "error", err)
continue
}

shouldSendMessage := false
if prInfo == nil {
// New PR, record it and send a message
log.Printf("Storing data in db")
slogs.Logr.Info("Storing data in db")
err := datastore.StorePRData(pr.Repo, int64(pr.PRNumber))
if err != nil {
log.Printf("Error storing PR data: %v", err)
slogs.Logr.Error("Error storing PR data", "error", err)
continue
}
shouldSendMessage = true
} else if time.Since(prInfo.LastMessageSent) > sendMsgDuration {
// 24 hours has elapsed since the last message was issues, update the record and send a message
log.Printf("Storing data in db")
// 24 hours has elapsed since the last message was issued, update the record and send a message
slogs.Logr.Info("Updating last_message_sent time in db")
err := datastore.StorePRData(pr.Repo, int64(pr.PRNumber))
if err != nil {
log.Printf("Error updating PR data: %v", err)
slogs.Logr.Error("Error updating PR data", "error", err)
continue
}
shouldSendMessage = true
}

if shouldSendMessage {
message := fmt.Sprintf("The following pull request is waiting for approval for CI checks to run: %s", pr.URL)
log.Printf("Sending message via keybase")
slogs.Logr.Info("Sending message via keybase")
if err := keybase.SendKeybaseMsg(message); err != nil {
log.Printf("Failed to send message: %s", err)
slogs.Logr.Error("Failed to send message", "error", err)
} else {
log.Printf("Message sent for PR: %s", pr.URL)
slogs.Logr.Info("Message sent for PR", "URL", pr.URL)
}
}
}

if !loop {
break
}
log.Printf("Waiting %s for next iteration\n", loopDuration.String())
slogs.Logr.Info("Waiting for next iteration", "duration", loopDuration.String())
time.Sleep(loopDuration)
}
},
Expand Down
30 changes: 16 additions & 14 deletions cmd/notifyStale.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cmd
import (
"context"
"fmt"
"log"
"time"

"github.com/google/go-github/v60/github"
Expand All @@ -14,15 +13,18 @@ import (
"github.com/chia-network/github-bot/internal/database"
github2 "github.com/chia-network/github-bot/internal/github"
"github.com/chia-network/github-bot/internal/keybase"

"github.com/chia-network/go-modules/pkg/slogs"
)

var notifyStaleCmd = &cobra.Command{
Use: "notify-stale",
Short: "Sends a Keybase message to a channel, alerting that a community PR has not been updated in 7 days",
Run: func(cmd *cobra.Command, args []string) {
slogs.Init("info")
cfg, err := config.LoadConfig(viper.GetString("config"))
if err != nil {
log.Fatalf("error loading config: %s\n", err.Error())
slogs.Logr.Fatal("Error loading config", "error", err)
}
client := github.NewClient(nil).WithAuthToken(cfg.GithubToken)

Expand All @@ -36,57 +38,57 @@ var notifyStaleCmd = &cobra.Command{
)

if err != nil {
log.Printf("[ERROR] Could not initialize mysql connection: %s", err.Error())
slogs.Logr.Error("Could not initialize mysql connection", "error", err)
return
}
loop := viper.GetBool("loop")
loopDuration := viper.GetDuration("loop-time")
sendMsgDuration := 24 * time.Hour // Define the sendMsgDuration
ctx := context.Background()
for {
log.Println("Checking for community PRs that have no update in the last 7 days")
slogs.Logr.Info("Checking for community PRs that have no update in the last 7 days")
listPendingPRs, err := github2.CheckStalePRs(ctx, client, cfg)
if err != nil {
log.Printf("The following error occurred while obtaining a list of stale PRs: %s", err)
slogs.Logr.Error("Error checking PR info in database", "error", err)
time.Sleep(loopDuration)
continue
}

for _, pr := range listPendingPRs {
prInfo, err := datastore.GetPRData(pr.Repo, int64(pr.PRNumber))
if err != nil {
log.Printf("Error checking PR info in database: %v", err)
slogs.Logr.Error("Error checking PR info in database", "error", err)
continue
}

shouldSendMessage := false
if prInfo == nil {
// New PR, record it and send a message
log.Printf("Storing data in db")
slogs.Logr.Info("Storing data in db")
err := datastore.StorePRData(pr.Repo, int64(pr.PRNumber))
if err != nil {
log.Printf("Error storing PR data: %v", err)
slogs.Logr.Error("Error storing PR data", "error", err)
continue
}
shouldSendMessage = true
} else if time.Since(prInfo.LastMessageSent) > sendMsgDuration {
// 24 hours has elapsed since the last message was issued, update the record and send a message
log.Printf("Updating last_message_sent time in db")
slogs.Logr.Info("Updating last_message_sent time in db")
err := datastore.StorePRData(pr.Repo, int64(pr.PRNumber))
if err != nil {
log.Printf("Error updating PR data: %v", err)
slogs.Logr.Error("Error updating PR data", "error", err)
continue
}
shouldSendMessage = true
}

if shouldSendMessage {
message := fmt.Sprintf("The following pull request is waiting for approval for CI checks to run: %s", pr.URL)
log.Printf("Sending message via keybase")
slogs.Logr.Info("Sending message via keybase")
if err := keybase.SendKeybaseMsg(message); err != nil {
log.Printf("Failed to send message: %s", err)
slogs.Logr.Error("Failed to send message", "error", err)
} else {
log.Printf("Message sent for PR: %s", pr.URL)
slogs.Logr.Info("Message sent for PR", "URL", pr.URL)
}
}
}
Expand All @@ -95,7 +97,7 @@ var notifyStaleCmd = &cobra.Command{
break
}

log.Printf("Waiting %s for next iteration\n", loopDuration.String())
slogs.Logr.Info("Waiting for next iteration", "duration", loopDuration.String())
time.Sleep(loopDuration)
}
},
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/chia-network/github-bot
go 1.22.1

require (
github.com/chia-network/go-modules v0.0.5
github.com/go-sql-driver/mysql v1.4.1
github.com/google/go-github/v60 v60.0.0
github.com/spf13/cobra v1.8.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/chia-network/go-modules v0.0.5 h1:5luTVlP6RgBXodnFcWFBk2sLdJn+6vQ4wObim683C7c=
github.com/chia-network/go-modules v0.0.5/go.mod h1:5AiYBxQSvf2aFSOizTqFXXSeb9AucZWrWmRCVwUMO3A=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down
24 changes: 12 additions & 12 deletions internal/github/checkPendingCI.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import (
"strings"
"time"

"github.com/chia-network/go-modules/pkg/slogs"
"github.com/google/go-github/v60/github" // Ensure your go-github library version matches

"github.com/chia-network/github-bot/internal/config"
log "github.com/chia-network/github-bot/internal/logger"
)

// PendingPR holds information about pending PRs
Expand All @@ -25,10 +25,10 @@ func CheckForPendingCI(ctx context.Context, githubClient *github.Client, cfg *co
var pendingPRs []PendingPR

for _, fullRepo := range cfg.CheckRepos {
log.Logger.Info("Checking repository", "repository", fullRepo.Name)
slogs.Logr.Info("Checking repository", "repository", fullRepo.Name)
parts := strings.Split(fullRepo.Name, "/")
if len(parts) != 2 {
log.Logger.Error("Invalid repository name - must contain owner and repository", "repository", fullRepo.Name)
slogs.Logr.Error("Invalid repository name - must contain owner and repository", "repository", fullRepo.Name)
continue
}
owner, repo := parts[0], parts[1]
Expand All @@ -45,37 +45,37 @@ func CheckForPendingCI(ctx context.Context, githubClient *github.Client, cfg *co
// Dynamic cutoff time based on the last commit to the PR
lastCommitTime, err := getLastCommitTime(prctx, githubClient, owner, repo, pr.GetNumber())
if err != nil {
log.Logger.Error("Error retrieving last commit time", "PR", pr.GetNumber(), "repository", fullRepo.Name, "error", err)
slogs.Logr.Error("Error retrieving last commit time", "PR", pr.GetNumber(), "repository", fullRepo.Name, "error", err)
continue
}
cutoffTime := lastCommitTime.Add(2 * time.Hour) // 2 hours after the last commit

if time.Now().Before(cutoffTime) {
log.Logger.Info("Skipping PR as it's still within the 2-hour window from the last commit", "PR", pr.GetNumber(), "repository", fullRepo.Name)
slogs.Logr.Info("Skipping PR as it's still within the 2-hour window from the last commit", "PR", pr.GetNumber(), "repository", fullRepo.Name)
continue
}

hasCIRuns, err := checkCIStatus(prctx, githubClient, owner, repo, pr.GetNumber())
if err != nil {
log.Logger.Error("Error checking CI status", "PR", pr.GetNumber(), "repository", fullRepo.Name, "error", err)
slogs.Logr.Error("Error checking CI status", "PR", pr.GetNumber(), "repository", fullRepo.Name, "error", err)
continue
}

teamMemberActivity, err := checkTeamMemberActivity(prctx, githubClient, owner, repo, pr.GetNumber(), teamMembers, lastCommitTime)
if err != nil {
log.Logger.Error("Error checking team member activity", "PR", pr.GetNumber(), "repository", fullRepo.Name, "error", err)
slogs.Logr.Error("Error checking team member activity", "PR", pr.GetNumber(), "repository", fullRepo.Name, "error", err)
continue // or handle the error as needed
}

if !hasCIRuns && !teamMemberActivity {
log.Logger.Info("PR is ready for CI and no CI actions have started yet, or it requires re-approval", "PR", pr.GetNumber(), "repository", fullRepo.Name, "user", pr.User.GetLogin(), "created_at", pr.CreatedAt)
slogs.Logr.Info("PR is ready for CI and no CI actions have started yet, or it requires re-approval", "PR", pr.GetNumber(), "repository", fullRepo.Name, "user", pr.User.GetLogin(), "created_at", pr.CreatedAt)
pendingPRs = append(pendingPRs, PendingPR{
Repo: repo,
PRNumber: pr.GetNumber(),
URL: pr.GetHTMLURL(),
})
} else {
log.Logger.Info("PR is not ready for CI approvals",
slogs.Logr.Info("PR is not ready for CI approvals",
"PR", pr.GetNumber(),
"repository", fullRepo.Name)
}
Expand All @@ -102,7 +102,7 @@ func getLastCommitTime(ctx context.Context, client *github.Client, owner, repo s
if commitTime == nil {
return time.Time{}, fmt.Errorf("commit time is nil for PR #%d of repo %s", prNumber, repo)
}
log.Logger.Info("The last commit time", "time", commitTime.Format(time.RFC3339), "PR", prNumber, "repository", repo)
slogs.Logr.Info("The last commit time", "time", commitTime.Format(time.RFC3339), "PR", prNumber, "repository", repo)

return *commitTime, nil // Safely dereference *time.Time to get time.Time
}
Expand Down Expand Up @@ -136,9 +136,9 @@ func checkTeamMemberActivity(ctx context.Context, client *github.Client, owner,
}

for _, comment := range comments {
log.Logger.Info("Checking comment by team member", "user", comment.User.GetLogin(), "created_at", comment.CreatedAt.Format(time.RFC3339), "PR", prNumber, "repository", repo)
slogs.Logr.Info("Checking comment by team member", "user", comment.User.GetLogin(), "created_at", comment.CreatedAt.Format(time.RFC3339), "PR", prNumber, "repository", repo)
if _, ok := teamMembers[comment.User.GetLogin()]; ok && comment.CreatedAt.After(lastCommitTime) {
log.Logger.Info("Found team member comment after last commit time", "time", comment.CreatedAt.Format(time.RFC3339), "PR", prNumber, "repository", repo)
slogs.Logr.Info("Found team member comment after last commit time", "time", comment.CreatedAt.Format(time.RFC3339), "PR", prNumber, "repository", repo)
// Check if the comment is after the last commit
return true, nil // Active and relevant participation
}
Expand Down
Loading