Skip to content
Open
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
1 change: 1 addition & 0 deletions csharp/Platform.Bot/Platform.Bot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="Discord.Net" Version="3.15.3" />
<PackageReference Include="Octokit" Version="7.0.1" />
<PackageReference Include="Platform.Communication.Protocol.Lino" Version="0.4.0" />
<PackageReference Include="Platform.Data.Doublets.Sequences" Version="0.1.1" />
Expand Down
39 changes: 35 additions & 4 deletions csharp/Platform.Bot/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using Platform.Bot.Trackers;
using Platform.Bot.Triggers;
using Platform.Bot.Triggers.Decorators;
using Platform.Bot.Services;

namespace Platform.Bot
{
Expand Down Expand Up @@ -73,29 +74,59 @@ private static async Task<int> Main(string[] args)
description: "Minimum interaction interval in seconds.",
getDefaultValue: () => 60);

var discordBotTokenOption = new Option<string?>(
name: "--discord-bot-token",
description: "Discord bot token for role synchronization.");

var enableFlowsSyncOption = new Option<bool>(
name: "--enable-flows-sync",
description: "Enable flows order sync functionality.",
getDefaultValue: () => true);

var rootCommand = new RootCommand("Sample app for System.CommandLine")
{
githubUserNameOption,
githubApiTokenOption,
githubApplicationNameOption,
databaseFilePathOption,
fileSetNameOption,
minimumInteractionIntervalOption
minimumInteractionIntervalOption,
discordBotTokenOption,
enableFlowsSyncOption
};

rootCommand.SetHandler(async (githubUserName, githubApiToken, githubApplicationName, databaseFilePath, fileSetName, minimumInteractionInterval) =>
rootCommand.SetHandler(async (githubUserName, githubApiToken, githubApplicationName, databaseFilePath, fileSetName, minimumInteractionInterval, discordBotToken, enableFlowsSync) =>
{
Debug.WriteLine($"Nickname: {githubUserName}");
Debug.WriteLine($"GitHub API Token: {githubApiToken}");
Debug.WriteLine($"Application Name: {githubApplicationName}");
Debug.WriteLine($"Database File Path: {databaseFilePath?.FullName}");
Debug.WriteLine($"File Set Name: {fileSetName}");
Debug.WriteLine($"Minimum Interaction Interval: {minimumInteractionInterval} seconds");
Debug.WriteLine($"Discord Bot Token: {(string.IsNullOrEmpty(discordBotToken) ? "Not provided" : "Provided")}");
Debug.WriteLine($"Flows Sync Enabled: {enableFlowsSync}");

var dbContext = new FileStorage(databaseFilePath?.FullName ?? new TemporaryFile().Filename);
Console.WriteLine($"Bot has been started. {Environment.NewLine}Press CTRL+C to close");
var githubStorage = new GitHubStorage(githubUserName, githubApiToken, githubApplicationName);
var issueTracker = new IssueTracker(githubStorage, new HelloWorldTrigger(githubStorage, dbContext, fileSetName), new OrganizationLastMonthActivityTrigger(githubStorage), new LastCommitActivityTrigger(githubStorage), new AdminAuthorIssueTriggerDecorator(new ProtectDefaultBranchTrigger(githubStorage), githubStorage), new AdminAuthorIssueTriggerDecorator(new ChangeOrganizationRepositoriesDefaultBranchTrigger(githubStorage, dbContext), githubStorage), new AdminAuthorIssueTriggerDecorator(new ChangeOrganizationPullRequestsBaseBranchTrigger(githubStorage, dbContext), githubStorage));

var triggers = new List<ITrigger<Issue>>
{
new HelloWorldTrigger(githubStorage, dbContext, fileSetName),
new OrganizationLastMonthActivityTrigger(githubStorage),
new LastCommitActivityTrigger(githubStorage),
new AdminAuthorIssueTriggerDecorator(new ProtectDefaultBranchTrigger(githubStorage), githubStorage),
new AdminAuthorIssueTriggerDecorator(new ChangeOrganizationRepositoriesDefaultBranchTrigger(githubStorage, dbContext), githubStorage),
new AdminAuthorIssueTriggerDecorator(new ChangeOrganizationPullRequestsBaseBranchTrigger(githubStorage, dbContext), githubStorage)
};

if (enableFlowsSync)
{
var discordService = new DiscordRoleSyncService(discordBotToken ?? string.Empty);
triggers.Add(new AdminAuthorIssueTriggerDecorator(new FlowsOrderSyncTrigger(githubStorage, dbContext, discordService), githubStorage));
}

var issueTracker = new IssueTracker(githubStorage, triggers.ToArray());
var pullRequenstTracker = new PullRequestTracker(githubStorage, new MergeDependabotBumpsTrigger(githubStorage));
var timestampTracker = new DateTimeTracker(githubStorage, new CreateAndSaveOrganizationRepositoriesMigrationTrigger(githubStorage, dbContext, Path.Combine(Directory.GetCurrentDirectory(), "/github-migrations")));
var cancellation = new CancellationTokenSource();
Expand All @@ -114,7 +145,7 @@ private static async Task<int> Main(string[] args)
}
}
},
githubUserNameOption, githubApiTokenOption, githubApplicationNameOption, databaseFilePathOption, fileSetNameOption, minimumInteractionIntervalOption);
githubUserNameOption, githubApiTokenOption, githubApplicationNameOption, databaseFilePathOption, fileSetNameOption, minimumInteractionIntervalOption, discordBotTokenOption, enableFlowsSyncOption);

return await rootCommand.InvokeAsync(args);
}
Expand Down
169 changes: 169 additions & 0 deletions csharp/Platform.Bot/Services/ContributionTrackingService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
using Octokit;
using Storage.Remote.GitHub;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Platform.Bot.Services
{
public class UserContribution
{
public User User { get; set; } = null!;
public int CommitCount { get; set; }
public int PullRequestCount { get; set; }
public int IssueCount { get; set; }
public int CodeReviewCount { get; set; }
public double WorkScore { get; set; }
public int Rank { get; set; }
}

public class ContributionTrackingService
{
private readonly GitHubStorage _githubStorage;

public ContributionTrackingService(GitHubStorage githubStorage)
{
_githubStorage = githubStorage;
}

public async Task<List<UserContribution>> GetOrganizationContributions(string organizationName, DateTime since)
{
var allMembers = await _githubStorage.GetAllOrganizationMembers(organizationName);
var allRepositories = await _githubStorage.GetAllRepositories(organizationName);

var contributions = new Dictionary<int, UserContribution>();

foreach (var member in allMembers)
{
contributions[member.Id] = new UserContribution
{
User = member,
CommitCount = 0,
PullRequestCount = 0,
IssueCount = 0,
CodeReviewCount = 0
};
}

foreach (var repository in allRepositories.Where(r => !r.Private))
{
await TrackCommitContributions(repository, contributions, since);
await TrackPullRequestContributions(repository, contributions, since);
await TrackIssueContributions(repository, contributions, since);
await TrackCodeReviewContributions(repository, contributions, since);
}

var contributionList = contributions.Values.ToList();
CalculateWorkScores(contributionList);
AssignRanks(contributionList);

return contributionList.OrderByDescending(c => c.WorkScore).ToList();
}

private async Task TrackCommitContributions(Repository repository, Dictionary<int, UserContribution> contributions, DateTime since)
{
try
{
var commits = await _githubStorage.GetCommits(repository.Id, new CommitRequest { Since = since });
foreach (var commit in commits)
{
if (commit.Author != null && contributions.ContainsKey(commit.Author.Id))
{
contributions[commit.Author.Id].CommitCount++;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error tracking commits for repository {repository.Name}: {ex.Message}");
}
}

private async Task TrackPullRequestContributions(Repository repository, Dictionary<int, UserContribution> contributions, DateTime since)
{
try
{
var pullRequests = _githubStorage.GetPullRequests(repository.Owner.Login, repository.Name);
foreach (var pr in pullRequests.Where(pr => pr.CreatedAt >= since))
{
if (pr.User != null && contributions.ContainsKey(pr.User.Id))
{
contributions[pr.User.Id].PullRequestCount++;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error tracking pull requests for repository {repository.Name}: {ex.Message}");
}
}

private async Task TrackIssueContributions(Repository repository, Dictionary<int, UserContribution> contributions, DateTime since)
{
try
{
var issues = _githubStorage.GetIssues(repository.Owner.Login, repository.Name);
foreach (var issue in issues.Where(i => i.CreatedAt >= since))
{
if (issue.User != null && contributions.ContainsKey(issue.User.Id))
{
contributions[issue.User.Id].IssueCount++;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error tracking issues for repository {repository.Name}: {ex.Message}");
}
}

private async Task TrackCodeReviewContributions(Repository repository, Dictionary<int, UserContribution> contributions, DateTime since)
{
try
{
var pullRequests = _githubStorage.GetPullRequests(repository.Owner.Login, repository.Name);
foreach (var pr in pullRequests.Where(pr => pr.CreatedAt >= since))
{
foreach (var reviewer in pr.RequestedReviewers)
{
if (contributions.ContainsKey(reviewer.Id))
{
contributions[reviewer.Id].CodeReviewCount++;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error tracking code reviews for repository {repository.Name}: {ex.Message}");
}
}

private void CalculateWorkScores(List<UserContribution> contributions)
{
const double commitWeight = 1.0;
const double pullRequestWeight = 3.0;
const double issueWeight = 1.5;
const double codeReviewWeight = 2.0;

foreach (var contribution in contributions)
{
contribution.WorkScore =
(contribution.CommitCount * commitWeight) +
(contribution.PullRequestCount * pullRequestWeight) +
(contribution.IssueCount * issueWeight) +
(contribution.CodeReviewCount * codeReviewWeight);
}
}

private void AssignRanks(List<UserContribution> contributions)
{
var sortedContributions = contributions.OrderByDescending(c => c.WorkScore).ToList();
for (int i = 0; i < sortedContributions.Count; i++)
{
sortedContributions[i].Rank = i + 1;
}
}
}
}
Loading
Loading