From de16ad0df8a4e4139736530c4ff7104410678790 Mon Sep 17 00:00:00 2001 From: Saumit Date: Fri, 13 Dec 2024 23:53:15 +0530 Subject: Adding commit count comparer --- main.go | 68 ++++++++++++++++++++++++++----------- main2.go | 115 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 20 deletions(-) create mode 100644 main2.go diff --git a/main.go b/main.go index 7110457..6ff0df4 100644 --- a/main.go +++ b/main.go @@ -9,11 +9,6 @@ import ( "time" ) -// Define the structure for GitHub commit activity response -type CommitActivity struct { - Total int `json:"total"` -} - // Function to fetch the user's commit count func getCommitCount(username string) (int, error) { // Set up the request URL @@ -64,31 +59,64 @@ func getCommitCount(username string) (int, error) { return int(totalCommits), nil } -// API handler for fetching commit count -func commitCountHandler(w http.ResponseWriter, r *http.Request) { - // Get the username from query parameters - username := r.URL.Query().Get("username") - if username == "" { - http.Error(w, "username parameter is required", http.StatusBadRequest) +// API handler for fetching commit difference and daily average +func commitDifferenceHandler(w http.ResponseWriter, r *http.Request) { + // Get usernames from query parameters + username1 := r.URL.Query().Get("username1") + username2 := r.URL.Query().Get("username2") + + if username1 == "" || username2 == "" { + http.Error(w, "Both username1 and username2 parameters are required", http.StatusBadRequest) + return + } + + // Fetch commit counts for both users + count1, err := getCommitCount(username1) + if err != nil { + http.Error(w, fmt.Sprintf("Error fetching commits for %s: %v", username1, err), http.StatusInternalServerError) return } - // Fetch the commit count - count, err := getCommitCount(username) + count2, err := getCommitCount(username2) if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + http.Error(w, fmt.Sprintf("Error fetching commits for %s: %v", username2, err), http.StatusInternalServerError) return } - // Return the commit count as JSON + // Calculate the difference and remaining days + difference := abs(count1 - count2) + remainingDays := daysUntilEndOfYear() + dailyAverage := difference / remainingDays + + // Return the results as JSON w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]int{"commit_count": count}) + json.NewEncoder(w).Encode(map[string]interface{}{ + "commit_count_user1": count1, + "commit_count_user2": count2, + "difference": difference, + "remaining_days": remainingDays, + "daily_average": dailyAverage, + }) +} + +// Utility function to calculate absolute value +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +// Utility function to calculate days remaining in the year +func daysUntilEndOfYear() int { + now := time.Now() + endOfYear := time.Date(now.Year(), time.December, 31, 23, 59, 59, 0, time.UTC) + return int(endOfYear.Sub(now).Hours() / 24) } func main() { // Set up the HTTP server - http.HandleFunc("/commit-count", commitCountHandler) - fmt.Println("Server is running on port 8080...") - log.Fatal(http.ListenAndServe(":8080", nil)) + http.HandleFunc("/commit-difference", commitDifferenceHandler) + fmt.Println("Server is running on port 3001...") + log.Fatal(http.ListenAndServe(":3001", nil)) } - diff --git a/main2.go b/main2.go new file mode 100644 index 0000000..fea9bcd --- /dev/null +++ b/main2.go @@ -0,0 +1,115 @@ +package main + +import ( + "encoding/json" + "fmt" + "math" + "net/http" + "os" + "time" +) + +type CommitsResponse struct { + Contestant1RequiredCommits float64 `json:"contestant_1_required_commits"` +} + +// Function to fetch the user's commit count +func getCommitCount(username string) (int, error) { + currentYear := time.Now().Year() + url := fmt.Sprintf("https://api.github.com/search/commits?q=author:%s+committer-date:%d-01-01..%d-12-31", username, currentYear, currentYear) + + // Retrieve the GitHub token from environment variables + githubToken := os.Getenv("GITHUB_TOKEN") + if githubToken == "" { + return 0, fmt.Errorf("GITHUB_TOKEN environment variable is not set") + } + + // Create a new HTTP request + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return 0, err + } + + // Add necessary headers + req.Header.Add("Accept", "application/vnd.github.cloak-preview") + req.Header.Add("Authorization", "Bearer "+githubToken) + + // Perform the request + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + + // Check if the response status code is 200 OK + if resp.StatusCode != http.StatusOK { + return 0, fmt.Errorf("GitHub API returned status: %s", resp.Status) + } + + // Parse the response body + var result struct { + TotalCount int `json:"total_count"` + } + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + return 0, err + } + + return result.TotalCount, nil +} + +// Calculate remaining days in the year +func daysUntilYearEnd() int { + today := time.Now() + endOfYear := time.Date(today.Year(), 12, 31, 23, 59, 59, 0, today.Location()) + return int(endOfYear.Sub(today).Hours() / 24) +} + +// Calculate required commits per day +func calculateRequiredCommits(commits1, commits2 int, remainingDays int) (float64) { + expectedCommits2 := float64(commits2) + float64(remainingDays) + + diffForContestant1 := math.Max(expectedCommits2-float64(commits1), 0) + + requiredCommitsPerDay1 := diffForContestant1 / float64(remainingDays) + + return requiredCommitsPerDay1 +} + +// HTTP handler for the API +func calculateCommitsHandler(w http.ResponseWriter, r *http.Request) { + + // Get commit counts for both contestants + commits1, err := getCommitCount("user1") // Replace with Contestant 1's GitHub username + if err != nil { + http.Error(w, fmt.Sprintf("Failed to fetch commits for Contestant 1: %s", err), http.StatusInternalServerError) + return + } + + commits2, err := getCommitCount("user2") // Replace with Contestant 2's GitHub username + if err != nil { + http.Error(w, fmt.Sprintf("Failed to fetch commits for Contestant 2: %s", err), http.StatusInternalServerError) + return + } + + // Calculate required commits + remainingDays := daysUntilYearEnd() + requiredCommits1 := calculateRequiredCommits(commits1, commits2, remainingDays) + + // Prepare response + response := CommitsResponse{ + Contestant1RequiredCommits: math.Round(requiredCommits1*100) / 100, // Round to 2 decimal places + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(response) +} + +func main() { + // Set up routes + http.HandleFunc("/calculate", calculateCommitsHandler) + + // Start the server + fmt.Println("Starting server on port 8080...") + http.ListenAndServe(":8080", nil) +} + -- cgit v1.2.3