Skip to content

Commit

Permalink
applied syntax rules
Browse files Browse the repository at this point in the history
  • Loading branch information
mackmarton committed Oct 24, 2024
1 parent 3c554ed commit 7eae16c
Show file tree
Hide file tree
Showing 43 changed files with 1,158 additions and 1,112 deletions.
Original file line number Diff line number Diff line change
@@ -1,53 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ahk.GitHub.Monitor.Services;
using Microsoft.Extensions.Caching.Memory;
using Octokit;

namespace Ahk.GitHub.Monitor.EventHandlers
namespace Ahk.GitHub.Monitor.EventHandlers;

public class ActionWorkflowRunHandler(
IGitHubClientFactory gitHubClientFactory,
IMemoryCache cache,
IServiceProvider serviceProvider)
: RepositoryEventBase<WorkflowRunEventPayload>(gitHubClientFactory, cache, serviceProvider)
{
public class ActionWorkflowRunHandler(
IGitHubClientFactory gitHubClientFactory,
IMemoryCache cache,
IServiceProvider serviceProvider)
: RepositoryEventBase<WorkflowRunEventPayload>(gitHubClientFactory, cache, serviceProvider)
{
public const int WorkflowRunThreshold = 5;
public const string GitHubWebhookEventName = "workflow_run";
public const int WorkflowRunThreshold = 5;
public const string GitHubWebhookEventName = "workflow_run";

private const string WarningText =
":exclamation: **You triggered too many automated evaluations; extra evaluations are penalized. Túl sok automata értékelést futtattál; az extra futtatások pontlevonással járnak.** ";
private const string WarningText =
":exclamation: **You triggered too many automated evaluations; extra evaluations are penalized. Túl sok automata értékelést futtattál; az extra futtatások pontlevonással járnak.** ";

protected override async Task<EventHandlerResult> executeCore(WorkflowRunEventPayload webhookPayload)
protected override async Task<EventHandlerResult> executeCore(WorkflowRunEventPayload webhookPayload)
{
if (webhookPayload.Action.Equals("completed", StringComparison.OrdinalIgnoreCase))
{
if (webhookPayload.Action.Equals("completed", StringComparison.OrdinalIgnoreCase))
if (string.IsNullOrEmpty(webhookPayload.Sender?.Login))
{
if (string.IsNullOrEmpty(webhookPayload.Sender?.Login))
return EventHandlerResult.PayloadError("missing actor user");
return EventHandlerResult.PayloadError("missing actor user");
}

if (await isUserOrganizationMember(webhookPayload, webhookPayload.Sender.Login))
return EventHandlerResult.NoActionNeeded("workflow_run ok, not triggered by student");
if (await this.isUserOrganizationMember(webhookPayload, webhookPayload.Sender.Login))
{
return EventHandlerResult.NoActionNeeded("workflow_run ok, not triggered by student");
}

var workflowRuns = await GitHubClient.CountWorkflowRunsInRepository(
webhookPayload.Repository.Owner.Login, webhookPayload.Repository.Name, webhookPayload.Sender.Login);
if (workflowRuns <= WorkflowRunThreshold)
return EventHandlerResult.NoActionNeeded("workflow_run ok, has less then threshold");
var workflowRuns = await this.GitHubClient.CountWorkflowRunsInRepository(
webhookPayload.Repository.Owner.Login, webhookPayload.Repository.Name, webhookPayload.Sender.Login);
if (workflowRuns <= WorkflowRunThreshold)
{
return EventHandlerResult.NoActionNeeded("workflow_run ok, has less then threshold");
}

var prNum = await getMostRecentPullRequest(webhookPayload);
if (prNum.HasValue)
await GitHubClient.Issue.Comment.Create(webhookPayload.Repository.Id, prNum.Value, WarningText);
return EventHandlerResult.ActionPerformed("workflow_run warning, threshold exceeded");
var prNum = await this.getMostRecentPullRequest(webhookPayload);
if (prNum.HasValue)
{
await this.GitHubClient.Issue.Comment.Create(webhookPayload.Repository.Id, prNum.Value, WarningText);
}

return EventHandlerResult.EventNotOfInterest(webhookPayload.Action);
return EventHandlerResult.ActionPerformed("workflow_run warning, threshold exceeded");
}

private async Task<int?> getMostRecentPullRequest(WorkflowRunEventPayload webhookPayload)
{
var list = await GitHubClient.PullRequest.GetAllForRepository(webhookPayload.Repository.Id,
new PullRequestRequest() { State = ItemStateFilter.All });
return list.OrderByDescending(p => p.UpdatedAt).FirstOrDefault()?.Number;
}
return EventHandlerResult.EventNotOfInterest(webhookPayload.Action);
}

private async Task<int?> getMostRecentPullRequest(WorkflowRunEventPayload webhookPayload)
{
IReadOnlyList<PullRequest> list = await this.GitHubClient.PullRequest.GetAllForRepository(
webhookPayload.Repository.Id,
new PullRequestRequest() { State = ItemStateFilter.All });
return list.OrderByDescending(p => p.UpdatedAt).FirstOrDefault()?.Number;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,57 +2,53 @@
using System.Threading.Tasks;
using Ahk.GitHub.Monitor.Services;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Octokit;

namespace Ahk.GitHub.Monitor.EventHandlers
namespace Ahk.GitHub.Monitor.EventHandlers;

public class BranchProtectionRuleHandler(
IGitHubClientFactory gitHubClientFactory,
IMemoryCache cache,
IServiceProvider serviceProvider)
: RepositoryEventBase<CreateEventPayload>(gitHubClientFactory, cache, serviceProvider)
{
public class BranchProtectionRuleHandler(
IGitHubClientFactory gitHubClientFactory,
IMemoryCache cache,
IServiceProvider serviceProvider)
: RepositoryEventBase<CreateEventPayload>(gitHubClientFactory, cache, serviceProvider)
{
public const string GitHubWebhookEventName = "create";
public const string GitHubWebhookEventName = "create";

protected override async Task<EventHandlerResult> executeCore(CreateEventPayload webhookPayload)
protected override async Task<EventHandlerResult> executeCore(CreateEventPayload webhookPayload)
{
if (!webhookPayload.RefType.StringValue.Equals("branch", StringComparison.OrdinalIgnoreCase))
{
if (!webhookPayload.RefType.StringValue.Equals("branch", StringComparison.OrdinalIgnoreCase))
{
return EventHandlerResult.NoActionNeeded(
$"create event for ref {webhookPayload.RefType} is not of interest");
}

await this.GitHubClient.Repository.Branch.UpdateBranchProtection(
webhookPayload.Repository.Id, webhookPayload.Ref,
getBranchProtectionSettingsUpdate(webhookPayload.Ref, webhookPayload.Repository.DefaultBranch));
return EventHandlerResult.ActionPerformed("branch protection rule applied");
return EventHandlerResult.NoActionNeeded(
$"create event for ref {webhookPayload.RefType} is not of interest");
}

private static BranchProtectionSettingsUpdate getBranchProtectionSettingsUpdate(string branchName,
string repositoryDefaultBranch)
{
// For default: prohibits the merge request into default to be merged
// For other branches: disables force push
return new BranchProtectionSettingsUpdate(
requiredStatusChecks: null, // Required. Require status checks to pass before merging. Set to null to disable.
requiredPullRequestReviews: getBranchProtectionRequiredReviewsUpdate(branchName,
repositoryDefaultBranch),
restrictions: null, // Push access restrictions. Null to disable.
enforceAdmins: false); // Required. Enforce all configured restrictions for administrators. Set to true to enforce required status checks for repository administrators. Set to null to disable.
}
await this.GitHubClient.Repository.Branch.UpdateBranchProtection(
webhookPayload.Repository.Id, webhookPayload.Ref,
getBranchProtectionSettingsUpdate(webhookPayload.Ref, webhookPayload.Repository.DefaultBranch));
return EventHandlerResult.ActionPerformed("branch protection rule applied");
}

private static BranchProtectionRequiredReviewsUpdate getBranchProtectionRequiredReviewsUpdate(string branchName,
string repositoryDefaultBranch)
{
if (branchName.Equals(repositoryDefaultBranch, StringComparison.OrdinalIgnoreCase))
{
return
new BranchProtectionRequiredReviewsUpdate(false, false,
1); // Prohibits the student from merging the pull request.
}
private static BranchProtectionSettingsUpdate getBranchProtectionSettingsUpdate(string branchName,
string repositoryDefaultBranch) =>
// For default: prohibits the merge request into default to be merged
// For other branches: disables force push
new(
null, // Required. Require status checks to pass before merging. Set to null to disable.
getBranchProtectionRequiredReviewsUpdate(branchName,
repositoryDefaultBranch),
null, // Push access restrictions. Null to disable.
false); // Required. Enforce all configured restrictions for administrators. Set to true to enforce required status checks for repository administrators. Set to null to disable.

return null;
private static BranchProtectionRequiredReviewsUpdate getBranchProtectionRequiredReviewsUpdate(string branchName,
string repositoryDefaultBranch)
{
if (branchName.Equals(repositoryDefaultBranch, StringComparison.OrdinalIgnoreCase))
{
return
new BranchProtectionRequiredReviewsUpdate(false, false,
1); // Prohibits the student from merging the pull request.
}

return null;
}
}
51 changes: 28 additions & 23 deletions github-monitor/Ahk.GitHub.Monitor/EventHandlers/ConfigYamlParser.cs
Original file line number Diff line number Diff line change
@@ -1,35 +1,40 @@
using System;
using System.Text.RegularExpressions;

namespace Ahk.GitHub.Monitor.EventHandlers
namespace Ahk.GitHub.Monitor.EventHandlers;

internal static class ConfigYamlParser
{
internal static class ConfigYamlParser
{
private static readonly Regex EnabledRegex = new Regex(
@"^enabled:?\s*(?<value>\w+)?",
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
private static readonly Regex EnabledRegex = new(
@"^enabled:?\s*(?<value>\w+)?",
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);

public static bool IsEnabled(string fileContent)
public static bool IsEnabled(string fileContent)
{
// missing file -> disabled
if (string.IsNullOrEmpty(fileContent))
{
// missing file -> disabled
if (string.IsNullOrEmpty(fileContent))
return false;

// file content does not match -> disabled
var m = EnabledRegex.Match(fileContent);
if (!m.Success)
return false;
return false;
}

var value = m.Groups[@"value"];
// file content does not match -> disabled
Match m = EnabledRegex.Match(fileContent);
if (!m.Success)
{
return false;
}

// no "true" or other part, just "enabled" -> ok
if (!value.Success)
return true;
Group value = m.Groups[@"value"];

// "enabled: ..." must match either of the following
return value.Value.Equals("true", StringComparison.OrdinalIgnoreCase)
|| value.Value.Equals("yes", StringComparison.OrdinalIgnoreCase)
|| value.Value.Equals("1", StringComparison.OrdinalIgnoreCase);
// no "true" or other part, just "enabled" -> ok
if (!value.Success)
{
return true;
}

// "enabled: ..." must match either of the following
return value.Value.Equals("true", StringComparison.OrdinalIgnoreCase)
|| value.Value.Equals("yes", StringComparison.OrdinalIgnoreCase)
|| value.Value.Equals("1", StringComparison.OrdinalIgnoreCase);
}
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
namespace Ahk.GitHub.Monitor.EventHandlers
namespace Ahk.GitHub.Monitor.EventHandlers;

public class EventHandlerResult(string result)
{
public class EventHandlerResult(string result)
{
public string Result { get; } = result;
public string Result { get; } = result;

public static EventHandlerResult PayloadError(string message) =>
new EventHandlerResult($"payload error: {message}");
public static EventHandlerResult PayloadError(string message) => new($"payload error: {message}");

public static EventHandlerResult NoActionNeeded(string message) =>
new EventHandlerResult($"no action needed: {message}");
public static EventHandlerResult NoActionNeeded(string message) => new($"no action needed: {message}");

public static EventHandlerResult ActionPerformed(string message) =>
new EventHandlerResult($"action performed: {message}");
public static EventHandlerResult ActionPerformed(string message) => new($"action performed: {message}");

public static EventHandlerResult EventNotOfInterest(string action) =>
new EventHandlerResult($"action not of interest: {action}");
public static EventHandlerResult EventNotOfInterest(string action) => new($"action not of interest: {action}");

public static EventHandlerResult Disabled(string message = null) =>
new EventHandlerResult(message == null ? $"event handler disabled" : $"event handler disabled: {message}");
}
public static EventHandlerResult Disabled(string message = null) =>
new(message == null ? $"event handler disabled" : $"event handler disabled: {message}");
}
Loading

0 comments on commit 7eae16c

Please sign in to comment.