From 9c5fc32cb226f0f67392169e82c305d6cbd29e0a Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Mon, 13 Jan 2025 13:29:30 +0000 Subject: [PATCH 01/14] fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/enterprise_rules.go | 26 +- github/enterprise_rules_test.go | 838 +++++++------- github/event_types.go | 75 +- github/event_types_test.go | 1834 +------------------------------ github/github-accessors.go | 518 +++------ github/github-accessors_test.go | 643 ++++------- github/orgs_rules.go | 34 +- github/orgs_rules_test.go | 754 +++++++------ github/repos_rules.go | 892 +-------------- github/repos_rules_test.go | 564 +--------- github/rules.go | 1251 +++++++++++++++++++++ github/rules_test.go | 101 ++ 12 files changed, 2797 insertions(+), 4733 deletions(-) create mode 100644 github/rules.go create mode 100644 github/rules_test.go diff --git a/github/enterprise_rules.go b/github/enterprise_rules.go index 29e3e4a568f..59610d2f8e4 100644 --- a/github/enterprise_rules.go +++ b/github/enterprise_rules.go @@ -10,12 +10,12 @@ import ( "fmt" ) -// CreateEnterpriseRuleset creates a ruleset for the specified enterprise. +// CreateRepositoryRuleset creates a repository ruleset for the specified enterprise. // // GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/enterprise-admin/rules#create-an-enterprise-repository-ruleset // //meta:operation POST /enterprises/{enterprise}/rulesets -func (s *EnterpriseService) CreateEnterpriseRuleset(ctx context.Context, enterprise string, ruleset Ruleset) (*Ruleset, *Response, error) { +func (s *EnterpriseService) CreateRepositoryRuleset(ctx context.Context, enterprise string, ruleset RepositoryRuleset) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("enterprises/%v/rulesets", enterprise) req, err := s.client.NewRequest("POST", u, ruleset) @@ -23,7 +23,7 @@ func (s *EnterpriseService) CreateEnterpriseRuleset(ctx context.Context, enterpr return nil, nil, err } - var rs *Ruleset + var rs *RepositoryRuleset resp, err := s.client.Do(ctx, req, &rs) if err != nil { return nil, resp, err @@ -32,12 +32,12 @@ func (s *EnterpriseService) CreateEnterpriseRuleset(ctx context.Context, enterpr return rs, resp, nil } -// GetEnterpriseRuleset gets a ruleset from the specified enterprise. +// GetRepositoryRuleset gets a repository ruleset for the specified enterprise. // // GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/enterprise-admin/rules#get-an-enterprise-repository-ruleset // //meta:operation GET /enterprises/{enterprise}/rulesets/{ruleset_id} -func (s *EnterpriseService) GetEnterpriseRuleset(ctx context.Context, enterprise string, rulesetID int64) (*Ruleset, *Response, error) { +func (s *EnterpriseService) GetRepositoryRuleset(ctx context.Context, enterprise string, rulesetID int64) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("enterprises/%v/rulesets/%v", enterprise, rulesetID) req, err := s.client.NewRequest("GET", u, nil) @@ -45,7 +45,7 @@ func (s *EnterpriseService) GetEnterpriseRuleset(ctx context.Context, enterprise return nil, nil, err } - var ruleset *Ruleset + var ruleset *RepositoryRuleset resp, err := s.client.Do(ctx, req, &ruleset) if err != nil { return nil, resp, err @@ -54,12 +54,12 @@ func (s *EnterpriseService) GetEnterpriseRuleset(ctx context.Context, enterprise return ruleset, resp, nil } -// UpdateEnterpriseRuleset updates a ruleset from the specified enterprise. +// UpdateRepositoryRuleset updates a repository ruleset for the specified enterprise. // // GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/enterprise-admin/rules#update-an-enterprise-repository-ruleset // //meta:operation PUT /enterprises/{enterprise}/rulesets/{ruleset_id} -func (s *EnterpriseService) UpdateEnterpriseRuleset(ctx context.Context, enterprise string, rulesetID int64, ruleset Ruleset) (*Ruleset, *Response, error) { +func (s *EnterpriseService) UpdateRepositoryRuleset(ctx context.Context, enterprise string, rulesetID int64, ruleset RepositoryRuleset) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("enterprises/%v/rulesets/%v", enterprise, rulesetID) req, err := s.client.NewRequest("PUT", u, ruleset) @@ -67,7 +67,7 @@ func (s *EnterpriseService) UpdateEnterpriseRuleset(ctx context.Context, enterpr return nil, nil, err } - var rs *Ruleset + var rs *RepositoryRuleset resp, err := s.client.Do(ctx, req, &rs) if err != nil { return nil, resp, err @@ -76,14 +76,14 @@ func (s *EnterpriseService) UpdateEnterpriseRuleset(ctx context.Context, enterpr return rs, resp, nil } -// UpdateEnterpriseRulesetClearBypassActor clears the ruleset bypass actors for a ruleset for the specified repository. +// UpdateRepositoryRulesetClearBypassActor clears the bypass actors for a repository ruleset for the specified enterprise. // // This function is necessary as the UpdateEnterpriseRuleset function does not marshal ByPassActor if passed as an empty array. // // GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/enterprise-admin/rules#update-an-enterprise-repository-ruleset // //meta:operation PUT /enterprises/{enterprise}/rulesets/{ruleset_id} -func (s *EnterpriseService) UpdateEnterpriseRulesetClearBypassActor(ctx context.Context, enterprise string, rulesetID int64) (*Response, error) { +func (s *EnterpriseService) UpdateRepositoryRulesetClearBypassActor(ctx context.Context, enterprise string, rulesetID int64) (*Response, error) { u := fmt.Sprintf("enterprises/%v/rulesets/%v", enterprise, rulesetID) rsClearBypassActor := rulesetClearBypassActors{} @@ -101,12 +101,12 @@ func (s *EnterpriseService) UpdateEnterpriseRulesetClearBypassActor(ctx context. return resp, nil } -// DeleteEnterpriseRuleset deletes a ruleset from the specified enterprise. +// DeleteRepositoryRuleset deletes a repository ruleset from the specified enterprise. // // GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/enterprise-admin/rules#delete-an-enterprise-repository-ruleset // //meta:operation DELETE /enterprises/{enterprise}/rulesets/{ruleset_id} -func (s *EnterpriseService) DeleteEnterpriseRuleset(ctx context.Context, enterprise string, rulesetID int64) (*Response, error) { +func (s *EnterpriseService) DeleteRepositoryRuleset(ctx context.Context, enterprise string, rulesetID int64) (*Response, error) { u := fmt.Sprintf("enterprises/%v/rulesets/%v", enterprise, rulesetID) req, err := s.client.NewRequest("DELETE", u, nil) diff --git a/github/enterprise_rules_test.go b/github/enterprise_rules_test.go index 574b8396591..69e810d15a1 100644 --- a/github/enterprise_rules_test.go +++ b/github/enterprise_rules_test.go @@ -14,14 +14,14 @@ import ( "github.com/google/go-cmp/cmp" ) -func TestEnterpriseService_CreateEnterpriseRuleset_OrgNameRepoName(t *testing.T) { +func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoName(t *testing.T) { t.Parallel() client, mux, _ := setup(t) mux.HandleFunc("/enterprises/e/rulesets", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") fmt.Fprint(w, `{ - "id": 21, + "id": 84, "name": "ruleset", "target": "branch", "source_type": "Enterprise", @@ -102,6 +102,7 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgNameRepoName(t *testing.T) { "type": "required_status_checks", "parameters": { + "do_not_enforce_on_create": true, "required_status_checks": [ { "context": "test", @@ -174,207 +175,209 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgNameRepoName(t *testing.T) }) ctx := context.Background() - ruleset, _, err := client.Enterprise.CreateEnterpriseRuleset(ctx, "e", Ruleset{ + ruleset, _, err := client.Enterprise.CreateRepositoryRuleset(ctx, "e", RepositoryRuleset{ Name: "ruleset", - Target: Ptr("branch"), + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - OrganizationName: &RulesetOrganizationNamesConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationName: &RepositoryRulesetOrganizationNamesConditionParameters{ Include: []string{"important_organization", "another_important_organization"}, Exclude: []string{"unimportant_organization"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, }) if err != nil { - t.Errorf("Enterprise.CreateEnterpriseRuleset returned error: %v", err) + t.Errorf("Enterprise.CreateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(21)), + want := &RepositoryRuleset{ + ID: Ptr(int64(84)), Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Enterprise"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - OrganizationName: &RulesetOrganizationNamesConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationName: &RepositoryRulesetOrganizationNamesConditionParameters{ Include: []string{"important_organization", "another_important_organization"}, Exclude: []string{"unimportant_organization"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, } if !cmp.Equal(ruleset, want) { - t.Errorf("Enterprise.CreateEnterpriseRuleset returned %+v, want %+v", ruleset, want) + t.Errorf("Enterprise.CreateRepositoryRuleset returned %+v, want %+v", ruleset, want) } - const methodName = "CreateEnterpriseRuleset" + const methodName = "CreateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Enterprise.CreateEnterpriseRuleset(ctx, "e", Ruleset{}) + got, resp, err := client.Enterprise.CreateRepositoryRuleset(ctx, "e", RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -382,14 +385,14 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgNameRepoName(t *testing.T) }) } -func TestEnterpriseService_CreateEnterpriseRuleset_OrgNameRepoProperty(t *testing.T) { +func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoProperty(t *testing.T) { t.Parallel() client, mux, _ := setup(t) mux.HandleFunc("/enterprises/e/rulesets", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") fmt.Fprint(w, `{ - "id": 21, + "id": 84, "name": "ruleset", "target": "branch", "source_type": "Enterprise", @@ -479,6 +482,7 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgNameRepoProperty(t *testin { "type": "required_status_checks", "parameters": { + "do_not_enforce_on_create": true, "required_status_checks": [ { "context": "test", @@ -551,227 +555,229 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgNameRepoProperty(t *testin }) ctx := context.Background() - ruleset, _, err := client.Enterprise.CreateEnterpriseRuleset(ctx, "e", Ruleset{ + ruleset, _, err := client.Enterprise.CreateRepositoryRuleset(ctx, "e", RepositoryRuleset{ Name: "ruleset", - Target: Ptr("branch"), + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - OrganizationName: &RulesetOrganizationNamesConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationName: &RepositoryRulesetOrganizationNamesConditionParameters{ Include: []string{"important_organization", "another_important_organization"}, Exclude: []string{"unimportant_organization"}, }, - RepositoryProperty: &RulesetRepositoryPropertyConditionParameters{ - Include: []RulesetRepositoryPropertyTargetParameters{ + RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ + Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testIncludeProp", Source: Ptr("custom"), Values: []string{"true"}, }, }, - Exclude: []RulesetRepositoryPropertyTargetParameters{ + Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testExcludeProp", Values: []string{"false"}, }, }, }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, }) if err != nil { - t.Errorf("Enterprise.CreateEnterpriseRuleset returned error: %v", err) + t.Errorf("Enterprise.CreateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(21)), + want := &RepositoryRuleset{ + ID: Ptr(int64(84)), Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Enterprise"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - OrganizationName: &RulesetOrganizationNamesConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationName: &RepositoryRulesetOrganizationNamesConditionParameters{ Include: []string{"important_organization", "another_important_organization"}, Exclude: []string{"unimportant_organization"}, }, - RepositoryProperty: &RulesetRepositoryPropertyConditionParameters{ - Include: []RulesetRepositoryPropertyTargetParameters{ + RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ + Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testIncludeProp", Source: Ptr("custom"), Values: []string{"true"}, }, }, - Exclude: []RulesetRepositoryPropertyTargetParameters{ + Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testExcludeProp", Values: []string{"false"}, }, }, }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, } if !cmp.Equal(ruleset, want) { - t.Errorf("Enterprise.CreateEnterpriseRuleset returned %+v, want %+v", ruleset, want) + t.Errorf("Enterprise.CreateRepositoryRuleset returned %+v, want %+v", ruleset, want) } - const methodName = "CreateEnterpriseRuleset" + const methodName = "CreateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Enterprise.CreateEnterpriseRuleset(ctx, "e", Ruleset{}) + got, resp, err := client.Enterprise.CreateRepositoryRuleset(ctx, "e", RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -779,14 +785,14 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgNameRepoProperty(t *testin }) } -func TestEnterpriseService_CreateEnterpriseRuleset_OrgIdRepoName(t *testing.T) { +func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoName(t *testing.T) { t.Parallel() client, mux, _ := setup(t) mux.HandleFunc("/enterprises/e/rulesets", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") fmt.Fprint(w, `{ - "id": 21, + "id": 84, "name": "ruleset", "target": "branch", "source_type": "Enterprise", @@ -861,6 +867,7 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgIdRepoName(t *testing.T) { { "type": "required_status_checks", "parameters": { + "do_not_enforce_on_create": true, "required_status_checks": [ { "context": "test", @@ -933,205 +940,207 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgIdRepoName(t *testing.T) { }) ctx := context.Background() - ruleset, _, err := client.Enterprise.CreateEnterpriseRuleset(ctx, "e", Ruleset{ + ruleset, _, err := client.Enterprise.CreateRepositoryRuleset(ctx, "e", RepositoryRuleset{ Name: "ruleset", - Target: Ptr("branch"), + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - OrganizationID: &RulesetOrganizationIDsConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationID: &RepositoryRulesetOrganizationIDsConditionParameters{ OrganizationIDs: []int64{1001, 1002}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, }) if err != nil { - t.Errorf("Enterprise.CreateEnterpriseRuleset returned error: %v", err) + t.Errorf("Enterprise.CreateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(21)), + want := &RepositoryRuleset{ + ID: Ptr(int64(84)), Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Enterprise"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - OrganizationID: &RulesetOrganizationIDsConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationID: &RepositoryRulesetOrganizationIDsConditionParameters{ OrganizationIDs: []int64{1001, 1002}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, } if !cmp.Equal(ruleset, want) { - t.Errorf("Enterprise.CreateEnterpriseRuleset returned %+v, want %+v", ruleset, want) + t.Errorf("Enterprise.CreateRepositoryRuleset returned %+v, want %+v", ruleset, want) } - const methodName = "CreateEnterpriseRuleset" + const methodName = "CreateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Enterprise.CreateEnterpriseRuleset(ctx, "e", Ruleset{}) + got, resp, err := client.Enterprise.CreateRepositoryRuleset(ctx, "e", RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -1139,14 +1148,14 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgIdRepoName(t *testing.T) { }) } -func TestEnterpriseService_CreateEnterpriseRuleset_OrgIdRepoProperty(t *testing.T) { +func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoProperty(t *testing.T) { t.Parallel() client, mux, _ := setup(t) mux.HandleFunc("/enterprises/e/rulesets", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") fmt.Fprint(w, `{ - "id": 21, + "id": 84, "name": "ruleset", "target": "branch", "source_type": "Enterprise", @@ -1230,6 +1239,7 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgIdRepoProperty(t *testing. { "type": "required_status_checks", "parameters": { + "do_not_enforce_on_create": true, "required_status_checks": [ { "context": "test", @@ -1302,225 +1312,227 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgIdRepoProperty(t *testing. }) ctx := context.Background() - ruleset, _, err := client.Enterprise.CreateEnterpriseRuleset(ctx, "e", Ruleset{ + ruleset, _, err := client.Enterprise.CreateRepositoryRuleset(ctx, "e", RepositoryRuleset{ Name: "ruleset", - Target: Ptr("branch"), + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - OrganizationID: &RulesetOrganizationIDsConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationID: &RepositoryRulesetOrganizationIDsConditionParameters{ OrganizationIDs: []int64{1001, 1002}, }, - RepositoryProperty: &RulesetRepositoryPropertyConditionParameters{ - Include: []RulesetRepositoryPropertyTargetParameters{ + RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ + Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testIncludeProp", Source: Ptr("custom"), Values: []string{"true"}, }, }, - Exclude: []RulesetRepositoryPropertyTargetParameters{ + Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testExcludeProp", Values: []string{"false"}, }, }, }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, }) if err != nil { - t.Errorf("Enterprise.CreateEnterpriseRuleset returned error: %v", err) + t.Errorf("Enterprise.CreateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(21)), + want := &RepositoryRuleset{ + ID: Ptr(int64(84)), Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Enterprise"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - OrganizationID: &RulesetOrganizationIDsConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationID: &RepositoryRulesetOrganizationIDsConditionParameters{ OrganizationIDs: []int64{1001, 1002}, }, - RepositoryProperty: &RulesetRepositoryPropertyConditionParameters{ - Include: []RulesetRepositoryPropertyTargetParameters{ + RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ + Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testIncludeProp", Source: Ptr("custom"), Values: []string{"true"}, }, }, - Exclude: []RulesetRepositoryPropertyTargetParameters{ + Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testExcludeProp", Values: []string{"false"}, }, }, }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, } if !cmp.Equal(ruleset, want) { - t.Errorf("Enterprise.CreateEnterpriseRuleset returned %+v, want %+v", ruleset, want) + t.Errorf("Enterprise.CreateRepositoryRuleset returned %+v, want %+v", ruleset, want) } - const methodName = "CreateEnterpriseRuleset" + const methodName = "CreateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Enterprise.CreateEnterpriseRuleset(ctx, "e", Ruleset{}) + got, resp, err := client.Enterprise.CreateRepositoryRuleset(ctx, "e", RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -1528,14 +1540,14 @@ func TestEnterpriseService_CreateEnterpriseRuleset_OrgIdRepoProperty(t *testing. }) } -func TestEnterpriseService_GetEnterpriseRuleset(t *testing.T) { +func TestEnterpriseService_GetRepositoryRuleset(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/enterprises/e/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/enterprises/e/rulesets/84", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `{ - "id": 26110, + "id": 84, "name": "test ruleset", "target": "branch", "source_type": "Enterprise", @@ -1545,7 +1557,7 @@ func TestEnterpriseService_GetEnterpriseRuleset(t *testing.T) { "node_id": "nid", "_links": { "self": { - "href": "https://api.github.com/enterprises/e/rulesets/26110" + "href": "https://api.github.com/enterprises/e/rulesets/84" } }, "conditions": { @@ -1587,49 +1599,47 @@ func TestEnterpriseService_GetEnterpriseRuleset(t *testing.T) { }) ctx := context.Background() - rulesets, _, err := client.Enterprise.GetEnterpriseRuleset(ctx, "e", 26110) + rulesets, _, err := client.Enterprise.GetRepositoryRuleset(ctx, "e", 84) if err != nil { - t.Errorf("Enterprise.GetEnterpriseRuleset returned error: %v", err) + t.Errorf("Enterprise.GetRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(26110)), + want := &RepositoryRuleset{ + ID: Ptr(int64(84)), Name: "test ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Enterprise"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", NodeID: Ptr("nid"), - Links: &RulesetLinks{ - Self: &RulesetLink{HRef: Ptr("https://api.github.com/enterprises/e/rulesets/26110")}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("https://api.github.com/enterprises/e/rulesets/84")}, }, - Conditions: &RulesetConditions{ - OrganizationName: &RulesetOrganizationNamesConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationName: &RepositoryRulesetOrganizationNamesConditionParameters{ Include: []string{"important_organization", "another_important_organization"}, Exclude: []string{"unimportant_organization"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - }, + Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, } if !cmp.Equal(rulesets, want) { - t.Errorf("Enterprise.GetEnterpriseRuleset returned %+v, want %+v", rulesets, want) + t.Errorf("Enterprise.GetRepositoryRuleset returned %+v, want %+v", rulesets, want) } - const methodName = "GetEnterpriseRuleset" + const methodName = "GetRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Enterprise.GetEnterpriseRuleset(ctx, "e", 26110) + got, resp, err := client.Enterprise.GetRepositoryRuleset(ctx, "e", 84) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -1637,14 +1647,14 @@ func TestEnterpriseService_GetEnterpriseRuleset(t *testing.T) { }) } -func TestEnterpriseService_UpdateEnterpriseRuleset(t *testing.T) { +func TestEnterpriseService_UpdateRepositoryRuleset(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/enterprises/e/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/enterprises/e/rulesets/84", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") fmt.Fprint(w, `{ - "id": 26110, + "id": 84, "name": "test ruleset", "target": "branch", "source_type": "Enterprise", @@ -1654,7 +1664,7 @@ func TestEnterpriseService_UpdateEnterpriseRuleset(t *testing.T) { "node_id": "nid", "_links": { "self": { - "href": "https://api.github.com/enterprises/e/rulesets/26110" + "href": "https://api.github.com/enterprises/e/rulesets/84" } }, "conditions": { @@ -1696,67 +1706,63 @@ func TestEnterpriseService_UpdateEnterpriseRuleset(t *testing.T) { }) ctx := context.Background() - rulesets, _, err := client.Enterprise.UpdateEnterpriseRuleset(ctx, "e", 26110, Ruleset{ + rulesets, _, err := client.Enterprise.UpdateRepositoryRuleset(ctx, "e", 84, RepositoryRuleset{ Name: "test ruleset", - Target: Ptr("branch"), + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - Conditions: &RulesetConditions{ - RefName: &RulesetRefConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - }, + Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, }) if err != nil { - t.Errorf("Enterprise.UpdateEnterpriseRuleset returned error: %v", err) + t.Errorf("Enterprise.UpdateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(26110)), + want := &RepositoryRuleset{ + ID: Ptr(int64(84)), Name: "test ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Enterprise"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", NodeID: Ptr("nid"), - Links: &RulesetLinks{ - Self: &RulesetLink{HRef: Ptr("https://api.github.com/enterprises/e/rulesets/26110")}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("https://api.github.com/enterprises/e/rulesets/84")}, }, - Conditions: &RulesetConditions{ - OrganizationName: &RulesetOrganizationNamesConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + OrganizationName: &RepositoryRulesetOrganizationNamesConditionParameters{ Include: []string{"important_organization", "another_important_organization"}, Exclude: []string{"unimportant_organization"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, - RefName: &RulesetRefConditionParameters{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - }, + Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, } if !cmp.Equal(rulesets, want) { - t.Errorf("Enterprise.UpdateEnterpriseRuleset returned %+v, want %+v", rulesets, want) + t.Errorf("Enterprise.UpdateRepositoryRuleset returned %+v, want %+v", rulesets, want) } - const methodName = "UpdateEnterpriseRuleset" + const methodName = "UpdateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Enterprise.UpdateEnterpriseRuleset(ctx, "e", 26110, Ruleset{}) + got, resp, err := client.Enterprise.UpdateRepositoryRuleset(ctx, "e", 84, RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -1764,14 +1770,14 @@ func TestEnterpriseService_UpdateEnterpriseRuleset(t *testing.T) { }) } -func TestEnterpriseService_UpdateEnterpriseRulesetClearBypassActor(t *testing.T) { +func TestEnterpriseService_UpdateRepositoryRulesetClearBypassActor(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/enterprises/e/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/enterprises/e/rulesets/84", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") fmt.Fprint(w, `{ - "id": 26110, + "id": 84, "name": "test ruleset", "target": "branch", "source_type": "Enterprise", @@ -1818,35 +1824,35 @@ func TestEnterpriseService_UpdateEnterpriseRulesetClearBypassActor(t *testing.T) ctx := context.Background() - _, err := client.Enterprise.UpdateEnterpriseRulesetClearBypassActor(ctx, "e", 26110) + _, err := client.Enterprise.UpdateRepositoryRulesetClearBypassActor(ctx, "e", 84) if err != nil { - t.Errorf("Enterprise.UpdateEnterpriseRulesetClearBypassActor returned error: %v \n", err) + t.Errorf("Enterprise.UpdateRepositoryRulesetClearBypassActor returned error: %v \n", err) } - const methodName = "UpdateEnterpriseRulesetClearBypassActor" + const methodName = "UpdateRepositoryRulesetClearBypassActor" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Enterprise.UpdateEnterpriseRulesetClearBypassActor(ctx, "e", 26110) + return client.Enterprise.UpdateRepositoryRulesetClearBypassActor(ctx, "e", 84) }) } -func TestEnterpriseService_DeleteEnterpriseRuleset(t *testing.T) { +func TestEnterpriseService_DeleteRepositoryRuleset(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/enterprises/e/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/enterprises/e/rulesets/84", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") }) ctx := context.Background() - _, err := client.Enterprise.DeleteEnterpriseRuleset(ctx, "e", 26110) + _, err := client.Enterprise.DeleteRepositoryRuleset(ctx, "e", 84) if err != nil { - t.Errorf("Enterprise.DeleteEnterpriseRuleset returned error: %v", err) + t.Errorf("Enterprise.DeleteRepositoryRuleset returned error: %v", err) } - const methodName = "DeleteEnterpriseRuleset" + const methodName = "DeleteRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Enterprise.DeleteEnterpriseRuleset(ctx, "e", 26110) + return client.Enterprise.DeleteRepositoryRuleset(ctx, "e", 84) }) } diff --git a/github/event_types.go b/github/event_types.go index 37e62c2fab9..3732bb3a126 100644 --- a/github/event_types.go +++ b/github/event_types.go @@ -1521,14 +1521,73 @@ type RepositoryImportEvent struct { // // GitHub API docs: https://docs.github.com/en/webhooks/webhook-events-and-payloads#repository_ruleset type RepositoryRulesetEvent struct { - Action *string `json:"action,omitempty"` - Enterprise *Enterprise `json:"enterprise,omitempty"` - Installation *Installation `json:"installation,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Repository *Repository `json:"repository,omitempty"` - RepositoryRuleset *RepositoryRuleset `json:"repository_ruleset"` - Changes *RepositoryRulesetEditedChanges `json:"changes,omitempty"` - Sender *User `json:"sender"` + Action *string `json:"action,omitempty"` + Enterprise *Enterprise `json:"enterprise,omitempty"` + Installation *Installation `json:"installation,omitempty"` + Organization *Organization `json:"organization,omitempty"` + Repository *Repository `json:"repository,omitempty"` + RepositoryRuleset *RepositoryRuleset `json:"repository_ruleset"` + Changes *RepositoryRulesetChanges `json:"changes,omitempty"` + Sender *User `json:"sender"` +} + +// RepositoryRulesetChanges represents the changes made to a repository ruleset. +type RepositoryRulesetChanges struct { + Name *RepositoryRulesetChangeSource `json:"name,omitempty"` + Enforcement *RepositoryRulesetChangeSource `json:"enforcement,omitempty"` + Conditions *RepositoryRulesetChangedConditions `json:"conditions,omitempty"` + Rules *RepositoryRulesetChangedRules `json:"rules,omitempty"` +} + +// RepositoryRulesetChangeSource represents a source change for the ruleset. +type RepositoryRulesetChangeSource struct { + From *string `json:"from,omitempty"` +} + +// RepositoryRulesetChangeSources represents multiple source changes for the ruleset. +type RepositoryRulesetChangeSources struct { + From []string `json:"from,omitempty"` +} + +// RepositoryRulesetChangedConditions holds changes to conditions in a ruleset. +type RepositoryRulesetChangedConditions struct { + Added []RepositoryRulesetConditions `json:"added,omitempty"` + Deleted []RepositoryRulesetConditions `json:"deleted,omitempty"` + Updated []RepositoryRulesetUpdatedConditions `json:"updated,omitempty"` +} + +// RepositoryRulesetUpdatedConditions represents the edited updates to conditions in a ruleset. +type RepositoryRulesetUpdatedConditions struct { + Condition *RepositoryRulesetConditions `json:"condition,omitempty"` + Changes *RepositoryRulesetUpdatedCondition `json:"changes,omitempty"` +} + +// RepositoryRulesetUpdatedCondition represents the changes to a condition in a ruleset. +type RepositoryRulesetUpdatedCondition struct { + ConditionType *RepositoryRulesetChangeSource `json:"condition_type,omitempty"` + Target *RepositoryRulesetChangeSource `json:"target,omitempty"` + Include *RepositoryRulesetChangeSources `json:"include,omitempty"` + Exclude *RepositoryRulesetChangeSources `json:"exclude,omitempty"` +} + +// RepositoryRulesetChangedRules holds changes to rules in a ruleset. +type RepositoryRulesetChangedRules struct { + Added []RepositoryRulesetRule `json:"added,omitempty"` + Deleted []RepositoryRulesetRule `json:"deleted,omitempty"` + Updated []RepositoryRulesetUpdatedRules `json:"updated,omitempty"` +} + +// RepositoryRulesetUpdatedRules holds updates to rules in a ruleset. +type RepositoryRulesetUpdatedRules struct { + Rule *RepositoryRulesetRule `json:"rule,omitempty"` + Changes *RepositoryRulesetChangedRule `json:"changes,omitempty"` +} + +// RepositoryRulesetChangedRule holds changes made to a rule in a ruleset. +type RepositoryRulesetChangedRule struct { + Configuration *RepositoryRulesetChangeSource `json:"configuration,omitempty"` + RuleType *RepositoryRulesetChangeSource `json:"rule_type,omitempty"` + Pattern *RepositoryRulesetChangeSource `json:"pattern,omitempty"` } // RepositoryVulnerabilityAlertEvent is triggered when a security alert is created, dismissed, or resolved. diff --git a/github/event_types_test.go b/github/event_types_test.go index b65d792e9bf..bdce6dd388f 100644 --- a/github/event_types_test.go +++ b/github/event_types_test.go @@ -7,7 +7,10 @@ package github import ( "encoding/json" + "fmt" "testing" + + "github.com/google/go-cmp/cmp" ) func TestEditChange_Marshal_TitleChange(t *testing.T) { @@ -9560,1789 +9563,68 @@ func TestReleaseEvent_Marshal(t *testing.T) { testJSONMarshal(t, u, want) } -func TestRepositoryRulesetEvent_Marshal(t *testing.T) { +func TestRepositoryRulesetEvent_Unmarshal(t *testing.T) { t.Parallel() - testJSONMarshal(t, &RepositoryRulesetEvent{}, "{}") - l := make(map[string]interface{}) - l["key"] = "value" + enterprise := &Enterprise{ + ID: Ptr(1), + NodeID: Ptr("n"), + Slug: Ptr("e"), + Name: Ptr("e"), + } - jsonMsg, _ := json.Marshal(&l) + installation := &Installation{ + ID: Ptr(int64(1)), + NodeID: Ptr("n"), + AppID: Ptr(int64(1)), + AppSlug: Ptr("a"), + } - u := &RepositoryRulesetEvent{ - Action: Ptr("a"), - Enterprise: &Enterprise{ - ID: Ptr(1), - Slug: Ptr("s"), - Name: Ptr("n"), - NodeID: Ptr("nid"), - AvatarURL: Ptr("au"), - Description: Ptr("d"), - WebsiteURL: Ptr("wu"), - HTMLURL: Ptr("hu"), - CreatedAt: &Timestamp{referenceTime}, - UpdatedAt: &Timestamp{referenceTime}, - }, - Installation: &Installation{ - ID: Ptr(int64(1)), - NodeID: Ptr("nid"), - AppID: Ptr(int64(1)), - AppSlug: Ptr("as"), - TargetID: Ptr(int64(1)), - Account: &User{ - Login: Ptr("l"), - ID: Ptr(int64(1)), - URL: Ptr("u"), - AvatarURL: Ptr("a"), - GravatarID: Ptr("g"), - Name: Ptr("n"), - Company: Ptr("c"), - Blog: Ptr("b"), - Location: Ptr("l"), - Email: Ptr("e"), - Hireable: Ptr(true), - Bio: Ptr("b"), - TwitterUsername: Ptr("t"), - PublicRepos: Ptr(1), - Followers: Ptr(1), - Following: Ptr(1), - CreatedAt: &Timestamp{referenceTime}, - SuspendedAt: &Timestamp{referenceTime}, - }, - AccessTokensURL: Ptr("atu"), - RepositoriesURL: Ptr("ru"), - HTMLURL: Ptr("hu"), - TargetType: Ptr("tt"), - SingleFileName: Ptr("sfn"), - RepositorySelection: Ptr("rs"), - Events: []string{"e"}, - SingleFilePaths: []string{"s"}, - Permissions: &InstallationPermissions{ - Actions: Ptr("a"), - Administration: Ptr("ad"), - Checks: Ptr("c"), - Contents: Ptr("co"), - ContentReferences: Ptr("cr"), - Deployments: Ptr("d"), - Environments: Ptr("e"), - Issues: Ptr("i"), - Metadata: Ptr("md"), - Members: Ptr("m"), - OrganizationAdministration: Ptr("oa"), - OrganizationHooks: Ptr("oh"), - OrganizationPlan: Ptr("op"), - OrganizationPreReceiveHooks: Ptr("opr"), - OrganizationProjects: Ptr("op"), - OrganizationSecrets: Ptr("os"), - OrganizationSelfHostedRunners: Ptr("osh"), - OrganizationUserBlocking: Ptr("oub"), - Packages: Ptr("pkg"), - Pages: Ptr("pg"), - PullRequests: Ptr("pr"), - RepositoryHooks: Ptr("rh"), - RepositoryProjects: Ptr("rp"), - RepositoryPreReceiveHooks: Ptr("rprh"), - Secrets: Ptr("s"), - SecretScanningAlerts: Ptr("ssa"), - SecurityEvents: Ptr("se"), - SingleFile: Ptr("sf"), - Statuses: Ptr("s"), - TeamDiscussions: Ptr("td"), - VulnerabilityAlerts: Ptr("va"), - Workflows: Ptr("w"), - }, - CreatedAt: &Timestamp{referenceTime}, - UpdatedAt: &Timestamp{referenceTime}, - HasMultipleSingleFiles: Ptr(false), - SuspendedBy: &User{ - Login: Ptr("l"), - ID: Ptr(int64(1)), - URL: Ptr("u"), - AvatarURL: Ptr("a"), - GravatarID: Ptr("g"), - Name: Ptr("n"), - Company: Ptr("c"), - Blog: Ptr("b"), - Location: Ptr("l"), - Email: Ptr("e"), - Hireable: Ptr(true), - Bio: Ptr("b"), - TwitterUsername: Ptr("t"), - PublicRepos: Ptr(1), - Followers: Ptr(1), - Following: Ptr(1), - CreatedAt: &Timestamp{referenceTime}, - SuspendedAt: &Timestamp{referenceTime}, - }, - SuspendedAt: &Timestamp{referenceTime}, - }, - Organization: &Organization{ - BillingEmail: Ptr("be"), - Blog: Ptr("b"), - Company: Ptr("c"), - Email: Ptr("e"), - TwitterUsername: Ptr("tu"), - Location: Ptr("loc"), - Name: Ptr("n"), - Description: Ptr("d"), - IsVerified: Ptr(true), - HasOrganizationProjects: Ptr(true), - HasRepositoryProjects: Ptr(true), - DefaultRepoPermission: Ptr("drp"), - MembersCanCreateRepos: Ptr(true), - MembersCanCreateInternalRepos: Ptr(true), - MembersCanCreatePrivateRepos: Ptr(true), - MembersCanCreatePublicRepos: Ptr(false), - MembersAllowedRepositoryCreationType: Ptr("marct"), - MembersCanCreatePages: Ptr(true), - MembersCanCreatePublicPages: Ptr(false), - MembersCanCreatePrivatePages: Ptr(true), - }, - Repository: &Repository{ - ID: Ptr(int64(1)), - URL: Ptr("u"), - Name: Ptr("n"), - }, - RepositoryRuleset: &RepositoryRuleset{ - ID: 1, - Name: "n", - Target: Ptr("branch"), - SourceType: Ptr("Repository"), - Source: "s", - Enforcement: "disabled", - BypassActors: []*BypassActor{ - { - ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), - BypassMode: Ptr("Always"), - }, - }, - CurrentUserCanBypass: Ptr("always"), - NodeID: Ptr("n"), - Links: &RepositoryRulesetLink{ - Self: &RulesetLink{ - HRef: Ptr("href"), - }, - HTML: &RulesetLink{ - HRef: Ptr("href"), - }, - }, - Conditions: json.RawMessage(jsonMsg), - Rules: []*RepositoryRulesetRule{ - { - Creation: &RepositoryRulesetRuleType{ - Type: "creation", - }, - Update: &RepositoryRulesetUpdateRule{ - Type: "update", - Parameters: &UpdateAllowsFetchAndMergeRuleParameters{ - UpdateAllowsFetchAndMerge: true, - }, - }, - Deletion: &RepositoryRulesetRuleType{ - Type: "deletion", - }, - RequiredLinearHistory: &RepositoryRulesetRuleType{ - Type: "required_linear_history", - }, - MergeQueue: &RepositoryRulesetMergeQueueRule{ - Type: "merge_queue", - Parameters: &MergeQueueRuleParameters{ - CheckResponseTimeoutMinutes: 35, - GroupingStrategy: "HEADGREEN", - MaxEntriesToBuild: 8, - MaxEntriesToMerge: 4, - MergeMethod: "SQUASH", - MinEntriesToMerge: 2, - MinEntriesToMergeWaitMinutes: 13, - }, - }, - RequiredDeployments: &RepositoryRulesetRequiredDeploymentsRule{ - Type: "required_deployments", - Parameters: &RequiredDeploymentEnvironmentsRuleParameters{ - RequiredDeploymentEnvironments: []string{"test"}, - }, - }, - RequiredSignatures: &RepositoryRulesetRuleType{ - Type: "required_signatures", - }, - PullRequest: &RepositoryRulesetPullRequestRule{ - Type: "pull_request", - Parameters: &PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, - DismissStaleReviewsOnPush: true, - RequireCodeOwnerReview: true, - RequireLastPushApproval: true, - RequiredApprovingReviewCount: 1, - RequiredReviewThreadResolution: true, - }, - }, - RequiredStatusChecks: &RepositoryRulesetRequiredStatusChecksRule{ - Type: "required_status_checks", - Parameters: &RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ - { - Context: "test", - IntegrationID: Ptr(int64(1)), - }, - }, - StrictRequiredStatusChecksPolicy: true, - }, - }, - NonFastForward: &RepositoryRulesetRuleType{ - Type: "non_fast_forward", - }, - CommitMessagePattern: &RepositoryRulesetPatternRule{ - Type: "commit_message_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid test commits"), - Negate: Ptr(true), - Operator: "starts_with", - Pattern: "[test]", - }, - }, - CommitAuthorEmailPattern: &RepositoryRulesetPatternRule{ - Type: "commit_author_email_pattern", - Parameters: &RulePatternParameters{ - Operator: "contains", - Pattern: "github", - }, - }, - CommitterEmailPattern: &RepositoryRulesetPatternRule{ - Type: "committer_email_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid commit emails"), - Negate: Ptr(true), - Operator: "ends_with", - Pattern: "abc", - }, - }, - BranchNamePattern: &RepositoryRulesetPatternRule{ - Type: "branch_name_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid branch names"), - Negate: Ptr(true), - Operator: "regex", - Pattern: "github$", - }, - }, - TagNamePattern: &RepositoryRulesetPatternRule{ - Type: "tag_name_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid tag names"), - Negate: Ptr(true), - Operator: "contains", - Pattern: "github", - }, - }, - FilePathRestriction: &RepositoryRulesetFilePathRestrictionRule{ - Type: "file_path_restriction", - Parameters: &RuleFileParameters{ - RestrictedFilePaths: &[]string{"/a/file"}, - }, - }, - MaxFilePathLength: &RepositoryRulesetMaxFilePathLengthRule{ - Type: "max_file_path_length", - Parameters: &RuleMaxFilePathLengthParameters{ - MaxFilePathLength: 255, - }, - }, - FileExtensionRestriction: &RepositoryRulesetFileExtensionRestrictionRule{ - Type: "file_extension_restriction", - Parameters: &RuleFileExtensionRestrictionParameters{ - RestrictedFileExtensions: []string{".exe"}, - }, - }, - MaxFileSize: &RepositoryRulesetMaxFileSizeRule{ - Type: "max_file_size", - Parameters: &RuleMaxFileSizeParameters{ - MaxFileSize: 1024, - }, - }, - Workflows: &RepositoryRulesetWorkflowsRule{ - Type: "workflows", - Parameters: &RequiredWorkflowsRuleParameters{ - RequiredWorkflows: []*RuleRequiredWorkflow{ - { - Path: ".github/workflows/test.yml", - RepositoryID: Ptr(int64(1)), - }, - }, - }, - }, - CodeScanning: &RepositoryRulesetCodeScanningRule{ - Type: "code_scanning", - Parameters: &RuleCodeScanningParameters{ - CodeScanningTools: []*CodeScanningTool{{ - AlertsThreshold: "alert", - SecurityAlertsThreshold: "security", - Tool: "tool", - }}, - }, - }, - }, - }, - CreatedAt: &Timestamp{referenceTime}, - UpdatedAt: &Timestamp{referenceTime}, - }, - Changes: &RepositoryRulesetEditedChanges{ - Name: &RepositoryRulesetEditedSource{ - From: Ptr("f"), - }, - Enforcement: &RepositoryRulesetEditedSource{ - From: Ptr("e"), - }, - Conditions: &RepositoryRulesetEditedConditions{ - Added: []*RepositoryRulesetRefCondition{ - { - RefName: &RulesetRefConditionParameters{ - Include: []string{"refs/heads/main", "refs/heads/master"}, - Exclude: []string{"refs/heads/dev*"}, - }, - }, - }, - Deleted: []*RepositoryRulesetRefCondition{ - { - RefName: &RulesetRefConditionParameters{ - Include: []string{"refs/heads/main", "refs/heads/master"}, - Exclude: []string{"refs/heads/dev*"}, - }, - }, - }, - Updated: []*RepositoryRulesetEditedUpdatedConditions{ - { - Condition: &RepositoryRulesetRefCondition{ - RefName: &RulesetRefConditionParameters{ - Include: []string{"refs/heads/main", "refs/heads/master"}, - Exclude: []string{"refs/heads/dev*"}, - }, - }, - Changes: &RepositoryRulesetUpdatedConditionsEdited{ - ConditionType: &RepositoryRulesetEditedSource{ - From: Ptr("c"), - }, - Target: &RepositoryRulesetEditedSource{ - From: Ptr("t"), - }, - Include: &RepositoryRulesetEditedSources{ - From: []string{"from"}, - }, - Exclude: &RepositoryRulesetEditedSources{ - From: []string{"to"}, - }, - }, - }, - }, - }, - Rules: &RepositoryRulesetEditedRules{ - Added: []*RepositoryRulesetRule{ - // Creating just one object with all the possible rules for testing - { - Creation: &RepositoryRulesetRuleType{ - Type: "creation", - }, - Update: &RepositoryRulesetUpdateRule{ - Type: "update", - Parameters: &UpdateAllowsFetchAndMergeRuleParameters{ - UpdateAllowsFetchAndMerge: true, - }, - }, - Deletion: &RepositoryRulesetRuleType{ - Type: "deletion", - }, - RequiredLinearHistory: &RepositoryRulesetRuleType{ - Type: "required_linear_history", - }, - MergeQueue: &RepositoryRulesetMergeQueueRule{ - Type: "merge_queue", - Parameters: &MergeQueueRuleParameters{ - CheckResponseTimeoutMinutes: 35, - GroupingStrategy: "HEADGREEN", - MaxEntriesToBuild: 8, - MaxEntriesToMerge: 4, - MergeMethod: "SQUASH", - MinEntriesToMerge: 2, - MinEntriesToMergeWaitMinutes: 13, - }, - }, - RequiredDeployments: &RepositoryRulesetRequiredDeploymentsRule{ - Type: "required_deployments", - Parameters: &RequiredDeploymentEnvironmentsRuleParameters{ - RequiredDeploymentEnvironments: []string{"test"}, - }, - }, - RequiredSignatures: &RepositoryRulesetRuleType{ - Type: "required_signatures", - }, - PullRequest: &RepositoryRulesetPullRequestRule{ - Type: "pull_request", - Parameters: &PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, - DismissStaleReviewsOnPush: true, - RequireCodeOwnerReview: true, - RequireLastPushApproval: true, - RequiredApprovingReviewCount: 1, - RequiredReviewThreadResolution: true, - }, - }, - RequiredStatusChecks: &RepositoryRulesetRequiredStatusChecksRule{ - Type: "required_status_checks", - Parameters: &RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ - { - Context: "test", - IntegrationID: Ptr(int64(1)), - }, - }, - StrictRequiredStatusChecksPolicy: true, - }, - }, - NonFastForward: &RepositoryRulesetRuleType{ - Type: "non_fast_forward", - }, - CommitMessagePattern: &RepositoryRulesetPatternRule{ - Type: "commit_message_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid test commits"), - Negate: Ptr(true), - Operator: "starts_with", - Pattern: "[test]", - }, - }, - CommitAuthorEmailPattern: &RepositoryRulesetPatternRule{ - Type: "commit_author_email_pattern", - Parameters: &RulePatternParameters{ - Operator: "contains", - Pattern: "github", - }, - }, - CommitterEmailPattern: &RepositoryRulesetPatternRule{ - Type: "committer_email_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid commit emails"), - Negate: Ptr(true), - Operator: "ends_with", - Pattern: "abc", - }, - }, - BranchNamePattern: &RepositoryRulesetPatternRule{ - Type: "branch_name_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid branch names"), - Negate: Ptr(true), - Operator: "regex", - Pattern: "github$", - }, - }, - TagNamePattern: &RepositoryRulesetPatternRule{ - Type: "tag_name_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid tag names"), - Negate: Ptr(true), - Operator: "contains", - Pattern: "github", - }, - }, - FilePathRestriction: &RepositoryRulesetFilePathRestrictionRule{ - Type: "file_path_restriction", - Parameters: &RuleFileParameters{ - RestrictedFilePaths: &[]string{"/a/file"}, - }, - }, - MaxFilePathLength: &RepositoryRulesetMaxFilePathLengthRule{ - Type: "max_file_path_length", - Parameters: &RuleMaxFilePathLengthParameters{ - MaxFilePathLength: 255, - }, - }, - FileExtensionRestriction: &RepositoryRulesetFileExtensionRestrictionRule{ - Type: "file_extension_restriction", - Parameters: &RuleFileExtensionRestrictionParameters{ - RestrictedFileExtensions: []string{".exe"}, - }, - }, - MaxFileSize: &RepositoryRulesetMaxFileSizeRule{ - Type: "max_file_size", - Parameters: &RuleMaxFileSizeParameters{ - MaxFileSize: 1024, - }, - }, - Workflows: &RepositoryRulesetWorkflowsRule{ - Type: "workflows", - Parameters: &RequiredWorkflowsRuleParameters{ - RequiredWorkflows: []*RuleRequiredWorkflow{ - { - Path: ".github/workflows/test.yml", - RepositoryID: Ptr(int64(1)), - }, - }, - }, - }, - CodeScanning: &RepositoryRulesetCodeScanningRule{ - Type: "code_scanning", - Parameters: &RuleCodeScanningParameters{ - CodeScanningTools: []*CodeScanningTool{{ - AlertsThreshold: "alert", - SecurityAlertsThreshold: "security", - Tool: "tool", - }}, - }, - }, - }, - }, - Deleted: []*RepositoryRulesetRule{ - // Creating just one object with all the possible rules for testing - { - Creation: &RepositoryRulesetRuleType{ - Type: "creation", - }, - Update: &RepositoryRulesetUpdateRule{ - Type: "update", - Parameters: &UpdateAllowsFetchAndMergeRuleParameters{ - UpdateAllowsFetchAndMerge: true, - }, - }, - Deletion: &RepositoryRulesetRuleType{ - Type: "deletion", - }, - RequiredLinearHistory: &RepositoryRulesetRuleType{ - Type: "required_linear_history", - }, - MergeQueue: &RepositoryRulesetMergeQueueRule{ - Type: "merge_queue", - Parameters: &MergeQueueRuleParameters{ - CheckResponseTimeoutMinutes: 35, - GroupingStrategy: "HEADGREEN", - MaxEntriesToBuild: 8, - MaxEntriesToMerge: 4, - MergeMethod: "SQUASH", - MinEntriesToMerge: 2, - MinEntriesToMergeWaitMinutes: 13, - }, - }, - RequiredDeployments: &RepositoryRulesetRequiredDeploymentsRule{ - Type: "required_deployments", - Parameters: &RequiredDeploymentEnvironmentsRuleParameters{ - RequiredDeploymentEnvironments: []string{"test"}, - }, - }, - RequiredSignatures: &RepositoryRulesetRuleType{ - Type: "required_signatures", - }, - PullRequest: &RepositoryRulesetPullRequestRule{ - Type: "pull_request", - Parameters: &PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, - DismissStaleReviewsOnPush: true, - RequireCodeOwnerReview: true, - RequireLastPushApproval: true, - RequiredApprovingReviewCount: 1, - RequiredReviewThreadResolution: true, - }, - }, - RequiredStatusChecks: &RepositoryRulesetRequiredStatusChecksRule{ - Type: "required_status_checks", - Parameters: &RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ - { - Context: "test", - IntegrationID: Ptr(int64(1)), - }, - }, - StrictRequiredStatusChecksPolicy: true, - }, - }, - NonFastForward: &RepositoryRulesetRuleType{ - Type: "non_fast_forward", - }, - CommitMessagePattern: &RepositoryRulesetPatternRule{ - Type: "commit_message_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid test commits"), - Negate: Ptr(true), - Operator: "starts_with", - Pattern: "[test]", - }, - }, - CommitAuthorEmailPattern: &RepositoryRulesetPatternRule{ - Type: "commit_author_email_pattern", - Parameters: &RulePatternParameters{ - Operator: "contains", - Pattern: "github", - }, - }, - CommitterEmailPattern: &RepositoryRulesetPatternRule{ - Type: "committer_email_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid commit emails"), - Negate: Ptr(true), - Operator: "ends_with", - Pattern: "abc", - }, - }, - BranchNamePattern: &RepositoryRulesetPatternRule{ - Type: "branch_name_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid branch names"), - Negate: Ptr(true), - Operator: "regex", - Pattern: "github$", - }, - }, - TagNamePattern: &RepositoryRulesetPatternRule{ - Type: "tag_name_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid tag names"), - Negate: Ptr(true), - Operator: "contains", - Pattern: "github", - }, - }, - FilePathRestriction: &RepositoryRulesetFilePathRestrictionRule{ - Type: "file_path_restriction", - Parameters: &RuleFileParameters{ - RestrictedFilePaths: &[]string{"/a/file"}, - }, - }, - MaxFilePathLength: &RepositoryRulesetMaxFilePathLengthRule{ - Type: "max_file_path_length", - Parameters: &RuleMaxFilePathLengthParameters{ - MaxFilePathLength: 255, - }, - }, - FileExtensionRestriction: &RepositoryRulesetFileExtensionRestrictionRule{ - Type: "file_extension_restriction", - Parameters: &RuleFileExtensionRestrictionParameters{ - RestrictedFileExtensions: []string{".exe"}, - }, - }, - MaxFileSize: &RepositoryRulesetMaxFileSizeRule{ - Type: "max_file_size", - Parameters: &RuleMaxFileSizeParameters{ - MaxFileSize: 1024, - }, - }, - Workflows: &RepositoryRulesetWorkflowsRule{ - Type: "workflows", - Parameters: &RequiredWorkflowsRuleParameters{ - RequiredWorkflows: []*RuleRequiredWorkflow{ - { - Path: ".github/workflows/test.yml", - RepositoryID: Ptr(int64(1)), - }, - }, - }, - }, - CodeScanning: &RepositoryRulesetCodeScanningRule{ - Type: "code_scanning", - Parameters: &RuleCodeScanningParameters{ - CodeScanningTools: []*CodeScanningTool{{ - AlertsThreshold: "alert", - SecurityAlertsThreshold: "security", - Tool: "tool", - }}, - }, - }, - }, - }, - Updated: []*RepositoryRulesetUpdatedRules{ - { - Rule: &RepositoryRulesetRule{ - Creation: &RepositoryRulesetRuleType{ - Type: "creation", - }, - Update: &RepositoryRulesetUpdateRule{ - Type: "update", - Parameters: &UpdateAllowsFetchAndMergeRuleParameters{ - UpdateAllowsFetchAndMerge: true, - }, - }, - Deletion: &RepositoryRulesetRuleType{ - Type: "deletion", - }, - RequiredLinearHistory: &RepositoryRulesetRuleType{ - Type: "required_linear_history", - }, - MergeQueue: &RepositoryRulesetMergeQueueRule{ - Type: "merge_queue", - Parameters: &MergeQueueRuleParameters{ - CheckResponseTimeoutMinutes: 35, - GroupingStrategy: "HEADGREEN", - MaxEntriesToBuild: 8, - MaxEntriesToMerge: 4, - MergeMethod: "SQUASH", - MinEntriesToMerge: 2, - MinEntriesToMergeWaitMinutes: 13, - }, - }, - RequiredDeployments: &RepositoryRulesetRequiredDeploymentsRule{ - Type: "required_deployments", - Parameters: &RequiredDeploymentEnvironmentsRuleParameters{ - RequiredDeploymentEnvironments: []string{"test"}, - }, - }, - RequiredSignatures: &RepositoryRulesetRuleType{ - Type: "required_signatures", - }, - PullRequest: &RepositoryRulesetPullRequestRule{ - Type: "pull_request", - Parameters: &PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, - DismissStaleReviewsOnPush: true, - RequireCodeOwnerReview: true, - RequireLastPushApproval: true, - RequiredApprovingReviewCount: 1, - RequiredReviewThreadResolution: true, - }, - }, - RequiredStatusChecks: &RepositoryRulesetRequiredStatusChecksRule{ - Type: "required_status_checks", - Parameters: &RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ - { - Context: "test", - IntegrationID: Ptr(int64(1)), - }, - }, - StrictRequiredStatusChecksPolicy: true, - }, - }, - NonFastForward: &RepositoryRulesetRuleType{ - Type: "non_fast_forward", - }, - CommitMessagePattern: &RepositoryRulesetPatternRule{ - Type: "commit_message_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid test commits"), - Negate: Ptr(true), - Operator: "starts_with", - Pattern: "[test]", - }, - }, - CommitAuthorEmailPattern: &RepositoryRulesetPatternRule{ - Type: "commit_author_email_pattern", - Parameters: &RulePatternParameters{ - Operator: "contains", - Pattern: "github", - }, - }, - CommitterEmailPattern: &RepositoryRulesetPatternRule{ - Type: "committer_email_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid commit emails"), - Negate: Ptr(true), - Operator: "ends_with", - Pattern: "abc", - }, - }, - BranchNamePattern: &RepositoryRulesetPatternRule{ - Type: "branch_name_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid branch names"), - Negate: Ptr(true), - Operator: "regex", - Pattern: "github$", - }, - }, - TagNamePattern: &RepositoryRulesetPatternRule{ - Type: "tag_name_pattern", - Parameters: &RulePatternParameters{ - Name: Ptr("avoid tag names"), - Negate: Ptr(true), - Operator: "contains", - Pattern: "github", - }, - }, - FilePathRestriction: &RepositoryRulesetFilePathRestrictionRule{ - Type: "file_path_restriction", - Parameters: &RuleFileParameters{ - RestrictedFilePaths: &[]string{"/a/file"}, - }, - }, - MaxFilePathLength: &RepositoryRulesetMaxFilePathLengthRule{ - Type: "max_file_path_length", - Parameters: &RuleMaxFilePathLengthParameters{ - MaxFilePathLength: 255, - }, - }, - FileExtensionRestriction: &RepositoryRulesetFileExtensionRestrictionRule{ - Type: "file_extension_restriction", - Parameters: &RuleFileExtensionRestrictionParameters{ - RestrictedFileExtensions: []string{".exe"}, - }, - }, - MaxFileSize: &RepositoryRulesetMaxFileSizeRule{ - Type: "max_file_size", - Parameters: &RuleMaxFileSizeParameters{ - MaxFileSize: 1024, - }, - }, - Workflows: &RepositoryRulesetWorkflowsRule{ - Type: "workflows", - Parameters: &RequiredWorkflowsRuleParameters{ - RequiredWorkflows: []*RuleRequiredWorkflow{ - { - Path: ".github/workflows/test.yml", - RepositoryID: Ptr(int64(1)), - }, - }, - }, - }, - CodeScanning: &RepositoryRulesetCodeScanningRule{ - Type: "code_scanning", - Parameters: &RuleCodeScanningParameters{ - CodeScanningTools: []*CodeScanningTool{{ - AlertsThreshold: "alert", - SecurityAlertsThreshold: "security", - Tool: "tool", - }}, - }, - }, - }, - Changes: &RepositoryRulesetEditedRuleChanges{ - Configuration: &RepositoryRulesetEditedSources{ - From: []string{"from"}, - }, - RuleType: &RepositoryRulesetEditedSources{ - From: []string{"from"}, - }, - Pattern: &RepositoryRulesetEditedSources{ - From: []string{"from"}, - }, - }, - }, - }, - }, - }, - Sender: &User{ - Login: Ptr("l"), - ID: Ptr(int64(1)), - NodeID: Ptr("n"), - URL: Ptr("u"), - ReposURL: Ptr("r"), - EventsURL: Ptr("e"), - AvatarURL: Ptr("a"), - }, + organization := &Organization{ + ID: Ptr(int64(1)), + NodeID: Ptr("n"), + Name: Ptr("o"), } - want := `{ - "action": "a", - "enterprise": { - "id": 1, - "slug": "s", - "name": "n", - "node_id": "nid", - "avatar_url": "au", - "description": "d", - "website_url": "wu", - "html_url": "hu", - "created_at": ` + referenceTimeStr + `, - "updated_at": ` + referenceTimeStr + ` - }, - "installation": { - "id": 1, - "node_id": "nid", - "app_id": 1, - "app_slug": "as", - "target_id": 1, - "account": { - "login": "l", - "id": 1, - "avatar_url": "a", - "gravatar_id": "g", - "name": "n", - "company": "c", - "blog": "b", - "location": "l", - "email": "e", - "hireable": true, - "bio": "b", - "twitter_username": "t", - "public_repos": 1, - "followers": 1, - "following": 1, - "created_at": ` + referenceTimeStr + `, - "suspended_at": ` + referenceTimeStr + `, - "url": "u" - }, - "access_tokens_url": "atu", - "repositories_url": "ru", - "html_url": "hu", - "target_type": "tt", - "single_file_name": "sfn", - "repository_selection": "rs", - "events": [ - "e" - ], - "single_file_paths": [ - "s" - ], - "permissions": { - "actions": "a", - "administration": "ad", - "checks": "c", - "contents": "co", - "content_references": "cr", - "deployments": "d", - "environments": "e", - "issues": "i", - "metadata": "md", - "members": "m", - "organization_administration": "oa", - "organization_hooks": "oh", - "organization_plan": "op", - "organization_pre_receive_hooks": "opr", - "organization_projects": "op", - "organization_secrets": "os", - "organization_self_hosted_runners": "osh", - "organization_user_blocking": "oub", - "packages": "pkg", - "pages": "pg", - "pull_requests": "pr", - "repository_hooks": "rh", - "repository_projects": "rp", - "repository_pre_receive_hooks": "rprh", - "secrets": "s", - "secret_scanning_alerts": "ssa", - "security_events": "se", - "single_file": "sf", - "statuses": "s", - "team_discussions": "td", - "vulnerability_alerts": "va", - "workflows": "w" - }, - "created_at": ` + referenceTimeStr + `, - "updated_at": ` + referenceTimeStr + `, - "has_multiple_single_files": false, - "suspended_by": { - "login": "l", - "id": 1, - "avatar_url": "a", - "gravatar_id": "g", - "name": "n", - "company": "c", - "blog": "b", - "location": "l", - "email": "e", - "hireable": true, - "bio": "b", - "twitter_username": "t", - "public_repos": 1, - "followers": 1, - "following": 1, - "created_at": ` + referenceTimeStr + `, - "suspended_at": ` + referenceTimeStr + `, - "url": "u" - }, - "suspended_at": ` + referenceTimeStr + ` - }, - "organization": { - "name": "n", - "company": "c", - "blog": "b", - "location": "loc", - "email": "e", - "twitter_username": "tu", - "description": "d", - "billing_email": "be", - "is_verified": true, - "has_organization_projects": true, - "has_repository_projects": true, - "default_repository_permission": "drp", - "members_can_create_repositories": true, - "members_can_create_public_repositories": false, - "members_can_create_private_repositories": true, - "members_can_create_internal_repositories": true, - "members_allowed_repository_creation_type": "marct", - "members_can_create_pages": true, - "members_can_create_public_pages": false, - "members_can_create_private_pages": true - }, - "repository": { - "id": 1, - "name": "n", - "url": "u" - }, - "repository_ruleset": { - "id": 1, - "name": "n", - "target": "branch", - "source_type": "Repository", - "source": "s", - "enforcement": "disabled", - "bypass_actors": [ - { - "actor_id": 234, - "actor_type": "Team", - "bypass_mode": "Always" - } - ], - "current_user_can_bypass": "always", - "node_id": "n", - "_links": { - "self": { - "href": "href" - }, - "html": { - "href": "href" - } - }, - "conditions": { - "key": "value" - }, - "rules": [ - { - "creation": { - "type": "creation" - }, - "update": { - "type": "update", - "parameters": { - "update_allows_fetch_and_merge": true - } - }, - "deletion": { - "type": "deletion" - }, - "required_linear_history": { - "type": "required_linear_history" - }, - "merge_queue": { - "type": "merge_queue", - "parameters": { - "check_response_timeout_minutes": 35, - "grouping_strategy": "HEADGREEN", - "max_entries_to_build": 8, - "max_entries_to_merge": 4, - "merge_method": "SQUASH", - "min_entries_to_merge": 2, - "min_entries_to_merge_wait_minutes": 13 - } - }, - "required_deployments": { - "type": "required_deployments", - "parameters": { - "required_deployment_environments": [ - "test" - ] - } - }, - "required_signatures": { - "type": "required_signatures" - }, - "pull_request": { - "type": "pull_request", - "parameters": { - "allowed_merge_methods": ["rebase","squash"], - "dismiss_stale_reviews_on_push": true, - "require_code_owner_review": true, - "require_last_push_approval": true, - "required_approving_review_count": 1, - "required_review_thread_resolution": true - } - }, - "required_status_checks": { - "type": "required_status_checks", - "parameters": { - "required_status_checks": [ - { - "context": "test", - "integration_id": 1 - } - ], - "strict_required_status_checks_policy": true - } - }, - "non_fast_forward": { - "type": "non_fast_forward" - }, - "commit_message_pattern": { - "type": "commit_message_pattern", - "parameters": { - "name": "avoid test commits", - "negate": true, - "operator": "starts_with", - "pattern": "[test]" - } - }, - "commit_author_email_pattern": { - "type": "commit_author_email_pattern", - "parameters": { - "operator": "contains", - "pattern": "github" - } - }, - "committer_email_pattern": { - "type": "committer_email_pattern", - "parameters": { - "name": "avoid commit emails", - "negate": true, - "operator": "ends_with", - "pattern": "abc" - } - }, - "branch_name_pattern": { - "type": "branch_name_pattern", - "parameters": { - "name": "avoid branch names", - "negate": true, - "operator": "regex", - "pattern": "github$" - } - }, - "tag_name_pattern": { - "type": "tag_name_pattern", - "parameters": { - "name": "avoid tag names", - "negate": true, - "operator": "contains", - "pattern": "github" - } - }, - "file_path_restriction": { - "type": "file_path_restriction", - "parameters": { - "restricted_file_paths": [ - "/a/file" - ] - } - }, - "max_file_path_length": { - "type": "max_file_path_length", - "parameters": { - "max_file_path_length": 255 - } - }, - "file_extension_restriction": { - "type": "file_extension_restriction", - "parameters": { - "restricted_file_extensions": [ - ".exe" - ] - } - }, - "max_file_size": { - "type": "max_file_size", - "parameters": { - "max_file_size": 1024 - } - }, - "workflows": { - "type": "workflows", - "parameters": { - "workflows": [ - { - "path": ".github/workflows/test.yml", - "repository_id": 1 - } - ] - } - }, - "code_scanning": { - "type": "code_scanning", - "parameters": { - "code_scanning_tools": [ - { - "alerts_threshold": "alert", - "security_alerts_threshold": "security", - "tool": "tool" - } - ] - } - } - } - ], - "created_at": ` + referenceTimeStr + `, - "updated_at": ` + referenceTimeStr + ` - }, - "changes": { - "name": { - "from": "f" - }, - "enforcement": { - "from": "e" - }, - "conditions": { - "added": [ - { - "ref_name": { - "include": [ - "refs/heads/main", - "refs/heads/master" - ], - "exclude": [ - "refs/heads/dev*" - ] - } - } - ], - "deleted": [ - { - "ref_name": { - "include": [ - "refs/heads/main", - "refs/heads/master" - ], - "exclude": [ - "refs/heads/dev*" - ] - } - } - ], - "updated": [ - { - "condition": { - "ref_name": { - "include": [ - "refs/heads/main", - "refs/heads/master" - ], - "exclude": [ - "refs/heads/dev*" - ] - } - }, - "changes": { - "condition_type": { - "from": "c" - }, - "target": { - "from": "t" - }, - "include": { - "from": [ - "from" - ] - }, - "exclude": { - "from": [ - "to" - ] - } - } - } - ] - }, - "rules": { - "added": [ - { - "creation": { - "type": "creation" - }, - "update": { - "type": "update", - "parameters": { - "update_allows_fetch_and_merge": true - } - }, - "deletion": { - "type": "deletion" - }, - "required_linear_history": { - "type": "required_linear_history" - }, - "merge_queue": { - "type": "merge_queue", - "parameters": { - "check_response_timeout_minutes": 35, - "grouping_strategy": "HEADGREEN", - "max_entries_to_build": 8, - "max_entries_to_merge": 4, - "merge_method": "SQUASH", - "min_entries_to_merge": 2, - "min_entries_to_merge_wait_minutes": 13 - } - }, - "required_deployments": { - "type": "required_deployments", - "parameters": { - "required_deployment_environments": [ - "test" - ] - } - }, - "required_signatures": { - "type": "required_signatures" - }, - "pull_request": { - "type": "pull_request", - "parameters": { - "allowed_merge_methods": ["rebase","squash"], - "dismiss_stale_reviews_on_push": true, - "require_code_owner_review": true, - "require_last_push_approval": true, - "required_approving_review_count": 1, - "required_review_thread_resolution": true - } - }, - "required_status_checks": { - "type": "required_status_checks", - "parameters": { - "required_status_checks": [ - { - "context": "test", - "integration_id": 1 - } - ], - "strict_required_status_checks_policy": true - } - }, - "non_fast_forward": { - "type": "non_fast_forward" - }, - "commit_message_pattern": { - "type": "commit_message_pattern", - "parameters": { - "name": "avoid test commits", - "negate": true, - "operator": "starts_with", - "pattern": "[test]" - } - }, - "commit_author_email_pattern": { - "type": "commit_author_email_pattern", - "parameters": { - "operator": "contains", - "pattern": "github" - } - }, - "committer_email_pattern": { - "type": "committer_email_pattern", - "parameters": { - "name": "avoid commit emails", - "negate": true, - "operator": "ends_with", - "pattern": "abc" - } - }, - "branch_name_pattern": { - "type": "branch_name_pattern", - "parameters": { - "name": "avoid branch names", - "negate": true, - "operator": "regex", - "pattern": "github$" - } - }, - "tag_name_pattern": { - "type": "tag_name_pattern", - "parameters": { - "name": "avoid tag names", - "negate": true, - "operator": "contains", - "pattern": "github" - } - }, - "file_path_restriction": { - "type": "file_path_restriction", - "parameters": { - "restricted_file_paths": [ - "/a/file" - ] - } - }, - "max_file_path_length": { - "type": "max_file_path_length", - "parameters": { - "max_file_path_length": 255 - } - }, - "file_extension_restriction": { - "type": "file_extension_restriction", - "parameters": { - "restricted_file_extensions": [ - ".exe" - ] - } - }, - "max_file_size": { - "type": "max_file_size", - "parameters": { - "max_file_size": 1024 - } - }, - "workflows": { - "type": "workflows", - "parameters": { - "workflows": [ - { - "path": ".github/workflows/test.yml", - "repository_id": 1 - } - ] - } - }, - "code_scanning": { - "type": "code_scanning", - "parameters": { - "code_scanning_tools": [ - { - "alerts_threshold": "alert", - "security_alerts_threshold": "security", - "tool": "tool" - } - ] - } - } - } - ], - "deleted": [ - { - "creation": { - "type": "creation" - }, - "update": { - "type": "update", - "parameters": { - "update_allows_fetch_and_merge": true - } - }, - "deletion": { - "type": "deletion" - }, - "required_linear_history": { - "type": "required_linear_history" - }, - "merge_queue": { - "type": "merge_queue", - "parameters": { - "check_response_timeout_minutes": 35, - "grouping_strategy": "HEADGREEN", - "max_entries_to_build": 8, - "max_entries_to_merge": 4, - "merge_method": "SQUASH", - "min_entries_to_merge": 2, - "min_entries_to_merge_wait_minutes": 13 - } - }, - "required_deployments": { - "type": "required_deployments", - "parameters": { - "required_deployment_environments": [ - "test" - ] - } - }, - "required_signatures": { - "type": "required_signatures" - }, - "pull_request": { - "type": "pull_request", - "parameters": { - "allowed_merge_methods": ["rebase","squash"], - "dismiss_stale_reviews_on_push": true, - "require_code_owner_review": true, - "require_last_push_approval": true, - "required_approving_review_count": 1, - "required_review_thread_resolution": true - } - }, - "required_status_checks": { - "type": "required_status_checks", - "parameters": { - "required_status_checks": [ - { - "context": "test", - "integration_id": 1 - } - ], - "strict_required_status_checks_policy": true - } - }, - "non_fast_forward": { - "type": "non_fast_forward" - }, - "commit_message_pattern": { - "type": "commit_message_pattern", - "parameters": { - "name": "avoid test commits", - "negate": true, - "operator": "starts_with", - "pattern": "[test]" - } - }, - "commit_author_email_pattern": { - "type": "commit_author_email_pattern", - "parameters": { - "operator": "contains", - "pattern": "github" - } - }, - "committer_email_pattern": { - "type": "committer_email_pattern", - "parameters": { - "name": "avoid commit emails", - "negate": true, - "operator": "ends_with", - "pattern": "abc" - } - }, - "branch_name_pattern": { - "type": "branch_name_pattern", - "parameters": { - "name": "avoid branch names", - "negate": true, - "operator": "regex", - "pattern": "github$" - } - }, - "tag_name_pattern": { - "type": "tag_name_pattern", - "parameters": { - "name": "avoid tag names", - "negate": true, - "operator": "contains", - "pattern": "github" - } - }, - "file_path_restriction": { - "type": "file_path_restriction", - "parameters": { - "restricted_file_paths": [ - "/a/file" - ] - } - }, - "max_file_path_length": { - "type": "max_file_path_length", - "parameters": { - "max_file_path_length": 255 - } - }, - "file_extension_restriction": { - "type": "file_extension_restriction", - "parameters": { - "restricted_file_extensions": [ - ".exe" - ] - } - }, - "max_file_size": { - "type": "max_file_size", - "parameters": { - "max_file_size": 1024 - } - }, - "workflows": { - "type": "workflows", - "parameters": { - "workflows": [ - { - "path": ".github/workflows/test.yml", - "repository_id": 1 - } - ] - } - }, - "code_scanning": { - "type": "code_scanning", - "parameters": { - "code_scanning_tools": [ - { - "alerts_threshold": "alert", - "security_alerts_threshold": "security", - "tool": "tool" - } - ] - } - } - } - ], - "updated": [ - { - "rule": { - "creation": { - "type": "creation" - }, - "update": { - "type": "update", - "parameters": { - "update_allows_fetch_and_merge": true - } - }, - "deletion": { - "type": "deletion" - }, - "required_linear_history": { - "type": "required_linear_history" - }, - "merge_queue": { - "type": "merge_queue", - "parameters": { - "check_response_timeout_minutes": 35, - "grouping_strategy": "HEADGREEN", - "max_entries_to_build": 8, - "max_entries_to_merge": 4, - "merge_method": "SQUASH", - "min_entries_to_merge": 2, - "min_entries_to_merge_wait_minutes": 13 - } - }, - "required_deployments": { - "type": "required_deployments", - "parameters": { - "required_deployment_environments": [ - "test" - ] - } - }, - "required_signatures": { - "type": "required_signatures" - }, - "pull_request": { - "type": "pull_request", - "parameters": { - "allowed_merge_methods": ["rebase","squash"], - "dismiss_stale_reviews_on_push": true, - "require_code_owner_review": true, - "require_last_push_approval": true, - "required_approving_review_count": 1, - "required_review_thread_resolution": true - } - }, - "required_status_checks": { - "type": "required_status_checks", - "parameters": { - "required_status_checks": [ - { - "context": "test", - "integration_id": 1 - } - ], - "strict_required_status_checks_policy": true - } - }, - "non_fast_forward": { - "type": "non_fast_forward" - }, - "commit_message_pattern": { - "type": "commit_message_pattern", - "parameters": { - "name": "avoid test commits", - "negate": true, - "operator": "starts_with", - "pattern": "[test]" - } - }, - "commit_author_email_pattern": { - "type": "commit_author_email_pattern", - "parameters": { - "operator": "contains", - "pattern": "github" - } - }, - "committer_email_pattern": { - "type": "committer_email_pattern", - "parameters": { - "name": "avoid commit emails", - "negate": true, - "operator": "ends_with", - "pattern": "abc" - } - }, - "branch_name_pattern": { - "type": "branch_name_pattern", - "parameters": { - "name": "avoid branch names", - "negate": true, - "operator": "regex", - "pattern": "github$" - } - }, - "tag_name_pattern": { - "type": "tag_name_pattern", - "parameters": { - "name": "avoid tag names", - "negate": true, - "operator": "contains", - "pattern": "github" - } - }, - "file_path_restriction": { - "type": "file_path_restriction", - "parameters": { - "restricted_file_paths": [ - "/a/file" - ] - } - }, - "max_file_path_length": { - "type": "max_file_path_length", - "parameters": { - "max_file_path_length": 255 - } - }, - "file_extension_restriction": { - "type": "file_extension_restriction", - "parameters": { - "restricted_file_extensions": [ - ".exe" - ] - } - }, - "max_file_size": { - "type": "max_file_size", - "parameters": { - "max_file_size": 1024 - } - }, - "workflows": { - "type": "workflows", - "parameters": { - "workflows": [ - { - "path": ".github/workflows/test.yml", - "repository_id": 1 - } - ] - } - }, - "code_scanning": { - "type": "code_scanning", - "parameters": { - "code_scanning_tools": [ - { - "alerts_threshold": "alert", - "security_alerts_threshold": "security", - "tool": "tool" - } - ] - } - } - }, - "changes": { - "configuration": { - "from": [ - "from" - ] - }, - "rule_type": { - "from": [ - "from" - ] - }, - "pattern": { - "from": [ - "from" - ] - } - } - } - ] - } - }, - "sender": { - "login": "l", - "id": 1, - "node_id": "n", - "avatar_url": "a", - "url": "u", - "events_url": "e", - "repos_url": "r" - } - }` + repository := &Repository{ + ID: Ptr(int64(1)), + NodeID: Ptr("n"), + Name: Ptr("r"), + FullName: Ptr("o/r"), + } - testJSONMarshal(t, u, want) + sender := &User{ + ID: Ptr(int64(1)), + NodeID: Ptr("n"), + Login: Ptr("l"), + } + + tests := []struct { + name string + json string + event *RepositoryRulesetEvent + }{ + {"empty", `{}`, &RepositoryRulesetEvent{}}, + {"created", fmt.Sprintf(`{"action":"created","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~ALL"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase","merge"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"high_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("created"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~ALL"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase, MergeMethodMerge}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, + {"edited", fmt.Sprintf(`{"action":"edited","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type": "required_signatures"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"changes":{"rules":{"added":[{"type": "required_signatures"}],"updated":[{"rule":{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},"changes":{"configuration":{"from":"{\\\"required_reviewers\\\":[],\\\"allowed_merge_methods\\\":[\\\"squash\\\",\\\"rebase\\\",\\\"merge\\\"],\\\"require_code_owner_review\\\":false,\\\"require_last_push_approval\\\":false,\\\"dismiss_stale_reviews_on_push\\\":false,\\\"required_approving_review_count\\\":2,\\\"authorized_dismissal_actors_only\\\":false,\\\"required_review_thread_resolution\\\":false,\\\"ignore_approvals_from_contributors\\\":false,\\\"automatic_copilot_code_review_enabled\\\":false}"}}},{"rule":{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}},"changes":{"configuration":{"from":"{\\\"code_scanning_tools\\\":[{\\\"tool\\\":\\\"CodeQL\\\",\\\"alerts_threshold\\\":\\\"errors\\\",\\\"security_alerts_threshold\\\":\\\"high_or_higher\\\"}]}"}}}],"deleted":[{"type":"required_linear_history"}]},"conditions":{"updated":[{"condition":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"changes":{"include":{"from":["~ALL"]}}}],"deleted":[]}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("edited"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Changes: &RepositoryRulesetChanges{Conditions: &RepositoryRulesetChangedConditions{Updated: []RepositoryRulesetUpdatedConditions{{Condition: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Changes: &RepositoryRulesetUpdatedCondition{Include: &RepositoryRulesetChangeSources{From: []string{"~ALL"}}}}}, Deleted: []RepositoryRulesetConditions{}}, Rules: &RepositoryRulesetChangedRules{Added: []RepositoryRulesetRule{{Type: RulesetRuleTypeRequiredSignatures}}, Updated: []RepositoryRulesetUpdatedRules{{Rule: &RepositoryRulesetRule{Type: RulesetRuleTypePullRequest, Parameters: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"required_reviewers\":[],\"allowed_merge_methods\":[\"squash\",\"rebase\",\"merge\"],\"require_code_owner_review\":false,\"require_last_push_approval\":false,\"dismiss_stale_reviews_on_push\":false,\"required_approving_review_count\":2,\"authorized_dismissal_actors_only\":false,\"required_review_thread_resolution\":false,\"ignore_approvals_from_contributors\":false,\"automatic_copilot_code_review_enabled\":false}`)}}}, {Rule: &RepositoryRulesetRule{Type: RulesetRuleTypeCodeScanning, Parameters: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"code_scanning_tools\":[{\"tool\":\"CodeQL\",\"alerts_threshold\":\"errors\",\"security_alerts_threshold\":\"high_or_higher\"}]}`)}}}}, Deleted: []RepositoryRulesetRule{{Type: RulesetRuleTypeRequiredLinearHistory}}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, + {"deleted", fmt.Sprintf(`{"action":"deleted","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("deleted"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + got := &RepositoryRulesetEvent{} + err := json.Unmarshal([]byte(test.json), got) + if err != nil { + t.Errorf("Unable to unmarshal JSON %v: %v", test.json, err) + } + + if diff := cmp.Diff(test.event, got); diff != "" { + t.Errorf("json.Unmarshal returned:\n%#v\nwant:\n%#v\ndiff:\n%v", got, test.event, diff) + } + }) + } } func TestContentReferenceEvent_Marshal(t *testing.T) { diff --git a/github/github-accessors.go b/github/github-accessors.go index ec7ac4f7b20..30609cbe96a 100644 --- a/github/github-accessors.go +++ b/github/github-accessors.go @@ -1934,20 +1934,20 @@ func (b *BypassActor) GetActorID() int64 { return *b.ActorID } -// GetActorType returns the ActorType field if it's non-nil, zero value otherwise. -func (b *BypassActor) GetActorType() string { - if b == nil || b.ActorType == nil { - return "" +// GetActorType returns the ActorType field. +func (b *BypassActor) GetActorType() *BypassActorType { + if b == nil { + return nil } - return *b.ActorType + return b.ActorType } -// GetBypassMode returns the BypassMode field if it's non-nil, zero value otherwise. -func (b *BypassActor) GetBypassMode() string { - if b == nil || b.BypassMode == nil { - return "" +// GetBypassMode returns the BypassMode field. +func (b *BypassActor) GetBypassMode() *BypassMode { + if b == nil { + return nil } - return *b.BypassMode + return b.BypassMode } // GetApp returns the App field. @@ -15206,6 +15206,22 @@ func (p *PagesUpdate) GetSource() *PagesSource { return p.Source } +// GetName returns the Name field if it's non-nil, zero value otherwise. +func (p *PatternRuleParameters) GetName() string { + if p == nil || p.Name == nil { + return "" + } + return *p.Name +} + +// GetNegate returns the Negate field if it's non-nil, zero value otherwise. +func (p *PatternRuleParameters) GetNegate() bool { + if p == nil || p.Negate == nil { + return false + } + return *p.Negate +} + // GetCurrentUserCanApprove returns the CurrentUserCanApprove field if it's non-nil, zero value otherwise. func (p *PendingDeployment) GetCurrentUserCanApprove() bool { if p == nil || p.CurrentUserCanApprove == nil { @@ -20822,12 +20838,12 @@ func (r *RepositoryRelease) GetZipballURL() string { return *r.ZipballURL } -// GetParameters returns the Parameters field if it's non-nil, zero value otherwise. -func (r *RepositoryRule) GetParameters() json.RawMessage { - if r == nil || r.Parameters == nil { - return json.RawMessage{} +// GetConditions returns the Conditions field. +func (r *RepositoryRuleset) GetConditions() *RepositoryRulesetConditions { + if r == nil { + return nil } - return *r.Parameters + return r.Conditions } // GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. @@ -20838,16 +20854,24 @@ func (r *RepositoryRuleset) GetCreatedAt() Timestamp { return *r.CreatedAt } -// GetCurrentUserCanBypass returns the CurrentUserCanBypass field if it's non-nil, zero value otherwise. -func (r *RepositoryRuleset) GetCurrentUserCanBypass() string { - if r == nil || r.CurrentUserCanBypass == nil { - return "" +// GetCurrentUserCanBypass returns the CurrentUserCanBypass field. +func (r *RepositoryRuleset) GetCurrentUserCanBypass() *BypassMode { + if r == nil { + return nil + } + return r.CurrentUserCanBypass +} + +// GetID returns the ID field if it's non-nil, zero value otherwise. +func (r *RepositoryRuleset) GetID() int64 { + if r == nil || r.ID == nil { + return 0 } - return *r.CurrentUserCanBypass + return *r.ID } // GetLinks returns the Links field. -func (r *RepositoryRuleset) GetLinks() *RepositoryRulesetLink { +func (r *RepositoryRuleset) GetLinks() *RepositoryRulesetLinks { if r == nil { return nil } @@ -20862,20 +20886,28 @@ func (r *RepositoryRuleset) GetNodeID() string { return *r.NodeID } -// GetSourceType returns the SourceType field if it's non-nil, zero value otherwise. -func (r *RepositoryRuleset) GetSourceType() string { - if r == nil || r.SourceType == nil { - return "" +// GetRules returns the Rules field. +func (r *RepositoryRuleset) GetRules() *RepositoryRulesetRules { + if r == nil { + return nil } - return *r.SourceType + return r.Rules } -// GetTarget returns the Target field if it's non-nil, zero value otherwise. -func (r *RepositoryRuleset) GetTarget() string { - if r == nil || r.Target == nil { - return "" +// GetSourceType returns the SourceType field. +func (r *RepositoryRuleset) GetSourceType() *RulesetSourceType { + if r == nil { + return nil } - return *r.Target + return r.SourceType +} + +// GetTarget returns the Target field. +func (r *RepositoryRuleset) GetTarget() *RulesetTarget { + if r == nil { + return nil + } + return r.Target } // GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. @@ -20886,16 +20918,40 @@ func (r *RepositoryRuleset) GetUpdatedAt() Timestamp { return *r.UpdatedAt } -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetCodeScanningRule) GetParameters() *RuleCodeScanningParameters { +// GetConfiguration returns the Configuration field. +func (r *RepositoryRulesetChangedRule) GetConfiguration() *RepositoryRulesetChangeSource { if r == nil { return nil } - return r.Parameters + return r.Configuration +} + +// GetPattern returns the Pattern field. +func (r *RepositoryRulesetChangedRule) GetPattern() *RepositoryRulesetChangeSource { + if r == nil { + return nil + } + return r.Pattern +} + +// GetRuleType returns the RuleType field. +func (r *RepositoryRulesetChangedRule) GetRuleType() *RepositoryRulesetChangeSource { + if r == nil { + return nil + } + return r.RuleType +} + +// GetFrom returns the From field if it's non-nil, zero value otherwise. +func (r *RepositoryRulesetChangeSource) GetFrom() string { + if r == nil || r.From == nil { + return "" + } + return *r.From } // GetConditions returns the Conditions field. -func (r *RepositoryRulesetEditedChanges) GetConditions() *RepositoryRulesetEditedConditions { +func (r *RepositoryRulesetChanges) GetConditions() *RepositoryRulesetChangedConditions { if r == nil { return nil } @@ -20903,7 +20959,7 @@ func (r *RepositoryRulesetEditedChanges) GetConditions() *RepositoryRulesetEdite } // GetEnforcement returns the Enforcement field. -func (r *RepositoryRulesetEditedChanges) GetEnforcement() *RepositoryRulesetEditedSource { +func (r *RepositoryRulesetChanges) GetEnforcement() *RepositoryRulesetChangeSource { if r == nil { return nil } @@ -20911,7 +20967,7 @@ func (r *RepositoryRulesetEditedChanges) GetEnforcement() *RepositoryRulesetEdit } // GetName returns the Name field. -func (r *RepositoryRulesetEditedChanges) GetName() *RepositoryRulesetEditedSource { +func (r *RepositoryRulesetChanges) GetName() *RepositoryRulesetChangeSource { if r == nil { return nil } @@ -20919,59 +20975,59 @@ func (r *RepositoryRulesetEditedChanges) GetName() *RepositoryRulesetEditedSourc } // GetRules returns the Rules field. -func (r *RepositoryRulesetEditedChanges) GetRules() *RepositoryRulesetEditedRules { +func (r *RepositoryRulesetChanges) GetRules() *RepositoryRulesetChangedRules { if r == nil { return nil } return r.Rules } -// GetConfiguration returns the Configuration field. -func (r *RepositoryRulesetEditedRuleChanges) GetConfiguration() *RepositoryRulesetEditedSources { +// GetOrganizationID returns the OrganizationID field. +func (r *RepositoryRulesetConditions) GetOrganizationID() *RepositoryRulesetOrganizationIDsConditionParameters { if r == nil { return nil } - return r.Configuration + return r.OrganizationID } -// GetPattern returns the Pattern field. -func (r *RepositoryRulesetEditedRuleChanges) GetPattern() *RepositoryRulesetEditedSources { +// GetOrganizationName returns the OrganizationName field. +func (r *RepositoryRulesetConditions) GetOrganizationName() *RepositoryRulesetOrganizationNamesConditionParameters { if r == nil { return nil } - return r.Pattern + return r.OrganizationName } -// GetRuleType returns the RuleType field. -func (r *RepositoryRulesetEditedRuleChanges) GetRuleType() *RepositoryRulesetEditedSources { +// GetRefName returns the RefName field. +func (r *RepositoryRulesetConditions) GetRefName() *RepositoryRulesetRefConditionParameters { if r == nil { return nil } - return r.RuleType + return r.RefName } -// GetFrom returns the From field if it's non-nil, zero value otherwise. -func (r *RepositoryRulesetEditedSource) GetFrom() string { - if r == nil || r.From == nil { - return "" +// GetRepositoryID returns the RepositoryID field. +func (r *RepositoryRulesetConditions) GetRepositoryID() *RepositoryRulesetRepositoryIDsConditionParameters { + if r == nil { + return nil } - return *r.From + return r.RepositoryID } -// GetChanges returns the Changes field. -func (r *RepositoryRulesetEditedUpdatedConditions) GetChanges() *RepositoryRulesetUpdatedConditionsEdited { +// GetRepositoryName returns the RepositoryName field. +func (r *RepositoryRulesetConditions) GetRepositoryName() *RepositoryRulesetRepositoryNamesConditionParameters { if r == nil { return nil } - return r.Changes + return r.RepositoryName } -// GetCondition returns the Condition field. -func (r *RepositoryRulesetEditedUpdatedConditions) GetCondition() *RepositoryRulesetRefCondition { +// GetRepositoryProperty returns the RepositoryProperty field. +func (r *RepositoryRulesetConditions) GetRepositoryProperty() *RepositoryRulesetRepositoryPropertyConditionParameters { if r == nil { return nil } - return r.Condition + return r.RepositoryProperty } // GetAction returns the Action field if it's non-nil, zero value otherwise. @@ -20983,7 +21039,7 @@ func (r *RepositoryRulesetEvent) GetAction() string { } // GetChanges returns the Changes field. -func (r *RepositoryRulesetEvent) GetChanges() *RepositoryRulesetEditedChanges { +func (r *RepositoryRulesetEvent) GetChanges() *RepositoryRulesetChanges { if r == nil { return nil } @@ -21038,24 +21094,16 @@ func (r *RepositoryRulesetEvent) GetSender() *User { return r.Sender } -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetFileExtensionRestrictionRule) GetParameters() *RuleFileExtensionRestrictionParameters { - if r == nil { - return nil - } - return r.Parameters -} - -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetFilePathRestrictionRule) GetParameters() *RuleFileParameters { - if r == nil { - return nil +// GetHRef returns the HRef field if it's non-nil, zero value otherwise. +func (r *RepositoryRulesetLink) GetHRef() string { + if r == nil || r.HRef == nil { + return "" } - return r.Parameters + return *r.HRef } // GetHTML returns the HTML field. -func (r *RepositoryRulesetLink) GetHTML() *RulesetLink { +func (r *RepositoryRulesetLinks) GetHTML() *RepositoryRulesetLink { if r == nil { return nil } @@ -21063,79 +21111,31 @@ func (r *RepositoryRulesetLink) GetHTML() *RulesetLink { } // GetSelf returns the Self field. -func (r *RepositoryRulesetLink) GetSelf() *RulesetLink { +func (r *RepositoryRulesetLinks) GetSelf() *RepositoryRulesetLink { if r == nil { return nil } return r.Self } -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetMaxFilePathLengthRule) GetParameters() *RuleMaxFilePathLengthParameters { - if r == nil { - return nil - } - return r.Parameters -} - -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetMaxFileSizeRule) GetParameters() *RuleMaxFileSizeParameters { - if r == nil { - return nil - } - return r.Parameters -} - -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetMergeQueueRule) GetParameters() *MergeQueueRuleParameters { - if r == nil { - return nil - } - return r.Parameters -} - -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetPatternRule) GetParameters() *RulePatternParameters { - if r == nil { - return nil - } - return r.Parameters -} - -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetPullRequestRule) GetParameters() *PullRequestRuleParameters { - if r == nil { - return nil - } - return r.Parameters -} - -// GetRefName returns the RefName field. -func (r *RepositoryRulesetRefCondition) GetRefName() *RulesetRefConditionParameters { - if r == nil { - return nil - } - return r.RefName -} - -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetRequiredDeploymentsRule) GetParameters() *RequiredDeploymentEnvironmentsRuleParameters { - if r == nil { - return nil +// GetProtected returns the Protected field if it's non-nil, zero value otherwise. +func (r *RepositoryRulesetRepositoryNamesConditionParameters) GetProtected() bool { + if r == nil || r.Protected == nil { + return false } - return r.Parameters + return *r.Protected } -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetRequiredStatusChecksRule) GetParameters() *RequiredStatusChecksRuleParameters { - if r == nil { - return nil +// GetSource returns the Source field if it's non-nil, zero value otherwise. +func (r *RepositoryRulesetRepositoryPropertyTargetParameters) GetSource() string { + if r == nil || r.Source == nil { + return "" } - return r.Parameters + return *r.Source } // GetBranchNamePattern returns the BranchNamePattern field. -func (r *RepositoryRulesetRule) GetBranchNamePattern() *RepositoryRulesetPatternRule { +func (r *RepositoryRulesetRules) GetBranchNamePattern() *PatternRuleParameters { if r == nil { return nil } @@ -21143,7 +21143,7 @@ func (r *RepositoryRulesetRule) GetBranchNamePattern() *RepositoryRulesetPattern } // GetCodeScanning returns the CodeScanning field. -func (r *RepositoryRulesetRule) GetCodeScanning() *RepositoryRulesetCodeScanningRule { +func (r *RepositoryRulesetRules) GetCodeScanning() *CodeScanningRuleParameters { if r == nil { return nil } @@ -21151,7 +21151,7 @@ func (r *RepositoryRulesetRule) GetCodeScanning() *RepositoryRulesetCodeScanning } // GetCommitAuthorEmailPattern returns the CommitAuthorEmailPattern field. -func (r *RepositoryRulesetRule) GetCommitAuthorEmailPattern() *RepositoryRulesetPatternRule { +func (r *RepositoryRulesetRules) GetCommitAuthorEmailPattern() *PatternRuleParameters { if r == nil { return nil } @@ -21159,7 +21159,7 @@ func (r *RepositoryRulesetRule) GetCommitAuthorEmailPattern() *RepositoryRuleset } // GetCommitMessagePattern returns the CommitMessagePattern field. -func (r *RepositoryRulesetRule) GetCommitMessagePattern() *RepositoryRulesetPatternRule { +func (r *RepositoryRulesetRules) GetCommitMessagePattern() *PatternRuleParameters { if r == nil { return nil } @@ -21167,7 +21167,7 @@ func (r *RepositoryRulesetRule) GetCommitMessagePattern() *RepositoryRulesetPatt } // GetCommitterEmailPattern returns the CommitterEmailPattern field. -func (r *RepositoryRulesetRule) GetCommitterEmailPattern() *RepositoryRulesetPatternRule { +func (r *RepositoryRulesetRules) GetCommitterEmailPattern() *PatternRuleParameters { if r == nil { return nil } @@ -21175,7 +21175,7 @@ func (r *RepositoryRulesetRule) GetCommitterEmailPattern() *RepositoryRulesetPat } // GetCreation returns the Creation field. -func (r *RepositoryRulesetRule) GetCreation() *RepositoryRulesetRuleType { +func (r *RepositoryRulesetRules) GetCreation() *EmptyRuleParameters { if r == nil { return nil } @@ -21183,7 +21183,7 @@ func (r *RepositoryRulesetRule) GetCreation() *RepositoryRulesetRuleType { } // GetDeletion returns the Deletion field. -func (r *RepositoryRulesetRule) GetDeletion() *RepositoryRulesetRuleType { +func (r *RepositoryRulesetRules) GetDeletion() *EmptyRuleParameters { if r == nil { return nil } @@ -21191,7 +21191,7 @@ func (r *RepositoryRulesetRule) GetDeletion() *RepositoryRulesetRuleType { } // GetFileExtensionRestriction returns the FileExtensionRestriction field. -func (r *RepositoryRulesetRule) GetFileExtensionRestriction() *RepositoryRulesetFileExtensionRestrictionRule { +func (r *RepositoryRulesetRules) GetFileExtensionRestriction() *FileExtensionRestrictionRuleParameters { if r == nil { return nil } @@ -21199,7 +21199,7 @@ func (r *RepositoryRulesetRule) GetFileExtensionRestriction() *RepositoryRuleset } // GetFilePathRestriction returns the FilePathRestriction field. -func (r *RepositoryRulesetRule) GetFilePathRestriction() *RepositoryRulesetFilePathRestrictionRule { +func (r *RepositoryRulesetRules) GetFilePathRestriction() *FilePathRestrictionRuleParameters { if r == nil { return nil } @@ -21207,7 +21207,7 @@ func (r *RepositoryRulesetRule) GetFilePathRestriction() *RepositoryRulesetFileP } // GetMaxFilePathLength returns the MaxFilePathLength field. -func (r *RepositoryRulesetRule) GetMaxFilePathLength() *RepositoryRulesetMaxFilePathLengthRule { +func (r *RepositoryRulesetRules) GetMaxFilePathLength() *MaxFilePathLengthRuleParameters { if r == nil { return nil } @@ -21215,7 +21215,7 @@ func (r *RepositoryRulesetRule) GetMaxFilePathLength() *RepositoryRulesetMaxFile } // GetMaxFileSize returns the MaxFileSize field. -func (r *RepositoryRulesetRule) GetMaxFileSize() *RepositoryRulesetMaxFileSizeRule { +func (r *RepositoryRulesetRules) GetMaxFileSize() *MaxFileSizeRuleParameters { if r == nil { return nil } @@ -21223,7 +21223,7 @@ func (r *RepositoryRulesetRule) GetMaxFileSize() *RepositoryRulesetMaxFileSizeRu } // GetMergeQueue returns the MergeQueue field. -func (r *RepositoryRulesetRule) GetMergeQueue() *RepositoryRulesetMergeQueueRule { +func (r *RepositoryRulesetRules) GetMergeQueue() *MergeQueueRuleParameters { if r == nil { return nil } @@ -21231,7 +21231,7 @@ func (r *RepositoryRulesetRule) GetMergeQueue() *RepositoryRulesetMergeQueueRule } // GetNonFastForward returns the NonFastForward field. -func (r *RepositoryRulesetRule) GetNonFastForward() *RepositoryRulesetRuleType { +func (r *RepositoryRulesetRules) GetNonFastForward() *EmptyRuleParameters { if r == nil { return nil } @@ -21239,7 +21239,7 @@ func (r *RepositoryRulesetRule) GetNonFastForward() *RepositoryRulesetRuleType { } // GetPullRequest returns the PullRequest field. -func (r *RepositoryRulesetRule) GetPullRequest() *RepositoryRulesetPullRequestRule { +func (r *RepositoryRulesetRules) GetPullRequest() *PullRequestRuleParameters { if r == nil { return nil } @@ -21247,7 +21247,7 @@ func (r *RepositoryRulesetRule) GetPullRequest() *RepositoryRulesetPullRequestRu } // GetRequiredDeployments returns the RequiredDeployments field. -func (r *RepositoryRulesetRule) GetRequiredDeployments() *RepositoryRulesetRequiredDeploymentsRule { +func (r *RepositoryRulesetRules) GetRequiredDeployments() *RequiredDeploymentsRuleParameters { if r == nil { return nil } @@ -21255,7 +21255,7 @@ func (r *RepositoryRulesetRule) GetRequiredDeployments() *RepositoryRulesetRequi } // GetRequiredLinearHistory returns the RequiredLinearHistory field. -func (r *RepositoryRulesetRule) GetRequiredLinearHistory() *RepositoryRulesetRuleType { +func (r *RepositoryRulesetRules) GetRequiredLinearHistory() *EmptyRuleParameters { if r == nil { return nil } @@ -21263,7 +21263,7 @@ func (r *RepositoryRulesetRule) GetRequiredLinearHistory() *RepositoryRulesetRul } // GetRequiredSignatures returns the RequiredSignatures field. -func (r *RepositoryRulesetRule) GetRequiredSignatures() *RepositoryRulesetRuleType { +func (r *RepositoryRulesetRules) GetRequiredSignatures() *EmptyRuleParameters { if r == nil { return nil } @@ -21271,7 +21271,7 @@ func (r *RepositoryRulesetRule) GetRequiredSignatures() *RepositoryRulesetRuleTy } // GetRequiredStatusChecks returns the RequiredStatusChecks field. -func (r *RepositoryRulesetRule) GetRequiredStatusChecks() *RepositoryRulesetRequiredStatusChecksRule { +func (r *RepositoryRulesetRules) GetRequiredStatusChecks() *RequiredStatusChecksRuleParameters { if r == nil { return nil } @@ -21279,7 +21279,7 @@ func (r *RepositoryRulesetRule) GetRequiredStatusChecks() *RepositoryRulesetRequ } // GetTagNamePattern returns the TagNamePattern field. -func (r *RepositoryRulesetRule) GetTagNamePattern() *RepositoryRulesetPatternRule { +func (r *RepositoryRulesetRules) GetTagNamePattern() *PatternRuleParameters { if r == nil { return nil } @@ -21287,7 +21287,7 @@ func (r *RepositoryRulesetRule) GetTagNamePattern() *RepositoryRulesetPatternRul } // GetUpdate returns the Update field. -func (r *RepositoryRulesetRule) GetUpdate() *RepositoryRulesetUpdateRule { +func (r *RepositoryRulesetRules) GetUpdate() *UpdateRuleParameters { if r == nil { return nil } @@ -21295,7 +21295,7 @@ func (r *RepositoryRulesetRule) GetUpdate() *RepositoryRulesetUpdateRule { } // GetWorkflows returns the Workflows field. -func (r *RepositoryRulesetRule) GetWorkflows() *RepositoryRulesetWorkflowsRule { +func (r *RepositoryRulesetRules) GetWorkflows() *WorkflowsRuleParameters { if r == nil { return nil } @@ -21303,7 +21303,7 @@ func (r *RepositoryRulesetRule) GetWorkflows() *RepositoryRulesetWorkflowsRule { } // GetConditionType returns the ConditionType field. -func (r *RepositoryRulesetUpdatedConditionsEdited) GetConditionType() *RepositoryRulesetEditedSource { +func (r *RepositoryRulesetUpdatedCondition) GetConditionType() *RepositoryRulesetChangeSource { if r == nil { return nil } @@ -21311,7 +21311,7 @@ func (r *RepositoryRulesetUpdatedConditionsEdited) GetConditionType() *Repositor } // GetExclude returns the Exclude field. -func (r *RepositoryRulesetUpdatedConditionsEdited) GetExclude() *RepositoryRulesetEditedSources { +func (r *RepositoryRulesetUpdatedCondition) GetExclude() *RepositoryRulesetChangeSources { if r == nil { return nil } @@ -21319,7 +21319,7 @@ func (r *RepositoryRulesetUpdatedConditionsEdited) GetExclude() *RepositoryRules } // GetInclude returns the Include field. -func (r *RepositoryRulesetUpdatedConditionsEdited) GetInclude() *RepositoryRulesetEditedSources { +func (r *RepositoryRulesetUpdatedCondition) GetInclude() *RepositoryRulesetChangeSources { if r == nil { return nil } @@ -21327,7 +21327,7 @@ func (r *RepositoryRulesetUpdatedConditionsEdited) GetInclude() *RepositoryRules } // GetTarget returns the Target field. -func (r *RepositoryRulesetUpdatedConditionsEdited) GetTarget() *RepositoryRulesetEditedSource { +func (r *RepositoryRulesetUpdatedCondition) GetTarget() *RepositoryRulesetChangeSource { if r == nil { return nil } @@ -21335,35 +21335,35 @@ func (r *RepositoryRulesetUpdatedConditionsEdited) GetTarget() *RepositoryRulese } // GetChanges returns the Changes field. -func (r *RepositoryRulesetUpdatedRules) GetChanges() *RepositoryRulesetEditedRuleChanges { +func (r *RepositoryRulesetUpdatedConditions) GetChanges() *RepositoryRulesetUpdatedCondition { if r == nil { return nil } return r.Changes } -// GetRule returns the Rule field. -func (r *RepositoryRulesetUpdatedRules) GetRule() *RepositoryRulesetRule { +// GetCondition returns the Condition field. +func (r *RepositoryRulesetUpdatedConditions) GetCondition() *RepositoryRulesetConditions { if r == nil { return nil } - return r.Rule + return r.Condition } -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetUpdateRule) GetParameters() *UpdateAllowsFetchAndMergeRuleParameters { +// GetChanges returns the Changes field. +func (r *RepositoryRulesetUpdatedRules) GetChanges() *RepositoryRulesetChangedRule { if r == nil { return nil } - return r.Parameters + return r.Changes } -// GetParameters returns the Parameters field. -func (r *RepositoryRulesetWorkflowsRule) GetParameters() *RequiredWorkflowsRuleParameters { +// GetRule returns the Rule field. +func (r *RepositoryRulesetUpdatedRules) GetRule() *RepositoryRulesetRule { if r == nil { return nil } - return r.Parameters + return r.Rule } // GetCommit returns the Commit field. @@ -21854,32 +21854,8 @@ func (r *Rule) GetSeverity() string { return *r.Severity } -// GetRestrictedFilePaths returns the RestrictedFilePaths field if it's non-nil, zero value otherwise. -func (r *RuleFileParameters) GetRestrictedFilePaths() []string { - if r == nil || r.RestrictedFilePaths == nil { - return nil - } - return *r.RestrictedFilePaths -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RulePatternParameters) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetNegate returns the Negate field if it's non-nil, zero value otherwise. -func (r *RulePatternParameters) GetNegate() bool { - if r == nil || r.Negate == nil { - return false - } - return *r.Negate -} - // GetIntegrationID returns the IntegrationID field if it's non-nil, zero value otherwise. -func (r *RuleRequiredStatusChecks) GetIntegrationID() int64 { +func (r *RuleStatusCheck) GetIntegrationID() int64 { if r == nil || r.IntegrationID == nil { return 0 } @@ -21887,7 +21863,7 @@ func (r *RuleRequiredStatusChecks) GetIntegrationID() int64 { } // GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (r *RuleRequiredWorkflow) GetRef() string { +func (r *RuleWorkflow) GetRef() string { if r == nil || r.Ref == nil { return "" } @@ -21895,7 +21871,7 @@ func (r *RuleRequiredWorkflow) GetRef() string { } // GetRepositoryID returns the RepositoryID field if it's non-nil, zero value otherwise. -func (r *RuleRequiredWorkflow) GetRepositoryID() int64 { +func (r *RuleWorkflow) GetRepositoryID() int64 { if r == nil || r.RepositoryID == nil { return 0 } @@ -21903,157 +21879,13 @@ func (r *RuleRequiredWorkflow) GetRepositoryID() int64 { } // GetSha returns the Sha field if it's non-nil, zero value otherwise. -func (r *RuleRequiredWorkflow) GetSha() string { +func (r *RuleWorkflow) GetSha() string { if r == nil || r.Sha == nil { return "" } return *r.Sha } -// GetConditions returns the Conditions field. -func (r *Ruleset) GetConditions() *RulesetConditions { - if r == nil { - return nil - } - return r.Conditions -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *Ruleset) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *Ruleset) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetLinks returns the Links field. -func (r *Ruleset) GetLinks() *RulesetLinks { - if r == nil { - return nil - } - return r.Links -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (r *Ruleset) GetNodeID() string { - if r == nil || r.NodeID == nil { - return "" - } - return *r.NodeID -} - -// GetSourceType returns the SourceType field if it's non-nil, zero value otherwise. -func (r *Ruleset) GetSourceType() string { - if r == nil || r.SourceType == nil { - return "" - } - return *r.SourceType -} - -// GetTarget returns the Target field if it's non-nil, zero value otherwise. -func (r *Ruleset) GetTarget() string { - if r == nil || r.Target == nil { - return "" - } - return *r.Target -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *Ruleset) GetUpdatedAt() Timestamp { - if r == nil || r.UpdatedAt == nil { - return Timestamp{} - } - return *r.UpdatedAt -} - -// GetOrganizationID returns the OrganizationID field. -func (r *RulesetConditions) GetOrganizationID() *RulesetOrganizationIDsConditionParameters { - if r == nil { - return nil - } - return r.OrganizationID -} - -// GetOrganizationName returns the OrganizationName field. -func (r *RulesetConditions) GetOrganizationName() *RulesetOrganizationNamesConditionParameters { - if r == nil { - return nil - } - return r.OrganizationName -} - -// GetRefName returns the RefName field. -func (r *RulesetConditions) GetRefName() *RulesetRefConditionParameters { - if r == nil { - return nil - } - return r.RefName -} - -// GetRepositoryID returns the RepositoryID field. -func (r *RulesetConditions) GetRepositoryID() *RulesetRepositoryIDsConditionParameters { - if r == nil { - return nil - } - return r.RepositoryID -} - -// GetRepositoryName returns the RepositoryName field. -func (r *RulesetConditions) GetRepositoryName() *RulesetRepositoryNamesConditionParameters { - if r == nil { - return nil - } - return r.RepositoryName -} - -// GetRepositoryProperty returns the RepositoryProperty field. -func (r *RulesetConditions) GetRepositoryProperty() *RulesetRepositoryPropertyConditionParameters { - if r == nil { - return nil - } - return r.RepositoryProperty -} - -// GetHRef returns the HRef field if it's non-nil, zero value otherwise. -func (r *RulesetLink) GetHRef() string { - if r == nil || r.HRef == nil { - return "" - } - return *r.HRef -} - -// GetSelf returns the Self field. -func (r *RulesetLinks) GetSelf() *RulesetLink { - if r == nil { - return nil - } - return r.Self -} - -// GetProtected returns the Protected field if it's non-nil, zero value otherwise. -func (r *RulesetRepositoryNamesConditionParameters) GetProtected() bool { - if r == nil || r.Protected == nil { - return false - } - return *r.Protected -} - -// GetSource returns the Source field if it's non-nil, zero value otherwise. -func (r *RulesetRepositoryPropertyTargetParameters) GetSource() string { - if r == nil || r.Source == nil { - return "" - } - return *r.Source -} - // GetBusy returns the Busy field if it's non-nil, zero value otherwise. func (r *Runner) GetBusy() bool { if r == nil || r.Busy == nil { @@ -26982,6 +26814,14 @@ func (w *Workflows) GetTotalCount() int { return *w.TotalCount } +// GetDoNotEnforceOnCreate returns the DoNotEnforceOnCreate field if it's non-nil, zero value otherwise. +func (w *WorkflowsRuleParameters) GetDoNotEnforceOnCreate() bool { + if w == nil || w.DoNotEnforceOnCreate == nil { + return false + } + return *w.DoNotEnforceOnCreate +} + // GetBillable returns the Billable field. func (w *WorkflowUsage) GetBillable() *WorkflowBillMap { if w == nil { diff --git a/github/github-accessors_test.go b/github/github-accessors_test.go index dca95aba16e..a16d2f286f5 100644 --- a/github/github-accessors_test.go +++ b/github/github-accessors_test.go @@ -2528,10 +2528,7 @@ func TestBypassActor_GetActorID(tt *testing.T) { func TestBypassActor_GetActorType(tt *testing.T) { tt.Parallel() - var zeroValue string - b := &BypassActor{ActorType: &zeroValue} - b.GetActorType() - b = &BypassActor{} + b := &BypassActor{} b.GetActorType() b = nil b.GetActorType() @@ -2539,10 +2536,7 @@ func TestBypassActor_GetActorType(tt *testing.T) { func TestBypassActor_GetBypassMode(tt *testing.T) { tt.Parallel() - var zeroValue string - b := &BypassActor{BypassMode: &zeroValue} - b.GetBypassMode() - b = &BypassActor{} + b := &BypassActor{} b.GetBypassMode() b = nil b.GetBypassMode() @@ -19671,6 +19665,28 @@ func TestPagesUpdate_GetSource(tt *testing.T) { p.GetSource() } +func TestPatternRuleParameters_GetName(tt *testing.T) { + tt.Parallel() + var zeroValue string + p := &PatternRuleParameters{Name: &zeroValue} + p.GetName() + p = &PatternRuleParameters{} + p.GetName() + p = nil + p.GetName() +} + +func TestPatternRuleParameters_GetNegate(tt *testing.T) { + tt.Parallel() + var zeroValue bool + p := &PatternRuleParameters{Negate: &zeroValue} + p.GetNegate() + p = &PatternRuleParameters{} + p.GetNegate() + p = nil + p.GetNegate() +} + func TestPendingDeployment_GetCurrentUserCanApprove(tt *testing.T) { tt.Parallel() var zeroValue bool @@ -26787,15 +26803,12 @@ func TestRepositoryRelease_GetZipballURL(tt *testing.T) { r.GetZipballURL() } -func TestRepositoryRule_GetParameters(tt *testing.T) { +func TestRepositoryRuleset_GetConditions(tt *testing.T) { tt.Parallel() - var zeroValue json.RawMessage - r := &RepositoryRule{Parameters: &zeroValue} - r.GetParameters() - r = &RepositoryRule{} - r.GetParameters() + r := &RepositoryRuleset{} + r.GetConditions() r = nil - r.GetParameters() + r.GetConditions() } func TestRepositoryRuleset_GetCreatedAt(tt *testing.T) { @@ -26811,15 +26824,23 @@ func TestRepositoryRuleset_GetCreatedAt(tt *testing.T) { func TestRepositoryRuleset_GetCurrentUserCanBypass(tt *testing.T) { tt.Parallel() - var zeroValue string - r := &RepositoryRuleset{CurrentUserCanBypass: &zeroValue} - r.GetCurrentUserCanBypass() - r = &RepositoryRuleset{} + r := &RepositoryRuleset{} r.GetCurrentUserCanBypass() r = nil r.GetCurrentUserCanBypass() } +func TestRepositoryRuleset_GetID(tt *testing.T) { + tt.Parallel() + var zeroValue int64 + r := &RepositoryRuleset{ID: &zeroValue} + r.GetID() + r = &RepositoryRuleset{} + r.GetID() + r = nil + r.GetID() +} + func TestRepositoryRuleset_GetLinks(tt *testing.T) { tt.Parallel() r := &RepositoryRuleset{} @@ -26839,12 +26860,17 @@ func TestRepositoryRuleset_GetNodeID(tt *testing.T) { r.GetNodeID() } +func TestRepositoryRuleset_GetRules(tt *testing.T) { + tt.Parallel() + r := &RepositoryRuleset{} + r.GetRules() + r = nil + r.GetRules() +} + func TestRepositoryRuleset_GetSourceType(tt *testing.T) { tt.Parallel() - var zeroValue string - r := &RepositoryRuleset{SourceType: &zeroValue} - r.GetSourceType() - r = &RepositoryRuleset{} + r := &RepositoryRuleset{} r.GetSourceType() r = nil r.GetSourceType() @@ -26852,10 +26878,7 @@ func TestRepositoryRuleset_GetSourceType(tt *testing.T) { func TestRepositoryRuleset_GetTarget(tt *testing.T) { tt.Parallel() - var zeroValue string - r := &RepositoryRuleset{Target: &zeroValue} - r.GetTarget() - r = &RepositoryRuleset{} + r := &RepositoryRuleset{} r.GetTarget() r = nil r.GetTarget() @@ -26872,95 +26895,119 @@ func TestRepositoryRuleset_GetUpdatedAt(tt *testing.T) { r.GetUpdatedAt() } -func TestRepositoryRulesetCodeScanningRule_GetParameters(tt *testing.T) { +func TestRepositoryRulesetChangedRule_GetConfiguration(tt *testing.T) { + tt.Parallel() + r := &RepositoryRulesetChangedRule{} + r.GetConfiguration() + r = nil + r.GetConfiguration() +} + +func TestRepositoryRulesetChangedRule_GetPattern(tt *testing.T) { + tt.Parallel() + r := &RepositoryRulesetChangedRule{} + r.GetPattern() + r = nil + r.GetPattern() +} + +func TestRepositoryRulesetChangedRule_GetRuleType(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetCodeScanningRule{} - r.GetParameters() + r := &RepositoryRulesetChangedRule{} + r.GetRuleType() r = nil - r.GetParameters() + r.GetRuleType() } -func TestRepositoryRulesetEditedChanges_GetConditions(tt *testing.T) { +func TestRepositoryRulesetChangedSource_GetFrom(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetEditedChanges{} + var zeroValue string + r := &RepositoryRulesetChangeSource{From: &zeroValue} + r.GetFrom() + r = &RepositoryRulesetChangeSource{} + r.GetFrom() + r = nil + r.GetFrom() +} + +func TestRepositoryRulesetChanges_GetConditions(tt *testing.T) { + tt.Parallel() + r := &RepositoryRulesetChanges{} r.GetConditions() r = nil r.GetConditions() } -func TestRepositoryRulesetEditedChanges_GetEnforcement(tt *testing.T) { +func TestRepositoryRulesetChanges_GetEnforcement(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetEditedChanges{} + r := &RepositoryRulesetChanges{} r.GetEnforcement() r = nil r.GetEnforcement() } -func TestRepositoryRulesetEditedChanges_GetName(tt *testing.T) { +func TestRepositoryRulesetChanges_GetName(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetEditedChanges{} + r := &RepositoryRulesetChanges{} r.GetName() r = nil r.GetName() } -func TestRepositoryRulesetEditedChanges_GetRules(tt *testing.T) { +func TestRepositoryRulesetChanges_GetRules(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetEditedChanges{} + r := &RepositoryRulesetChanges{} r.GetRules() r = nil r.GetRules() } -func TestRepositoryRulesetEditedRuleChanges_GetConfiguration(tt *testing.T) { +func TestRepositoryRulesetConditions_GetOrganizationID(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetEditedRuleChanges{} - r.GetConfiguration() + r := &RepositoryRulesetConditions{} + r.GetOrganizationID() r = nil - r.GetConfiguration() + r.GetOrganizationID() } -func TestRepositoryRulesetEditedRuleChanges_GetPattern(tt *testing.T) { +func TestRepositoryRulesetConditions_GetOrganizationName(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetEditedRuleChanges{} - r.GetPattern() + r := &RepositoryRulesetConditions{} + r.GetOrganizationName() r = nil - r.GetPattern() + r.GetOrganizationName() } -func TestRepositoryRulesetEditedRuleChanges_GetRuleType(tt *testing.T) { +func TestRepositoryRulesetConditions_GetRefName(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetEditedRuleChanges{} - r.GetRuleType() + r := &RepositoryRulesetConditions{} + r.GetRefName() r = nil - r.GetRuleType() + r.GetRefName() } -func TestRepositoryRulesetEditedSource_GetFrom(tt *testing.T) { +func TestRepositoryRulesetConditions_GetRepositoryID(tt *testing.T) { tt.Parallel() - var zeroValue string - r := &RepositoryRulesetEditedSource{From: &zeroValue} - r.GetFrom() - r = &RepositoryRulesetEditedSource{} - r.GetFrom() + r := &RepositoryRulesetConditions{} + r.GetRepositoryID() r = nil - r.GetFrom() + r.GetRepositoryID() } -func TestRepositoryRulesetEditedUpdatedConditions_GetChanges(tt *testing.T) { +func TestRepositoryRulesetConditions_GetRepositoryName(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetEditedUpdatedConditions{} - r.GetChanges() + r := &RepositoryRulesetConditions{} + r.GetRepositoryName() r = nil - r.GetChanges() + r.GetRepositoryName() } -func TestRepositoryRulesetEditedUpdatedConditions_GetCondition(tt *testing.T) { +func TestRepositoryRulesetConditions_GetRepositoryProperty(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetEditedUpdatedConditions{} - r.GetCondition() + r := &RepositoryRulesetConditions{} + r.GetRepositoryProperty() r = nil - r.GetCondition() + r.GetRepositoryProperty() } func TestRepositoryRulesetEvent_GetAction(tt *testing.T) { @@ -27030,332 +27077,285 @@ func TestRepositoryRulesetEvent_GetSender(tt *testing.T) { r.GetSender() } -func TestRepositoryRulesetFileExtensionRestrictionRule_GetParameters(tt *testing.T) { - tt.Parallel() - r := &RepositoryRulesetFileExtensionRestrictionRule{} - r.GetParameters() - r = nil - r.GetParameters() -} - -func TestRepositoryRulesetFilePathRestrictionRule_GetParameters(tt *testing.T) { +func TestRepositoryRulesetLink_GetHRef(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetFilePathRestrictionRule{} - r.GetParameters() + var zeroValue string + r := &RepositoryRulesetLink{HRef: &zeroValue} + r.GetHRef() + r = &RepositoryRulesetLink{} + r.GetHRef() r = nil - r.GetParameters() + r.GetHRef() } -func TestRepositoryRulesetLink_GetHTML(tt *testing.T) { +func TestRepositoryRulesetLinks_GetHTML(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetLink{} + r := &RepositoryRulesetLinks{} r.GetHTML() r = nil r.GetHTML() } -func TestRepositoryRulesetLink_GetSelf(tt *testing.T) { +func TestRepositoryRulesetLinks_GetSelf(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetLink{} + r := &RepositoryRulesetLinks{} r.GetSelf() r = nil r.GetSelf() } -func TestRepositoryRulesetMaxFilePathLengthRule_GetParameters(tt *testing.T) { - tt.Parallel() - r := &RepositoryRulesetMaxFilePathLengthRule{} - r.GetParameters() - r = nil - r.GetParameters() -} - -func TestRepositoryRulesetMaxFileSizeRule_GetParameters(tt *testing.T) { - tt.Parallel() - r := &RepositoryRulesetMaxFileSizeRule{} - r.GetParameters() - r = nil - r.GetParameters() -} - -func TestRepositoryRulesetMergeQueueRule_GetParameters(tt *testing.T) { +func TestRepositoryRulesetRepositoryNamesConditionParameters_GetProtected(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetMergeQueueRule{} - r.GetParameters() - r = nil - r.GetParameters() -} - -func TestRepositoryRulesetPatternRule_GetParameters(tt *testing.T) { - tt.Parallel() - r := &RepositoryRulesetPatternRule{} - r.GetParameters() - r = nil - r.GetParameters() -} - -func TestRepositoryRulesetPullRequestRule_GetParameters(tt *testing.T) { - tt.Parallel() - r := &RepositoryRulesetPullRequestRule{} - r.GetParameters() - r = nil - r.GetParameters() -} - -func TestRepositoryRulesetRefCondition_GetRefName(tt *testing.T) { - tt.Parallel() - r := &RepositoryRulesetRefCondition{} - r.GetRefName() - r = nil - r.GetRefName() -} - -func TestRepositoryRulesetRequiredDeploymentsRule_GetParameters(tt *testing.T) { - tt.Parallel() - r := &RepositoryRulesetRequiredDeploymentsRule{} - r.GetParameters() + var zeroValue bool + r := &RepositoryRulesetRepositoryNamesConditionParameters{Protected: &zeroValue} + r.GetProtected() + r = &RepositoryRulesetRepositoryNamesConditionParameters{} + r.GetProtected() r = nil - r.GetParameters() + r.GetProtected() } -func TestRepositoryRulesetRequiredStatusChecksRule_GetParameters(tt *testing.T) { +func TestRepositoryRulesetRepositoryPropertyTargetParameters_GetSource(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRequiredStatusChecksRule{} - r.GetParameters() + var zeroValue string + r := &RepositoryRulesetRepositoryPropertyTargetParameters{Source: &zeroValue} + r.GetSource() + r = &RepositoryRulesetRepositoryPropertyTargetParameters{} + r.GetSource() r = nil - r.GetParameters() + r.GetSource() } -func TestRepositoryRulesetRule_GetBranchNamePattern(tt *testing.T) { +func TestRepositoryRulesetRules_GetBranchNamePattern(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetBranchNamePattern() r = nil r.GetBranchNamePattern() } -func TestRepositoryRulesetRule_GetCodeScanning(tt *testing.T) { +func TestRepositoryRulesetRules_GetCodeScanning(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetCodeScanning() r = nil r.GetCodeScanning() } -func TestRepositoryRulesetRule_GetCommitAuthorEmailPattern(tt *testing.T) { +func TestRepositoryRulesetRules_GetCommitAuthorEmailPattern(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetCommitAuthorEmailPattern() r = nil r.GetCommitAuthorEmailPattern() } -func TestRepositoryRulesetRule_GetCommitMessagePattern(tt *testing.T) { +func TestRepositoryRulesetRules_GetCommitMessagePattern(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetCommitMessagePattern() r = nil r.GetCommitMessagePattern() } -func TestRepositoryRulesetRule_GetCommitterEmailPattern(tt *testing.T) { +func TestRepositoryRulesetRules_GetCommitterEmailPattern(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetCommitterEmailPattern() r = nil r.GetCommitterEmailPattern() } -func TestRepositoryRulesetRule_GetCreation(tt *testing.T) { +func TestRepositoryRulesetRules_GetCreation(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetCreation() r = nil r.GetCreation() } -func TestRepositoryRulesetRule_GetDeletion(tt *testing.T) { +func TestRepositoryRulesetRules_GetDeletion(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetDeletion() r = nil r.GetDeletion() } -func TestRepositoryRulesetRule_GetFileExtensionRestriction(tt *testing.T) { +func TestRepositoryRulesetRules_GetFileExtensionRestriction(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetFileExtensionRestriction() r = nil r.GetFileExtensionRestriction() } -func TestRepositoryRulesetRule_GetFilePathRestriction(tt *testing.T) { +func TestRepositoryRulesetRules_GetFilePathRestriction(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetFilePathRestriction() r = nil r.GetFilePathRestriction() } -func TestRepositoryRulesetRule_GetMaxFilePathLength(tt *testing.T) { +func TestRepositoryRulesetRules_GetMaxFilePathLength(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetMaxFilePathLength() r = nil r.GetMaxFilePathLength() } -func TestRepositoryRulesetRule_GetMaxFileSize(tt *testing.T) { +func TestRepositoryRulesetRules_GetMaxFileSize(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetMaxFileSize() r = nil r.GetMaxFileSize() } -func TestRepositoryRulesetRule_GetMergeQueue(tt *testing.T) { +func TestRepositoryRulesetRules_GetMergeQueue(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetMergeQueue() r = nil r.GetMergeQueue() } -func TestRepositoryRulesetRule_GetNonFastForward(tt *testing.T) { +func TestRepositoryRulesetRules_GetNonFastForward(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetNonFastForward() r = nil r.GetNonFastForward() } -func TestRepositoryRulesetRule_GetPullRequest(tt *testing.T) { +func TestRepositoryRulesetRules_GetPullRequest(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetPullRequest() r = nil r.GetPullRequest() } -func TestRepositoryRulesetRule_GetRequiredDeployments(tt *testing.T) { +func TestRepositoryRulesetRules_GetRequiredDeployments(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetRequiredDeployments() r = nil r.GetRequiredDeployments() } -func TestRepositoryRulesetRule_GetRequiredLinearHistory(tt *testing.T) { +func TestRepositoryRulesetRules_GetRequiredLinearHistory(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetRequiredLinearHistory() r = nil r.GetRequiredLinearHistory() } -func TestRepositoryRulesetRule_GetRequiredSignatures(tt *testing.T) { +func TestRepositoryRulesetRules_GetRequiredSignatures(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetRequiredSignatures() r = nil r.GetRequiredSignatures() } -func TestRepositoryRulesetRule_GetRequiredStatusChecks(tt *testing.T) { +func TestRepositoryRulesetRules_GetRequiredStatusChecks(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetRequiredStatusChecks() r = nil r.GetRequiredStatusChecks() } -func TestRepositoryRulesetRule_GetTagNamePattern(tt *testing.T) { +func TestRepositoryRulesetRules_GetTagNamePattern(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetTagNamePattern() r = nil r.GetTagNamePattern() } -func TestRepositoryRulesetRule_GetUpdate(tt *testing.T) { +func TestRepositoryRulesetRules_GetUpdate(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetUpdate() r = nil r.GetUpdate() } -func TestRepositoryRulesetRule_GetWorkflows(tt *testing.T) { +func TestRepositoryRulesetRules_GetWorkflows(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetRule{} + r := &RepositoryRulesetRules{} r.GetWorkflows() r = nil r.GetWorkflows() } -func TestRepositoryRulesetUpdatedConditionsEdited_GetConditionType(tt *testing.T) { +func TestRepositoryRulesetUpdatedCondition_GetConditionType(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetUpdatedConditionsEdited{} + r := &RepositoryRulesetUpdatedCondition{} r.GetConditionType() r = nil r.GetConditionType() } -func TestRepositoryRulesetUpdatedConditionsEdited_GetExclude(tt *testing.T) { +func TestRepositoryRulesetUpdatedCondition_GetExclude(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetUpdatedConditionsEdited{} + r := &RepositoryRulesetUpdatedCondition{} r.GetExclude() r = nil r.GetExclude() } -func TestRepositoryRulesetUpdatedConditionsEdited_GetInclude(tt *testing.T) { +func TestRepositoryRulesetUpdatedCondition_GetInclude(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetUpdatedConditionsEdited{} + r := &RepositoryRulesetUpdatedCondition{} r.GetInclude() r = nil r.GetInclude() } -func TestRepositoryRulesetUpdatedConditionsEdited_GetTarget(tt *testing.T) { +func TestRepositoryRulesetUpdatedCondition_GetTarget(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetUpdatedConditionsEdited{} + r := &RepositoryRulesetUpdatedCondition{} r.GetTarget() r = nil r.GetTarget() } -func TestRepositoryRulesetUpdatedRules_GetChanges(tt *testing.T) { +func TestRepositoryRulesetUpdatedConditions_GetChanges(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetUpdatedRules{} + r := &RepositoryRulesetUpdatedConditions{} r.GetChanges() r = nil r.GetChanges() } -func TestRepositoryRulesetUpdatedRules_GetRule(tt *testing.T) { +func TestRepositoryRulesetUpdatedConditions_GetCondition(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetUpdatedRules{} - r.GetRule() + r := &RepositoryRulesetUpdatedConditions{} + r.GetCondition() r = nil - r.GetRule() + r.GetCondition() } -func TestRepositoryRulesetUpdateRule_GetParameters(tt *testing.T) { +func TestRepositoryRulesetUpdatedRules_GetChanges(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetUpdateRule{} - r.GetParameters() + r := &RepositoryRulesetUpdatedRules{} + r.GetChanges() r = nil - r.GetParameters() + r.GetChanges() } -func TestRepositoryRulesetWorkflowsRule_GetParameters(tt *testing.T) { +func TestRepositoryRulesetUpdatedRules_GetRule(tt *testing.T) { tt.Parallel() - r := &RepositoryRulesetWorkflowsRule{} - r.GetParameters() + r := &RepositoryRulesetUpdatedRules{} + r.GetRule() r = nil - r.GetParameters() + r.GetRule() } func TestRepositoryTag_GetCommit(tt *testing.T) { @@ -28005,254 +28005,50 @@ func TestRule_GetSeverity(tt *testing.T) { r.GetSeverity() } -func TestRuleFileParameters_GetRestrictedFilePaths(tt *testing.T) { - tt.Parallel() - var zeroValue []string - r := &RuleFileParameters{RestrictedFilePaths: &zeroValue} - r.GetRestrictedFilePaths() - r = &RuleFileParameters{} - r.GetRestrictedFilePaths() - r = nil - r.GetRestrictedFilePaths() -} - -func TestRulePatternParameters_GetName(tt *testing.T) { - tt.Parallel() - var zeroValue string - r := &RulePatternParameters{Name: &zeroValue} - r.GetName() - r = &RulePatternParameters{} - r.GetName() - r = nil - r.GetName() -} - -func TestRulePatternParameters_GetNegate(tt *testing.T) { - tt.Parallel() - var zeroValue bool - r := &RulePatternParameters{Negate: &zeroValue} - r.GetNegate() - r = &RulePatternParameters{} - r.GetNegate() - r = nil - r.GetNegate() -} - -func TestRuleRequiredStatusChecks_GetIntegrationID(tt *testing.T) { +func TestRuleStatusCheck_GetIntegrationID(tt *testing.T) { tt.Parallel() var zeroValue int64 - r := &RuleRequiredStatusChecks{IntegrationID: &zeroValue} + r := &RuleStatusCheck{IntegrationID: &zeroValue} r.GetIntegrationID() - r = &RuleRequiredStatusChecks{} + r = &RuleStatusCheck{} r.GetIntegrationID() r = nil r.GetIntegrationID() } -func TestRuleRequiredWorkflow_GetRef(tt *testing.T) { +func TestRuleWorkflow_GetRef(tt *testing.T) { tt.Parallel() var zeroValue string - r := &RuleRequiredWorkflow{Ref: &zeroValue} + r := &RuleWorkflow{Ref: &zeroValue} r.GetRef() - r = &RuleRequiredWorkflow{} + r = &RuleWorkflow{} r.GetRef() r = nil r.GetRef() } -func TestRuleRequiredWorkflow_GetRepositoryID(tt *testing.T) { +func TestRuleWorkflow_GetRepositoryID(tt *testing.T) { tt.Parallel() var zeroValue int64 - r := &RuleRequiredWorkflow{RepositoryID: &zeroValue} + r := &RuleWorkflow{RepositoryID: &zeroValue} r.GetRepositoryID() - r = &RuleRequiredWorkflow{} + r = &RuleWorkflow{} r.GetRepositoryID() r = nil r.GetRepositoryID() } -func TestRuleRequiredWorkflow_GetSha(tt *testing.T) { +func TestRuleWorkflow_GetSha(tt *testing.T) { tt.Parallel() var zeroValue string - r := &RuleRequiredWorkflow{Sha: &zeroValue} + r := &RuleWorkflow{Sha: &zeroValue} r.GetSha() - r = &RuleRequiredWorkflow{} + r = &RuleWorkflow{} r.GetSha() r = nil r.GetSha() } -func TestRuleset_GetConditions(tt *testing.T) { - tt.Parallel() - r := &Ruleset{} - r.GetConditions() - r = nil - r.GetConditions() -} - -func TestRuleset_GetCreatedAt(tt *testing.T) { - tt.Parallel() - var zeroValue Timestamp - r := &Ruleset{CreatedAt: &zeroValue} - r.GetCreatedAt() - r = &Ruleset{} - r.GetCreatedAt() - r = nil - r.GetCreatedAt() -} - -func TestRuleset_GetID(tt *testing.T) { - tt.Parallel() - var zeroValue int64 - r := &Ruleset{ID: &zeroValue} - r.GetID() - r = &Ruleset{} - r.GetID() - r = nil - r.GetID() -} - -func TestRuleset_GetLinks(tt *testing.T) { - tt.Parallel() - r := &Ruleset{} - r.GetLinks() - r = nil - r.GetLinks() -} - -func TestRuleset_GetNodeID(tt *testing.T) { - tt.Parallel() - var zeroValue string - r := &Ruleset{NodeID: &zeroValue} - r.GetNodeID() - r = &Ruleset{} - r.GetNodeID() - r = nil - r.GetNodeID() -} - -func TestRuleset_GetSourceType(tt *testing.T) { - tt.Parallel() - var zeroValue string - r := &Ruleset{SourceType: &zeroValue} - r.GetSourceType() - r = &Ruleset{} - r.GetSourceType() - r = nil - r.GetSourceType() -} - -func TestRuleset_GetTarget(tt *testing.T) { - tt.Parallel() - var zeroValue string - r := &Ruleset{Target: &zeroValue} - r.GetTarget() - r = &Ruleset{} - r.GetTarget() - r = nil - r.GetTarget() -} - -func TestRuleset_GetUpdatedAt(tt *testing.T) { - tt.Parallel() - var zeroValue Timestamp - r := &Ruleset{UpdatedAt: &zeroValue} - r.GetUpdatedAt() - r = &Ruleset{} - r.GetUpdatedAt() - r = nil - r.GetUpdatedAt() -} - -func TestRulesetConditions_GetOrganizationID(tt *testing.T) { - tt.Parallel() - r := &RulesetConditions{} - r.GetOrganizationID() - r = nil - r.GetOrganizationID() -} - -func TestRulesetConditions_GetOrganizationName(tt *testing.T) { - tt.Parallel() - r := &RulesetConditions{} - r.GetOrganizationName() - r = nil - r.GetOrganizationName() -} - -func TestRulesetConditions_GetRefName(tt *testing.T) { - tt.Parallel() - r := &RulesetConditions{} - r.GetRefName() - r = nil - r.GetRefName() -} - -func TestRulesetConditions_GetRepositoryID(tt *testing.T) { - tt.Parallel() - r := &RulesetConditions{} - r.GetRepositoryID() - r = nil - r.GetRepositoryID() -} - -func TestRulesetConditions_GetRepositoryName(tt *testing.T) { - tt.Parallel() - r := &RulesetConditions{} - r.GetRepositoryName() - r = nil - r.GetRepositoryName() -} - -func TestRulesetConditions_GetRepositoryProperty(tt *testing.T) { - tt.Parallel() - r := &RulesetConditions{} - r.GetRepositoryProperty() - r = nil - r.GetRepositoryProperty() -} - -func TestRulesetLink_GetHRef(tt *testing.T) { - tt.Parallel() - var zeroValue string - r := &RulesetLink{HRef: &zeroValue} - r.GetHRef() - r = &RulesetLink{} - r.GetHRef() - r = nil - r.GetHRef() -} - -func TestRulesetLinks_GetSelf(tt *testing.T) { - tt.Parallel() - r := &RulesetLinks{} - r.GetSelf() - r = nil - r.GetSelf() -} - -func TestRulesetRepositoryNamesConditionParameters_GetProtected(tt *testing.T) { - tt.Parallel() - var zeroValue bool - r := &RulesetRepositoryNamesConditionParameters{Protected: &zeroValue} - r.GetProtected() - r = &RulesetRepositoryNamesConditionParameters{} - r.GetProtected() - r = nil - r.GetProtected() -} - -func TestRulesetRepositoryPropertyTargetParameters_GetSource(tt *testing.T) { - tt.Parallel() - var zeroValue string - r := &RulesetRepositoryPropertyTargetParameters{Source: &zeroValue} - r.GetSource() - r = &RulesetRepositoryPropertyTargetParameters{} - r.GetSource() - r = nil - r.GetSource() -} - func TestRunner_GetBusy(tt *testing.T) { tt.Parallel() var zeroValue bool @@ -34621,6 +34417,17 @@ func TestWorkflows_GetTotalCount(tt *testing.T) { w.GetTotalCount() } +func TestWorkflowsRuleParameters_GetDoNotEnforceOnCreate(tt *testing.T) { + tt.Parallel() + var zeroValue bool + w := &WorkflowsRuleParameters{DoNotEnforceOnCreate: &zeroValue} + w.GetDoNotEnforceOnCreate() + w = &WorkflowsRuleParameters{} + w.GetDoNotEnforceOnCreate() + w = nil + w.GetDoNotEnforceOnCreate() +} + func TestWorkflowUsage_GetBillable(tt *testing.T) { tt.Parallel() w := &WorkflowUsage{} diff --git a/github/orgs_rules.go b/github/orgs_rules.go index b0773fab917..8cb2e5d1f92 100644 --- a/github/orgs_rules.go +++ b/github/orgs_rules.go @@ -10,12 +10,12 @@ import ( "fmt" ) -// GetAllOrganizationRulesets gets all the rulesets for the specified organization. +// GetAllRepositoryRulesets gets all the repository rulesets for the specified organization. // // GitHub API docs: https://docs.github.com/rest/orgs/rules#get-all-organization-repository-rulesets // //meta:operation GET /orgs/{org}/rulesets -func (s *OrganizationsService) GetAllOrganizationRulesets(ctx context.Context, org string) ([]*Ruleset, *Response, error) { +func (s *OrganizationsService) GetAllRepositoryRulesets(ctx context.Context, org string) ([]*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("orgs/%v/rulesets", org) req, err := s.client.NewRequest("GET", u, nil) @@ -23,7 +23,7 @@ func (s *OrganizationsService) GetAllOrganizationRulesets(ctx context.Context, o return nil, nil, err } - var rulesets []*Ruleset + var rulesets []*RepositoryRuleset resp, err := s.client.Do(ctx, req, &rulesets) if err != nil { return nil, resp, err @@ -32,12 +32,12 @@ func (s *OrganizationsService) GetAllOrganizationRulesets(ctx context.Context, o return rulesets, resp, nil } -// CreateOrganizationRuleset creates a ruleset for the specified organization. +// CreateRepositoryRuleset creates a repository ruleset for the specified organization. // // GitHub API docs: https://docs.github.com/rest/orgs/rules#create-an-organization-repository-ruleset // //meta:operation POST /orgs/{org}/rulesets -func (s *OrganizationsService) CreateOrganizationRuleset(ctx context.Context, org string, ruleset Ruleset) (*Ruleset, *Response, error) { +func (s *OrganizationsService) CreateRepositoryRuleset(ctx context.Context, org string, ruleset RepositoryRuleset) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("orgs/%v/rulesets", org) req, err := s.client.NewRequest("POST", u, ruleset) @@ -45,7 +45,7 @@ func (s *OrganizationsService) CreateOrganizationRuleset(ctx context.Context, or return nil, nil, err } - var rs *Ruleset + var rs *RepositoryRuleset resp, err := s.client.Do(ctx, req, &rs) if err != nil { return nil, resp, err @@ -54,12 +54,12 @@ func (s *OrganizationsService) CreateOrganizationRuleset(ctx context.Context, or return rs, resp, nil } -// GetOrganizationRuleset gets a ruleset from the specified organization. +// GetRepositoryRuleset gets a repository ruleset for the specified organization. // // GitHub API docs: https://docs.github.com/rest/orgs/rules#get-an-organization-repository-ruleset // //meta:operation GET /orgs/{org}/rulesets/{ruleset_id} -func (s *OrganizationsService) GetOrganizationRuleset(ctx context.Context, org string, rulesetID int64) (*Ruleset, *Response, error) { +func (s *OrganizationsService) GetRepositoryRuleset(ctx context.Context, org string, rulesetID int64) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("orgs/%v/rulesets/%v", org, rulesetID) req, err := s.client.NewRequest("GET", u, nil) @@ -67,7 +67,7 @@ func (s *OrganizationsService) GetOrganizationRuleset(ctx context.Context, org s return nil, nil, err } - var ruleset *Ruleset + var ruleset *RepositoryRuleset resp, err := s.client.Do(ctx, req, &ruleset) if err != nil { return nil, resp, err @@ -76,12 +76,12 @@ func (s *OrganizationsService) GetOrganizationRuleset(ctx context.Context, org s return ruleset, resp, nil } -// UpdateOrganizationRuleset updates a ruleset from the specified organization. +// UpdateRepositoryRuleset updates a repository ruleset for the specified organization. // // GitHub API docs: https://docs.github.com/rest/orgs/rules#update-an-organization-repository-ruleset // //meta:operation PUT /orgs/{org}/rulesets/{ruleset_id} -func (s *OrganizationsService) UpdateOrganizationRuleset(ctx context.Context, org string, rulesetID int64, ruleset Ruleset) (*Ruleset, *Response, error) { +func (s *OrganizationsService) UpdateRepositoryRuleset(ctx context.Context, org string, rulesetID int64, ruleset RepositoryRuleset) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("orgs/%v/rulesets/%v", org, rulesetID) req, err := s.client.NewRequest("PUT", u, ruleset) @@ -89,7 +89,7 @@ func (s *OrganizationsService) UpdateOrganizationRuleset(ctx context.Context, or return nil, nil, err } - var rs *Ruleset + var rs *RepositoryRuleset resp, err := s.client.Do(ctx, req, &rs) if err != nil { return nil, resp, err @@ -98,14 +98,14 @@ func (s *OrganizationsService) UpdateOrganizationRuleset(ctx context.Context, or return rs, resp, nil } -// UpdateOrganizationRulesetClearBypassActor clears the ruleset bypass actors for a ruleset for the specified repository. +// UpdateRepositoryRulesetClearBypassActor clears the bypass actors for a repository ruleset for the specified organization. // -// This function is necessary as the UpdateOrganizationRuleset function does not marshal ByPassActor if passed as an empty array. +// This function is necessary as the UpdateRepositoryRuleset function does not marshal ByPassActor if passed as an empty array. // // GitHub API docs: https://docs.github.com/rest/orgs/rules#update-an-organization-repository-ruleset // //meta:operation PUT /orgs/{org}/rulesets/{ruleset_id} -func (s *OrganizationsService) UpdateOrganizationRulesetClearBypassActor(ctx context.Context, org string, rulesetID int64) (*Response, error) { +func (s *OrganizationsService) UpdateRepositoryRulesetClearBypassActor(ctx context.Context, org string, rulesetID int64) (*Response, error) { u := fmt.Sprintf("orgs/%v/rulesets/%v", org, rulesetID) rsClearBypassActor := rulesetClearBypassActors{} @@ -123,12 +123,12 @@ func (s *OrganizationsService) UpdateOrganizationRulesetClearBypassActor(ctx con return resp, nil } -// DeleteOrganizationRuleset deletes a ruleset from the specified organization. +// DeleteRepositoryRuleset deletes a repository ruleset from the specified organization. // // GitHub API docs: https://docs.github.com/rest/orgs/rules#delete-an-organization-repository-ruleset // //meta:operation DELETE /orgs/{org}/rulesets/{ruleset_id} -func (s *OrganizationsService) DeleteOrganizationRuleset(ctx context.Context, org string, rulesetID int64) (*Response, error) { +func (s *OrganizationsService) DeleteRepositoryRuleset(ctx context.Context, org string, rulesetID int64) (*Response, error) { u := fmt.Sprintf("orgs/%v/rulesets/%v", org, rulesetID) req, err := s.client.NewRequest("DELETE", u, nil) diff --git a/github/orgs_rules_test.go b/github/orgs_rules_test.go index 13afd4f058e..1ab4b9b3973 100644 --- a/github/orgs_rules_test.go +++ b/github/orgs_rules_test.go @@ -14,14 +14,14 @@ import ( "github.com/google/go-cmp/cmp" ) -func TestOrganizationsService_GetAllOrganizationRulesets(t *testing.T) { +func TestOrganizationsService_GetAllRepositoryRulesets(t *testing.T) { t.Parallel() client, mux, _ := setup(t) mux.HandleFunc("/orgs/o/rulesets", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `[{ - "id": 26110, + "id": 21, "name": "test ruleset", "target": "branch", "source_type": "Organization", @@ -31,38 +31,38 @@ func TestOrganizationsService_GetAllOrganizationRulesets(t *testing.T) { "node_id": "nid", "_links": { "self": { - "href": "https://api.github.com/orgs/o/rulesets/26110" + "href": "https://api.github.com/orgs/o/rulesets/21" } } }]`) }) ctx := context.Background() - rulesets, _, err := client.Organizations.GetAllOrganizationRulesets(ctx, "o") + rulesets, _, err := client.Organizations.GetAllRepositoryRulesets(ctx, "o") if err != nil { - t.Errorf("Organizations.GetAllOrganizationRulesets returned error: %v", err) + t.Errorf("Organizations.GetAllRepositoryRulesets returned error: %v", err) } - want := []*Ruleset{{ - ID: Ptr(int64(26110)), + want := []*RepositoryRuleset{{ + ID: Ptr(int64(21)), Name: "test ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", NodeID: Ptr("nid"), - Links: &RulesetLinks{ - Self: &RulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/26110")}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/21")}, }, }} if !cmp.Equal(rulesets, want) { - t.Errorf("Organizations.GetAllOrganizationRulesets returned %+v, want %+v", rulesets, want) + t.Errorf("Organizations.GetAllRepositoryRulesets returned %+v, want %+v", rulesets, want) } - const methodName = "GetAllOrganizationRulesets" + const methodName = "GetAllRepositoryRulesets" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Organizations.GetAllOrganizationRulesets(ctx, "o") + got, resp, err := client.Organizations.GetAllRepositoryRulesets(ctx, "o") if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -70,7 +70,7 @@ func TestOrganizationsService_GetAllOrganizationRulesets(t *testing.T) { }) } -func TestOrganizationsService_CreateOrganizationRuleset_RepoNames(t *testing.T) { +func TestOrganizationsService_CreateRepositoryRuleset_RepoNames(t *testing.T) { t.Parallel() client, mux, _ := setup(t) @@ -149,6 +149,7 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoNames(t *testing.T) { "type": "required_status_checks", "parameters": { + "do_not_enforce_on_create": true, "required_status_checks": [ { "context": "test", @@ -221,202 +222,201 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoNames(t *testing.T) }) ctx := context.Background() - ruleset, _, err := client.Organizations.CreateOrganizationRuleset(ctx, "o", Ruleset{ - ID: Ptr(int64(21)), + ruleset, _, err := client.Organizations.CreateRepositoryRuleset(ctx, "o", RepositoryRuleset{ Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), - Source: "o", + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - RefName: &RulesetRefConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, }) if err != nil { - t.Errorf("Organizations.CreateOrganizationRuleset returned error: %v", err) + t.Errorf("Organizations.CreateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ + want := &RepositoryRuleset{ ID: Ptr(int64(21)), Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - RefName: &RulesetRefConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, } if !cmp.Equal(ruleset, want) { - t.Errorf("Organizations.CreateOrganizationRuleset returned %+v, want %+v", ruleset, want) + t.Errorf("Organizations.CreateRepositoryRuleset returned %+v, want %+v", ruleset, want) } - const methodName = "CreateOrganizationRuleset" + const methodName = "CreateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Organizations.CreateOrganizationRuleset(ctx, "o", Ruleset{}) + got, resp, err := client.Organizations.CreateRepositoryRuleset(ctx, "o", RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -424,7 +424,7 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoNames(t *testing.T) }) } -func TestOrganizationsService_CreateOrganizationRuleset_RepoProperty(t *testing.T) { +func TestOrganizationsService_CreateRepositoryRuleset_RepoProperty(t *testing.T) { t.Parallel() client, mux, _ := setup(t) @@ -503,6 +503,7 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoProperty(t *testing. { "type": "required_status_checks", "parameters": { + "do_not_enforce_on_create": true, "required_status_checks": [ { "context": "test", @@ -575,29 +576,26 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoProperty(t *testing. }) ctx := context.Background() - ruleset, _, err := client.Organizations.CreateOrganizationRuleset(ctx, "o", Ruleset{ - ID: Ptr(int64(21)), + ruleset, _, err := client.Organizations.CreateRepositoryRuleset(ctx, "o", RepositoryRuleset{ Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), - Source: "o", + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - RepositoryProperty: &RulesetRepositoryPropertyConditionParameters{ - Include: []RulesetRepositoryPropertyTargetParameters{ + Conditions: &RepositoryRulesetConditions{ + RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ + Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testIncludeProp", Source: Ptr("custom"), Values: []string{"true"}, }, }, - Exclude: []RulesetRepositoryPropertyTargetParameters{ + Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testExcludeProp", Values: []string{"false"}, @@ -605,101 +603,102 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoProperty(t *testing. }, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, }) if err != nil { - t.Errorf("Organizations.CreateOrganizationRuleset returned error: %v", err) + t.Errorf("Organizations.CreateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ + want := &RepositoryRuleset{ ID: Ptr(int64(21)), Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - RepositoryProperty: &RulesetRepositoryPropertyConditionParameters{ - Include: []RulesetRepositoryPropertyTargetParameters{ + Conditions: &RepositoryRulesetConditions{ + RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ + Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testIncludeProp", Source: Ptr("custom"), Values: []string{"true"}, }, }, - Exclude: []RulesetRepositoryPropertyTargetParameters{ + Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testExcludeProp", Values: []string{"false"}, @@ -707,82 +706,83 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoProperty(t *testing. }, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, } if !cmp.Equal(ruleset, want) { - t.Errorf("Organizations.CreateOrganizationRuleset returned %+v, want %+v", ruleset, want) + t.Errorf("Organizations.CreateRepositoryRuleset returned %+v, want %+v", ruleset, want) } - const methodName = "CreateOrganizationRuleset" + const methodName = "CreateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Organizations.CreateOrganizationRuleset(ctx, "o", Ruleset{}) + got, resp, err := client.Organizations.CreateRepositoryRuleset(ctx, "o", RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -790,7 +790,7 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoProperty(t *testing. }) } -func TestOrganizationsService_CreateOrganizationRuleset_RepoIDs(t *testing.T) { +func TestOrganizationsService_CreateRepositoryRuleset_RepoIDs(t *testing.T) { t.Parallel() client, mux, _ := setup(t) @@ -862,6 +862,7 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoIDs(t *testing.T) { { "type": "required_status_checks", "parameters": { + "do_not_enforce_on_create": true, "required_status_checks": [ { "context": "test", @@ -934,198 +935,197 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoIDs(t *testing.T) { }) ctx := context.Background() - ruleset, _, err := client.Organizations.CreateOrganizationRuleset(ctx, "o", Ruleset{ - ID: Ptr(int64(21)), + ruleset, _, err := client.Organizations.CreateRepositoryRuleset(ctx, "o", RepositoryRuleset{ Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), - Source: "o", + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - RefName: &RulesetRefConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, - RepositoryID: &RulesetRepositoryIDsConditionParameters{ + RepositoryID: &RepositoryRulesetRepositoryIDsConditionParameters{ RepositoryIDs: []int64{123, 456}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, }) if err != nil { - t.Errorf("Organizations.CreateOrganizationRuleset returned error: %v", err) + t.Errorf("Organizations.CreateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ + want := &RepositoryRuleset{ ID: Ptr(int64(21)), Name: "ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", - BypassActors: []*BypassActor{ + BypassActors: []BypassActor{ { ActorID: Ptr(int64(234)), - ActorType: Ptr("Team"), + ActorType: Ptr(BypassActorTypeTeam), }, }, - Conditions: &RulesetConditions{ - RefName: &RulesetRefConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, - RepositoryID: &RulesetRepositoryIDsConditionParameters{ + RepositoryID: &RepositoryRulesetRepositoryIDsConditionParameters{ RepositoryIDs: []int64{123, 456}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{ UpdateAllowsFetchAndMerge: true, - }), - NewDeletionRule(), - NewRequiredLinearHistoryRule(), - NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ + }, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ RequiredDeploymentEnvironments: []string{"test"}, - }), - NewRequiredSignaturesRule(), - NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{MergeMethodRebase, MergeMethodSquash}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 1, RequiredReviewThreadResolution: true, - }), - NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - RequiredStatusChecks: []RuleRequiredStatusChecks{ + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), }, }, StrictRequiredStatusChecksPolicy: true, - }), - NewNonFastForwardRule(), - NewCommitMessagePatternRule(&RulePatternParameters{ + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ Name: Ptr("avoid test commits"), Negate: Ptr(true), Operator: "starts_with", Pattern: "[test]", - }), - NewCommitAuthorEmailPatternRule(&RulePatternParameters{ + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ Operator: "contains", Pattern: "github", - }), - NewCommitterEmailPatternRule(&RulePatternParameters{ + }, + CommitterEmailPattern: &PatternRuleParameters{ Name: Ptr("avoid commit emails"), Negate: Ptr(true), Operator: "ends_with", Pattern: "abc", - }), - NewBranchNamePatternRule(&RulePatternParameters{ + }, + BranchNamePattern: &PatternRuleParameters{ Name: Ptr("avoid branch names"), Negate: Ptr(true), Operator: "regex", Pattern: "github$", - }), - NewTagNamePatternRule(&RulePatternParameters{ + }, + TagNamePattern: &PatternRuleParameters{ Name: Ptr("avoid tag names"), Negate: Ptr(true), Operator: "contains", Pattern: "github", - }), - NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []RuleCodeScanningTool{ { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", }, }, - }), + }, }, } if !cmp.Equal(ruleset, want) { - t.Errorf("Organizations.CreateOrganizationRuleset returned %+v, want %+v", ruleset, want) + t.Errorf("Organizations.CreateRepositoryRuleset returned %+v, want %+v", ruleset, want) } - const methodName = "CreateOrganizationRuleset" + const methodName = "CreateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Organizations.CreateOrganizationRuleset(ctx, "o", Ruleset{}) + got, resp, err := client.Organizations.CreateRepositoryRuleset(ctx, "o", RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -1133,14 +1133,14 @@ func TestOrganizationsService_CreateOrganizationRuleset_RepoIDs(t *testing.T) { }) } -func TestOrganizationsService_GetOrganizationRuleset(t *testing.T) { +func TestOrganizationsService_GetRepositoryRuleset(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/orgs/o/rulesets/21", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `{ - "id": 26110, + "id": 21, "name": "test ruleset", "target": "branch", "source_type": "Organization", @@ -1150,7 +1150,7 @@ func TestOrganizationsService_GetOrganizationRuleset(t *testing.T) { "node_id": "nid", "_links": { "self": { - "href": "https://api.github.com/orgs/o/rulesets/26110" + "href": "https://api.github.com/orgs/o/rulesets/21" } }, "conditions": { @@ -1183,45 +1183,43 @@ func TestOrganizationsService_GetOrganizationRuleset(t *testing.T) { }) ctx := context.Background() - rulesets, _, err := client.Organizations.GetOrganizationRuleset(ctx, "o", 26110) + rulesets, _, err := client.Organizations.GetRepositoryRuleset(ctx, "o", 21) if err != nil { t.Errorf("Organizations.GetOrganizationRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(26110)), + want := &RepositoryRuleset{ + ID: Ptr(int64(21)), Name: "test ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", NodeID: Ptr("nid"), - Links: &RulesetLinks{ - Self: &RulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/26110")}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/21")}, }, - Conditions: &RulesetConditions{ - RefName: &RulesetRefConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - }, + Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, } if !cmp.Equal(rulesets, want) { - t.Errorf("Organizations.GetOrganizationRuleset returned %+v, want %+v", rulesets, want) + t.Errorf("Organizations.GetRepositoryRuleset returned %+v, want %+v", rulesets, want) } - const methodName = "GetOrganizationRuleset" + const methodName = "GetRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Organizations.GetOrganizationRuleset(ctx, "o", 26110) + got, resp, err := client.Organizations.GetRepositoryRuleset(ctx, "o", 21) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -1229,14 +1227,14 @@ func TestOrganizationsService_GetOrganizationRuleset(t *testing.T) { }) } -func TestOrganizationsService_GetOrganizationRulesetWithRepoPropCondition(t *testing.T) { +func TestOrganizationsService_GetRepositoryRulesetWithRepoPropCondition(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/orgs/o/rulesets/21", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `{ - "id": 26110, + "id": 21, "name": "test ruleset", "target": "branch", "source_type": "Organization", @@ -1246,7 +1244,7 @@ func TestOrganizationsService_GetOrganizationRulesetWithRepoPropCondition(t *tes "node_id": "nid", "_links": { "self": { - "href": "https://api.github.com/orgs/o/rulesets/26110" + "href": "https://api.github.com/orgs/o/rulesets/21" } }, "conditions": { @@ -1272,46 +1270,44 @@ func TestOrganizationsService_GetOrganizationRulesetWithRepoPropCondition(t *tes }) ctx := context.Background() - rulesets, _, err := client.Organizations.GetOrganizationRuleset(ctx, "o", 26110) + rulesets, _, err := client.Organizations.GetRepositoryRuleset(ctx, "o", 21) if err != nil { t.Errorf("Organizations.GetOrganizationRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(26110)), + want := &RepositoryRuleset{ + ID: Ptr(int64(21)), Name: "test ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", NodeID: Ptr("nid"), - Links: &RulesetLinks{ - Self: &RulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/26110")}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/21")}, }, - Conditions: &RulesetConditions{ - RepositoryProperty: &RulesetRepositoryPropertyConditionParameters{ - Include: []RulesetRepositoryPropertyTargetParameters{ + Conditions: &RepositoryRulesetConditions{ + RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ + Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testIncludeProp", Source: Ptr("custom"), Values: []string{"true"}, }, }, - Exclude: []RulesetRepositoryPropertyTargetParameters{}, + Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - }, + Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, } if !cmp.Equal(rulesets, want) { - t.Errorf("Organizations.GetOrganizationRuleset returned %+v, want %+v", rulesets, want) + t.Errorf("Organizations.GetRepositoryRuleset returned %+v, want %+v", rulesets, want) } - const methodName = "GetOrganizationRuleset" + const methodName = "GetRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Organizations.GetOrganizationRuleset(ctx, "o", 26110) + got, resp, err := client.Organizations.GetRepositoryRuleset(ctx, "o", 21) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -1319,14 +1315,14 @@ func TestOrganizationsService_GetOrganizationRulesetWithRepoPropCondition(t *tes }) } -func TestOrganizationsService_UpdateOrganizationRuleset(t *testing.T) { +func TestOrganizationsService_UpdateRepositoryRuleset(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/orgs/o/rulesets/21", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") fmt.Fprint(w, `{ - "id": 26110, + "id": 21, "name": "test ruleset", "target": "branch", "source_type": "Organization", @@ -1336,7 +1332,7 @@ func TestOrganizationsService_UpdateOrganizationRuleset(t *testing.T) { "node_id": "nid", "_links": { "self": { - "href": "https://api.github.com/orgs/o/rulesets/26110" + "href": "https://api.github.com/orgs/o/rulesets/21" } }, "conditions": { @@ -1369,63 +1365,59 @@ func TestOrganizationsService_UpdateOrganizationRuleset(t *testing.T) { }) ctx := context.Background() - rulesets, _, err := client.Organizations.UpdateOrganizationRuleset(ctx, "o", 26110, Ruleset{ + rulesets, _, err := client.Organizations.UpdateRepositoryRuleset(ctx, "o", 21, RepositoryRuleset{ Name: "test ruleset", - Target: Ptr("branch"), + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - Conditions: &RulesetConditions{ - RefName: &RulesetRefConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - }, + Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, }) if err != nil { - t.Errorf("Organizations.UpdateOrganizationRuleset returned error: %v", err) + t.Errorf("Organizations.UpdateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(26110)), + want := &RepositoryRuleset{ + ID: Ptr(int64(21)), Name: "test ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", NodeID: Ptr("nid"), - Links: &RulesetLinks{ - Self: &RulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/26110")}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/21")}, }, - Conditions: &RulesetConditions{ - RefName: &RulesetRefConditionParameters{ + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ Include: []string{"refs/heads/main", "refs/heads/master"}, Exclude: []string{"refs/heads/dev*"}, }, - RepositoryName: &RulesetRepositoryNamesConditionParameters{ + RepositoryName: &RepositoryRulesetRepositoryNamesConditionParameters{ Include: []string{"important_repository", "another_important_repository"}, Exclude: []string{"unimportant_repository"}, Protected: Ptr(true), }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - }, + Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, } if !cmp.Equal(rulesets, want) { - t.Errorf("Organizations.UpdateOrganizationRuleset returned %+v, want %+v", rulesets, want) + t.Errorf("Organizations.UpdateRepositoryRuleset returned %+v, want %+v", rulesets, want) } - const methodName = "UpdateOrganizationRuleset" + const methodName = "UpdateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Organizations.UpdateOrganizationRuleset(ctx, "o", 26110, Ruleset{}) + got, resp, err := client.Organizations.UpdateRepositoryRuleset(ctx, "o", 21, RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -1433,14 +1425,14 @@ func TestOrganizationsService_UpdateOrganizationRuleset(t *testing.T) { }) } -func TestOrganizationsService_UpdateOrganizationRulesetWithRepoProp(t *testing.T) { +func TestOrganizationsService_UpdateRepositoryRulesetWithRepoProp(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/orgs/o/rulesets/21", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") fmt.Fprint(w, `{ - "id": 26110, + "id": 21, "name": "test ruleset", "target": "branch", "source_type": "Organization", @@ -1450,7 +1442,7 @@ func TestOrganizationsService_UpdateOrganizationRulesetWithRepoProp(t *testing.T "node_id": "nid", "_links": { "self": { - "href": "https://api.github.com/orgs/o/rulesets/26110" + "href": "https://api.github.com/orgs/o/rulesets/21" } }, "conditions": { @@ -1476,65 +1468,61 @@ func TestOrganizationsService_UpdateOrganizationRulesetWithRepoProp(t *testing.T }) ctx := context.Background() - rulesets, _, err := client.Organizations.UpdateOrganizationRuleset(ctx, "o", 26110, Ruleset{ + rulesets, _, err := client.Organizations.UpdateRepositoryRuleset(ctx, "o", 21, RepositoryRuleset{ Name: "test ruleset", - Target: Ptr("branch"), + Target: Ptr(RulesetTargetBranch), Enforcement: "active", - Conditions: &RulesetConditions{ - RepositoryProperty: &RulesetRepositoryPropertyConditionParameters{ - Include: []RulesetRepositoryPropertyTargetParameters{ + Conditions: &RepositoryRulesetConditions{ + RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ + Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testIncludeProp", Source: Ptr("custom"), Values: []string{"true"}, }, }, - Exclude: []RulesetRepositoryPropertyTargetParameters{}, + Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - }, + Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, }) if err != nil { - t.Errorf("Organizations.UpdateOrganizationRuleset returned error: %v", err) + t.Errorf("Organizations.UpdateRepositoryRuleset returned error: %v", err) } - want := &Ruleset{ - ID: Ptr(int64(26110)), + want := &RepositoryRuleset{ + ID: Ptr(int64(21)), Name: "test ruleset", - Target: Ptr("branch"), - SourceType: Ptr("Organization"), + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", NodeID: Ptr("nid"), - Links: &RulesetLinks{ - Self: &RulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/26110")}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("https://api.github.com/orgs/o/rulesets/21")}, }, - Conditions: &RulesetConditions{ - RepositoryProperty: &RulesetRepositoryPropertyConditionParameters{ - Include: []RulesetRepositoryPropertyTargetParameters{ + Conditions: &RepositoryRulesetConditions{ + RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ + Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ { Name: "testIncludeProp", Source: Ptr("custom"), Values: []string{"true"}, }, }, - Exclude: []RulesetRepositoryPropertyTargetParameters{}, + Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{}, }, }, - Rules: []*RepositoryRule{ - NewCreationRule(), - }, + Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, } if !cmp.Equal(rulesets, want) { - t.Errorf("Organizations.UpdateOrganizationRuleset returned %+v, want %+v", rulesets, want) + t.Errorf("Organizations.UpdateRepositoryRuleset returned %+v, want %+v", rulesets, want) } - const methodName = "UpdateOrganizationRuleset" + const methodName = "UpdateRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Organizations.UpdateOrganizationRuleset(ctx, "o", 26110, Ruleset{}) + got, resp, err := client.Organizations.UpdateRepositoryRuleset(ctx, "o", 21, RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -1542,14 +1530,14 @@ func TestOrganizationsService_UpdateOrganizationRulesetWithRepoProp(t *testing.T }) } -func TestOrganizationsService_UpdateOrganizationRulesetClearBypassActor(t *testing.T) { +func TestOrganizationsService_UpdateRepositoryRulesetClearBypassActor(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/orgs/o/rulesets/21", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") fmt.Fprint(w, `{ - "id": 26110, + "id": 21, "name": "test ruleset", "target": "branch", "source_type": "Organization", @@ -1587,35 +1575,35 @@ func TestOrganizationsService_UpdateOrganizationRulesetClearBypassActor(t *testi ctx := context.Background() - _, err := client.Organizations.UpdateOrganizationRulesetClearBypassActor(ctx, "o", 26110) + _, err := client.Organizations.UpdateRepositoryRulesetClearBypassActor(ctx, "o", 21) if err != nil { - t.Errorf("Organizations.UpdateOrganizationRulesetClearBypassActor returned error: %v \n", err) + t.Errorf("Organizations.UpdateRepositoryRulesetClearBypassActor returned error: %v \n", err) } - const methodName = "UpdateOrganizationRulesetClearBypassActor" + const methodName = "UpdateRepositoryRulesetClearBypassActor" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Organizations.UpdateOrganizationRulesetClearBypassActor(ctx, "o", 26110) + return client.Organizations.UpdateRepositoryRulesetClearBypassActor(ctx, "o", 21) }) } -func TestOrganizationsService_DeleteOrganizationRuleset(t *testing.T) { +func TestOrganizationsService_DeleteRepositoryRuleset(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - mux.HandleFunc("/orgs/o/rulesets/26110", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/orgs/o/rulesets/21", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") }) ctx := context.Background() - _, err := client.Organizations.DeleteOrganizationRuleset(ctx, "o", 26110) + _, err := client.Organizations.DeleteRepositoryRuleset(ctx, "o", 21) if err != nil { - t.Errorf("Organizations.DeleteOrganizationRuleset returned error: %v", err) + t.Errorf("Organizations.DeleteRepositoryRuleset returned error: %v", err) } - const methodName = "DeleteOrganizationRuleset" + const methodName = "DeleteRepositoryRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - return client.Organizations.DeleteOrganizationRuleset(ctx, "0", 26110) + return client.Organizations.DeleteRepositoryRuleset(ctx, "0", 21) }) } diff --git a/github/repos_rules.go b/github/repos_rules.go index 60e9739cdf7..cda5a488057 100644 --- a/github/repos_rules.go +++ b/github/repos_rules.go @@ -7,845 +7,25 @@ package github import ( "context" - "encoding/json" "fmt" ) -// MergeMethod models a GitHub merge method. -type MergeMethod string - -// This is the set of GitHub merge methods. -const ( - MergeMethodMerge MergeMethod = "merge" - MergeMethodRebase MergeMethod = "rebase" - MergeMethodSquash MergeMethod = "squash" -) - -// BypassActor represents the bypass actors from a ruleset. -type BypassActor struct { - ActorID *int64 `json:"actor_id,omitempty"` - // Possible values for ActorType are: RepositoryRole, Team, Integration, OrganizationAdmin - ActorType *string `json:"actor_type,omitempty"` - // Possible values for BypassMode are: always, pull_request - BypassMode *string `json:"bypass_mode,omitempty"` -} - -// RulesetLink represents a single link object from GitHub ruleset request _links. -type RulesetLink struct { - HRef *string `json:"href,omitempty"` -} - -// RulesetLinks represents the "_links" object in a Ruleset. -type RulesetLinks struct { - Self *RulesetLink `json:"self,omitempty"` -} - -// RulesetRefConditionParameters represents the conditions object for ref_names. -type RulesetRefConditionParameters struct { - Include []string `json:"include"` - Exclude []string `json:"exclude"` -} - -// RulesetRepositoryNamesConditionParameters represents the conditions object for repository_name. -type RulesetRepositoryNamesConditionParameters struct { - Include []string `json:"include"` - Exclude []string `json:"exclude"` - Protected *bool `json:"protected,omitempty"` -} - -// RulesetRepositoryIDsConditionParameters represents the conditions object for repository_id. -type RulesetRepositoryIDsConditionParameters struct { - RepositoryIDs []int64 `json:"repository_ids,omitempty"` -} - -// RulesetRepositoryPropertyTargetParameters represents a repository_property name and values to be used for targeting. -type RulesetRepositoryPropertyTargetParameters struct { - Name string `json:"name"` - Values []string `json:"property_values"` - Source *string `json:"source,omitempty"` -} - -// RulesetRepositoryPropertyConditionParameters represents the conditions object for repository_property. -type RulesetRepositoryPropertyConditionParameters struct { - Include []RulesetRepositoryPropertyTargetParameters `json:"include"` - Exclude []RulesetRepositoryPropertyTargetParameters `json:"exclude"` -} - -// RulesetOrganizationNamesConditionParameters represents the conditions object for organization_name. -type RulesetOrganizationNamesConditionParameters struct { - Include []string `json:"include"` - Exclude []string `json:"exclude"` -} - -// RulesetOrganizationIDsConditionParameters represents the conditions object for organization_id. -type RulesetOrganizationIDsConditionParameters struct { - OrganizationIDs []int64 `json:"organization_ids,omitempty"` -} - -// RulesetConditions represents the conditions object in a ruleset. -// Set either RepositoryName or RepositoryID or RepositoryProperty, not more than one. -type RulesetConditions struct { - RefName *RulesetRefConditionParameters `json:"ref_name,omitempty"` - RepositoryName *RulesetRepositoryNamesConditionParameters `json:"repository_name,omitempty"` - RepositoryID *RulesetRepositoryIDsConditionParameters `json:"repository_id,omitempty"` - RepositoryProperty *RulesetRepositoryPropertyConditionParameters `json:"repository_property,omitempty"` - OrganizationName *RulesetOrganizationNamesConditionParameters `json:"organization_name,omitempty"` - OrganizationID *RulesetOrganizationIDsConditionParameters `json:"organization_id,omitempty"` -} - -// RulePatternParameters represents the rule pattern parameters. -type RulePatternParameters struct { - Name *string `json:"name,omitempty"` - // If Negate is true, the rule will fail if the pattern matches. - Negate *bool `json:"negate,omitempty"` - // Possible values for Operator are: starts_with, ends_with, contains, regex - Operator string `json:"operator"` - Pattern string `json:"pattern"` -} - -// RuleFileParameters represents a list of file paths. -type RuleFileParameters struct { - RestrictedFilePaths *[]string `json:"restricted_file_paths"` -} - -// RuleMaxFilePathLengthParameters represents the max_file_path_length rule parameters. -type RuleMaxFilePathLengthParameters struct { - MaxFilePathLength int `json:"max_file_path_length"` -} - -// RuleFileExtensionRestrictionParameters represents the file_extension_restriction rule parameters. -type RuleFileExtensionRestrictionParameters struct { - RestrictedFileExtensions []string `json:"restricted_file_extensions"` -} - -// RuleMaxFileSizeParameters represents the max_file_size rule parameters. -type RuleMaxFileSizeParameters struct { - MaxFileSize int64 `json:"max_file_size"` -} - -// UpdateAllowsFetchAndMergeRuleParameters represents the update rule parameters. -type UpdateAllowsFetchAndMergeRuleParameters struct { - UpdateAllowsFetchAndMerge bool `json:"update_allows_fetch_and_merge"` -} - -// RequiredDeploymentEnvironmentsRuleParameters represents the required_deployments rule parameters. -type RequiredDeploymentEnvironmentsRuleParameters struct { - RequiredDeploymentEnvironments []string `json:"required_deployment_environments"` -} - -// PullRequestRuleParameters represents the pull_request rule parameters. -type PullRequestRuleParameters struct { - AllowedMergeMethods []MergeMethod `json:"allowed_merge_methods"` - DismissStaleReviewsOnPush bool `json:"dismiss_stale_reviews_on_push"` - RequireCodeOwnerReview bool `json:"require_code_owner_review"` - RequireLastPushApproval bool `json:"require_last_push_approval"` - RequiredApprovingReviewCount int `json:"required_approving_review_count"` - RequiredReviewThreadResolution bool `json:"required_review_thread_resolution"` -} - -// RuleRequiredStatusChecks represents the RequiredStatusChecks for the RequiredStatusChecksRuleParameters object. -type RuleRequiredStatusChecks struct { - Context string `json:"context"` - IntegrationID *int64 `json:"integration_id,omitempty"` -} - -// MergeQueueRuleParameters represents the merge_queue rule parameters. -type MergeQueueRuleParameters struct { - CheckResponseTimeoutMinutes int `json:"check_response_timeout_minutes"` - // Possible values for GroupingStrategy are: ALLGREEN, HEADGREEN - GroupingStrategy string `json:"grouping_strategy"` - MaxEntriesToBuild int `json:"max_entries_to_build"` - MaxEntriesToMerge int `json:"max_entries_to_merge"` - // Possible values for MergeMethod are: MERGE, SQUASH, REBASE - MergeMethod string `json:"merge_method"` - MinEntriesToMerge int `json:"min_entries_to_merge"` - MinEntriesToMergeWaitMinutes int `json:"min_entries_to_merge_wait_minutes"` -} - -// RequiredStatusChecksRuleParameters represents the required_status_checks rule parameters. -type RequiredStatusChecksRuleParameters struct { - DoNotEnforceOnCreate *bool `json:"do_not_enforce_on_create,omitempty"` - RequiredStatusChecks []RuleRequiredStatusChecks `json:"required_status_checks"` - StrictRequiredStatusChecksPolicy bool `json:"strict_required_status_checks_policy"` -} - -// RuleRequiredWorkflow represents the Workflow for the RequireWorkflowsRuleParameters object. -type RuleRequiredWorkflow struct { - Path string `json:"path"` - Ref *string `json:"ref,omitempty"` - RepositoryID *int64 `json:"repository_id,omitempty"` - Sha *string `json:"sha,omitempty"` -} - -// RequiredWorkflowsRuleParameters represents the workflows rule parameters. -type RequiredWorkflowsRuleParameters struct { - DoNotEnforceOnCreate bool `json:"do_not_enforce_on_create,omitempty"` - RequiredWorkflows []*RuleRequiredWorkflow `json:"workflows"` -} - -// RuleRequiredCodeScanningTool represents a single required code-scanning tool for the RequiredCodeScanningParameters object. -type RuleRequiredCodeScanningTool struct { - AlertsThreshold string `json:"alerts_threshold"` - SecurityAlertsThreshold string `json:"security_alerts_threshold"` - Tool string `json:"tool"` -} - -// RequiredCodeScanningRuleParameters represents the code_scanning rule parameters. -type RequiredCodeScanningRuleParameters struct { - RequiredCodeScanningTools []*RuleRequiredCodeScanningTool `json:"code_scanning_tools"` -} - -// RepositoryRule represents a GitHub Rule. -type RepositoryRule struct { - Type string `json:"type"` - Parameters *json.RawMessage `json:"parameters,omitempty"` - RulesetSourceType string `json:"ruleset_source_type"` - RulesetSource string `json:"ruleset_source"` - RulesetID int64 `json:"ruleset_id"` -} - -// RepositoryRulesetEditedChanges represents the changes made to a repository ruleset. -type RepositoryRulesetEditedChanges struct { - Name *RepositoryRulesetEditedSource `json:"name,omitempty"` - Enforcement *RepositoryRulesetEditedSource `json:"enforcement,omitempty"` - Conditions *RepositoryRulesetEditedConditions `json:"conditions,omitempty"` - Rules *RepositoryRulesetEditedRules `json:"rules,omitempty"` -} - -// RepositoryRulesetEditedSource represents a source change for the ruleset. -type RepositoryRulesetEditedSource struct { - From *string `json:"from,omitempty"` -} - -// RepositoryRulesetEditedSources represents multiple source changes for the ruleset. -type RepositoryRulesetEditedSources struct { - From []string `json:"from,omitempty"` -} - -// RepositoryRulesetEditedConditions holds changes to conditions in a ruleset. -type RepositoryRulesetEditedConditions struct { - Added []*RepositoryRulesetRefCondition `json:"added,omitempty"` - Deleted []*RepositoryRulesetRefCondition `json:"deleted,omitempty"` - Updated []*RepositoryRulesetEditedUpdatedConditions `json:"updated,omitempty"` -} - -// RepositoryRulesetEditedRules holds changes to rules in a ruleset. -type RepositoryRulesetEditedRules struct { - Added []*RepositoryRulesetRule `json:"added,omitempty"` - Deleted []*RepositoryRulesetRule `json:"deleted,omitempty"` - Updated []*RepositoryRulesetUpdatedRules `json:"updated,omitempty"` -} - -// RepositoryRulesetRefCondition represents a reference condition for the ruleset. -type RepositoryRulesetRefCondition struct { - RefName *RulesetRefConditionParameters `json:"ref_name,omitempty"` -} - -// RepositoryRulesetEditedUpdatedConditions holds updates to conditions in a ruleset. -type RepositoryRulesetEditedUpdatedConditions struct { - Condition *RepositoryRulesetRefCondition `json:"condition,omitempty"` - Changes *RepositoryRulesetUpdatedConditionsEdited `json:"changes,omitempty"` -} - -// RepositoryRulesetUpdatedConditionsEdited holds the edited updates to conditions in a ruleset. -type RepositoryRulesetUpdatedConditionsEdited struct { - ConditionType *RepositoryRulesetEditedSource `json:"condition_type,omitempty"` - Target *RepositoryRulesetEditedSource `json:"target,omitempty"` - Include *RepositoryRulesetEditedSources `json:"include,omitempty"` - Exclude *RepositoryRulesetEditedSources `json:"exclude,omitempty"` -} - -// RepositoryRulesetUpdatedRules holds updates to rules in a ruleset. -type RepositoryRulesetUpdatedRules struct { - Rule *RepositoryRulesetRule `json:"rule,omitempty"` - Changes *RepositoryRulesetEditedRuleChanges `json:"changes,omitempty"` -} - -// RepositoryRulesetEditedRuleChanges holds changes made to a rule in a ruleset. -type RepositoryRulesetEditedRuleChanges struct { - Configuration *RepositoryRulesetEditedSources `json:"configuration,omitempty"` - RuleType *RepositoryRulesetEditedSources `json:"rule_type,omitempty"` - Pattern *RepositoryRulesetEditedSources `json:"pattern,omitempty"` -} - -// RepositoryRuleset represents the structure of a ruleset associated with a GitHub repository. -type RepositoryRuleset struct { - ID int64 `json:"id"` - Name string `json:"name"` - // Possible values for target: "branch", "tag", "push" - Target *string `json:"target,omitempty"` - // Possible values for source type: "Repository", "Organization" - SourceType *string `json:"source_type,omitempty"` - Source string `json:"source"` - // Possible values for enforcement: "disabled", "active", "evaluate" - Enforcement string `json:"enforcement"` - BypassActors []*BypassActor `json:"bypass_actors,omitempty"` - // Possible values for current user can bypass: "always", "pull_requests_only", "never" - CurrentUserCanBypass *string `json:"current_user_can_bypass,omitempty"` - NodeID *string `json:"node_id,omitempty"` - Links *RepositoryRulesetLink `json:"_links,omitempty"` - Conditions json.RawMessage `json:"conditions,omitempty"` - Rules []*RepositoryRulesetRule `json:"rules,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` -} - -// RepositoryRulesetRule represents individual rules which are present in a repository's ruleset. -type RepositoryRulesetRule struct { - Creation *RepositoryRulesetRuleType `json:"creation,omitempty"` - Update *RepositoryRulesetUpdateRule `json:"update,omitempty"` - Deletion *RepositoryRulesetRuleType `json:"deletion,omitempty"` - RequiredLinearHistory *RepositoryRulesetRuleType `json:"required_linear_history,omitempty"` - MergeQueue *RepositoryRulesetMergeQueueRule `json:"merge_queue,omitempty"` - RequiredDeployments *RepositoryRulesetRequiredDeploymentsRule `json:"required_deployments,omitempty"` - RequiredSignatures *RepositoryRulesetRuleType `json:"required_signatures,omitempty"` - PullRequest *RepositoryRulesetPullRequestRule `json:"pull_request,omitempty"` - RequiredStatusChecks *RepositoryRulesetRequiredStatusChecksRule `json:"required_status_checks,omitempty"` - NonFastForward *RepositoryRulesetRuleType `json:"non_fast_forward,omitempty"` - CommitMessagePattern *RepositoryRulesetPatternRule `json:"commit_message_pattern,omitempty"` - CommitAuthorEmailPattern *RepositoryRulesetPatternRule `json:"commit_author_email_pattern,omitempty"` - CommitterEmailPattern *RepositoryRulesetPatternRule `json:"committer_email_pattern,omitempty"` - BranchNamePattern *RepositoryRulesetPatternRule `json:"branch_name_pattern,omitempty"` - TagNamePattern *RepositoryRulesetPatternRule `json:"tag_name_pattern,omitempty"` - FilePathRestriction *RepositoryRulesetFilePathRestrictionRule `json:"file_path_restriction,omitempty"` - MaxFilePathLength *RepositoryRulesetMaxFilePathLengthRule `json:"max_file_path_length,omitempty"` - FileExtensionRestriction *RepositoryRulesetFileExtensionRestrictionRule `json:"file_extension_restriction,omitempty"` - MaxFileSize *RepositoryRulesetMaxFileSizeRule `json:"max_file_size,omitempty"` - Workflows *RepositoryRulesetWorkflowsRule `json:"workflows,omitempty"` - CodeScanning *RepositoryRulesetCodeScanningRule `json:"code_scanning,omitempty"` -} - -// RepositoryRulesetLink represents Links associated with a repository's rulesets. These links are used to provide more information about the ruleset. -type RepositoryRulesetLink struct { - Self *RulesetLink `json:"self,omitempty"` - HTML *RulesetLink `json:"html,omitempty"` -} - -// RepositoryRulesetRuleType represents the type of a ruleset rule. -type RepositoryRulesetRuleType struct { - Type string `json:"type"` -} - -// RepositoryRulesetUpdateRule defines an update rule for the repository. -type RepositoryRulesetUpdateRule struct { - // Type can be one of: "update". - Type string `json:"type"` - Parameters *UpdateAllowsFetchAndMergeRuleParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetMergeQueueRule defines a merge queue rule for the repository. -type RepositoryRulesetMergeQueueRule struct { - // Type can be one of: "merge_queue". - Type string `json:"type"` - Parameters *MergeQueueRuleParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetRequiredDeploymentsRule defines a rule for required deployments. -type RepositoryRulesetRequiredDeploymentsRule struct { - // Type can be one of: "required_deployments". - Type string `json:"type"` - Parameters *RequiredDeploymentEnvironmentsRuleParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetPullRequestRule defines a rule for pull requests. -type RepositoryRulesetPullRequestRule struct { - // Type can be one of: "pull_request". - - Type string `json:"type"` - Parameters *PullRequestRuleParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetRequiredStatusChecksRule defines a rule for required status checks. -type RepositoryRulesetRequiredStatusChecksRule struct { - // Type can be one of: "required_status_checks". - - Type string `json:"type"` - Parameters *RequiredStatusChecksRuleParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetPatternRule defines a pattern rule for the repository. -type RepositoryRulesetPatternRule struct { - Type string `json:"type"` - Parameters *RulePatternParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetFilePathRestrictionRule defines a file path restriction rule for the repository. -type RepositoryRulesetFilePathRestrictionRule struct { - // Type can be one of: "file_path_restriction". - Type string `json:"type"` - Parameters *RuleFileParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetMaxFilePathLengthRule defines a maximum file path length rule for the repository. -type RepositoryRulesetMaxFilePathLengthRule struct { - // Type can be one of: "max_file_path_length". - - Type string `json:"type"` - Parameters *RuleMaxFilePathLengthParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetFileExtensionRestrictionRule defines a file extension restriction rule for the repository. -type RepositoryRulesetFileExtensionRestrictionRule struct { - // Type can be one of: "file_extension_restriction". - Type string `json:"type"` - Parameters *RuleFileExtensionRestrictionParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetMaxFileSizeRule defines a maximum file size rule for the repository. -type RepositoryRulesetMaxFileSizeRule struct { - // Type can be one of: "max_file_size". - Type string `json:"type"` - Parameters *RuleMaxFileSizeParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetWorkflowsRule defines a workflow rule for the repository. -type RepositoryRulesetWorkflowsRule struct { - // Type can be one of: "workflows". - Type string `json:"type"` - Parameters *RequiredWorkflowsRuleParameters `json:"parameters,omitempty"` -} - -// RepositoryRulesetCodeScanningRule defines a code scanning rule for the repository. -type RepositoryRulesetCodeScanningRule struct { - // Type can be one of: "code_scanning". - Type string `json:"type"` - Parameters *RuleCodeScanningParameters `json:"parameters,omitempty"` -} - -// RuleCodeScanningParameters defines parameters for code scanning rules. -type RuleCodeScanningParameters struct { - CodeScanningTools []*CodeScanningTool `json:"code_scanning_tools,omitempty"` -} - -// CodeScanningTool defines a specific tool used for code scanning. -type CodeScanningTool struct { - AlertsThreshold string `json:"alerts_threshold"` - SecurityAlertsThreshold string `json:"security_alerts_threshold"` - Tool string `json:"tool"` -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -// This helps us handle the fact that RepositoryRule parameter field can be of numerous types. -func (r *RepositoryRule) UnmarshalJSON(data []byte) error { - type rule RepositoryRule - var repositoryRule rule - if err := json.Unmarshal(data, &repositoryRule); err != nil { - return err - } - - r.RulesetID = repositoryRule.RulesetID - r.RulesetSourceType = repositoryRule.RulesetSourceType - r.RulesetSource = repositoryRule.RulesetSource - r.Type = repositoryRule.Type - - switch repositoryRule.Type { - case "creation", "deletion", "non_fast_forward", "required_linear_history", "required_signatures": - r.Parameters = nil - case "update": - if repositoryRule.Parameters == nil { - r.Parameters = nil - return nil - } - params := UpdateAllowsFetchAndMergeRuleParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "merge_queue": - if repositoryRule.Parameters == nil { - r.Parameters = nil - return nil - } - params := MergeQueueRuleParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "required_deployments": - params := RequiredDeploymentEnvironmentsRuleParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "commit_message_pattern", "commit_author_email_pattern", "committer_email_pattern", "branch_name_pattern", "tag_name_pattern": - params := RulePatternParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "pull_request": - params := PullRequestRuleParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "required_status_checks": - params := RequiredStatusChecksRuleParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "workflows": - params := RequiredWorkflowsRuleParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "file_path_restriction": - params := RuleFileParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "code_scanning": - params := RequiredCodeScanningRuleParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "max_file_path_length": - params := RuleMaxFilePathLengthParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "file_extension_restriction": - params := RuleFileExtensionRestrictionParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - case "max_file_size": - params := RuleMaxFileSizeParameters{} - if err := json.Unmarshal(*repositoryRule.Parameters, ¶ms); err != nil { - return err - } - bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) - - r.Parameters = &rawParams - default: - r.Type = "" - r.Parameters = nil - return fmt.Errorf("RepositoryRule.Type %q is not yet implemented, unable to unmarshal (%#v)", repositoryRule.Type, repositoryRule) - } - - return nil -} - -// NewMergeQueueRule creates a rule to only allow merges via a merge queue. -func NewMergeQueueRule(params *MergeQueueRuleParameters) (rule *RepositoryRule) { - if params != nil { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "merge_queue", - Parameters: &rawParams, - } - } - return &RepositoryRule{ - Type: "merge_queue", - } -} - -// NewCreationRule creates a rule to only allow users with bypass permission to create matching refs. -func NewCreationRule() (rule *RepositoryRule) { - return &RepositoryRule{ - Type: "creation", - } -} - -// NewUpdateRule creates a rule to only allow users with bypass permission to update matching refs. -func NewUpdateRule(params *UpdateAllowsFetchAndMergeRuleParameters) (rule *RepositoryRule) { - if params != nil { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "update", - Parameters: &rawParams, - } - } - return &RepositoryRule{ - Type: "update", - } -} - -// NewDeletionRule creates a rule to only allow users with bypass permissions to delete matching refs. -func NewDeletionRule() (rule *RepositoryRule) { - return &RepositoryRule{ - Type: "deletion", - } -} - -// NewRequiredLinearHistoryRule creates a rule to prevent merge commits from being pushed to matching branches. -func NewRequiredLinearHistoryRule() (rule *RepositoryRule) { - return &RepositoryRule{ - Type: "required_linear_history", - } -} - -// NewRequiredDeploymentsRule creates a rule to require environments to be successfully deployed before they can be merged into the matching branches. -func NewRequiredDeploymentsRule(params *RequiredDeploymentEnvironmentsRuleParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "required_deployments", - Parameters: &rawParams, - } -} - -// NewRequiredSignaturesRule creates a rule a to require commits pushed to matching branches to have verified signatures. -func NewRequiredSignaturesRule() (rule *RepositoryRule) { - return &RepositoryRule{ - Type: "required_signatures", - } -} - -// NewPullRequestRule creates a rule to require all commits be made to a non-target branch and submitted via a pull request before they can be merged. -func NewPullRequestRule(params *PullRequestRuleParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "pull_request", - Parameters: &rawParams, - } -} - -// NewRequiredStatusChecksRule creates a rule to require which status checks must pass before branches can be merged into a branch rule. -func NewRequiredStatusChecksRule(params *RequiredStatusChecksRuleParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "required_status_checks", - Parameters: &rawParams, - } -} - -// NewNonFastForwardRule creates a rule as part to prevent users with push access from force pushing to matching branches. -func NewNonFastForwardRule() (rule *RepositoryRule) { - return &RepositoryRule{ - Type: "non_fast_forward", - } -} - -// NewCommitMessagePatternRule creates a rule to restrict commit message patterns being pushed to matching branches. -func NewCommitMessagePatternRule(params *RulePatternParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "commit_message_pattern", - Parameters: &rawParams, - } -} - -// NewCommitAuthorEmailPatternRule creates a rule to restrict commits with author email patterns being merged into matching branches. -func NewCommitAuthorEmailPatternRule(params *RulePatternParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "commit_author_email_pattern", - Parameters: &rawParams, - } -} - -// NewCommitterEmailPatternRule creates a rule to restrict commits with committer email patterns being merged into matching branches. -func NewCommitterEmailPatternRule(params *RulePatternParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "committer_email_pattern", - Parameters: &rawParams, - } -} - -// NewBranchNamePatternRule creates a rule to restrict branch patterns from being merged into matching branches. -func NewBranchNamePatternRule(params *RulePatternParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "branch_name_pattern", - Parameters: &rawParams, - } -} - -// NewTagNamePatternRule creates a rule to restrict tag patterns contained in non-target branches from being merged into matching branches. -func NewTagNamePatternRule(params *RulePatternParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "tag_name_pattern", - Parameters: &rawParams, - } -} - -// NewRequiredWorkflowsRule creates a rule to require which status checks must pass before branches can be merged into a branch rule. -func NewRequiredWorkflowsRule(params *RequiredWorkflowsRuleParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "workflows", - Parameters: &rawParams, - } -} - -// NewRequiredCodeScanningRule creates a rule to require which tools must provide code scanning results before the reference is updated. -func NewRequiredCodeScanningRule(params *RequiredCodeScanningRuleParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "code_scanning", - Parameters: &rawParams, - } -} - -// NewFilePathRestrictionRule creates a rule to restrict file paths from being pushed to. -func NewFilePathRestrictionRule(params *RuleFileParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "file_path_restriction", - Parameters: &rawParams, - } -} - -// NewMaxFilePathLengthRule creates a rule to restrict file paths longer than the limit from being pushed. -func NewMaxFilePathLengthRule(params *RuleMaxFilePathLengthParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "max_file_path_length", - Parameters: &rawParams, - } -} - -// NewFileExtensionRestrictionRule creates a rule to restrict file extensions from being pushed to a commit. -func NewFileExtensionRestrictionRule(params *RuleFileExtensionRestrictionParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "file_extension_restriction", - Parameters: &rawParams, - } -} - -// NewMaxFileSizeRule creates a rule to restrict file sizes from being pushed to a commit. -func NewMaxFileSizeRule(params *RuleMaxFileSizeParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) - - rawParams := json.RawMessage(bytes) - - return &RepositoryRule{ - Type: "max_file_size", - Parameters: &rawParams, - } -} - -// Ruleset represents a GitHub ruleset object. -type Ruleset struct { - ID *int64 `json:"id,omitempty"` - Name string `json:"name"` - // Possible values for Target are branch, tag, push - Target *string `json:"target,omitempty"` - // Possible values for SourceType are: Repository, Organization - SourceType *string `json:"source_type,omitempty"` - Source string `json:"source"` - // Possible values for Enforcement are: disabled, active, evaluate - Enforcement string `json:"enforcement"` - BypassActors []*BypassActor `json:"bypass_actors,omitempty"` - NodeID *string `json:"node_id,omitempty"` - Links *RulesetLinks `json:"_links,omitempty"` - Conditions *RulesetConditions `json:"conditions,omitempty"` - Rules []*RepositoryRule `json:"rules,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` -} - // rulesetNoOmitBypassActors represents a GitHub ruleset object. The struct does not omit bypassActors if the field is nil or an empty array is passed. type rulesetNoOmitBypassActors struct { - ID *int64 `json:"id,omitempty"` - Name string `json:"name"` - // Possible values for Target are branch, tag - Target *string `json:"target,omitempty"` - // Possible values for SourceType are: Repository, Organization - SourceType *string `json:"source_type,omitempty"` - Source string `json:"source"` - // Possible values for Enforcement are: disabled, active, evaluate - Enforcement string `json:"enforcement"` - BypassActors []*BypassActor `json:"bypass_actors"` - NodeID *string `json:"node_id,omitempty"` - Links *RulesetLinks `json:"_links,omitempty"` - Conditions *RulesetConditions `json:"conditions,omitempty"` - Rules []*RepositoryRule `json:"rules,omitempty"` + ID *int64 `json:"id,omitempty"` + Name string `json:"name"` + Target *RulesetTarget `json:"target,omitempty"` + SourceType *RulesetSourceType `json:"source_type,omitempty"` + Source string `json:"source"` + Enforcement RulesetEnforcement `json:"enforcement"` + BypassActors []BypassActor `json:"bypass_actors"` + CurrentUserCanBypass *BypassMode `json:"current_user_can_bypass,omitempty"` + NodeID *string `json:"node_id,omitempty"` + Links *RepositoryRulesetLinks `json:"_links,omitempty"` + Conditions *RepositoryRulesetConditions `json:"conditions,omitempty"` + Rules *RepositoryRulesetRules `json:"rules,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` } // rulesetClearBypassActors is used to clear the bypass actors when modifying a GitHub ruleset object. @@ -853,12 +33,12 @@ type rulesetClearBypassActors struct { BypassActors []*BypassActor `json:"bypass_actors"` } -// GetRulesForBranch gets all the rules that apply to the specified branch. +// GetRulesForBranch gets all the repository rules that apply to the specified branch. // // GitHub API docs: https://docs.github.com/rest/repos/rules#get-rules-for-a-branch // //meta:operation GET /repos/{owner}/{repo}/rules/branches/{branch} -func (s *RepositoriesService) GetRulesForBranch(ctx context.Context, owner, repo, branch string) ([]*RepositoryRule, *Response, error) { +func (s *RepositoriesService) GetRulesForBranch(ctx context.Context, owner, repo, branch string) (*BranchRules, *Response, error) { u := fmt.Sprintf("repos/%v/%v/rules/branches/%v", owner, repo, branch) req, err := s.client.NewRequest("GET", u, nil) @@ -866,7 +46,7 @@ func (s *RepositoriesService) GetRulesForBranch(ctx context.Context, owner, repo return nil, nil, err } - var rules []*RepositoryRule + var rules *BranchRules resp, err := s.client.Do(ctx, req, &rules) if err != nil { return nil, resp, err @@ -875,13 +55,13 @@ func (s *RepositoriesService) GetRulesForBranch(ctx context.Context, owner, repo return rules, resp, nil } -// GetAllRulesets gets all the rules that apply to the specified repository. -// If includesParents is true, rulesets configured at the organization level that apply to the repository will be returned. +// GetAllRulesets gets all the repository rulesets for the specified repository. +// If includesParents is true, rulesets configured at the organization or enterprise level that apply to the repository will be returned. // // GitHub API docs: https://docs.github.com/rest/repos/rules#get-all-repository-rulesets // //meta:operation GET /repos/{owner}/{repo}/rulesets -func (s *RepositoriesService) GetAllRulesets(ctx context.Context, owner, repo string, includesParents bool) ([]*Ruleset, *Response, error) { +func (s *RepositoriesService) GetAllRulesets(ctx context.Context, owner, repo string, includesParents bool) ([]*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("repos/%v/%v/rulesets?includes_parents=%v", owner, repo, includesParents) req, err := s.client.NewRequest("GET", u, nil) @@ -889,7 +69,7 @@ func (s *RepositoriesService) GetAllRulesets(ctx context.Context, owner, repo st return nil, nil, err } - var ruleset []*Ruleset + var ruleset []*RepositoryRuleset resp, err := s.client.Do(ctx, req, &ruleset) if err != nil { return nil, resp, err @@ -898,12 +78,12 @@ func (s *RepositoriesService) GetAllRulesets(ctx context.Context, owner, repo st return ruleset, resp, nil } -// CreateRuleset creates a ruleset for the specified repository. +// CreateRuleset creates a repository ruleset for the specified repository. // // GitHub API docs: https://docs.github.com/rest/repos/rules#create-a-repository-ruleset // //meta:operation POST /repos/{owner}/{repo}/rulesets -func (s *RepositoriesService) CreateRuleset(ctx context.Context, owner, repo string, ruleset Ruleset) (*Ruleset, *Response, error) { +func (s *RepositoriesService) CreateRuleset(ctx context.Context, owner, repo string, ruleset RepositoryRuleset) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("repos/%v/%v/rulesets", owner, repo) req, err := s.client.NewRequest("POST", u, ruleset) @@ -911,7 +91,7 @@ func (s *RepositoriesService) CreateRuleset(ctx context.Context, owner, repo str return nil, nil, err } - var rs *Ruleset + var rs *RepositoryRuleset resp, err := s.client.Do(ctx, req, &rs) if err != nil { return nil, resp, err @@ -920,13 +100,13 @@ func (s *RepositoriesService) CreateRuleset(ctx context.Context, owner, repo str return rs, resp, nil } -// GetRuleset gets a ruleset for the specified repository. -// If includesParents is true, rulesets configured at the organization level that apply to the repository will be returned. +// GetRuleset gets a repository ruleset for the specified repository. +// If includesParents is true, rulesets configured at the organization or enterprise level that apply to the repository will be returned. // // GitHub API docs: https://docs.github.com/rest/repos/rules#get-a-repository-ruleset // //meta:operation GET /repos/{owner}/{repo}/rulesets/{ruleset_id} -func (s *RepositoriesService) GetRuleset(ctx context.Context, owner, repo string, rulesetID int64, includesParents bool) (*Ruleset, *Response, error) { +func (s *RepositoriesService) GetRuleset(ctx context.Context, owner, repo string, rulesetID int64, includesParents bool) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("repos/%v/%v/rulesets/%v?includes_parents=%v", owner, repo, rulesetID, includesParents) req, err := s.client.NewRequest("GET", u, nil) @@ -934,7 +114,7 @@ func (s *RepositoriesService) GetRuleset(ctx context.Context, owner, repo string return nil, nil, err } - var ruleset *Ruleset + var ruleset *RepositoryRuleset resp, err := s.client.Do(ctx, req, &ruleset) if err != nil { return nil, resp, err @@ -943,12 +123,12 @@ func (s *RepositoriesService) GetRuleset(ctx context.Context, owner, repo string return ruleset, resp, nil } -// UpdateRuleset updates a ruleset for the specified repository. +// UpdateRuleset updates a repository ruleset for the specified repository. // // GitHub API docs: https://docs.github.com/rest/repos/rules#update-a-repository-ruleset // //meta:operation PUT /repos/{owner}/{repo}/rulesets/{ruleset_id} -func (s *RepositoriesService) UpdateRuleset(ctx context.Context, owner, repo string, rulesetID int64, ruleset Ruleset) (*Ruleset, *Response, error) { +func (s *RepositoriesService) UpdateRuleset(ctx context.Context, owner, repo string, rulesetID int64, ruleset RepositoryRuleset) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("repos/%v/%v/rulesets/%v", owner, repo, rulesetID) req, err := s.client.NewRequest("PUT", u, ruleset) @@ -956,7 +136,7 @@ func (s *RepositoriesService) UpdateRuleset(ctx context.Context, owner, repo str return nil, nil, err } - var rs *Ruleset + var rs *RepositoryRuleset resp, err := s.client.Do(ctx, req, &rs) if err != nil { return nil, resp, err @@ -965,7 +145,7 @@ func (s *RepositoriesService) UpdateRuleset(ctx context.Context, owner, repo str return rs, resp, nil } -// UpdateRulesetClearBypassActor clears the ruleset bypass actors for a ruleset for the specified repository. +// UpdateRulesetClearBypassActor clears the bypass actors for a repository ruleset for the specified repository. // // This function is necessary as the UpdateRuleset function does not marshal ByPassActor if passed as an empty array. // @@ -990,7 +170,7 @@ func (s *RepositoriesService) UpdateRulesetClearBypassActor(ctx context.Context, return resp, nil } -// UpdateRulesetNoBypassActor updates a ruleset for the specified repository. +// UpdateRulesetNoBypassActor updates a repository ruleset for the specified repository. // // This function is necessary as the UpdateRuleset function does not marshal ByPassActor if passed as an empty array. // @@ -999,7 +179,7 @@ func (s *RepositoriesService) UpdateRulesetClearBypassActor(ctx context.Context, // GitHub API docs: https://docs.github.com/rest/repos/rules#update-a-repository-ruleset // //meta:operation PUT /repos/{owner}/{repo}/rulesets/{ruleset_id} -func (s *RepositoriesService) UpdateRulesetNoBypassActor(ctx context.Context, owner, repo string, rulesetID int64, ruleset Ruleset) (*Ruleset, *Response, error) { +func (s *RepositoriesService) UpdateRulesetNoBypassActor(ctx context.Context, owner, repo string, rulesetID int64, ruleset RepositoryRuleset) (*RepositoryRuleset, *Response, error) { u := fmt.Sprintf("repos/%v/%v/rulesets/%v", owner, repo, rulesetID) rsNoBypassActor := rulesetNoOmitBypassActors{ @@ -1021,7 +201,7 @@ func (s *RepositoriesService) UpdateRulesetNoBypassActor(ctx context.Context, ow return nil, nil, err } - var rs *Ruleset + var rs *RepositoryRuleset resp, err := s.client.Do(ctx, req, &rs) if err != nil { return nil, resp, err @@ -1030,7 +210,7 @@ func (s *RepositoriesService) UpdateRulesetNoBypassActor(ctx context.Context, ow return rs, resp, nil } -// DeleteRuleset deletes a ruleset for the specified repository. +// DeleteRuleset deletes a repository ruleset for the specified repository. // // GitHub API docs: https://docs.github.com/rest/repos/rules#delete-a-repository-ruleset // diff --git a/github/repos_rules_test.go b/github/repos_rules_test.go index 8ee8b9749ec..c1f274e6cf5 100644 --- a/github/repos_rules_test.go +++ b/github/repos_rules_test.go @@ -14,399 +14,6 @@ import ( "github.com/google/go-cmp/cmp" ) -func TestRepositoryRule_UnmarshalJSON(t *testing.T) { - t.Parallel() - tests := map[string]struct { - data string - want *RepositoryRule - wantErr bool - }{ - "Invalid JSON": { - data: `{`, - want: &RepositoryRule{ - Type: "", - Parameters: nil, - }, - wantErr: true, - }, - "With Metadata": { - data: `{ - "type": "creation", - "ruleset_source_type": "Repository", - "ruleset_source": "google", - "ruleset_id": 1984 - }`, - want: &RepositoryRule{ - RulesetSource: "google", - RulesetSourceType: "Repository", - RulesetID: 1984, - Type: "creation", - }, - }, - "Valid creation": { - data: `{"type":"creation"}`, - want: NewCreationRule(), - }, - "Valid deletion": { - data: `{"type":"deletion"}`, - want: &RepositoryRule{ - Type: "deletion", - Parameters: nil, - }, - }, - "Valid required_linear_history": { - data: `{"type":"required_linear_history"}`, - want: &RepositoryRule{ - Type: "required_linear_history", - Parameters: nil, - }, - }, - "Valid required_signatures": { - data: `{"type":"required_signatures"}`, - want: &RepositoryRule{ - Type: "required_signatures", - Parameters: nil, - }, - }, - "Valid merge_queue": { - data: `{"type":"merge_queue"}`, - want: &RepositoryRule{ - Type: "merge_queue", - Parameters: nil, - }, - }, - "Valid merge_queue with params": { - data: `{ - "type":"merge_queue", - "parameters":{ - "check_response_timeout_minutes": 35, - "grouping_strategy": "HEADGREEN", - "max_entries_to_build": 8, - "max_entries_to_merge": 4, - "merge_method": "SQUASH", - "min_entries_to_merge": 2, - "min_entries_to_merge_wait_minutes": 13 - } - }`, - want: NewMergeQueueRule(&MergeQueueRuleParameters{ - CheckResponseTimeoutMinutes: 35, - GroupingStrategy: "HEADGREEN", - MaxEntriesToBuild: 8, - MaxEntriesToMerge: 4, - MergeMethod: "SQUASH", - MinEntriesToMerge: 2, - MinEntriesToMergeWaitMinutes: 13, - }), - }, - "Invalid merge_queue with params": { - data: `{ - "type":"merge_queue", - "parameters":{ - "check_response_timeout_minutes": "35", - "grouping_strategy": "HEADGREEN", - "max_entries_to_build": "8", - "max_entries_to_merge": "4", - "merge_method": "SQUASH", - "min_entries_to_merge": "2", - "min_entries_to_merge_wait_minutes": "13" - } - }`, - want: &RepositoryRule{ - Type: "merge_queue", - Parameters: nil, - }, - wantErr: true, - }, - "Valid non_fast_forward": { - data: `{"type":"non_fast_forward"}`, - want: &RepositoryRule{ - Type: "non_fast_forward", - Parameters: nil, - }, - }, - "Valid update params": { - data: `{"type":"update","parameters":{"update_allows_fetch_and_merge":true}}`, - want: NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{UpdateAllowsFetchAndMerge: true}), - }, - "Invalid update params": { - data: `{"type":"update","parameters":{"update_allows_fetch_and_merge":"true"}}`, - want: &RepositoryRule{ - Type: "update", - Parameters: nil, - }, - wantErr: true, - }, - "Valid required_deployments params": { - data: `{"type":"required_deployments","parameters":{"required_deployment_environments":["test"]}}`, - want: NewRequiredDeploymentsRule(&RequiredDeploymentEnvironmentsRuleParameters{ - RequiredDeploymentEnvironments: []string{"test"}, - }), - }, - "Invalid required_deployments params": { - data: `{"type":"required_deployments","parameters":{"required_deployment_environments":true}}`, - want: &RepositoryRule{ - Type: "required_deployments", - Parameters: nil, - }, - wantErr: true, - }, - "Valid commit_message_pattern params": { - data: `{"type":"commit_message_pattern","parameters":{"operator":"starts_with","pattern":"github"}}`, - want: NewCommitMessagePatternRule(&RulePatternParameters{ - Operator: "starts_with", - Pattern: "github", - }), - }, - "Invalid commit_message_pattern params": { - data: `{"type":"commit_message_pattern","parameters":{"operator":"starts_with","pattern":1}}`, - want: &RepositoryRule{ - Type: "commit_message_pattern", - Parameters: nil, - }, - wantErr: true, - }, - "Valid commit_author_email_pattern params": { - data: `{"type":"commit_author_email_pattern","parameters":{"operator":"starts_with","pattern":"github"}}`, - want: NewCommitAuthorEmailPatternRule(&RulePatternParameters{ - Operator: "starts_with", - Pattern: "github", - }), - }, - "Invalid commit_author_email_pattern params": { - data: `{"type":"commit_author_email_pattern","parameters":{"operator":"starts_with","pattern":1}}`, - want: &RepositoryRule{ - Type: "commit_author_email_pattern", - Parameters: nil, - }, - wantErr: true, - }, - "Valid committer_email_pattern params": { - data: `{"type":"committer_email_pattern","parameters":{"operator":"starts_with","pattern":"github"}}`, - want: NewCommitterEmailPatternRule(&RulePatternParameters{ - Operator: "starts_with", - Pattern: "github", - }), - }, - "Invalid committer_email_pattern params": { - data: `{"type":"committer_email_pattern","parameters":{"operator":"starts_with","pattern":1}}`, - want: &RepositoryRule{ - Type: "committer_email_pattern", - Parameters: nil, - }, - wantErr: true, - }, - "Valid branch_name_pattern params": { - data: `{"type":"branch_name_pattern","parameters":{"operator":"starts_with","pattern":"github"}}`, - want: NewBranchNamePatternRule(&RulePatternParameters{ - Operator: "starts_with", - Pattern: "github", - }), - }, - "Invalid branch_name_pattern params": { - data: `{"type":"branch_name_pattern","parameters":{"operator":"starts_with","pattern":1}}`, - want: &RepositoryRule{ - Type: "branch_name_pattern", - Parameters: nil, - }, - wantErr: true, - }, - "Valid tag_name_pattern params": { - data: `{"type":"tag_name_pattern","parameters":{"operator":"starts_with","pattern":"github"}}`, - want: NewTagNamePatternRule(&RulePatternParameters{ - Operator: "starts_with", - Pattern: "github", - }), - }, - "Invalid tag_name_pattern params": { - data: `{"type":"tag_name_pattern","parameters":{"operator":"starts_with","pattern":1}}`, - want: &RepositoryRule{ - Type: "tag_name_pattern", - Parameters: nil, - }, - wantErr: true, - }, - "Valid file_path_restriction params": { - data: `{"type":"file_path_restriction","parameters":{"restricted_file_paths":["/a/file"]}}`, - want: NewFilePathRestrictionRule(&RuleFileParameters{ - RestrictedFilePaths: &[]string{"/a/file"}, - }), - }, - "Invalid file_path_restriction params": { - data: `{"type":"file_path_restriction","parameters":{"restricted_file_paths":true}}`, - want: &RepositoryRule{ - Type: "file_path_restriction", - Parameters: nil, - }, - wantErr: true, - }, - "Valid pull_request params": { - data: `{ - "type":"pull_request", - "parameters":{ - "allowed_merge_methods": ["rebase","squash"], - "dismiss_stale_reviews_on_push": true, - "require_code_owner_review": true, - "require_last_push_approval": true, - "required_approving_review_count": 1, - "required_review_thread_resolution":true - } - }`, - want: NewPullRequestRule(&PullRequestRuleParameters{ - AllowedMergeMethods: []MergeMethod{"rebase", "squash"}, - DismissStaleReviewsOnPush: true, - RequireCodeOwnerReview: true, - RequireLastPushApproval: true, - RequiredApprovingReviewCount: 1, - RequiredReviewThreadResolution: true, - }), - }, - "Invalid pull_request params": { - data: `{"type":"pull_request","parameters": {"dismiss_stale_reviews_on_push":"true"}}`, - want: &RepositoryRule{ - Type: "pull_request", - Parameters: nil, - }, - wantErr: true, - }, - "Valid required_status_checks params": { - data: `{"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test","integration_id":1}],"strict_required_status_checks_policy":true,"do_not_enforce_on_create":true}}`, - want: NewRequiredStatusChecksRule(&RequiredStatusChecksRuleParameters{ - DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleRequiredStatusChecks{ - { - Context: "test", - IntegrationID: Ptr(int64(1)), - }, - }, - StrictRequiredStatusChecksPolicy: true, - }), - }, - "Invalid required_status_checks params": { - data: `{"type":"required_status_checks", - "parameters": { - "required_status_checks": [ - { - "context": 1 - } - ] - }}`, - want: &RepositoryRule{ - Type: "required_status_checks", - Parameters: nil, - }, - wantErr: true, - }, - "Valid Required workflows params": { - data: `{"type":"workflows","parameters":{"workflows":[{"path": ".github/workflows/test.yml", "repository_id": 1}]}}`, - want: NewRequiredWorkflowsRule(&RequiredWorkflowsRuleParameters{ - RequiredWorkflows: []*RuleRequiredWorkflow{ - { - Path: ".github/workflows/test.yml", - RepositoryID: Ptr(int64(1)), - }, - }, - }), - }, - "Invalid Required workflows params": { - data: `{"type":"workflows","parameters":{"workflows":[{"path": ".github/workflows/test.yml", "repository_id": "test"}]}}`, - want: &RepositoryRule{ - Type: "workflows", - Parameters: nil, - }, - wantErr: true, - }, - "Valid Required code_scanning params": { - data: `{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool": "CodeQL", "security_alerts_threshold": "high_or_higher", "alerts_threshold": "errors"}]}}`, - want: NewRequiredCodeScanningRule(&RequiredCodeScanningRuleParameters{ - RequiredCodeScanningTools: []*RuleRequiredCodeScanningTool{ - { - Tool: "CodeQL", - SecurityAlertsThreshold: "high_or_higher", - AlertsThreshold: "errors", - }, - }, - }), - }, - "Invalid Required code_scanning params": { - data: `{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool": 1}]}}`, - want: &RepositoryRule{ - Type: "code_scanning", - Parameters: nil, - }, - wantErr: true, - }, - "Invalid type": { - data: `{"type":"unknown"}`, - want: &RepositoryRule{ - Type: "", - Parameters: nil, - }, - wantErr: true, - }, - "Valid max_file_path_length params": { - data: `{"type":"max_file_path_length","parameters":{"max_file_path_length": 255}}`, - want: NewMaxFilePathLengthRule(&RuleMaxFilePathLengthParameters{ - MaxFilePathLength: 255, - }), - }, - "Invalid max_file_path_length params": { - data: `{"type":"max_file_path_length","parameters":{"max_file_path_length": "255"}}`, - want: &RepositoryRule{ - Type: "max_file_path_length", - Parameters: nil, - }, - wantErr: true, - }, - "Valid file_extension_restriction params": { - data: `{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe"]}}`, - want: NewFileExtensionRestrictionRule(&RuleFileExtensionRestrictionParameters{ - RestrictedFileExtensions: []string{".exe"}, - }), - }, - "Invalid file_extension_restriction params": { - data: `{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":true}}`, - want: &RepositoryRule{ - Type: "file_extension_restriction", - Parameters: nil, - }, - wantErr: true, - }, - "Valid max_file_size params": { - data: `{"type":"max_file_size","parameters":{"max_file_size": 1024}}`, - want: NewMaxFileSizeRule(&RuleMaxFileSizeParameters{ - MaxFileSize: 1024, - }), - }, - "Invalid max_file_size params": { - data: `{"type":"max_file_size","parameters":{"max_file_size": "1024"}}`, - want: &RepositoryRule{ - Type: "max_file_size", - Parameters: nil, - }, - wantErr: true, - }, - } - - for name, tc := range tests { - tc := tc - rule := &RepositoryRule{} - - t.Run(name, func(t *testing.T) { - t.Parallel() - err := rule.UnmarshalJSON([]byte(tc.data)) - if err == nil && tc.wantErr { - t.Errorf("RepositoryRule.UnmarshalJSON returned nil instead of an error") - } - if err != nil && !tc.wantErr { - t.Errorf("RepositoryRule.UnmarshalJSON returned an unexpected error: %+v", err) - } - if !cmp.Equal(tc.want, rule) { - t.Errorf("RepositoryRule.UnmarshalJSON expected rule %+v, got %+v", tc.want, rule) - } - }) - } -} - func TestRepositoriesService_GetRulesForBranch(t *testing.T) { t.Parallel() client, mux, _ := setup(t) @@ -417,7 +24,7 @@ func TestRepositoriesService_GetRulesForBranch(t *testing.T) { { "ruleset_id": 42069, "ruleset_source_type": "Repository", - "ruleset_source": "google", + "ruleset_source": "google/a", "type": "creation" }, { @@ -438,62 +45,13 @@ func TestRepositoriesService_GetRulesForBranch(t *testing.T) { t.Errorf("Repositories.GetRulesForBranch returned error: %v", err) } - creationRule := NewCreationRule() - creationRule.RulesetID = 42069 - creationRule.RulesetSource = "google" - creationRule.RulesetSourceType = "Repository" - updateRule := NewUpdateRule(&UpdateAllowsFetchAndMergeRuleParameters{ - UpdateAllowsFetchAndMerge: true, - }) - updateRule.RulesetID = 42069 - updateRule.RulesetSource = "google" - updateRule.RulesetSourceType = "Organization" - - want := []*RepositoryRule{ - creationRule, - updateRule, - } - if !cmp.Equal(rules, want) { - t.Errorf("Repositories.GetRulesForBranch returned %+v, want %+v", rules, want) - } - - const methodName = "GetRulesForBranch" - - testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Repositories.GetRulesForBranch(ctx, "o", "repo", "branch") - if got != nil { - t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) - } - return resp, err - }) -} - -func TestRepositoriesService_GetRulesForBranchEmptyUpdateRule(t *testing.T) { - t.Parallel() - client, mux, _ := setup(t) - - mux.HandleFunc("/repos/o/repo/rules/branches/branch", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[ - { - "type": "update" - } - ]`) - }) - - ctx := context.Background() - rules, _, err := client.Repositories.GetRulesForBranch(ctx, "o", "repo", "branch") - if err != nil { - t.Errorf("Repositories.GetRulesForBranch returned error: %v", err) + want := &BranchRules{ + Creation: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "google/a", RulesetID: 42069}}, + Update: []UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeOrganization, RulesetSource: "google", RulesetID: 42069}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}, } - updateRule := NewUpdateRule(nil) - - want := []*RepositoryRule{ - updateRule, - } if !cmp.Equal(rules, want) { - t.Errorf("Repositories.GetRulesForBranch returned %+v, want %+v", Stringify(rules), Stringify(want)) + t.Errorf("Repositories.GetRulesForBranch returned %+v, want %+v", rules, want) } const methodName = "GetRulesForBranch" @@ -513,26 +71,26 @@ func TestRepositoriesService_GetAllRulesets(t *testing.T) { mux.HandleFunc("/repos/o/repo/rulesets", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") - fmt.Fprint(w, `[ + fmt.Fprintf(w, `[ { "id": 42, "name": "ruleset", "source_type": "Repository", "source": "o/repo", - "enforcement": "enabled", - "created_at": `+referenceTimeStr+`, - "updated_at": `+referenceTimeStr+` + "enforcement": "active", + "created_at": %[1]s, + "updated_at": %[1]s }, { "id": 314, "name": "Another ruleset", "source_type": "Repository", "source": "o/repo", - "enforcement": "enabled", - "created_at": `+referenceTimeStr+`, - "updated_at": `+referenceTimeStr+` + "enforcement": "active", + "created_at": %[1]s, + "updated_at": %[1]s } - ]`) + ]`, referenceTimeStr) }) ctx := context.Background() @@ -541,22 +99,22 @@ func TestRepositoriesService_GetAllRulesets(t *testing.T) { t.Errorf("Repositories.GetAllRulesets returned error: %v", err) } - want := []*Ruleset{ + want := []*RepositoryRuleset{ { ID: Ptr(int64(42)), Name: "ruleset", - SourceType: Ptr("Repository"), + SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/repo", - Enforcement: "enabled", + Enforcement: RulesetEnforcementActive, CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, }, { ID: Ptr(int64(314)), Name: "Another ruleset", - SourceType: Ptr("Repository"), + SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/repo", - Enforcement: "enabled", + Enforcement: RulesetEnforcementActive, CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, }, @@ -587,25 +145,25 @@ func TestRepositoriesService_CreateRuleset(t *testing.T) { "name": "ruleset", "source_type": "Repository", "source": "o/repo", - "enforcement": "enabled" + "enforcement": "active" }`) }) ctx := context.Background() - ruleSet, _, err := client.Repositories.CreateRuleset(ctx, "o", "repo", Ruleset{ + ruleSet, _, err := client.Repositories.CreateRuleset(ctx, "o", "repo", RepositoryRuleset{ Name: "ruleset", - Enforcement: "enabled", + Enforcement: RulesetEnforcementActive, }) if err != nil { t.Errorf("Repositories.CreateRuleset returned error: %v", err) } - want := &Ruleset{ + want := &RepositoryRuleset{ ID: Ptr(int64(42)), Name: "ruleset", - SourceType: Ptr("Repository"), + SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/repo", - Enforcement: "enabled", + Enforcement: RulesetEnforcementActive, } if !cmp.Equal(ruleSet, want) { t.Errorf("Repositories.CreateRuleset returned %+v, want %+v", ruleSet, want) @@ -614,7 +172,7 @@ func TestRepositoriesService_CreateRuleset(t *testing.T) { const methodName = "CreateRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Repositories.CreateRuleset(ctx, "o", "repo", Ruleset{}) + got, resp, err := client.Repositories.CreateRuleset(ctx, "o", "repo", RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -633,7 +191,7 @@ func TestRepositoriesService_CreateRulesetWithPushRules(t *testing.T) { "name": "ruleset", "source_type": "Repository", "source": "o/repo", - "enforcement": "enabled", + "enforcement": "active", "target": "push", "rules": [ { @@ -665,34 +223,26 @@ func TestRepositoriesService_CreateRulesetWithPushRules(t *testing.T) { }) ctx := context.Background() - ruleSet, _, err := client.Repositories.CreateRuleset(ctx, "o", "repo", Ruleset{ + ruleSet, _, err := client.Repositories.CreateRuleset(ctx, "o", "repo", RepositoryRuleset{ Name: "ruleset", - Enforcement: "enabled", + Enforcement: RulesetEnforcementActive, }) if err != nil { t.Errorf("Repositories.CreateRuleset returned error: %v", err) } - want := &Ruleset{ + want := &RepositoryRuleset{ ID: Ptr(int64(42)), Name: "ruleset", - SourceType: Ptr("Repository"), + SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/repo", - Target: Ptr("push"), - Enforcement: "enabled", - Rules: []*RepositoryRule{ - NewFilePathRestrictionRule(&RuleFileParameters{ - RestrictedFilePaths: &[]string{"/a/file"}, - }), - NewMaxFilePathLengthRule(&RuleMaxFilePathLengthParameters{ - MaxFilePathLength: 255, - }), - NewFileExtensionRestrictionRule(&RuleFileExtensionRestrictionParameters{ - RestrictedFileExtensions: []string{".exe"}, - }), - NewMaxFileSizeRule(&RuleMaxFileSizeParameters{ - MaxFileSize: 1024, - }), + Target: Ptr(RulesetTargetPush), + Enforcement: RulesetEnforcementActive, + Rules: &RepositoryRulesetRules{ + FilePathRestriction: &FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"/a/file"}}, + MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 255}, + FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe"}}, + MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, }, } if !cmp.Equal(ruleSet, want) { @@ -702,7 +252,7 @@ func TestRepositoriesService_CreateRulesetWithPushRules(t *testing.T) { const methodName = "CreateRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Repositories.CreateRuleset(ctx, "o", "repo", Ruleset{}) + got, resp, err := client.Repositories.CreateRuleset(ctx, "o", "repo", RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -721,7 +271,7 @@ func TestRepositoriesService_GetRuleset(t *testing.T) { "name": "ruleset", "source_type": "Organization", "source": "o", - "enforcement": "enabled", + "enforcement": "active", "created_at": `+referenceTimeStr+`, "updated_at": `+referenceTimeStr+` }`) @@ -733,12 +283,12 @@ func TestRepositoriesService_GetRuleset(t *testing.T) { t.Errorf("Repositories.GetRuleset returned error: %v", err) } - want := &Ruleset{ + want := &RepositoryRuleset{ ID: Ptr(int64(42)), Name: "ruleset", - SourceType: Ptr("Organization"), + SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", - Enforcement: "enabled", + Enforcement: RulesetEnforcementActive, CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, } @@ -768,25 +318,25 @@ func TestRepositoriesService_UpdateRuleset(t *testing.T) { "name": "ruleset", "source_type": "Repository", "source": "o/repo", - "enforcement": "enabled" + "enforcement": "active" }`) }) ctx := context.Background() - ruleSet, _, err := client.Repositories.UpdateRuleset(ctx, "o", "repo", 42, Ruleset{ + ruleSet, _, err := client.Repositories.UpdateRuleset(ctx, "o", "repo", 42, RepositoryRuleset{ Name: "ruleset", - Enforcement: "enabled", + Enforcement: RulesetEnforcementActive, }) if err != nil { t.Errorf("Repositories.UpdateRuleset returned error: %v", err) } - want := &Ruleset{ + want := &RepositoryRuleset{ ID: Ptr(int64(42)), Name: "ruleset", - SourceType: Ptr("Repository"), + SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/repo", - Enforcement: "enabled", + Enforcement: "active", } if !cmp.Equal(ruleSet, want) { @@ -796,7 +346,7 @@ func TestRepositoriesService_UpdateRuleset(t *testing.T) { const methodName = "UpdateRuleset" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Repositories.UpdateRuleset(ctx, "o", "repo", 42, Ruleset{}) + got, resp, err := client.Repositories.UpdateRuleset(ctx, "o", "repo", 42, RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } @@ -815,7 +365,7 @@ func TestRepositoriesService_UpdateRulesetClearBypassActor(t *testing.T) { "name": "ruleset", "source_type": "Repository", "source": "o/repo", - "enforcement": "enabled" + "enforcement": "active" "conditions": { "ref_name": { "include": [ @@ -853,10 +403,10 @@ func TestRepositoriesService_UpdateRulesetNoBypassActor(t *testing.T) { t.Parallel() client, mux, _ := setup(t) - rs := Ruleset{ + rs := RepositoryRuleset{ Name: "ruleset", Source: "o/repo", - Enforcement: "enabled", + Enforcement: RulesetEnforcementActive, } mux.HandleFunc("/repos/o/repo/rulesets/42", func(w http.ResponseWriter, r *http.Request) { @@ -866,7 +416,7 @@ func TestRepositoriesService_UpdateRulesetNoBypassActor(t *testing.T) { "name": "ruleset", "source_type": "Repository", "source": "o/repo", - "enforcement": "enabled" + "enforcement": "active" }`) }) @@ -877,12 +427,12 @@ func TestRepositoriesService_UpdateRulesetNoBypassActor(t *testing.T) { t.Errorf("Repositories.UpdateRulesetNoBypassActor returned error: %v \n", err) } - want := &Ruleset{ + want := &RepositoryRuleset{ ID: Ptr(int64(42)), Name: "ruleset", - SourceType: Ptr("Repository"), + SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/repo", - Enforcement: "enabled", + Enforcement: RulesetEnforcementActive, } if !cmp.Equal(ruleSet, want) { @@ -892,7 +442,7 @@ func TestRepositoriesService_UpdateRulesetNoBypassActor(t *testing.T) { const methodName = "UpdateRulesetNoBypassActor" testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { - got, resp, err := client.Repositories.UpdateRulesetNoBypassActor(ctx, "o", "repo", 42, Ruleset{}) + got, resp, err := client.Repositories.UpdateRulesetNoBypassActor(ctx, "o", "repo", 42, RepositoryRuleset{}) if got != nil { t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) } diff --git a/github/rules.go b/github/rules.go new file mode 100644 index 00000000000..fab50bc9e34 --- /dev/null +++ b/github/rules.go @@ -0,0 +1,1251 @@ +// Copyright 2025 The go-github AUTHORS. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package github + +import ( + "encoding/json" +) + +// RulesetTarget represents a GitHub ruleset target. +type RulesetTarget string + +// This is the set of GitHub ruleset targets. +const ( + RulesetTargetBranch RulesetTarget = "branch" + RulesetTargetTag RulesetTarget = "tag" + RulesetTargetPush RulesetTarget = "push" +) + +// RulesetSourceType represents a GitHub ruleset source type. +type RulesetSourceType string + +// This is the set of GitHub ruleset source types. +const ( + RulesetSourceTypeRepository RulesetSourceType = "Repository" + RulesetSourceTypeOrganization RulesetSourceType = "Organization" + RulesetSourceTypeEnterprise RulesetSourceType = "Enterprise" +) + +// RulesetEnforcement represents a GitHub ruleset enforcement. +type RulesetEnforcement string + +// This is the set of GitHub ruleset enforcements. +const ( + RulesetEnforcementDisabled RulesetEnforcement = "disabled" + RulesetEnforcementActive RulesetEnforcement = "active" + RulesetEnforcementEvaluate RulesetEnforcement = "evaluate" +) + +// BypassActorType represents a GitHub ruleset bypass actor type. +type BypassActorType string + +// This is the set of GitHub ruleset bypass actor types. +const ( + BypassActorTypeIntegration BypassActorType = "Integration" + BypassActorTypeOrganizationAdmin BypassActorType = "OrganizationAdmin" + BypassActorTypeRepositoryRole BypassActorType = "RepositoryRole" + BypassActorTypeTeam BypassActorType = "Team" + BypassActorTypeDeployKey BypassActorType = "DeployKey" +) + +// BypassMode represents a GitHub ruleset bypass mode. +type BypassMode string + +// This is the set of GitHub ruleset bypass modes. +const ( + BypassModeAlways BypassMode = "always" + BypassModePullRequest BypassMode = "pull_request" + BypassModeNever BypassMode = "never" +) + +// RulesetRuleType represents a GitHub ruleset rule type. +type RulesetRuleType string + +// This is the set of GitHub ruleset rule types. +const ( + RulesetRuleTypeCreation RulesetRuleType = "creation" + RulesetRuleTypeUpdate RulesetRuleType = "update" + RulesetRuleTypeDeletion RulesetRuleType = "deletion" + RulesetRuleTypeRequiredLinearHistory RulesetRuleType = "required_linear_history" + RulesetRuleTypeMergeQueue RulesetRuleType = "merge_queue" + RulesetRuleTypeRequiredDeployments RulesetRuleType = "required_deployments" + RulesetRuleTypeRequiredSignatures RulesetRuleType = "required_signatures" + RulesetRuleTypePullRequest RulesetRuleType = "pull_request" + RulesetRuleTypeRequiredStatusChecks RulesetRuleType = "required_status_checks" + RulesetRuleTypeNonFastForward RulesetRuleType = "non_fast_forward" + RulesetRuleTypeCommitMessagePattern RulesetRuleType = "commit_message_pattern" + RulesetRuleTypeCommitAuthorEmailPattern RulesetRuleType = "commit_author_email_pattern" + RulesetRuleTypeCommitterEmailPattern RulesetRuleType = "committer_email_pattern" + RulesetRuleTypeBranchNamePattern RulesetRuleType = "branch_name_pattern" + RulesetRuleTypeTagNamePattern RulesetRuleType = "tag_name_pattern" + RulesetRuleTypeFilePathRestriction RulesetRuleType = "file_path_restriction" + RulesetRuleTypeMaxFilePathLength RulesetRuleType = "max_file_path_length" + RulesetRuleTypeFileExtensionRestriction RulesetRuleType = "file_extension_restriction" + RulesetRuleTypeMaxFileSize RulesetRuleType = "max_file_size" + RulesetRuleTypeWorkflows RulesetRuleType = "workflows" + RulesetRuleTypeCodeScanning RulesetRuleType = "code_scanning" +) + +// MergeGroupingStrategy models a GitHub merge grouping strategy. +type MergeGroupingStrategy string + +// This is the set of GitHub merge grouping strategies. +const ( + MergeGroupingStrategyAllGreen MergeGroupingStrategy = "ALLGREEN" + MergeGroupingStrategyHeadGreen MergeGroupingStrategy = "HEADGREEN" +) + +// MergeMethod models a GitHub merge method. +type MergeMethod string + +// This is the set of GitHub merge methods. +const ( + MergeMethodMerge MergeMethod = "merge" + MergeMethodRebase MergeMethod = "rebase" + MergeMethodSquash MergeMethod = "squash" +) + +// PatternRuleOperator models a GitHub pattern rule operator. +type PatternRuleOperator string + +// This is the set of GitHub pattern rule operators. +const ( + PatternRuleOperatorStartsWith PatternRuleOperator = "starts_with" + PatternRuleOperatorEndsWith PatternRuleOperator = "ends_with" + PatternRuleOperatorContains PatternRuleOperator = "contains" + PatternRuleOperatorRegex PatternRuleOperator = "regex" +) + +// CodeScanningAlertsThreshold models a GitHub code scanning alerts threshold. +type CodeScanningAlertsThreshold string + +// This is the set of GitHub code scanning alerts thresholds. +const ( + CodeScanningAlertsThresholdNone CodeScanningAlertsThreshold = "none" + CodeScanningAlertsThresholdErrors CodeScanningAlertsThreshold = "errors" + CodeScanningAlertsThresholdErrorsAndWarnings CodeScanningAlertsThreshold = "errors_and_warnings" + CodeScanningAlertsThresholdAll CodeScanningAlertsThreshold = "all" +) + +// CodeScanningSecurityAlertsThreshold models a GitHub code scanning security alerts threshold. +type CodeScanningSecurityAlertsThreshold string + +// This is the set of GitHub code scanning security alerts thresholds. +const ( + CodeScanningSecurityAlertsThresholdNone CodeScanningSecurityAlertsThreshold = "none" + CodeScanningSecurityAlertsThresholdCritical CodeScanningSecurityAlertsThreshold = "critical" + CodeScanningSecurityAlertsThresholdHighOrHigher CodeScanningSecurityAlertsThreshold = "high_or_higher" + CodeScanningSecurityAlertsThresholdMediumOrHigher CodeScanningSecurityAlertsThreshold = "medium_or_higher" + CodeScanningSecurityAlertsThresholdAll CodeScanningSecurityAlertsThreshold = "all" +) + +// RepositoryRuleset represents a GitHub ruleset object. +type RepositoryRuleset struct { + ID *int64 `json:"id,omitempty"` + Name string `json:"name"` + Target *RulesetTarget `json:"target,omitempty"` + SourceType *RulesetSourceType `json:"source_type,omitempty"` + Source string `json:"source"` + Enforcement RulesetEnforcement `json:"enforcement"` + BypassActors []BypassActor `json:"bypass_actors,omitempty"` + CurrentUserCanBypass *BypassMode `json:"current_user_can_bypass,omitempty"` + NodeID *string `json:"node_id,omitempty"` + Links *RepositoryRulesetLinks `json:"_links,omitempty"` + Conditions *RepositoryRulesetConditions `json:"conditions,omitempty"` + Rules *RepositoryRulesetRules `json:"rules,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` +} + +// BypassActor represents the bypass actors from a ruleset. +type BypassActor struct { + ActorID *int64 `json:"actor_id,omitempty"` + ActorType *BypassActorType `json:"actor_type,omitempty"` + BypassMode *BypassMode `json:"bypass_mode,omitempty"` +} + +// RepositoryRulesetLinks represents the "_links" object in a Ruleset. +type RepositoryRulesetLinks struct { + Self *RepositoryRulesetLink `json:"self,omitempty"` + HTML *RepositoryRulesetLink `json:"html,omitempty"` +} + +// RepositoryRulesetLink represents a single link object from GitHub ruleset request _links. +type RepositoryRulesetLink struct { + HRef *string `json:"href,omitempty"` +} + +// RepositoryRulesetConditions represents the conditions object in a ruleset. +// Set either RepositoryName or RepositoryID or RepositoryProperty, not more than one. +type RepositoryRulesetConditions struct { + RefName *RepositoryRulesetRefConditionParameters `json:"ref_name,omitempty"` + RepositoryID *RepositoryRulesetRepositoryIDsConditionParameters `json:"repository_id,omitempty"` + RepositoryName *RepositoryRulesetRepositoryNamesConditionParameters `json:"repository_name,omitempty"` + RepositoryProperty *RepositoryRulesetRepositoryPropertyConditionParameters `json:"repository_property,omitempty"` + OrganizationID *RepositoryRulesetOrganizationIDsConditionParameters `json:"organization_id,omitempty"` + OrganizationName *RepositoryRulesetOrganizationNamesConditionParameters `json:"organization_name,omitempty"` +} + +// RepositoryRulesetRefConditionParameters represents the conditions object for ref_names. +type RepositoryRulesetRefConditionParameters struct { + Include []string `json:"include"` + Exclude []string `json:"exclude"` +} + +// RepositoryRulesetRepositoryIDsConditionParameters represents the conditions object for repository_id. +type RepositoryRulesetRepositoryIDsConditionParameters struct { + RepositoryIDs []int64 `json:"repository_ids,omitempty"` +} + +// RepositoryRulesetRepositoryNamesConditionParameters represents the conditions object for repository_name. +type RepositoryRulesetRepositoryNamesConditionParameters struct { + Include []string `json:"include"` + Exclude []string `json:"exclude"` + Protected *bool `json:"protected,omitempty"` +} + +// RepositoryRulesetRepositoryPropertyConditionParameters represents the conditions object for repository_property. +type RepositoryRulesetRepositoryPropertyConditionParameters struct { + Include []RepositoryRulesetRepositoryPropertyTargetParameters `json:"include"` + Exclude []RepositoryRulesetRepositoryPropertyTargetParameters `json:"exclude"` +} + +// RepositoryRulesetRepositoryPropertyTargetParameters represents a repository_property name and values to be used for targeting. +type RepositoryRulesetRepositoryPropertyTargetParameters struct { + Name string `json:"name"` + Values []string `json:"property_values"` + Source *string `json:"source,omitempty"` +} + +// RepositoryRulesetOrganizationIDsConditionParameters represents the conditions object for organization_id. +type RepositoryRulesetOrganizationIDsConditionParameters struct { + OrganizationIDs []int64 `json:"organization_ids,omitempty"` +} + +// RepositoryRulesetOrganizationNamesConditionParameters represents the conditions object for organization_name. +type RepositoryRulesetOrganizationNamesConditionParameters struct { + Include []string `json:"include"` + Exclude []string `json:"exclude"` +} + +// RepositoryRulesetRule represents a GitHub ruleset rule object. +type RepositoryRulesetRule struct { + Type RulesetRuleType `json:"type"` + Parameters any `json:"parameters,omitempty"` +} + +// RepositoryRulesetRules represents a GitHub ruleset rules object. +type RepositoryRulesetRules struct { + Creation *EmptyRuleParameters + Update *UpdateRuleParameters + Deletion *EmptyRuleParameters + RequiredLinearHistory *EmptyRuleParameters + MergeQueue *MergeQueueRuleParameters + RequiredDeployments *RequiredDeploymentsRuleParameters + RequiredSignatures *EmptyRuleParameters + PullRequest *PullRequestRuleParameters + RequiredStatusChecks *RequiredStatusChecksRuleParameters + NonFastForward *EmptyRuleParameters + CommitMessagePattern *PatternRuleParameters + CommitAuthorEmailPattern *PatternRuleParameters + CommitterEmailPattern *PatternRuleParameters + BranchNamePattern *PatternRuleParameters + TagNamePattern *PatternRuleParameters + FilePathRestriction *FilePathRestrictionRuleParameters + MaxFilePathLength *MaxFilePathLengthRuleParameters + FileExtensionRestriction *FileExtensionRestrictionRuleParameters + MaxFileSize *MaxFileSizeRuleParameters + Workflows *WorkflowsRuleParameters + CodeScanning *CodeScanningRuleParameters +} + +// BranchRules represents the rules active for a GitHub repository branch. +type BranchRules struct { + Creation []BranchRuleMetadata + Update []UpdateBranchRule + Deletion []BranchRuleMetadata + RequiredLinearHistory []BranchRuleMetadata + MergeQueue []MergeQueueBranchRule + RequiredDeployments []RequiredDeploymentsBranchRule + RequiredSignatures []BranchRuleMetadata + PullRequest []PullRequestBranchRule + RequiredStatusChecks []RequiredStatusChecksBranchRule + NonFastForward []BranchRuleMetadata + CommitMessagePattern []PatternBranchRule + CommitAuthorEmailPattern []PatternBranchRule + CommitterEmailPattern []PatternBranchRule + BranchNamePattern []PatternBranchRule + TagNamePattern []PatternBranchRule + FilePathRestriction []FilePathRestrictionBranchRule + MaxFilePathLength []MaxFilePathLengthBranchRule + FileExtensionRestriction []FileExtensionRestrictionBranchRule + MaxFileSize []MaxFileSizeBranchRule + Workflows []WorkflowsBranchRule + CodeScanning []CodeScanningBranchRule +} + +// BranchRuleMetadata represents the metadata for a branch rule. +type BranchRuleMetadata struct { + RulesetSourceType RulesetSourceType `json:"ruleset_source_type"` + RulesetSource string `json:"ruleset_source"` + RulesetID int64 `json:"ruleset_id"` +} + +// UpdateBranchRule represents an update branch rule. +type UpdateBranchRule struct { + BranchRuleMetadata + Parameters UpdateRuleParameters `json:"parameters"` +} + +// MergeQueueBranchRule represents a merge queue branch rule. +type MergeQueueBranchRule struct { + BranchRuleMetadata + Parameters MergeQueueRuleParameters `json:"parameters"` +} + +// RequiredDeploymentsBranchRule represents a required deployments branch rule. +type RequiredDeploymentsBranchRule struct { + BranchRuleMetadata + Parameters RequiredDeploymentsRuleParameters `json:"parameters"` +} + +// PullRequestBranchRule represents a pull request branch rule. +type PullRequestBranchRule struct { + BranchRuleMetadata + Parameters PullRequestRuleParameters `json:"parameters"` +} + +// RequiredStatusChecksBranchRule represents a required status checks branch rule. +type RequiredStatusChecksBranchRule struct { + BranchRuleMetadata + Parameters RequiredStatusChecksRuleParameters `json:"parameters"` +} + +// PatternBranchRule represents a pattern branch rule. +type PatternBranchRule struct { + BranchRuleMetadata + Parameters PatternRuleParameters `json:"parameters"` +} + +// FilePathRestrictionBranchRule represents a file path restriction branch rule. +type FilePathRestrictionBranchRule struct { + BranchRuleMetadata + Parameters FilePathRestrictionRuleParameters `json:"parameters"` +} + +// MaxFilePathLengthBranchRule represents a max file path length branch rule. +type MaxFilePathLengthBranchRule struct { + BranchRuleMetadata + Parameters MaxFilePathLengthRuleParameters `json:"parameters"` +} + +// FileExtensionRestrictionBranchRule represents a file extension restriction branch rule. +type FileExtensionRestrictionBranchRule struct { + BranchRuleMetadata + Parameters FileExtensionRestrictionRuleParameters `json:"parameters"` +} + +// MaxFileSizeBranchRule represents a max file size branch rule. +type MaxFileSizeBranchRule struct { + BranchRuleMetadata + Parameters MaxFileSizeRuleParameters `json:"parameters"` +} + +// WorkflowsBranchRule represents a workflows branch rule. +type WorkflowsBranchRule struct { + BranchRuleMetadata + Parameters WorkflowsRuleParameters `json:"parameters"` +} + +// CodeScanningBranchRule represents a code scanning branch rule. +type CodeScanningBranchRule struct { + BranchRuleMetadata + Parameters CodeScanningRuleParameters `json:"parameters"` +} + +// EmptyRuleParameters represents the parameters for a rule with no options. +type EmptyRuleParameters struct{} + +// UpdateRuleParameters represents the update rule parameters. +type UpdateRuleParameters struct { + UpdateAllowsFetchAndMerge bool `json:"update_allows_fetch_and_merge"` +} + +// MergeQueueRuleParameters represents the merge_queue rule parameters. +type MergeQueueRuleParameters struct { + CheckResponseTimeoutMinutes int `json:"check_response_timeout_minutes"` + GroupingStrategy MergeGroupingStrategy `json:"grouping_strategy"` + MaxEntriesToBuild int `json:"max_entries_to_build"` + MaxEntriesToMerge int `json:"max_entries_to_merge"` + MergeMethod MergeMethod `json:"merge_method"` + MinEntriesToMerge int `json:"min_entries_to_merge"` + MinEntriesToMergeWaitMinutes int `json:"min_entries_to_merge_wait_minutes"` +} + +// RequiredDeploymentsRuleParameters represents the required deployments rule parameters. +type RequiredDeploymentsRuleParameters struct { + RequiredDeploymentEnvironments []string `json:"required_deployment_environments"` +} + +// PullRequestRuleParameters represents the pull_request rule parameters. +type PullRequestRuleParameters struct { + AllowedMergeMethods []MergeMethod `json:"allowed_merge_methods"` + DismissStaleReviewsOnPush bool `json:"dismiss_stale_reviews_on_push"` + RequireCodeOwnerReview bool `json:"require_code_owner_review"` + RequireLastPushApproval bool `json:"require_last_push_approval"` + RequiredApprovingReviewCount int `json:"required_approving_review_count"` + RequiredReviewThreadResolution bool `json:"required_review_thread_resolution"` +} + +// RequiredStatusChecksRuleParameters represents the required status checks rule parameters. +type RequiredStatusChecksRuleParameters struct { + DoNotEnforceOnCreate *bool `json:"do_not_enforce_on_create,omitempty"` + RequiredStatusChecks []RuleStatusCheck `json:"required_status_checks"` + StrictRequiredStatusChecksPolicy bool `json:"strict_required_status_checks_policy"` +} + +// RuleStatusCheck represents a status checks for the required status checks rule parameters. +type RuleStatusCheck struct { + Context string `json:"context"` + IntegrationID *int64 `json:"integration_id,omitempty"` +} + +// PatternRuleParameters represents the parameters for a pattern rule. +type PatternRuleParameters struct { + Name *string `json:"name,omitempty"` + // If Negate is true, the rule will fail if the pattern matches. + Negate *bool `json:"negate,omitempty"` + Operator PatternRuleOperator `json:"operator"` + Pattern string `json:"pattern"` +} + +// FilePathRestrictionRuleParameters represents the file path restriction rule parameters. +type FilePathRestrictionRuleParameters struct { + RestrictedFilePaths []string `json:"restricted_file_paths"` +} + +// MaxFilePathLengthRuleParameters represents the max file path length rule parameters. +type MaxFilePathLengthRuleParameters struct { + MaxFilePathLength int `json:"max_file_path_length"` +} + +// FileExtensionRestrictionRuleParameters represents the file extension restriction rule parameters. +type FileExtensionRestrictionRuleParameters struct { + RestrictedFileExtensions []string `json:"restricted_file_extensions"` +} + +// MaxFileSizeRuleParameters represents the max file size rule parameters. +type MaxFileSizeRuleParameters struct { + MaxFileSize int64 `json:"max_file_size"` +} + +// WorkflowsRuleParameters represents the workflows rule parameters. +type WorkflowsRuleParameters struct { + DoNotEnforceOnCreate *bool `json:"do_not_enforce_on_create,omitempty"` + Workflows []RuleWorkflow `json:"workflows"` +} + +// RuleWorkflow represents a Workflow for the workflows rule parameters. +type RuleWorkflow struct { + Path string `json:"path"` + Ref *string `json:"ref,omitempty"` + RepositoryID *int64 `json:"repository_id,omitempty"` + Sha *string `json:"sha,omitempty"` +} + +// CodeScanningRuleParameters represents the code scanning rule parameters. +type CodeScanningRuleParameters struct { + CodeScanningTools []RuleCodeScanningTool `json:"code_scanning_tools"` +} + +// RuleCodeScanningTool represents a single code scanning tool for the code scanning parameters. +type RuleCodeScanningTool struct { + AlertsThreshold CodeScanningAlertsThreshold `json:"alerts_threshold"` + SecurityAlertsThreshold CodeScanningSecurityAlertsThreshold `json:"security_alerts_threshold"` + Tool string `json:"tool"` +} + +// repositoryRulesetRuleWrapper is a helper type to marshal & unmarshal a ruleset rule. +type repositoryRulesetRuleWrapper struct { + Type RulesetRuleType `json:"type"` + Parameters *json.RawMessage `json:"parameters,omitempty"` +} + +// MarshalJSON is a custom JSON marshaller for RulesetRules. +func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { + // If new rules are added to RulesetRules the capacity needs increasing + arr := make([]json.RawMessage, 0, 21) + + if r.Creation != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeCreation, nil) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.Update != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeUpdate, r.Update) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.Deletion != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeDeletion, nil) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.RequiredLinearHistory != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeRequiredLinearHistory, nil) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.MergeQueue != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeMergeQueue, r.MergeQueue) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.RequiredDeployments != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeRequiredDeployments, r.RequiredDeployments) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.RequiredSignatures != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeRequiredSignatures, nil) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.PullRequest != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypePullRequest, r.PullRequest) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.RequiredStatusChecks != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeRequiredStatusChecks, r.RequiredStatusChecks) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.NonFastForward != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeNonFastForward, nil) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.CommitMessagePattern != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeCommitMessagePattern, r.CommitMessagePattern) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.CommitAuthorEmailPattern != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeCommitAuthorEmailPattern, r.CommitAuthorEmailPattern) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.CommitterEmailPattern != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeCommitterEmailPattern, r.CommitterEmailPattern) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.BranchNamePattern != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeBranchNamePattern, r.BranchNamePattern) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.TagNamePattern != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeTagNamePattern, r.TagNamePattern) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.FilePathRestriction != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeFilePathRestriction, r.FilePathRestriction) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.MaxFilePathLength != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeMaxFilePathLength, r.MaxFilePathLength) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.FileExtensionRestriction != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeFileExtensionRestriction, r.FileExtensionRestriction) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.MaxFileSize != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeMaxFileSize, r.MaxFileSize) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.Workflows != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeWorkflows, r.Workflows) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + if r.CodeScanning != nil { + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeCodeScanning, r.CodeScanning) + if err != nil { + return nil, err + } + arr = append(arr, json.RawMessage(bytes)) + } + + return json.Marshal(arr) +} + +// marshalRepositoryRulesetRule is a helper function to marshal a ruleset rule. +func marshalRepositoryRulesetRule(t RulesetRuleType, params any) ([]byte, error) { + if params == nil { + return json.Marshal(repositoryRulesetRuleWrapper{Type: t}) + } + + bytes, err := json.Marshal(params) + if err != nil { + return nil, err + } + + return json.Marshal(repositoryRulesetRuleWrapper{Type: t, Parameters: Ptr(json.RawMessage(bytes))}) +} + +// UnmarshalJSON is a custom JSON unmarshaller for RulesetRules. +func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { + // If new rules are added to RulesetRules the capacity needs increasing + arr := make([]repositoryRulesetRuleWrapper, 0, 21) + + err := json.Unmarshal(data, &arr) + if err != nil { + return err + } + + for _, w := range arr { + switch w.Type { + case RulesetRuleTypeCreation: + r.Creation = &EmptyRuleParameters{} + case RulesetRuleTypeUpdate: + r.Update = &UpdateRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.Update) + if err != nil { + return err + } + } + case RulesetRuleTypeDeletion: + r.Deletion = &EmptyRuleParameters{} + case RulesetRuleTypeRequiredLinearHistory: + r.RequiredLinearHistory = &EmptyRuleParameters{} + case RulesetRuleTypeMergeQueue: + r.MergeQueue = &MergeQueueRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.MergeQueue) + if err != nil { + return err + } + } + case RulesetRuleTypeRequiredDeployments: + r.RequiredDeployments = &RequiredDeploymentsRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.RequiredDeployments) + if err != nil { + return err + } + } + case RulesetRuleTypeRequiredSignatures: + r.RequiredSignatures = &EmptyRuleParameters{} + case RulesetRuleTypePullRequest: + r.PullRequest = &PullRequestRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.PullRequest) + if err != nil { + return err + } + } + case RulesetRuleTypeRequiredStatusChecks: + r.RequiredStatusChecks = &RequiredStatusChecksRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.RequiredStatusChecks) + if err != nil { + return err + } + } + case RulesetRuleTypeNonFastForward: + r.NonFastForward = &EmptyRuleParameters{} + case RulesetRuleTypeCommitMessagePattern: + r.CommitMessagePattern = &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.CommitMessagePattern) + if err != nil { + return err + } + } + case RulesetRuleTypeCommitAuthorEmailPattern: + r.CommitAuthorEmailPattern = &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.CommitAuthorEmailPattern) + if err != nil { + return err + } + } + case RulesetRuleTypeCommitterEmailPattern: + r.CommitterEmailPattern = &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.CommitterEmailPattern) + if err != nil { + return err + } + } + case RulesetRuleTypeBranchNamePattern: + r.BranchNamePattern = &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.BranchNamePattern) + if err != nil { + return err + } + } + case RulesetRuleTypeTagNamePattern: + r.TagNamePattern = &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.TagNamePattern) + if err != nil { + return err + } + } + case RulesetRuleTypeFilePathRestriction: + r.FilePathRestriction = &FilePathRestrictionRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.FilePathRestriction) + if err != nil { + return err + } + } + case RulesetRuleTypeMaxFilePathLength: + r.MaxFilePathLength = &MaxFilePathLengthRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.MaxFilePathLength) + if err != nil { + return err + } + } + case RulesetRuleTypeFileExtensionRestriction: + r.FileExtensionRestriction = &FileExtensionRestrictionRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.FileExtensionRestriction) + if err != nil { + return err + } + } + case RulesetRuleTypeMaxFileSize: + r.MaxFileSize = &MaxFileSizeRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.MaxFileSize) + if err != nil { + return err + } + } + case RulesetRuleTypeWorkflows: + r.Workflows = &WorkflowsRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.Workflows) + if err != nil { + return err + } + } + case RulesetRuleTypeCodeScanning: + r.CodeScanning = &CodeScanningRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, r.CodeScanning) + if err != nil { + return err + } + } + } + } + + return nil +} + +// branchRuleWrapper is a helper type to unmarshal a branch rule. +type branchRuleWrapper struct { + Type RulesetRuleType `json:"type"` + BranchRuleMetadata + Parameters *json.RawMessage `json:"parameters,omitempty"` +} + +// UnmarshalJSON is a custom JSON unmarshaller for BranchRules. +func (r *BranchRules) UnmarshalJSON(data []byte) error { + // If new rules are added to RulesetRules the capacity needs increasing + arr := make([]branchRuleWrapper, 0, 21) + + err := json.Unmarshal(data, &arr) + if err != nil { + return err + } + + for _, w := range arr { + switch w.Type { + case RulesetRuleTypeCreation: + r.Creation = append(r.Creation, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + case RulesetRuleTypeUpdate: + params := &UpdateRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.Update = append(r.Update, UpdateBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeDeletion: + r.Deletion = append(r.Deletion, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + case RulesetRuleTypeRequiredLinearHistory: + r.RequiredLinearHistory = append(r.RequiredLinearHistory, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + case RulesetRuleTypeMergeQueue: + params := &MergeQueueRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.MergeQueue = append(r.MergeQueue, MergeQueueBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeRequiredDeployments: + params := &RequiredDeploymentsRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.RequiredDeployments = append(r.RequiredDeployments, RequiredDeploymentsBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeRequiredSignatures: + r.RequiredSignatures = append(r.RequiredSignatures, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + case RulesetRuleTypePullRequest: + params := &PullRequestRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.PullRequest = append(r.PullRequest, PullRequestBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeRequiredStatusChecks: + params := &RequiredStatusChecksRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.RequiredStatusChecks = append(r.RequiredStatusChecks, RequiredStatusChecksBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeNonFastForward: + r.NonFastForward = append(r.NonFastForward, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + case RulesetRuleTypeCommitMessagePattern: + params := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.CommitMessagePattern = append(r.CommitMessagePattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeCommitAuthorEmailPattern: + params := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.CommitAuthorEmailPattern = append(r.CommitAuthorEmailPattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeCommitterEmailPattern: + params := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.CommitterEmailPattern = append(r.CommitterEmailPattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeBranchNamePattern: + params := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.BranchNamePattern = append(r.BranchNamePattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeTagNamePattern: + params := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.TagNamePattern = append(r.TagNamePattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeFilePathRestriction: + params := &FilePathRestrictionRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.FilePathRestriction = append(r.FilePathRestriction, FilePathRestrictionBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeMaxFilePathLength: + params := &MaxFilePathLengthRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.MaxFilePathLength = append(r.MaxFilePathLength, MaxFilePathLengthBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeFileExtensionRestriction: + params := &FileExtensionRestrictionRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.FileExtensionRestriction = append(r.FileExtensionRestriction, FileExtensionRestrictionBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeMaxFileSize: + params := &MaxFileSizeRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.MaxFileSize = append(r.MaxFileSize, MaxFileSizeBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeWorkflows: + params := &WorkflowsRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.Workflows = append(r.Workflows, WorkflowsBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + case RulesetRuleTypeCodeScanning: + params := &CodeScanningRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, params) + if err != nil { + return err + } + } + + r.CodeScanning = append(r.CodeScanning, CodeScanningBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + } + } + + return nil +} + +// UnmarshalJSON is a custom JSON unmarshaller for RulesetRule. +func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { + w := repositoryRulesetRuleWrapper{} + + err := json.Unmarshal(data, &w) + if err != nil { + return err + } + + r.Type = w.Type + + switch r.Type { + case RulesetRuleTypeCreation: + r.Parameters = nil + case RulesetRuleTypeUpdate: + p := &UpdateRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeDeletion: + r.Parameters = nil + case RulesetRuleTypeRequiredLinearHistory: + r.Parameters = nil + case RulesetRuleTypeMergeQueue: + p := &MergeQueueRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeRequiredDeployments: + p := &RequiredDeploymentsRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeRequiredSignatures: + r.Parameters = nil + case RulesetRuleTypePullRequest: + p := &PullRequestRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeRequiredStatusChecks: + p := &RequiredStatusChecksRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeNonFastForward: + r.Parameters = nil + case RulesetRuleTypeCommitMessagePattern: + p := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeCommitAuthorEmailPattern: + p := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeCommitterEmailPattern: + p := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeBranchNamePattern: + p := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeTagNamePattern: + p := &PatternRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeFilePathRestriction: + p := &FilePathRestrictionRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeMaxFilePathLength: + p := &MaxFilePathLengthRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeFileExtensionRestriction: + p := &FileExtensionRestrictionRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeMaxFileSize: + p := &MaxFileSizeRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeWorkflows: + p := &WorkflowsRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + case RulesetRuleTypeCodeScanning: + p := &CodeScanningRuleParameters{} + + if w.Parameters != nil { + err = json.Unmarshal(*w.Parameters, p) + if err != nil { + return err + } + } + + r.Parameters = p + } + + return nil +} diff --git a/github/rules_test.go b/github/rules_test.go new file mode 100644 index 00000000000..ff8b8c05450 --- /dev/null +++ b/github/rules_test.go @@ -0,0 +1,101 @@ +// Copyright 2025 The go-github AUTHORS. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package github + +import ( + "encoding/json" + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestRulesetRules(t *testing.T) { + t.Parallel() + tests := []struct { + name string + rules *RepositoryRulesetRules + json string + }{ + {"empty", &RepositoryRulesetRules{}, `[]`}, + {"single_rule_with_empty_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, `[{"type":"creation"}]`}, + {"single_ule_with_required_params", &RepositoryRulesetRules{Update: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}, `[{"type":"update","parameters":{"update_allows_fetch_and_merge":true}}]`}, + {"all_rules_with_required_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, MergeQueue: &MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}, RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{RequiredStatusChecks: []RuleStatusCheck{{Context: "test1"}, {Context: "test2"}}, StrictRequiredStatusChecksPolicy: true}, NonFastForward: &EmptyRuleParameters{}, CommitMessagePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitAuthorEmailPattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitterEmailPattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, BranchNamePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, TagNamePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, FilePathRestriction: &FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}, MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}, MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, Workflows: &WorkflowsRuleParameters{Workflows: []RuleWorkflow{{Path: ".github/workflows/test1.yaml"}, {Path: ".github/workflows/test2.yaml"}}}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}, `[{"type":"creation"},{"type":"update","parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test1"},{"context":"test2"}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"workflows":[{"path":".github/workflows/test1.yaml"},{"path":".github/workflows/test2.yaml"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, + {"all_rules_with_all_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, MergeQueue: &MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}, RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{DoNotEnforceOnCreate: Ptr(true), RequiredStatusChecks: []RuleStatusCheck{{Context: "test1", IntegrationID: Ptr(int64(1))}, {Context: "test2", IntegrationID: Ptr(int64(2))}}, StrictRequiredStatusChecksPolicy: true}, NonFastForward: &EmptyRuleParameters{}, CommitMessagePattern: &PatternRuleParameters{Name: Ptr("cmp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitAuthorEmailPattern: &PatternRuleParameters{Name: Ptr("caep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitterEmailPattern: &PatternRuleParameters{Name: Ptr("cep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, BranchNamePattern: &PatternRuleParameters{Name: Ptr("bp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, TagNamePattern: &PatternRuleParameters{Name: Ptr("tp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, FilePathRestriction: &FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}, MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}, MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, Workflows: &WorkflowsRuleParameters{DoNotEnforceOnCreate: Ptr(true), Workflows: []RuleWorkflow{{Path: ".github/workflows/test1.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(1)), Sha: Ptr("aaaa")}, {Path: ".github/workflows/test2.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(2)), Sha: Ptr("bbbb")}}}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}, `[{"type":"creation"},{"type":"update","parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, + } + + t.Run("MarshalJSON", func(t *testing.T) { + t.Parallel() + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + got, err := json.Marshal(test.rules) + if err != nil { + t.Errorf("Unable to marshal JSON for %#v", test.rules) + } + + if diff := cmp.Diff(test.json, string(got)); diff != "" { + t.Errorf("json.Marshal returned:\n%s\nwant:\n%s\ndiff:\n%v", got, test.json, diff) + } + }) + } + }) + + t.Run("UnmarshalJSON", func(t *testing.T) { + t.Parallel() + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + got := &RepositoryRulesetRules{} + err := json.Unmarshal([]byte(test.json), got) + if err != nil { + t.Errorf("Unable to unmarshal JSON %v: %v", test.json, err) + } + + if diff := cmp.Diff(test.rules, got); diff != "" { + t.Errorf("json.Unmarshal returned:\n%#v\nwant:\n%#v\ndiff:\n%v", got, test.rules, diff) + } + }) + } + }) +} + +func TestBranchRules(t *testing.T) { + t.Parallel() + tests := []struct { + name string + rules *BranchRules + json string + }{ + {"empty", &BranchRules{}, `[]`}, + {"single_rule_type_single_rule_empty_params", &BranchRules{Creation: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}}, `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1}]`}, + {"single_rule_type_single_rule_with_params", &BranchRules{Update: []UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}}, `[{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}}]`}, + {"all_rule_types_with_all_parameters", &BranchRules{Creation: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, Update: []UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}, Deletion: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, RequiredLinearHistory: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, MergeQueue: []MergeQueueBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}}}, RequiredDeployments: []RequiredDeploymentsBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}}}, RequiredSignatures: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, PullRequest: []PullRequestBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}}}, RequiredStatusChecks: []RequiredStatusChecksBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: RequiredStatusChecksRuleParameters{DoNotEnforceOnCreate: Ptr(true), RequiredStatusChecks: []RuleStatusCheck{{Context: "test1", IntegrationID: Ptr(int64(1))}, {Context: "test2", IntegrationID: Ptr(int64(2))}}, StrictRequiredStatusChecksPolicy: true}}}, NonFastForward: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, CommitMessagePattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("cmp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, CommitAuthorEmailPattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("caep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, CommitterEmailPattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("cep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, BranchNamePattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("bp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, TagNamePattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("tp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, FilePathRestriction: []FilePathRestrictionBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}}}, MaxFilePathLength: []MaxFilePathLengthBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}}}, FileExtensionRestriction: []FileExtensionRestrictionBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}}}, MaxFileSize: []MaxFileSizeBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MaxFileSizeRuleParameters{MaxFileSize: 1024}}}, Workflows: []WorkflowsBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: WorkflowsRuleParameters{DoNotEnforceOnCreate: Ptr(true), Workflows: []RuleWorkflow{{Path: ".github/workflows/test1.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(1)), Sha: Ptr("aaaa")}, {Path: ".github/workflows/test2.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(2)), Sha: Ptr("bbbb")}}}}}, CodeScanning: []CodeScanningBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}}}, `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"required_linear_history","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"merge_queue","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"pull_request","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"commit_message_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_size":1024}},{"type":"workflows","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, + } + + t.Run("UnmarshalJSON", func(t *testing.T) { + t.Parallel() + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + got := &BranchRules{} + err := json.Unmarshal([]byte(test.json), got) + if err != nil { + t.Errorf("Unable to unmarshal JSON %v: %v", test.json, err) + } + + if diff := cmp.Diff(test.rules, got); diff != "" { + t.Errorf("json.Unmarshal returned:\n%#v\nwant:\n%#v\ndiff:\n%v", got, test.rules, diff) + } + }) + } + }) +} From a38ea41861d7f3d38014e72654ac451e1eab3265 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Mon, 13 Jan 2025 15:51:25 +0000 Subject: [PATCH 02/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/github-accessors.go | 16 ++++++++-------- github/github-accessors_test.go | 22 +++++++++++----------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/github/github-accessors.go b/github/github-accessors.go index 30609cbe96a..122c476c6af 100644 --- a/github/github-accessors.go +++ b/github/github-accessors.go @@ -20942,14 +20942,6 @@ func (r *RepositoryRulesetChangedRule) GetRuleType() *RepositoryRulesetChangeSou return r.RuleType } -// GetFrom returns the From field if it's non-nil, zero value otherwise. -func (r *RepositoryRulesetChangeSource) GetFrom() string { - if r == nil || r.From == nil { - return "" - } - return *r.From -} - // GetConditions returns the Conditions field. func (r *RepositoryRulesetChanges) GetConditions() *RepositoryRulesetChangedConditions { if r == nil { @@ -20982,6 +20974,14 @@ func (r *RepositoryRulesetChanges) GetRules() *RepositoryRulesetChangedRules { return r.Rules } +// GetFrom returns the From field if it's non-nil, zero value otherwise. +func (r *RepositoryRulesetChangeSource) GetFrom() string { + if r == nil || r.From == nil { + return "" + } + return *r.From +} + // GetOrganizationID returns the OrganizationID field. func (r *RepositoryRulesetConditions) GetOrganizationID() *RepositoryRulesetOrganizationIDsConditionParameters { if r == nil { diff --git a/github/github-accessors_test.go b/github/github-accessors_test.go index a16d2f286f5..e2baa98a231 100644 --- a/github/github-accessors_test.go +++ b/github/github-accessors_test.go @@ -26919,17 +26919,6 @@ func TestRepositoryRulesetChangedRule_GetRuleType(tt *testing.T) { r.GetRuleType() } -func TestRepositoryRulesetChangedSource_GetFrom(tt *testing.T) { - tt.Parallel() - var zeroValue string - r := &RepositoryRulesetChangeSource{From: &zeroValue} - r.GetFrom() - r = &RepositoryRulesetChangeSource{} - r.GetFrom() - r = nil - r.GetFrom() -} - func TestRepositoryRulesetChanges_GetConditions(tt *testing.T) { tt.Parallel() r := &RepositoryRulesetChanges{} @@ -26962,6 +26951,17 @@ func TestRepositoryRulesetChanges_GetRules(tt *testing.T) { r.GetRules() } +func TestRepositoryRulesetChangeSource_GetFrom(tt *testing.T) { + tt.Parallel() + var zeroValue string + r := &RepositoryRulesetChangeSource{From: &zeroValue} + r.GetFrom() + r = &RepositoryRulesetChangeSource{} + r.GetFrom() + r = nil + r.GetFrom() +} + func TestRepositoryRulesetConditions_GetOrganizationID(tt *testing.T) { tt.Parallel() r := &RepositoryRulesetConditions{} From 152169ab59530664a179b94882c3f0801985b781 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Mon, 13 Jan 2025 20:00:28 +0000 Subject: [PATCH 03/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/enterprise_rules_test.go | 104 +++++++------- github/event_types.go | 12 +- github/event_types_test.go | 4 +- github/github-accessors.go | 8 +- github/github-accessors_test.go | 10 +- github/orgs_rules_test.go | 94 ++++++------- github/repos_rules.go | 2 +- github/repos_rules_test.go | 4 +- github/rules.go | 235 ++++++++++++++++---------------- github/rules_test.go | 12 +- 10 files changed, 245 insertions(+), 240 deletions(-) diff --git a/github/enterprise_rules_test.go b/github/enterprise_rules_test.go index 69e810d15a1..87c44102883 100644 --- a/github/enterprise_rules_test.go +++ b/github/enterprise_rules_test.go @@ -179,7 +179,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoName(t *testing.T) Name: "ruleset", Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -221,7 +221,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoName(t *testing.T) }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -259,7 +259,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoName(t *testing.T) Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -280,7 +280,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoName(t *testing.T) SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -322,7 +322,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoName(t *testing.T) }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -360,7 +360,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoName(t *testing.T) Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -559,7 +559,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoProperty(t *testin Name: "ruleset", Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -571,17 +571,17 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoProperty(t *testin Exclude: []string{"unimportant_organization"}, }, RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ - Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Include: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testIncludeProp", - Source: Ptr("custom"), - Values: []string{"true"}, + Name: "testIncludeProp", + Source: Ptr("custom"), + PropertyValues: []string{"true"}, }, }, - Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Exclude: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testExcludeProp", - Values: []string{"false"}, + Name: "testExcludeProp", + PropertyValues: []string{"false"}, }, }, }, @@ -611,7 +611,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoProperty(t *testin }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -649,7 +649,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoProperty(t *testin Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -670,7 +670,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoProperty(t *testin SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -682,17 +682,17 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoProperty(t *testin Exclude: []string{"unimportant_organization"}, }, RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ - Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Include: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testIncludeProp", - Source: Ptr("custom"), - Values: []string{"true"}, + Name: "testIncludeProp", + Source: Ptr("custom"), + PropertyValues: []string{"true"}, }, }, - Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Exclude: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testExcludeProp", - Values: []string{"false"}, + Name: "testExcludeProp", + PropertyValues: []string{"false"}, }, }, }, @@ -722,7 +722,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoProperty(t *testin }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -760,7 +760,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgNameRepoProperty(t *testin Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -944,7 +944,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoName(t *testing.T) { Name: "ruleset", Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -985,7 +985,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoName(t *testing.T) { }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -1023,7 +1023,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoName(t *testing.T) { Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -1044,7 +1044,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoName(t *testing.T) { SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -1085,7 +1085,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoName(t *testing.T) { }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -1123,7 +1123,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoName(t *testing.T) { Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -1316,7 +1316,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoProperty(t *testing. Name: "ruleset", Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -1327,17 +1327,17 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoProperty(t *testing. OrganizationIDs: []int64{1001, 1002}, }, RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ - Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Include: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testIncludeProp", - Source: Ptr("custom"), - Values: []string{"true"}, + Name: "testIncludeProp", + Source: Ptr("custom"), + PropertyValues: []string{"true"}, }, }, - Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Exclude: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testExcludeProp", - Values: []string{"false"}, + Name: "testExcludeProp", + PropertyValues: []string{"false"}, }, }, }, @@ -1367,7 +1367,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoProperty(t *testing. }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -1405,7 +1405,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoProperty(t *testing. Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -1426,7 +1426,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoProperty(t *testing. SourceType: Ptr(RulesetSourceTypeEnterprise), Source: "e", Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -1437,17 +1437,17 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoProperty(t *testing. OrganizationIDs: []int64{1001, 1002}, }, RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ - Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Include: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testIncludeProp", - Source: Ptr("custom"), - Values: []string{"true"}, + Name: "testIncludeProp", + Source: Ptr("custom"), + PropertyValues: []string{"true"}, }, }, - Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Exclude: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testExcludeProp", - Values: []string{"false"}, + Name: "testExcludeProp", + PropertyValues: []string{"false"}, }, }, }, @@ -1477,7 +1477,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoProperty(t *testing. }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -1515,7 +1515,7 @@ func TestEnterpriseService_CreateRepositoryRuleset_OrgIdRepoProperty(t *testing. Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, diff --git a/github/event_types.go b/github/event_types.go index 3732bb3a126..a211191ac49 100644 --- a/github/event_types.go +++ b/github/event_types.go @@ -1551,9 +1551,9 @@ type RepositoryRulesetChangeSources struct { // RepositoryRulesetChangedConditions holds changes to conditions in a ruleset. type RepositoryRulesetChangedConditions struct { - Added []RepositoryRulesetConditions `json:"added,omitempty"` - Deleted []RepositoryRulesetConditions `json:"deleted,omitempty"` - Updated []RepositoryRulesetUpdatedConditions `json:"updated,omitempty"` + Added []*RepositoryRulesetConditions `json:"added,omitempty"` + Deleted []*RepositoryRulesetConditions `json:"deleted,omitempty"` + Updated []*RepositoryRulesetUpdatedConditions `json:"updated,omitempty"` } // RepositoryRulesetUpdatedConditions represents the edited updates to conditions in a ruleset. @@ -1572,9 +1572,9 @@ type RepositoryRulesetUpdatedCondition struct { // RepositoryRulesetChangedRules holds changes to rules in a ruleset. type RepositoryRulesetChangedRules struct { - Added []RepositoryRulesetRule `json:"added,omitempty"` - Deleted []RepositoryRulesetRule `json:"deleted,omitempty"` - Updated []RepositoryRulesetUpdatedRules `json:"updated,omitempty"` + Added []*RepositoryRulesetRule `json:"added,omitempty"` + Deleted []*RepositoryRulesetRule `json:"deleted,omitempty"` + Updated []*RepositoryRulesetUpdatedRules `json:"updated,omitempty"` } // RepositoryRulesetUpdatedRules holds updates to rules in a ruleset. diff --git a/github/event_types_test.go b/github/event_types_test.go index bdce6dd388f..1c60a0c2e0e 100644 --- a/github/event_types_test.go +++ b/github/event_types_test.go @@ -9605,8 +9605,8 @@ func TestRepositoryRulesetEvent_Unmarshal(t *testing.T) { event *RepositoryRulesetEvent }{ {"empty", `{}`, &RepositoryRulesetEvent{}}, - {"created", fmt.Sprintf(`{"action":"created","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~ALL"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase","merge"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"high_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("created"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~ALL"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase, MergeMethodMerge}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, - {"edited", fmt.Sprintf(`{"action":"edited","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type": "required_signatures"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"changes":{"rules":{"added":[{"type": "required_signatures"}],"updated":[{"rule":{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},"changes":{"configuration":{"from":"{\\\"required_reviewers\\\":[],\\\"allowed_merge_methods\\\":[\\\"squash\\\",\\\"rebase\\\",\\\"merge\\\"],\\\"require_code_owner_review\\\":false,\\\"require_last_push_approval\\\":false,\\\"dismiss_stale_reviews_on_push\\\":false,\\\"required_approving_review_count\\\":2,\\\"authorized_dismissal_actors_only\\\":false,\\\"required_review_thread_resolution\\\":false,\\\"ignore_approvals_from_contributors\\\":false,\\\"automatic_copilot_code_review_enabled\\\":false}"}}},{"rule":{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}},"changes":{"configuration":{"from":"{\\\"code_scanning_tools\\\":[{\\\"tool\\\":\\\"CodeQL\\\",\\\"alerts_threshold\\\":\\\"errors\\\",\\\"security_alerts_threshold\\\":\\\"high_or_higher\\\"}]}"}}}],"deleted":[{"type":"required_linear_history"}]},"conditions":{"updated":[{"condition":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"changes":{"include":{"from":["~ALL"]}}}],"deleted":[]}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("edited"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Changes: &RepositoryRulesetChanges{Conditions: &RepositoryRulesetChangedConditions{Updated: []RepositoryRulesetUpdatedConditions{{Condition: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Changes: &RepositoryRulesetUpdatedCondition{Include: &RepositoryRulesetChangeSources{From: []string{"~ALL"}}}}}, Deleted: []RepositoryRulesetConditions{}}, Rules: &RepositoryRulesetChangedRules{Added: []RepositoryRulesetRule{{Type: RulesetRuleTypeRequiredSignatures}}, Updated: []RepositoryRulesetUpdatedRules{{Rule: &RepositoryRulesetRule{Type: RulesetRuleTypePullRequest, Parameters: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"required_reviewers\":[],\"allowed_merge_methods\":[\"squash\",\"rebase\",\"merge\"],\"require_code_owner_review\":false,\"require_last_push_approval\":false,\"dismiss_stale_reviews_on_push\":false,\"required_approving_review_count\":2,\"authorized_dismissal_actors_only\":false,\"required_review_thread_resolution\":false,\"ignore_approvals_from_contributors\":false,\"automatic_copilot_code_review_enabled\":false}`)}}}, {Rule: &RepositoryRulesetRule{Type: RulesetRuleTypeCodeScanning, Parameters: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"code_scanning_tools\":[{\"tool\":\"CodeQL\",\"alerts_threshold\":\"errors\",\"security_alerts_threshold\":\"high_or_higher\"}]}`)}}}}, Deleted: []RepositoryRulesetRule{{Type: RulesetRuleTypeRequiredLinearHistory}}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, + {"created", fmt.Sprintf(`{"action":"created","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~ALL"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase","merge"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"high_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("created"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~ALL"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase, MergeMethodMerge}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, + {"edited", fmt.Sprintf(`{"action":"edited","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type": "required_signatures"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"changes":{"rules":{"added":[{"type": "required_signatures"}],"updated":[{"rule":{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},"changes":{"configuration":{"from":"{\\\"required_reviewers\\\":[],\\\"allowed_merge_methods\\\":[\\\"squash\\\",\\\"rebase\\\",\\\"merge\\\"],\\\"require_code_owner_review\\\":false,\\\"require_last_push_approval\\\":false,\\\"dismiss_stale_reviews_on_push\\\":false,\\\"required_approving_review_count\\\":2,\\\"authorized_dismissal_actors_only\\\":false,\\\"required_review_thread_resolution\\\":false,\\\"ignore_approvals_from_contributors\\\":false,\\\"automatic_copilot_code_review_enabled\\\":false}"}}},{"rule":{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}},"changes":{"configuration":{"from":"{\\\"code_scanning_tools\\\":[{\\\"tool\\\":\\\"CodeQL\\\",\\\"alerts_threshold\\\":\\\"errors\\\",\\\"security_alerts_threshold\\\":\\\"high_or_higher\\\"}]}"}}}],"deleted":[{"type":"required_linear_history"}]},"conditions":{"updated":[{"condition":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"changes":{"include":{"from":["~ALL"]}}}],"deleted":[]}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("edited"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Changes: &RepositoryRulesetChanges{Conditions: &RepositoryRulesetChangedConditions{Updated: []*RepositoryRulesetUpdatedConditions{{Condition: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Changes: &RepositoryRulesetUpdatedCondition{Include: &RepositoryRulesetChangeSources{From: []string{"~ALL"}}}}}, Deleted: []*RepositoryRulesetConditions{}}, Rules: &RepositoryRulesetChangedRules{Added: []*RepositoryRulesetRule{{Type: RulesetRuleTypeRequiredSignatures}}, Updated: []*RepositoryRulesetUpdatedRules{{Rule: &RepositoryRulesetRule{Type: RulesetRuleTypePullRequest, Parameters: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"required_reviewers\":[],\"allowed_merge_methods\":[\"squash\",\"rebase\",\"merge\"],\"require_code_owner_review\":false,\"require_last_push_approval\":false,\"dismiss_stale_reviews_on_push\":false,\"required_approving_review_count\":2,\"authorized_dismissal_actors_only\":false,\"required_review_thread_resolution\":false,\"ignore_approvals_from_contributors\":false,\"automatic_copilot_code_review_enabled\":false}`)}}}, {Rule: &RepositoryRulesetRule{Type: RulesetRuleTypeCodeScanning, Parameters: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"code_scanning_tools\":[{\"tool\":\"CodeQL\",\"alerts_threshold\":\"errors\",\"security_alerts_threshold\":\"high_or_higher\"}]}`)}}}}, Deleted: []*RepositoryRulesetRule{{Type: RulesetRuleTypeRequiredLinearHistory}}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, {"deleted", fmt.Sprintf(`{"action":"deleted","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("deleted"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, } diff --git a/github/github-accessors.go b/github/github-accessors.go index 122c476c6af..aef6de92296 100644 --- a/github/github-accessors.go +++ b/github/github-accessors.go @@ -21878,12 +21878,12 @@ func (r *RuleWorkflow) GetRepositoryID() int64 { return *r.RepositoryID } -// GetSha returns the Sha field if it's non-nil, zero value otherwise. -func (r *RuleWorkflow) GetSha() string { - if r == nil || r.Sha == nil { +// GetSHA returns the SHA field if it's non-nil, zero value otherwise. +func (r *RuleWorkflow) GetSHA() string { + if r == nil || r.SHA == nil { return "" } - return *r.Sha + return *r.SHA } // GetBusy returns the Busy field if it's non-nil, zero value otherwise. diff --git a/github/github-accessors_test.go b/github/github-accessors_test.go index e2baa98a231..5f48b89c6ff 100644 --- a/github/github-accessors_test.go +++ b/github/github-accessors_test.go @@ -28038,15 +28038,15 @@ func TestRuleWorkflow_GetRepositoryID(tt *testing.T) { r.GetRepositoryID() } -func TestRuleWorkflow_GetSha(tt *testing.T) { +func TestRuleWorkflow_GetSHA(tt *testing.T) { tt.Parallel() var zeroValue string - r := &RuleWorkflow{Sha: &zeroValue} - r.GetSha() + r := &RuleWorkflow{SHA: &zeroValue} + r.GetSHA() r = &RuleWorkflow{} - r.GetSha() + r.GetSHA() r = nil - r.GetSha() + r.GetSHA() } func TestRunner_GetBusy(tt *testing.T) { diff --git a/github/orgs_rules_test.go b/github/orgs_rules_test.go index 1ab4b9b3973..2d2080a7f4c 100644 --- a/github/orgs_rules_test.go +++ b/github/orgs_rules_test.go @@ -226,7 +226,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoNames(t *testing.T) { Name: "ruleset", Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -264,7 +264,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoNames(t *testing.T) { }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -302,7 +302,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoNames(t *testing.T) { Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -323,7 +323,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoNames(t *testing.T) { SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -361,7 +361,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoNames(t *testing.T) { }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -399,7 +399,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoNames(t *testing.T) { Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -580,7 +580,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoProperty(t *testing.T) Name: "ruleset", Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -588,17 +588,17 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoProperty(t *testing.T) }, Conditions: &RepositoryRulesetConditions{ RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ - Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Include: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testIncludeProp", - Source: Ptr("custom"), - Values: []string{"true"}, + Name: "testIncludeProp", + Source: Ptr("custom"), + PropertyValues: []string{"true"}, }, }, - Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Exclude: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testExcludeProp", - Values: []string{"false"}, + Name: "testExcludeProp", + PropertyValues: []string{"false"}, }, }, }, @@ -624,7 +624,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoProperty(t *testing.T) }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -662,7 +662,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoProperty(t *testing.T) Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -683,7 +683,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoProperty(t *testing.T) SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -691,17 +691,17 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoProperty(t *testing.T) }, Conditions: &RepositoryRulesetConditions{ RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ - Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Include: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testIncludeProp", - Source: Ptr("custom"), - Values: []string{"true"}, + Name: "testIncludeProp", + Source: Ptr("custom"), + PropertyValues: []string{"true"}, }, }, - Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Exclude: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testExcludeProp", - Values: []string{"false"}, + Name: "testExcludeProp", + PropertyValues: []string{"false"}, }, }, }, @@ -727,7 +727,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoProperty(t *testing.T) }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -765,7 +765,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoProperty(t *testing.T) Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -939,7 +939,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoIDs(t *testing.T) { Name: "ruleset", Target: Ptr(RulesetTargetBranch), Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -975,7 +975,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoIDs(t *testing.T) { }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -1013,7 +1013,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoIDs(t *testing.T) { Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -1034,7 +1034,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoIDs(t *testing.T) { SourceType: Ptr(RulesetSourceTypeOrganization), Source: "o", Enforcement: "active", - BypassActors: []BypassActor{ + BypassActors: []*BypassActor{ { ActorID: Ptr(int64(234)), ActorType: Ptr(BypassActorTypeTeam), @@ -1070,7 +1070,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoIDs(t *testing.T) { }, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ DoNotEnforceOnCreate: Ptr(true), - RequiredStatusChecks: []RuleStatusCheck{ + RequiredStatusChecks: []*RuleStatusCheck{ { Context: "test", IntegrationID: Ptr(int64(1)), @@ -1108,7 +1108,7 @@ func TestOrganizationsService_CreateRepositoryRuleset_RepoIDs(t *testing.T) { Pattern: "github", }, CodeScanning: &CodeScanningRuleParameters{ - CodeScanningTools: []RuleCodeScanningTool{ + CodeScanningTools: []*RuleCodeScanningTool{ { AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, @@ -1288,14 +1288,14 @@ func TestOrganizationsService_GetRepositoryRulesetWithRepoPropCondition(t *testi }, Conditions: &RepositoryRulesetConditions{ RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ - Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Include: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testIncludeProp", - Source: Ptr("custom"), - Values: []string{"true"}, + Name: "testIncludeProp", + Source: Ptr("custom"), + PropertyValues: []string{"true"}, }, }, - Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{}, + Exclude: []*RepositoryRulesetRepositoryPropertyTargetParameters{}, }, }, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, @@ -1474,14 +1474,14 @@ func TestOrganizationsService_UpdateRepositoryRulesetWithRepoProp(t *testing.T) Enforcement: "active", Conditions: &RepositoryRulesetConditions{ RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ - Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Include: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testIncludeProp", - Source: Ptr("custom"), - Values: []string{"true"}, + Name: "testIncludeProp", + Source: Ptr("custom"), + PropertyValues: []string{"true"}, }, }, - Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{}, + Exclude: []*RepositoryRulesetRepositoryPropertyTargetParameters{}, }, }, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, @@ -1503,14 +1503,14 @@ func TestOrganizationsService_UpdateRepositoryRulesetWithRepoProp(t *testing.T) }, Conditions: &RepositoryRulesetConditions{ RepositoryProperty: &RepositoryRulesetRepositoryPropertyConditionParameters{ - Include: []RepositoryRulesetRepositoryPropertyTargetParameters{ + Include: []*RepositoryRulesetRepositoryPropertyTargetParameters{ { - Name: "testIncludeProp", - Source: Ptr("custom"), - Values: []string{"true"}, + Name: "testIncludeProp", + Source: Ptr("custom"), + PropertyValues: []string{"true"}, }, }, - Exclude: []RepositoryRulesetRepositoryPropertyTargetParameters{}, + Exclude: []*RepositoryRulesetRepositoryPropertyTargetParameters{}, }, }, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, diff --git a/github/repos_rules.go b/github/repos_rules.go index cda5a488057..d38e35cdd77 100644 --- a/github/repos_rules.go +++ b/github/repos_rules.go @@ -18,7 +18,7 @@ type rulesetNoOmitBypassActors struct { SourceType *RulesetSourceType `json:"source_type,omitempty"` Source string `json:"source"` Enforcement RulesetEnforcement `json:"enforcement"` - BypassActors []BypassActor `json:"bypass_actors"` + BypassActors []*BypassActor `json:"bypass_actors"` CurrentUserCanBypass *BypassMode `json:"current_user_can_bypass,omitempty"` NodeID *string `json:"node_id,omitempty"` Links *RepositoryRulesetLinks `json:"_links,omitempty"` diff --git a/github/repos_rules_test.go b/github/repos_rules_test.go index c1f274e6cf5..bb43d532a55 100644 --- a/github/repos_rules_test.go +++ b/github/repos_rules_test.go @@ -46,8 +46,8 @@ func TestRepositoriesService_GetRulesForBranch(t *testing.T) { } want := &BranchRules{ - Creation: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "google/a", RulesetID: 42069}}, - Update: []UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeOrganization, RulesetSource: "google", RulesetID: 42069}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}, + Creation: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "google/a", RulesetID: 42069}}, + Update: []*UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeOrganization, RulesetSource: "google", RulesetID: 42069}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}, } if !cmp.Equal(rules, want) { diff --git a/github/rules.go b/github/rules.go index fab50bc9e34..c8b24bfe94c 100644 --- a/github/rules.go +++ b/github/rules.go @@ -7,6 +7,7 @@ package github import ( "encoding/json" + "reflect" ) // RulesetTarget represents a GitHub ruleset target. @@ -150,7 +151,7 @@ type RepositoryRuleset struct { SourceType *RulesetSourceType `json:"source_type,omitempty"` Source string `json:"source"` Enforcement RulesetEnforcement `json:"enforcement"` - BypassActors []BypassActor `json:"bypass_actors,omitempty"` + BypassActors []*BypassActor `json:"bypass_actors,omitempty"` CurrentUserCanBypass *BypassMode `json:"current_user_can_bypass,omitempty"` NodeID *string `json:"node_id,omitempty"` Links *RepositoryRulesetLinks `json:"_links,omitempty"` @@ -209,15 +210,15 @@ type RepositoryRulesetRepositoryNamesConditionParameters struct { // RepositoryRulesetRepositoryPropertyConditionParameters represents the conditions object for repository_property. type RepositoryRulesetRepositoryPropertyConditionParameters struct { - Include []RepositoryRulesetRepositoryPropertyTargetParameters `json:"include"` - Exclude []RepositoryRulesetRepositoryPropertyTargetParameters `json:"exclude"` + Include []*RepositoryRulesetRepositoryPropertyTargetParameters `json:"include"` + Exclude []*RepositoryRulesetRepositoryPropertyTargetParameters `json:"exclude"` } // RepositoryRulesetRepositoryPropertyTargetParameters represents a repository_property name and values to be used for targeting. type RepositoryRulesetRepositoryPropertyTargetParameters struct { - Name string `json:"name"` - Values []string `json:"property_values"` - Source *string `json:"source,omitempty"` + Name string `json:"name"` + PropertyValues []string `json:"property_values"` + Source *string `json:"source,omitempty"` } // RepositoryRulesetOrganizationIDsConditionParameters represents the conditions object for organization_id. @@ -238,6 +239,7 @@ type RepositoryRulesetRule struct { } // RepositoryRulesetRules represents a GitHub ruleset rules object. +// This type doesn't have JSON annotations as it uses custom marshalling. type RepositoryRulesetRules struct { Creation *EmptyRuleParameters Update *UpdateRuleParameters @@ -263,28 +265,29 @@ type RepositoryRulesetRules struct { } // BranchRules represents the rules active for a GitHub repository branch. +// This type doesn't have JSON annotations as it uses custom marshalling. type BranchRules struct { - Creation []BranchRuleMetadata - Update []UpdateBranchRule - Deletion []BranchRuleMetadata - RequiredLinearHistory []BranchRuleMetadata - MergeQueue []MergeQueueBranchRule - RequiredDeployments []RequiredDeploymentsBranchRule - RequiredSignatures []BranchRuleMetadata - PullRequest []PullRequestBranchRule - RequiredStatusChecks []RequiredStatusChecksBranchRule - NonFastForward []BranchRuleMetadata - CommitMessagePattern []PatternBranchRule - CommitAuthorEmailPattern []PatternBranchRule - CommitterEmailPattern []PatternBranchRule - BranchNamePattern []PatternBranchRule - TagNamePattern []PatternBranchRule - FilePathRestriction []FilePathRestrictionBranchRule - MaxFilePathLength []MaxFilePathLengthBranchRule - FileExtensionRestriction []FileExtensionRestrictionBranchRule - MaxFileSize []MaxFileSizeBranchRule - Workflows []WorkflowsBranchRule - CodeScanning []CodeScanningBranchRule + Creation []*BranchRuleMetadata + Update []*UpdateBranchRule + Deletion []*BranchRuleMetadata + RequiredLinearHistory []*BranchRuleMetadata + MergeQueue []*MergeQueueBranchRule + RequiredDeployments []*RequiredDeploymentsBranchRule + RequiredSignatures []*BranchRuleMetadata + PullRequest []*PullRequestBranchRule + RequiredStatusChecks []*RequiredStatusChecksBranchRule + NonFastForward []*BranchRuleMetadata + CommitMessagePattern []*PatternBranchRule + CommitAuthorEmailPattern []*PatternBranchRule + CommitterEmailPattern []*PatternBranchRule + BranchNamePattern []*PatternBranchRule + TagNamePattern []*PatternBranchRule + FilePathRestriction []*FilePathRestrictionBranchRule + MaxFilePathLength []*MaxFilePathLengthBranchRule + FileExtensionRestriction []*FileExtensionRestrictionBranchRule + MaxFileSize []*MaxFileSizeBranchRule + Workflows []*WorkflowsBranchRule + CodeScanning []*CodeScanningBranchRule } // BranchRuleMetadata represents the metadata for a branch rule. @@ -371,7 +374,7 @@ type EmptyRuleParameters struct{} // UpdateRuleParameters represents the update rule parameters. type UpdateRuleParameters struct { - UpdateAllowsFetchAndMerge bool `json:"update_allows_fetch_and_merge"` + UpdateAllowsFetchAndMerge bool `json:"update_allows_fetch_and_merge,omitempty"` } // MergeQueueRuleParameters represents the merge_queue rule parameters. @@ -402,9 +405,9 @@ type PullRequestRuleParameters struct { // RequiredStatusChecksRuleParameters represents the required status checks rule parameters. type RequiredStatusChecksRuleParameters struct { - DoNotEnforceOnCreate *bool `json:"do_not_enforce_on_create,omitempty"` - RequiredStatusChecks []RuleStatusCheck `json:"required_status_checks"` - StrictRequiredStatusChecksPolicy bool `json:"strict_required_status_checks_policy"` + DoNotEnforceOnCreate *bool `json:"do_not_enforce_on_create,omitempty"` + RequiredStatusChecks []*RuleStatusCheck `json:"required_status_checks"` + StrictRequiredStatusChecksPolicy bool `json:"strict_required_status_checks_policy"` } // RuleStatusCheck represents a status checks for the required status checks rule parameters. @@ -444,8 +447,8 @@ type MaxFileSizeRuleParameters struct { // WorkflowsRuleParameters represents the workflows rule parameters. type WorkflowsRuleParameters struct { - DoNotEnforceOnCreate *bool `json:"do_not_enforce_on_create,omitempty"` - Workflows []RuleWorkflow `json:"workflows"` + DoNotEnforceOnCreate *bool `json:"do_not_enforce_on_create,omitempty"` + Workflows []*RuleWorkflow `json:"workflows"` } // RuleWorkflow represents a Workflow for the workflows rule parameters. @@ -453,12 +456,12 @@ type RuleWorkflow struct { Path string `json:"path"` Ref *string `json:"ref,omitempty"` RepositoryID *int64 `json:"repository_id,omitempty"` - Sha *string `json:"sha,omitempty"` + SHA *string `json:"sha,omitempty"` } // CodeScanningRuleParameters represents the code scanning rule parameters. type CodeScanningRuleParameters struct { - CodeScanningTools []RuleCodeScanningTool `json:"code_scanning_tools"` + CodeScanningTools []*RuleCodeScanningTool `json:"code_scanning_tools"` } // RuleCodeScanningTool represents a single code scanning tool for the code scanning parameters. @@ -470,8 +473,8 @@ type RuleCodeScanningTool struct { // repositoryRulesetRuleWrapper is a helper type to marshal & unmarshal a ruleset rule. type repositoryRulesetRuleWrapper struct { - Type RulesetRuleType `json:"type"` - Parameters *json.RawMessage `json:"parameters,omitempty"` + Type RulesetRuleType `json:"type"` + Parameters json.RawMessage `json:"parameters,omitempty"` } // MarshalJSON is a custom JSON marshaller for RulesetRules. @@ -480,7 +483,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { arr := make([]json.RawMessage, 0, 21) if r.Creation != nil { - bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeCreation, nil) + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeCreation, r.Creation) if err != nil { return nil, err } @@ -496,7 +499,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { } if r.Deletion != nil { - bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeDeletion, nil) + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeDeletion, r.Deletion) if err != nil { return nil, err } @@ -504,7 +507,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { } if r.RequiredLinearHistory != nil { - bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeRequiredLinearHistory, nil) + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeRequiredLinearHistory, r.RequiredLinearHistory) if err != nil { return nil, err } @@ -528,7 +531,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { } if r.RequiredSignatures != nil { - bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeRequiredSignatures, nil) + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeRequiredSignatures, r.RequiredSignatures) if err != nil { return nil, err } @@ -552,7 +555,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { } if r.NonFastForward != nil { - bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeNonFastForward, nil) + bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeNonFastForward, r.NonFastForward) if err != nil { return nil, err } @@ -651,8 +654,10 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { } // marshalRepositoryRulesetRule is a helper function to marshal a ruleset rule. -func marshalRepositoryRulesetRule(t RulesetRuleType, params any) ([]byte, error) { - if params == nil { +func marshalRepositoryRulesetRule[T any](t RulesetRuleType, params T) ([]byte, error) { + paramsType := reflect.TypeFor[T]() + + if paramsType.Kind() == reflect.Pointer && (reflect.ValueOf(params).IsNil() || reflect.ValueOf(params).Elem().IsZero()) { return json.Marshal(repositoryRulesetRuleWrapper{Type: t}) } @@ -661,7 +666,7 @@ func marshalRepositoryRulesetRule(t RulesetRuleType, params any) ([]byte, error) return nil, err } - return json.Marshal(repositoryRulesetRuleWrapper{Type: t, Parameters: Ptr(json.RawMessage(bytes))}) + return json.Marshal(repositoryRulesetRuleWrapper{Type: t, Parameters: json.RawMessage(bytes)}) } // UnmarshalJSON is a custom JSON unmarshaller for RulesetRules. @@ -682,7 +687,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.Update = &UpdateRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.Update) + err = json.Unmarshal(w.Parameters, r.Update) if err != nil { return err } @@ -695,7 +700,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.MergeQueue = &MergeQueueRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.MergeQueue) + err = json.Unmarshal(w.Parameters, r.MergeQueue) if err != nil { return err } @@ -704,7 +709,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.RequiredDeployments = &RequiredDeploymentsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.RequiredDeployments) + err = json.Unmarshal(w.Parameters, r.RequiredDeployments) if err != nil { return err } @@ -715,7 +720,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.PullRequest = &PullRequestRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.PullRequest) + err = json.Unmarshal(w.Parameters, r.PullRequest) if err != nil { return err } @@ -724,7 +729,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.RequiredStatusChecks = &RequiredStatusChecksRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.RequiredStatusChecks) + err = json.Unmarshal(w.Parameters, r.RequiredStatusChecks) if err != nil { return err } @@ -735,7 +740,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CommitMessagePattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.CommitMessagePattern) + err = json.Unmarshal(w.Parameters, r.CommitMessagePattern) if err != nil { return err } @@ -744,7 +749,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CommitAuthorEmailPattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.CommitAuthorEmailPattern) + err = json.Unmarshal(w.Parameters, r.CommitAuthorEmailPattern) if err != nil { return err } @@ -753,7 +758,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CommitterEmailPattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.CommitterEmailPattern) + err = json.Unmarshal(w.Parameters, r.CommitterEmailPattern) if err != nil { return err } @@ -762,7 +767,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.BranchNamePattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.BranchNamePattern) + err = json.Unmarshal(w.Parameters, r.BranchNamePattern) if err != nil { return err } @@ -771,7 +776,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.TagNamePattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.TagNamePattern) + err = json.Unmarshal(w.Parameters, r.TagNamePattern) if err != nil { return err } @@ -780,7 +785,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.FilePathRestriction = &FilePathRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.FilePathRestriction) + err = json.Unmarshal(w.Parameters, r.FilePathRestriction) if err != nil { return err } @@ -789,7 +794,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.MaxFilePathLength = &MaxFilePathLengthRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.MaxFilePathLength) + err = json.Unmarshal(w.Parameters, r.MaxFilePathLength) if err != nil { return err } @@ -798,7 +803,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.FileExtensionRestriction = &FileExtensionRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.FileExtensionRestriction) + err = json.Unmarshal(w.Parameters, r.FileExtensionRestriction) if err != nil { return err } @@ -807,7 +812,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.MaxFileSize = &MaxFileSizeRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.MaxFileSize) + err = json.Unmarshal(w.Parameters, r.MaxFileSize) if err != nil { return err } @@ -816,7 +821,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.Workflows = &WorkflowsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.Workflows) + err = json.Unmarshal(w.Parameters, r.Workflows) if err != nil { return err } @@ -825,7 +830,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CodeScanning = &CodeScanningRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, r.CodeScanning) + err = json.Unmarshal(w.Parameters, r.CodeScanning) if err != nil { return err } @@ -840,7 +845,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { type branchRuleWrapper struct { Type RulesetRuleType `json:"type"` BranchRuleMetadata - Parameters *json.RawMessage `json:"parameters,omitempty"` + Parameters json.RawMessage `json:"parameters,omitempty"` } // UnmarshalJSON is a custom JSON unmarshaller for BranchRules. @@ -856,191 +861,191 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { for _, w := range arr { switch w.Type { case RulesetRuleTypeCreation: - r.Creation = append(r.Creation, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + r.Creation = append(r.Creation, &BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) case RulesetRuleTypeUpdate: params := &UpdateRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.Update = append(r.Update, UpdateBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.Update = append(r.Update, &UpdateBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeDeletion: - r.Deletion = append(r.Deletion, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + r.Deletion = append(r.Deletion, &BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) case RulesetRuleTypeRequiredLinearHistory: - r.RequiredLinearHistory = append(r.RequiredLinearHistory, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + r.RequiredLinearHistory = append(r.RequiredLinearHistory, &BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) case RulesetRuleTypeMergeQueue: params := &MergeQueueRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.MergeQueue = append(r.MergeQueue, MergeQueueBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.MergeQueue = append(r.MergeQueue, &MergeQueueBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeRequiredDeployments: params := &RequiredDeploymentsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.RequiredDeployments = append(r.RequiredDeployments, RequiredDeploymentsBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.RequiredDeployments = append(r.RequiredDeployments, &RequiredDeploymentsBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeRequiredSignatures: - r.RequiredSignatures = append(r.RequiredSignatures, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + r.RequiredSignatures = append(r.RequiredSignatures, &BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) case RulesetRuleTypePullRequest: params := &PullRequestRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.PullRequest = append(r.PullRequest, PullRequestBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.PullRequest = append(r.PullRequest, &PullRequestBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeRequiredStatusChecks: params := &RequiredStatusChecksRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.RequiredStatusChecks = append(r.RequiredStatusChecks, RequiredStatusChecksBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.RequiredStatusChecks = append(r.RequiredStatusChecks, &RequiredStatusChecksBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeNonFastForward: - r.NonFastForward = append(r.NonFastForward, BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) + r.NonFastForward = append(r.NonFastForward, &BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) case RulesetRuleTypeCommitMessagePattern: params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.CommitMessagePattern = append(r.CommitMessagePattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.CommitMessagePattern = append(r.CommitMessagePattern, &PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeCommitAuthorEmailPattern: params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.CommitAuthorEmailPattern = append(r.CommitAuthorEmailPattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.CommitAuthorEmailPattern = append(r.CommitAuthorEmailPattern, &PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeCommitterEmailPattern: params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.CommitterEmailPattern = append(r.CommitterEmailPattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.CommitterEmailPattern = append(r.CommitterEmailPattern, &PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeBranchNamePattern: params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.BranchNamePattern = append(r.BranchNamePattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.BranchNamePattern = append(r.BranchNamePattern, &PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeTagNamePattern: params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.TagNamePattern = append(r.TagNamePattern, PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.TagNamePattern = append(r.TagNamePattern, &PatternBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeFilePathRestriction: params := &FilePathRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.FilePathRestriction = append(r.FilePathRestriction, FilePathRestrictionBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.FilePathRestriction = append(r.FilePathRestriction, &FilePathRestrictionBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeMaxFilePathLength: params := &MaxFilePathLengthRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.MaxFilePathLength = append(r.MaxFilePathLength, MaxFilePathLengthBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.MaxFilePathLength = append(r.MaxFilePathLength, &MaxFilePathLengthBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeFileExtensionRestriction: params := &FileExtensionRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.FileExtensionRestriction = append(r.FileExtensionRestriction, FileExtensionRestrictionBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.FileExtensionRestriction = append(r.FileExtensionRestriction, &FileExtensionRestrictionBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeMaxFileSize: params := &MaxFileSizeRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.MaxFileSize = append(r.MaxFileSize, MaxFileSizeBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.MaxFileSize = append(r.MaxFileSize, &MaxFileSizeBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeWorkflows: params := &WorkflowsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.Workflows = append(r.Workflows, WorkflowsBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.Workflows = append(r.Workflows, &WorkflowsBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) case RulesetRuleTypeCodeScanning: params := &CodeScanningRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, params) + err = json.Unmarshal(w.Parameters, params) if err != nil { return err } } - r.CodeScanning = append(r.CodeScanning, CodeScanningBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) + r.CodeScanning = append(r.CodeScanning, &CodeScanningBranchRule{BranchRuleMetadata: w.BranchRuleMetadata, Parameters: *params}) } } @@ -1065,7 +1070,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &UpdateRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1080,7 +1085,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &MergeQueueRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1091,7 +1096,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &RequiredDeploymentsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1104,7 +1109,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PullRequestRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1115,7 +1120,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &RequiredStatusChecksRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1128,7 +1133,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1139,7 +1144,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1150,7 +1155,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1161,7 +1166,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1172,7 +1177,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1183,7 +1188,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &FilePathRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1194,7 +1199,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &MaxFilePathLengthRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1205,7 +1210,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &FileExtensionRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1216,7 +1221,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &MaxFileSizeRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1227,7 +1232,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &WorkflowsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } @@ -1238,7 +1243,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &CodeScanningRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(*w.Parameters, p) + err = json.Unmarshal(w.Parameters, p) if err != nil { return err } diff --git a/github/rules_test.go b/github/rules_test.go index ff8b8c05450..ea6e4d4f46c 100644 --- a/github/rules_test.go +++ b/github/rules_test.go @@ -21,9 +21,9 @@ func TestRulesetRules(t *testing.T) { }{ {"empty", &RepositoryRulesetRules{}, `[]`}, {"single_rule_with_empty_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, `[{"type":"creation"}]`}, - {"single_ule_with_required_params", &RepositoryRulesetRules{Update: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}, `[{"type":"update","parameters":{"update_allows_fetch_and_merge":true}}]`}, - {"all_rules_with_required_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, MergeQueue: &MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}, RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{RequiredStatusChecks: []RuleStatusCheck{{Context: "test1"}, {Context: "test2"}}, StrictRequiredStatusChecksPolicy: true}, NonFastForward: &EmptyRuleParameters{}, CommitMessagePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitAuthorEmailPattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitterEmailPattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, BranchNamePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, TagNamePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, FilePathRestriction: &FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}, MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}, MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, Workflows: &WorkflowsRuleParameters{Workflows: []RuleWorkflow{{Path: ".github/workflows/test1.yaml"}, {Path: ".github/workflows/test2.yaml"}}}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}, `[{"type":"creation"},{"type":"update","parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test1"},{"context":"test2"}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"workflows":[{"path":".github/workflows/test1.yaml"},{"path":".github/workflows/test2.yaml"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, - {"all_rules_with_all_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, MergeQueue: &MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}, RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{DoNotEnforceOnCreate: Ptr(true), RequiredStatusChecks: []RuleStatusCheck{{Context: "test1", IntegrationID: Ptr(int64(1))}, {Context: "test2", IntegrationID: Ptr(int64(2))}}, StrictRequiredStatusChecksPolicy: true}, NonFastForward: &EmptyRuleParameters{}, CommitMessagePattern: &PatternRuleParameters{Name: Ptr("cmp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitAuthorEmailPattern: &PatternRuleParameters{Name: Ptr("caep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitterEmailPattern: &PatternRuleParameters{Name: Ptr("cep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, BranchNamePattern: &PatternRuleParameters{Name: Ptr("bp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, TagNamePattern: &PatternRuleParameters{Name: Ptr("tp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, FilePathRestriction: &FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}, MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}, MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, Workflows: &WorkflowsRuleParameters{DoNotEnforceOnCreate: Ptr(true), Workflows: []RuleWorkflow{{Path: ".github/workflows/test1.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(1)), Sha: Ptr("aaaa")}, {Path: ".github/workflows/test2.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(2)), Sha: Ptr("bbbb")}}}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}, `[{"type":"creation"},{"type":"update","parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, + {"single_rule_with_required_params", &RepositoryRulesetRules{RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test"}}}, `[{"type":"required_deployments","parameters":{"required_deployment_environments":["test"]}}]`}, + {"all_rules_with_required_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, MergeQueue: &MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}, RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{RequiredStatusChecks: []*RuleStatusCheck{{Context: "test1"}, {Context: "test2"}}, StrictRequiredStatusChecksPolicy: true}, NonFastForward: &EmptyRuleParameters{}, CommitMessagePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitAuthorEmailPattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitterEmailPattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, BranchNamePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, TagNamePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, FilePathRestriction: &FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}, MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}, MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, Workflows: &WorkflowsRuleParameters{Workflows: []*RuleWorkflow{{Path: ".github/workflows/test1.yaml"}, {Path: ".github/workflows/test2.yaml"}}}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}, `[{"type":"creation"},{"type":"update"},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test1"},{"context":"test2"}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"workflows":[{"path":".github/workflows/test1.yaml"},{"path":".github/workflows/test2.yaml"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, + {"all_rules_with_all_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, MergeQueue: &MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}, RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{DoNotEnforceOnCreate: Ptr(true), RequiredStatusChecks: []*RuleStatusCheck{{Context: "test1", IntegrationID: Ptr(int64(1))}, {Context: "test2", IntegrationID: Ptr(int64(2))}}, StrictRequiredStatusChecksPolicy: true}, NonFastForward: &EmptyRuleParameters{}, CommitMessagePattern: &PatternRuleParameters{Name: Ptr("cmp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitAuthorEmailPattern: &PatternRuleParameters{Name: Ptr("caep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitterEmailPattern: &PatternRuleParameters{Name: Ptr("cep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, BranchNamePattern: &PatternRuleParameters{Name: Ptr("bp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, TagNamePattern: &PatternRuleParameters{Name: Ptr("tp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, FilePathRestriction: &FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}, MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}, MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, Workflows: &WorkflowsRuleParameters{DoNotEnforceOnCreate: Ptr(true), Workflows: []*RuleWorkflow{{Path: ".github/workflows/test1.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(1)), SHA: Ptr("aaaa")}, {Path: ".github/workflows/test2.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(2)), SHA: Ptr("bbbb")}}}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}, `[{"type":"creation"},{"type":"update","parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, } t.Run("MarshalJSON", func(t *testing.T) { @@ -74,9 +74,9 @@ func TestBranchRules(t *testing.T) { json string }{ {"empty", &BranchRules{}, `[]`}, - {"single_rule_type_single_rule_empty_params", &BranchRules{Creation: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}}, `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1}]`}, - {"single_rule_type_single_rule_with_params", &BranchRules{Update: []UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}}, `[{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}}]`}, - {"all_rule_types_with_all_parameters", &BranchRules{Creation: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, Update: []UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}, Deletion: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, RequiredLinearHistory: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, MergeQueue: []MergeQueueBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}}}, RequiredDeployments: []RequiredDeploymentsBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}}}, RequiredSignatures: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, PullRequest: []PullRequestBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}}}, RequiredStatusChecks: []RequiredStatusChecksBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: RequiredStatusChecksRuleParameters{DoNotEnforceOnCreate: Ptr(true), RequiredStatusChecks: []RuleStatusCheck{{Context: "test1", IntegrationID: Ptr(int64(1))}, {Context: "test2", IntegrationID: Ptr(int64(2))}}, StrictRequiredStatusChecksPolicy: true}}}, NonFastForward: []BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, CommitMessagePattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("cmp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, CommitAuthorEmailPattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("caep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, CommitterEmailPattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("cep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, BranchNamePattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("bp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, TagNamePattern: []PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("tp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, FilePathRestriction: []FilePathRestrictionBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}}}, MaxFilePathLength: []MaxFilePathLengthBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}}}, FileExtensionRestriction: []FileExtensionRestrictionBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}}}, MaxFileSize: []MaxFileSizeBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MaxFileSizeRuleParameters{MaxFileSize: 1024}}}, Workflows: []WorkflowsBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: WorkflowsRuleParameters{DoNotEnforceOnCreate: Ptr(true), Workflows: []RuleWorkflow{{Path: ".github/workflows/test1.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(1)), Sha: Ptr("aaaa")}, {Path: ".github/workflows/test2.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(2)), Sha: Ptr("bbbb")}}}}}, CodeScanning: []CodeScanningBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: CodeScanningRuleParameters{CodeScanningTools: []RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}}}, `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"required_linear_history","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"merge_queue","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"pull_request","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"commit_message_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_size":1024}},{"type":"workflows","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, + {"single_rule_type_single_rule_empty_params", &BranchRules{Creation: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}}, `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1}]`}, + {"single_rule_type_single_rule_with_params", &BranchRules{Update: []*UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}}, `[{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}}]`}, + {"all_rule_types_with_all_parameters", &BranchRules{Creation: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, Update: []*UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}, Deletion: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, RequiredLinearHistory: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, MergeQueue: []*MergeQueueBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}}}, RequiredDeployments: []*RequiredDeploymentsBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}}}, RequiredSignatures: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, PullRequest: []*PullRequestBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}}}, RequiredStatusChecks: []*RequiredStatusChecksBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: RequiredStatusChecksRuleParameters{DoNotEnforceOnCreate: Ptr(true), RequiredStatusChecks: []*RuleStatusCheck{{Context: "test1", IntegrationID: Ptr(int64(1))}, {Context: "test2", IntegrationID: Ptr(int64(2))}}, StrictRequiredStatusChecksPolicy: true}}}, NonFastForward: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, CommitMessagePattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("cmp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, CommitAuthorEmailPattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("caep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, CommitterEmailPattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("cep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, BranchNamePattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("bp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, TagNamePattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("tp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, FilePathRestriction: []*FilePathRestrictionBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}}}, MaxFilePathLength: []*MaxFilePathLengthBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}}}, FileExtensionRestriction: []*FileExtensionRestrictionBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}}}, MaxFileSize: []*MaxFileSizeBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MaxFileSizeRuleParameters{MaxFileSize: 1024}}}, Workflows: []*WorkflowsBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: WorkflowsRuleParameters{DoNotEnforceOnCreate: Ptr(true), Workflows: []*RuleWorkflow{{Path: ".github/workflows/test1.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(1)), SHA: Ptr("aaaa")}, {Path: ".github/workflows/test2.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(2)), SHA: Ptr("bbbb")}}}}}, CodeScanning: []*CodeScanningBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}}}, `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"required_linear_history","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"merge_queue","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"pull_request","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"commit_message_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_size":1024}},{"type":"workflows","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, } t.Run("UnmarshalJSON", func(t *testing.T) { From 959df1e64418e691ff4696a303bbac88c60109fc Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Tue, 14 Jan 2025 11:14:12 +0000 Subject: [PATCH 04/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- example/verifyartifact/main.go | 5 ++-- github/github.go | 1 - github/rules.go | 52 ++++++++++++++++++---------------- 3 files changed, 29 insertions(+), 29 deletions(-) diff --git a/example/verifyartifact/main.go b/example/verifyartifact/main.go index 7409bade079..50387d8e380 100644 --- a/example/verifyartifact/main.go +++ b/example/verifyartifact/main.go @@ -109,7 +109,6 @@ func main() { } err := runVerification(sev, pb, b) - if err != nil { log.Fatal(err) } @@ -188,11 +187,11 @@ func runVerification(sev *verify.SignedEntityVerifier, pb *verify.PolicyBuilder, fmt.Fprintf(os.Stderr, "Verification successful!\n") - marshaled, err := json.MarshalIndent(res, "", " ") + marshalled, err := json.MarshalIndent(res, "", " ") if err != nil { return err } - fmt.Println(string(marshaled)) + fmt.Println(string(marshalled)) return nil } diff --git a/github/github.go b/github/github.go index 34ca4394fe2..481e8d4ceb9 100644 --- a/github/github.go +++ b/github/github.go @@ -961,7 +961,6 @@ var errInvalidLocation = errors.New("invalid or empty Location header in redirec // canceled or times out, ctx.Err() will be returned. func (c *Client) bareDoUntilFound(ctx context.Context, req *http.Request, maxRedirects int) (*url.URL, *Response, error) { response, err := c.bareDoIgnoreRedirects(ctx, req) - if err != nil { rerr, ok := err.(*RedirectionError) if ok { diff --git a/github/rules.go b/github/rules.go index c8b24bfe94c..1c116e6c5ac 100644 --- a/github/rules.go +++ b/github/rules.go @@ -239,7 +239,7 @@ type RepositoryRulesetRule struct { } // RepositoryRulesetRules represents a GitHub ruleset rules object. -// This type doesn't have JSON annotations as it uses custom marshalling. +// This type doesn't have JSON annotations as it uses custom marshaling. type RepositoryRulesetRules struct { Creation *EmptyRuleParameters Update *UpdateRuleParameters @@ -265,7 +265,7 @@ type RepositoryRulesetRules struct { } // BranchRules represents the rules active for a GitHub repository branch. -// This type doesn't have JSON annotations as it uses custom marshalling. +// This type doesn't have JSON annotations as it uses custom marshaling. type BranchRules struct { Creation []*BranchRuleMetadata Update []*UpdateBranchRule @@ -477,7 +477,7 @@ type repositoryRulesetRuleWrapper struct { Parameters json.RawMessage `json:"parameters,omitempty"` } -// MarshalJSON is a custom JSON marshaller for RulesetRules. +// MarshalJSON is a custom JSON marshaler for RulesetRules. func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { // If new rules are added to RulesetRules the capacity needs increasing arr := make([]json.RawMessage, 0, 21) @@ -654,6 +654,9 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { } // marshalRepositoryRulesetRule is a helper function to marshal a ruleset rule. +// +// TODO: Benchmark the code that uses reflection. +// TODO: Use a generator here instead of reflection if there is a significant performance hit. func marshalRepositoryRulesetRule[T any](t RulesetRuleType, params T) ([]byte, error) { paramsType := reflect.TypeFor[T]() @@ -669,13 +672,12 @@ func marshalRepositoryRulesetRule[T any](t RulesetRuleType, params T) ([]byte, e return json.Marshal(repositoryRulesetRuleWrapper{Type: t, Parameters: json.RawMessage(bytes)}) } -// UnmarshalJSON is a custom JSON unmarshaller for RulesetRules. +// UnmarshalJSON is a custom JSON unmarshaler for RulesetRules. func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { // If new rules are added to RulesetRules the capacity needs increasing arr := make([]repositoryRulesetRuleWrapper, 0, 21) - err := json.Unmarshal(data, &arr) - if err != nil { + if err := json.Unmarshal(data, &arr); err != nil { return err } @@ -687,7 +689,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.Update = &UpdateRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.Update) + err := json.Unmarshal(w.Parameters, r.Update) if err != nil { return err } @@ -700,7 +702,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.MergeQueue = &MergeQueueRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.MergeQueue) + err := json.Unmarshal(w.Parameters, r.MergeQueue) if err != nil { return err } @@ -709,7 +711,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.RequiredDeployments = &RequiredDeploymentsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.RequiredDeployments) + err := json.Unmarshal(w.Parameters, r.RequiredDeployments) if err != nil { return err } @@ -720,7 +722,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.PullRequest = &PullRequestRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.PullRequest) + err := json.Unmarshal(w.Parameters, r.PullRequest) if err != nil { return err } @@ -729,7 +731,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.RequiredStatusChecks = &RequiredStatusChecksRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.RequiredStatusChecks) + err := json.Unmarshal(w.Parameters, r.RequiredStatusChecks) if err != nil { return err } @@ -740,7 +742,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CommitMessagePattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.CommitMessagePattern) + err := json.Unmarshal(w.Parameters, r.CommitMessagePattern) if err != nil { return err } @@ -749,7 +751,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CommitAuthorEmailPattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.CommitAuthorEmailPattern) + err := json.Unmarshal(w.Parameters, r.CommitAuthorEmailPattern) if err != nil { return err } @@ -758,7 +760,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CommitterEmailPattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.CommitterEmailPattern) + err := json.Unmarshal(w.Parameters, r.CommitterEmailPattern) if err != nil { return err } @@ -767,7 +769,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.BranchNamePattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.BranchNamePattern) + err := json.Unmarshal(w.Parameters, r.BranchNamePattern) if err != nil { return err } @@ -776,7 +778,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.TagNamePattern = &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.TagNamePattern) + err := json.Unmarshal(w.Parameters, r.TagNamePattern) if err != nil { return err } @@ -785,7 +787,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.FilePathRestriction = &FilePathRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.FilePathRestriction) + err := json.Unmarshal(w.Parameters, r.FilePathRestriction) if err != nil { return err } @@ -794,7 +796,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.MaxFilePathLength = &MaxFilePathLengthRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.MaxFilePathLength) + err := json.Unmarshal(w.Parameters, r.MaxFilePathLength) if err != nil { return err } @@ -803,7 +805,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.FileExtensionRestriction = &FileExtensionRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.FileExtensionRestriction) + err := json.Unmarshal(w.Parameters, r.FileExtensionRestriction) if err != nil { return err } @@ -812,7 +814,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.MaxFileSize = &MaxFileSizeRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.MaxFileSize) + err := json.Unmarshal(w.Parameters, r.MaxFileSize) if err != nil { return err } @@ -821,7 +823,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.Workflows = &WorkflowsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.Workflows) + err := json.Unmarshal(w.Parameters, r.Workflows) if err != nil { return err } @@ -830,7 +832,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CodeScanning = &CodeScanningRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, r.CodeScanning) + err := json.Unmarshal(w.Parameters, r.CodeScanning) if err != nil { return err } @@ -848,7 +850,7 @@ type branchRuleWrapper struct { Parameters json.RawMessage `json:"parameters,omitempty"` } -// UnmarshalJSON is a custom JSON unmarshaller for BranchRules. +// UnmarshalJSON is a custom JSON unmarshaler for BranchRules. func (r *BranchRules) UnmarshalJSON(data []byte) error { // If new rules are added to RulesetRules the capacity needs increasing arr := make([]branchRuleWrapper, 0, 21) @@ -866,7 +868,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &UpdateRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) + err := json.Unmarshal(w.Parameters, params) if err != nil { return err } @@ -1052,7 +1054,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { return nil } -// UnmarshalJSON is a custom JSON unmarshaller for RulesetRule. +// UnmarshalJSON is a custom JSON unmarshaler for RulesetRule. func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { w := repositoryRulesetRuleWrapper{} From a149d40206656a09cd3ce20ac3f1b1496b6816e6 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Tue, 14 Jan 2025 14:41:29 +0000 Subject: [PATCH 05/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/rules.go | 150 ++++++++++++++++-------------------------------- 1 file changed, 50 insertions(+), 100 deletions(-) diff --git a/github/rules.go b/github/rules.go index 1c116e6c5ac..3b3d5bd3d41 100644 --- a/github/rules.go +++ b/github/rules.go @@ -689,8 +689,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.Update = &UpdateRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.Update) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.Update); err != nil { return err } } @@ -702,8 +701,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.MergeQueue = &MergeQueueRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.MergeQueue) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.MergeQueue); err != nil { return err } } @@ -711,8 +709,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.RequiredDeployments = &RequiredDeploymentsRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.RequiredDeployments) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.RequiredDeployments); err != nil { return err } } @@ -722,8 +719,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.PullRequest = &PullRequestRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.PullRequest) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.PullRequest); err != nil { return err } } @@ -731,8 +727,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.RequiredStatusChecks = &RequiredStatusChecksRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.RequiredStatusChecks) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.RequiredStatusChecks); err != nil { return err } } @@ -742,8 +737,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CommitMessagePattern = &PatternRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.CommitMessagePattern) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.CommitMessagePattern); err != nil { return err } } @@ -751,8 +745,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CommitAuthorEmailPattern = &PatternRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.CommitAuthorEmailPattern) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.CommitAuthorEmailPattern); err != nil { return err } } @@ -760,8 +753,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CommitterEmailPattern = &PatternRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.CommitterEmailPattern) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.CommitterEmailPattern); err != nil { return err } } @@ -769,8 +761,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.BranchNamePattern = &PatternRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.BranchNamePattern) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.BranchNamePattern); err != nil { return err } } @@ -778,8 +769,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.TagNamePattern = &PatternRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.TagNamePattern) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.TagNamePattern); err != nil { return err } } @@ -787,8 +777,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.FilePathRestriction = &FilePathRestrictionRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.FilePathRestriction) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.FilePathRestriction); err != nil { return err } } @@ -796,8 +785,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.MaxFilePathLength = &MaxFilePathLengthRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.MaxFilePathLength) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.MaxFilePathLength); err != nil { return err } } @@ -805,8 +793,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.FileExtensionRestriction = &FileExtensionRestrictionRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.FileExtensionRestriction) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.FileExtensionRestriction); err != nil { return err } } @@ -814,8 +801,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.MaxFileSize = &MaxFileSizeRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.MaxFileSize) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.MaxFileSize); err != nil { return err } } @@ -823,8 +809,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.Workflows = &WorkflowsRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.Workflows) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.Workflows); err != nil { return err } } @@ -832,8 +817,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { r.CodeScanning = &CodeScanningRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, r.CodeScanning) - if err != nil { + if err := json.Unmarshal(w.Parameters, r.CodeScanning); err != nil { return err } } @@ -855,8 +839,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { // If new rules are added to RulesetRules the capacity needs increasing arr := make([]branchRuleWrapper, 0, 21) - err := json.Unmarshal(data, &arr) - if err != nil { + if err := json.Unmarshal(data, &arr); err != nil { return err } @@ -868,8 +851,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &UpdateRuleParameters{} if w.Parameters != nil { - err := json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -883,8 +865,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &MergeQueueRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -894,8 +875,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &RequiredDeploymentsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -907,8 +887,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &PullRequestRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -918,8 +897,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &RequiredStatusChecksRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -931,8 +909,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -942,8 +919,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -953,8 +929,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -964,8 +939,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -975,8 +949,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -986,8 +959,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &FilePathRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -997,8 +969,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &MaxFilePathLengthRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -1008,8 +979,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &FileExtensionRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -1019,8 +989,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &MaxFileSizeRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -1030,8 +999,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &WorkflowsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -1041,8 +1009,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { params := &CodeScanningRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, params) - if err != nil { + if err := json.Unmarshal(w.Parameters, params); err != nil { return err } } @@ -1058,8 +1025,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { w := repositoryRulesetRuleWrapper{} - err := json.Unmarshal(data, &w) - if err != nil { + if err := json.Unmarshal(data, &w); err != nil { return err } @@ -1072,8 +1038,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &UpdateRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1087,8 +1052,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &MergeQueueRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1098,8 +1062,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &RequiredDeploymentsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1111,8 +1074,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PullRequestRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1122,8 +1084,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &RequiredStatusChecksRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1135,8 +1096,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1146,8 +1106,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1157,8 +1116,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1168,8 +1126,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1179,8 +1136,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &PatternRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1190,8 +1146,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &FilePathRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1201,8 +1156,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &MaxFilePathLengthRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1212,8 +1166,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &FileExtensionRestrictionRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1223,8 +1176,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &MaxFileSizeRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1234,8 +1186,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &WorkflowsRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } @@ -1245,8 +1196,7 @@ func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { p := &CodeScanningRuleParameters{} if w.Parameters != nil { - err = json.Unmarshal(w.Parameters, p) - if err != nil { + if err := json.Unmarshal(w.Parameters, p); err != nil { return err } } From b9041af0accff07d9f28a8ccd6b8573d759f2d6e Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Tue, 14 Jan 2025 14:42:35 +0000 Subject: [PATCH 06/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- example/verifyartifact/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/example/verifyartifact/main.go b/example/verifyartifact/main.go index 50387d8e380..23e3017e60d 100644 --- a/example/verifyartifact/main.go +++ b/example/verifyartifact/main.go @@ -187,11 +187,11 @@ func runVerification(sev *verify.SignedEntityVerifier, pb *verify.PolicyBuilder, fmt.Fprintf(os.Stderr, "Verification successful!\n") - marshalled, err := json.MarshalIndent(res, "", " ") + marshaled, err := json.MarshalIndent(res, "", " ") if err != nil { return err } - fmt.Println(string(marshalled)) + fmt.Println(string(marshaled)) return nil } From a24903b9adb4c331b1794da00eb048ca00f9f9e4 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Tue, 14 Jan 2025 17:13:28 +0000 Subject: [PATCH 07/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/event_types.go | 6 ++-- github/event_types_test.go | 2 +- github/github-accessors.go | 2 +- github/rules.go | 64 +++++++++++++++++++------------------- 4 files changed, 37 insertions(+), 37 deletions(-) diff --git a/github/event_types.go b/github/event_types.go index a211191ac49..0df3b30c381 100644 --- a/github/event_types.go +++ b/github/event_types.go @@ -1572,14 +1572,14 @@ type RepositoryRulesetUpdatedCondition struct { // RepositoryRulesetChangedRules holds changes to rules in a ruleset. type RepositoryRulesetChangedRules struct { - Added []*RepositoryRulesetRule `json:"added,omitempty"` - Deleted []*RepositoryRulesetRule `json:"deleted,omitempty"` + Added []*RepositoryRule `json:"added,omitempty"` + Deleted []*RepositoryRule `json:"deleted,omitempty"` Updated []*RepositoryRulesetUpdatedRules `json:"updated,omitempty"` } // RepositoryRulesetUpdatedRules holds updates to rules in a ruleset. type RepositoryRulesetUpdatedRules struct { - Rule *RepositoryRulesetRule `json:"rule,omitempty"` + Rule *RepositoryRule `json:"rule,omitempty"` Changes *RepositoryRulesetChangedRule `json:"changes,omitempty"` } diff --git a/github/event_types_test.go b/github/event_types_test.go index 1c60a0c2e0e..1d166e474f8 100644 --- a/github/event_types_test.go +++ b/github/event_types_test.go @@ -9606,7 +9606,7 @@ func TestRepositoryRulesetEvent_Unmarshal(t *testing.T) { }{ {"empty", `{}`, &RepositoryRulesetEvent{}}, {"created", fmt.Sprintf(`{"action":"created","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~ALL"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase","merge"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"high_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("created"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~ALL"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase, MergeMethodMerge}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, - {"edited", fmt.Sprintf(`{"action":"edited","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type": "required_signatures"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"changes":{"rules":{"added":[{"type": "required_signatures"}],"updated":[{"rule":{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},"changes":{"configuration":{"from":"{\\\"required_reviewers\\\":[],\\\"allowed_merge_methods\\\":[\\\"squash\\\",\\\"rebase\\\",\\\"merge\\\"],\\\"require_code_owner_review\\\":false,\\\"require_last_push_approval\\\":false,\\\"dismiss_stale_reviews_on_push\\\":false,\\\"required_approving_review_count\\\":2,\\\"authorized_dismissal_actors_only\\\":false,\\\"required_review_thread_resolution\\\":false,\\\"ignore_approvals_from_contributors\\\":false,\\\"automatic_copilot_code_review_enabled\\\":false}"}}},{"rule":{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}},"changes":{"configuration":{"from":"{\\\"code_scanning_tools\\\":[{\\\"tool\\\":\\\"CodeQL\\\",\\\"alerts_threshold\\\":\\\"errors\\\",\\\"security_alerts_threshold\\\":\\\"high_or_higher\\\"}]}"}}}],"deleted":[{"type":"required_linear_history"}]},"conditions":{"updated":[{"condition":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"changes":{"include":{"from":["~ALL"]}}}],"deleted":[]}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("edited"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Changes: &RepositoryRulesetChanges{Conditions: &RepositoryRulesetChangedConditions{Updated: []*RepositoryRulesetUpdatedConditions{{Condition: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Changes: &RepositoryRulesetUpdatedCondition{Include: &RepositoryRulesetChangeSources{From: []string{"~ALL"}}}}}, Deleted: []*RepositoryRulesetConditions{}}, Rules: &RepositoryRulesetChangedRules{Added: []*RepositoryRulesetRule{{Type: RulesetRuleTypeRequiredSignatures}}, Updated: []*RepositoryRulesetUpdatedRules{{Rule: &RepositoryRulesetRule{Type: RulesetRuleTypePullRequest, Parameters: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"required_reviewers\":[],\"allowed_merge_methods\":[\"squash\",\"rebase\",\"merge\"],\"require_code_owner_review\":false,\"require_last_push_approval\":false,\"dismiss_stale_reviews_on_push\":false,\"required_approving_review_count\":2,\"authorized_dismissal_actors_only\":false,\"required_review_thread_resolution\":false,\"ignore_approvals_from_contributors\":false,\"automatic_copilot_code_review_enabled\":false}`)}}}, {Rule: &RepositoryRulesetRule{Type: RulesetRuleTypeCodeScanning, Parameters: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"code_scanning_tools\":[{\"tool\":\"CodeQL\",\"alerts_threshold\":\"errors\",\"security_alerts_threshold\":\"high_or_higher\"}]}`)}}}}, Deleted: []*RepositoryRulesetRule{{Type: RulesetRuleTypeRequiredLinearHistory}}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, + {"edited", fmt.Sprintf(`{"action":"edited","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type": "required_signatures"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"changes":{"rules":{"added":[{"type": "required_signatures"}],"updated":[{"rule":{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},"changes":{"configuration":{"from":"{\\\"required_reviewers\\\":[],\\\"allowed_merge_methods\\\":[\\\"squash\\\",\\\"rebase\\\",\\\"merge\\\"],\\\"require_code_owner_review\\\":false,\\\"require_last_push_approval\\\":false,\\\"dismiss_stale_reviews_on_push\\\":false,\\\"required_approving_review_count\\\":2,\\\"authorized_dismissal_actors_only\\\":false,\\\"required_review_thread_resolution\\\":false,\\\"ignore_approvals_from_contributors\\\":false,\\\"automatic_copilot_code_review_enabled\\\":false}"}}},{"rule":{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}},"changes":{"configuration":{"from":"{\\\"code_scanning_tools\\\":[{\\\"tool\\\":\\\"CodeQL\\\",\\\"alerts_threshold\\\":\\\"errors\\\",\\\"security_alerts_threshold\\\":\\\"high_or_higher\\\"}]}"}}}],"deleted":[{"type":"required_linear_history"}]},"conditions":{"updated":[{"condition":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"changes":{"include":{"from":["~ALL"]}}}],"deleted":[]}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("edited"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Changes: &RepositoryRulesetChanges{Conditions: &RepositoryRulesetChangedConditions{Updated: []*RepositoryRulesetUpdatedConditions{{Condition: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Changes: &RepositoryRulesetUpdatedCondition{Include: &RepositoryRulesetChangeSources{From: []string{"~ALL"}}}}}, Deleted: []*RepositoryRulesetConditions{}}, Rules: &RepositoryRulesetChangedRules{Added: []*RepositoryRule{{Type: RulesetRuleTypeRequiredSignatures}}, Updated: []*RepositoryRulesetUpdatedRules{{Rule: &RepositoryRule{Type: RulesetRuleTypePullRequest, Parameters: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"required_reviewers\":[],\"allowed_merge_methods\":[\"squash\",\"rebase\",\"merge\"],\"require_code_owner_review\":false,\"require_last_push_approval\":false,\"dismiss_stale_reviews_on_push\":false,\"required_approving_review_count\":2,\"authorized_dismissal_actors_only\":false,\"required_review_thread_resolution\":false,\"ignore_approvals_from_contributors\":false,\"automatic_copilot_code_review_enabled\":false}`)}}}, {Rule: &RepositoryRule{Type: RulesetRuleTypeCodeScanning, Parameters: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"code_scanning_tools\":[{\"tool\":\"CodeQL\",\"alerts_threshold\":\"errors\",\"security_alerts_threshold\":\"high_or_higher\"}]}`)}}}}, Deleted: []*RepositoryRule{{Type: RulesetRuleTypeRequiredLinearHistory}}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, {"deleted", fmt.Sprintf(`{"action":"deleted","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("deleted"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, } diff --git a/github/github-accessors.go b/github/github-accessors.go index aef6de92296..a5c653cdb64 100644 --- a/github/github-accessors.go +++ b/github/github-accessors.go @@ -21359,7 +21359,7 @@ func (r *RepositoryRulesetUpdatedRules) GetChanges() *RepositoryRulesetChangedRu } // GetRule returns the Rule field. -func (r *RepositoryRulesetUpdatedRules) GetRule() *RepositoryRulesetRule { +func (r *RepositoryRulesetUpdatedRules) GetRule() *RepositoryRule { if r == nil { return nil } diff --git a/github/rules.go b/github/rules.go index 3b3d5bd3d41..425a8089a19 100644 --- a/github/rules.go +++ b/github/rules.go @@ -62,32 +62,32 @@ const ( BypassModeNever BypassMode = "never" ) -// RulesetRuleType represents a GitHub ruleset rule type. -type RulesetRuleType string +// RepositoryRuleType represents a GitHub ruleset rule type. +type RepositoryRuleType string // This is the set of GitHub ruleset rule types. const ( - RulesetRuleTypeCreation RulesetRuleType = "creation" - RulesetRuleTypeUpdate RulesetRuleType = "update" - RulesetRuleTypeDeletion RulesetRuleType = "deletion" - RulesetRuleTypeRequiredLinearHistory RulesetRuleType = "required_linear_history" - RulesetRuleTypeMergeQueue RulesetRuleType = "merge_queue" - RulesetRuleTypeRequiredDeployments RulesetRuleType = "required_deployments" - RulesetRuleTypeRequiredSignatures RulesetRuleType = "required_signatures" - RulesetRuleTypePullRequest RulesetRuleType = "pull_request" - RulesetRuleTypeRequiredStatusChecks RulesetRuleType = "required_status_checks" - RulesetRuleTypeNonFastForward RulesetRuleType = "non_fast_forward" - RulesetRuleTypeCommitMessagePattern RulesetRuleType = "commit_message_pattern" - RulesetRuleTypeCommitAuthorEmailPattern RulesetRuleType = "commit_author_email_pattern" - RulesetRuleTypeCommitterEmailPattern RulesetRuleType = "committer_email_pattern" - RulesetRuleTypeBranchNamePattern RulesetRuleType = "branch_name_pattern" - RulesetRuleTypeTagNamePattern RulesetRuleType = "tag_name_pattern" - RulesetRuleTypeFilePathRestriction RulesetRuleType = "file_path_restriction" - RulesetRuleTypeMaxFilePathLength RulesetRuleType = "max_file_path_length" - RulesetRuleTypeFileExtensionRestriction RulesetRuleType = "file_extension_restriction" - RulesetRuleTypeMaxFileSize RulesetRuleType = "max_file_size" - RulesetRuleTypeWorkflows RulesetRuleType = "workflows" - RulesetRuleTypeCodeScanning RulesetRuleType = "code_scanning" + RulesetRuleTypeCreation RepositoryRuleType = "creation" + RulesetRuleTypeUpdate RepositoryRuleType = "update" + RulesetRuleTypeDeletion RepositoryRuleType = "deletion" + RulesetRuleTypeRequiredLinearHistory RepositoryRuleType = "required_linear_history" + RulesetRuleTypeMergeQueue RepositoryRuleType = "merge_queue" + RulesetRuleTypeRequiredDeployments RepositoryRuleType = "required_deployments" + RulesetRuleTypeRequiredSignatures RepositoryRuleType = "required_signatures" + RulesetRuleTypePullRequest RepositoryRuleType = "pull_request" + RulesetRuleTypeRequiredStatusChecks RepositoryRuleType = "required_status_checks" + RulesetRuleTypeNonFastForward RepositoryRuleType = "non_fast_forward" + RulesetRuleTypeCommitMessagePattern RepositoryRuleType = "commit_message_pattern" + RulesetRuleTypeCommitAuthorEmailPattern RepositoryRuleType = "commit_author_email_pattern" + RulesetRuleTypeCommitterEmailPattern RepositoryRuleType = "committer_email_pattern" + RulesetRuleTypeBranchNamePattern RepositoryRuleType = "branch_name_pattern" + RulesetRuleTypeTagNamePattern RepositoryRuleType = "tag_name_pattern" + RulesetRuleTypeFilePathRestriction RepositoryRuleType = "file_path_restriction" + RulesetRuleTypeMaxFilePathLength RepositoryRuleType = "max_file_path_length" + RulesetRuleTypeFileExtensionRestriction RepositoryRuleType = "file_extension_restriction" + RulesetRuleTypeMaxFileSize RepositoryRuleType = "max_file_size" + RulesetRuleTypeWorkflows RepositoryRuleType = "workflows" + RulesetRuleTypeCodeScanning RepositoryRuleType = "code_scanning" ) // MergeGroupingStrategy models a GitHub merge grouping strategy. @@ -232,10 +232,10 @@ type RepositoryRulesetOrganizationNamesConditionParameters struct { Exclude []string `json:"exclude"` } -// RepositoryRulesetRule represents a GitHub ruleset rule object. -type RepositoryRulesetRule struct { - Type RulesetRuleType `json:"type"` - Parameters any `json:"parameters,omitempty"` +// RepositoryRule represents a GitHub ruleset rule object. +type RepositoryRule struct { + Type RepositoryRuleType `json:"type"` + Parameters any `json:"parameters,omitempty"` } // RepositoryRulesetRules represents a GitHub ruleset rules object. @@ -473,8 +473,8 @@ type RuleCodeScanningTool struct { // repositoryRulesetRuleWrapper is a helper type to marshal & unmarshal a ruleset rule. type repositoryRulesetRuleWrapper struct { - Type RulesetRuleType `json:"type"` - Parameters json.RawMessage `json:"parameters,omitempty"` + Type RepositoryRuleType `json:"type"` + Parameters json.RawMessage `json:"parameters,omitempty"` } // MarshalJSON is a custom JSON marshaler for RulesetRules. @@ -657,7 +657,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { // // TODO: Benchmark the code that uses reflection. // TODO: Use a generator here instead of reflection if there is a significant performance hit. -func marshalRepositoryRulesetRule[T any](t RulesetRuleType, params T) ([]byte, error) { +func marshalRepositoryRulesetRule[T any](t RepositoryRuleType, params T) ([]byte, error) { paramsType := reflect.TypeFor[T]() if paramsType.Kind() == reflect.Pointer && (reflect.ValueOf(params).IsNil() || reflect.ValueOf(params).Elem().IsZero()) { @@ -829,7 +829,7 @@ func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { // branchRuleWrapper is a helper type to unmarshal a branch rule. type branchRuleWrapper struct { - Type RulesetRuleType `json:"type"` + Type RepositoryRuleType `json:"type"` BranchRuleMetadata Parameters json.RawMessage `json:"parameters,omitempty"` } @@ -1022,7 +1022,7 @@ func (r *BranchRules) UnmarshalJSON(data []byte) error { } // UnmarshalJSON is a custom JSON unmarshaler for RulesetRule. -func (r *RepositoryRulesetRule) UnmarshalJSON(data []byte) error { +func (r *RepositoryRule) UnmarshalJSON(data []byte) error { w := repositoryRulesetRuleWrapper{} if err := json.Unmarshal(data, &w); err != nil { From b12b08cd12d61553b9a418b302fa373b053a857a Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Mon, 20 Jan 2025 14:22:53 +0000 Subject: [PATCH 08/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- example/verifyartifact/main.go | 1 + 1 file changed, 1 insertion(+) diff --git a/example/verifyartifact/main.go b/example/verifyartifact/main.go index 23e3017e60d..7409bade079 100644 --- a/example/verifyartifact/main.go +++ b/example/verifyartifact/main.go @@ -109,6 +109,7 @@ func main() { } err := runVerification(sev, pb, b) + if err != nil { log.Fatal(err) } From 6971bef427710fbd27be5e2ab1e150ecad2c4c03 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Mon, 20 Jan 2025 14:40:26 +0000 Subject: [PATCH 09/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/enterprise_rules.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/github/enterprise_rules.go b/github/enterprise_rules.go index 59610d2f8e4..f438223370f 100644 --- a/github/enterprise_rules.go +++ b/github/enterprise_rules.go @@ -78,7 +78,7 @@ func (s *EnterpriseService) UpdateRepositoryRuleset(ctx context.Context, enterpr // UpdateRepositoryRulesetClearBypassActor clears the bypass actors for a repository ruleset for the specified enterprise. // -// This function is necessary as the UpdateEnterpriseRuleset function does not marshal ByPassActor if passed as an empty array. +// This function is necessary as the UpdateRepositoryRuleset function does not marshal ByPassActor if passed as an empty array. // // GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/enterprise-admin/rules#update-an-enterprise-repository-ruleset // From 1f00cfec80029b423bc26803e2f4db7903a64482 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Mon, 20 Jan 2025 16:45:24 +0000 Subject: [PATCH 10/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/event_types_test.go | 240 ++++++++++++++++- github/rules_test.go | 538 ++++++++++++++++++++++++++++++++++++- 2 files changed, 768 insertions(+), 10 deletions(-) diff --git a/github/event_types_test.go b/github/event_types_test.go index 1d166e474f8..947f97026a9 100644 --- a/github/event_types_test.go +++ b/github/event_types_test.go @@ -9605,9 +9605,243 @@ func TestRepositoryRulesetEvent_Unmarshal(t *testing.T) { event *RepositoryRulesetEvent }{ {"empty", `{}`, &RepositoryRulesetEvent{}}, - {"created", fmt.Sprintf(`{"action":"created","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~ALL"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase","merge"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"high_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("created"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~ALL"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase, MergeMethodMerge}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, - {"edited", fmt.Sprintf(`{"action":"edited","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type": "required_signatures"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"changes":{"rules":{"added":[{"type": "required_signatures"}],"updated":[{"rule":{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},"changes":{"configuration":{"from":"{\\\"required_reviewers\\\":[],\\\"allowed_merge_methods\\\":[\\\"squash\\\",\\\"rebase\\\",\\\"merge\\\"],\\\"require_code_owner_review\\\":false,\\\"require_last_push_approval\\\":false,\\\"dismiss_stale_reviews_on_push\\\":false,\\\"required_approving_review_count\\\":2,\\\"authorized_dismissal_actors_only\\\":false,\\\"required_review_thread_resolution\\\":false,\\\"ignore_approvals_from_contributors\\\":false,\\\"automatic_copilot_code_review_enabled\\\":false}"}}},{"rule":{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}},"changes":{"configuration":{"from":"{\\\"code_scanning_tools\\\":[{\\\"tool\\\":\\\"CodeQL\\\",\\\"alerts_threshold\\\":\\\"errors\\\",\\\"security_alerts_threshold\\\":\\\"high_or_higher\\\"}]}"}}}],"deleted":[{"type":"required_linear_history"}]},"conditions":{"updated":[{"condition":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"changes":{"include":{"from":["~ALL"]}}}],"deleted":[]}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("edited"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Changes: &RepositoryRulesetChanges{Conditions: &RepositoryRulesetChangedConditions{Updated: []*RepositoryRulesetUpdatedConditions{{Condition: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Changes: &RepositoryRulesetUpdatedCondition{Include: &RepositoryRulesetChangeSources{From: []string{"~ALL"}}}}}, Deleted: []*RepositoryRulesetConditions{}}, Rules: &RepositoryRulesetChangedRules{Added: []*RepositoryRule{{Type: RulesetRuleTypeRequiredSignatures}}, Updated: []*RepositoryRulesetUpdatedRules{{Rule: &RepositoryRule{Type: RulesetRuleTypePullRequest, Parameters: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: false, RequireCodeOwnerReview: false, RequireLastPushApproval: false, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: false}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"required_reviewers\":[],\"allowed_merge_methods\":[\"squash\",\"rebase\",\"merge\"],\"require_code_owner_review\":false,\"require_last_push_approval\":false,\"dismiss_stale_reviews_on_push\":false,\"required_approving_review_count\":2,\"authorized_dismissal_actors_only\":false,\"required_review_thread_resolution\":false,\"ignore_approvals_from_contributors\":false,\"automatic_copilot_code_review_enabled\":false}`)}}}, {Rule: &RepositoryRule{Type: RulesetRuleTypeCodeScanning, Parameters: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdErrors, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, Tool: "CodeQL"}}}}, Changes: &RepositoryRulesetChangedRule{Configuration: &RepositoryRulesetChangeSource{From: Ptr(`{\"code_scanning_tools\":[{\"tool\":\"CodeQL\",\"alerts_threshold\":\"errors\",\"security_alerts_threshold\":\"high_or_higher\"}]}`)}}}}, Deleted: []*RepositoryRule{{Type: RulesetRuleTypeRequiredLinearHistory}}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, - {"deleted", fmt.Sprintf(`{"action":"deleted","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, referenceTimeStr), &RepositoryRulesetEvent{Action: Ptr("deleted"), RepositoryRuleset: &RepositoryRuleset{ID: Ptr(int64(1)), Name: "r", Target: Ptr(RulesetTargetBranch), SourceType: Ptr(RulesetSourceTypeRepository), Source: "o/r", Enforcement: RulesetEnforcementActive, Conditions: &RepositoryRulesetConditions{RefName: &RepositoryRulesetRefConditionParameters{Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, Exclude: []string{}}}, Rules: &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}}, NodeID: Ptr("n"), CreatedAt: &Timestamp{referenceTime}, UpdatedAt: &Timestamp{referenceTime}, Links: &RepositoryRulesetLinks{Self: &RepositoryRulesetLink{HRef: Ptr("a")}, HTML: &RepositoryRulesetLink{HRef: Ptr("a")}}}, Repository: repository, Organization: organization, Enterprise: enterprise, Installation: installation, Sender: sender}}, + { + "created", + fmt.Sprintf( + `{"action":"created","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~ALL"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase","merge"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"high_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, + referenceTimeStr, + ), + &RepositoryRulesetEvent{ + Action: Ptr("created"), + RepositoryRuleset: &RepositoryRuleset{ + ID: Ptr(int64(1)), + Name: "r", + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeRepository), + Source: "o/r", + Enforcement: RulesetEnforcementActive, + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ + Include: []string{"~ALL"}, + Exclude: []string{}, + }, + }, + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{}, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{ + MergeMethodSquash, + MergeMethodRebase, + MergeMethodMerge, + }, + DismissStaleReviewsOnPush: false, + RequireCodeOwnerReview: false, + RequireLastPushApproval: false, + RequiredApprovingReviewCount: 2, + RequiredReviewThreadResolution: false, + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []*RuleCodeScanningTool{ + { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdHighOrHigher, + Tool: "CodeQL", + }, + }, + }, + }, + NodeID: Ptr("n"), + CreatedAt: &Timestamp{referenceTime}, + UpdatedAt: &Timestamp{referenceTime}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("a")}, + HTML: &RepositoryRulesetLink{HRef: Ptr("a")}, + }, + }, + Repository: repository, + Organization: organization, + Enterprise: enterprise, + Installation: installation, + Sender: sender, + }, + }, + { + "edited", + fmt.Sprintf( + `{"action":"edited","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type": "required_signatures"},{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"changes":{"rules":{"added":[{"type": "required_signatures"}],"updated":[{"rule":{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false,"automatic_copilot_code_review_enabled":false,"allowed_merge_methods":["squash","rebase"]}},"changes":{"configuration":{"from":"{\\\"required_reviewers\\\":[],\\\"allowed_merge_methods\\\":[\\\"squash\\\",\\\"rebase\\\",\\\"merge\\\"],\\\"require_code_owner_review\\\":false,\\\"require_last_push_approval\\\":false,\\\"dismiss_stale_reviews_on_push\\\":false,\\\"required_approving_review_count\\\":2,\\\"authorized_dismissal_actors_only\\\":false,\\\"required_review_thread_resolution\\\":false,\\\"ignore_approvals_from_contributors\\\":false,\\\"automatic_copilot_code_review_enabled\\\":false}"}}},{"rule":{"type":"code_scanning","parameters":{"code_scanning_tools":[{"tool":"CodeQL","security_alerts_threshold":"medium_or_higher","alerts_threshold":"errors"}]}},"changes":{"configuration":{"from":"{\\\"code_scanning_tools\\\":[{\\\"tool\\\":\\\"CodeQL\\\",\\\"alerts_threshold\\\":\\\"errors\\\",\\\"security_alerts_threshold\\\":\\\"high_or_higher\\\"}]}"}}}],"deleted":[{"type":"required_linear_history"}]},"conditions":{"updated":[{"condition":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"changes":{"include":{"from":["~ALL"]}}}],"deleted":[]}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, + referenceTimeStr, + ), + &RepositoryRulesetEvent{ + Action: Ptr("edited"), + RepositoryRuleset: &RepositoryRuleset{ + ID: Ptr(int64(1)), + Name: "r", + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeRepository), + Source: "o/r", + Enforcement: RulesetEnforcementActive, + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ + Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, + Exclude: []string{}, + }, + }, + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{}, + Deletion: &EmptyRuleParameters{}, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{ + MergeMethodSquash, + MergeMethodRebase, + }, + DismissStaleReviewsOnPush: false, + RequireCodeOwnerReview: false, + RequireLastPushApproval: false, + RequiredApprovingReviewCount: 2, + RequiredReviewThreadResolution: false, + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []*RuleCodeScanningTool{ + { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, + Tool: "CodeQL", + }, + }, + }, + }, + NodeID: Ptr("n"), + CreatedAt: &Timestamp{referenceTime}, + UpdatedAt: &Timestamp{referenceTime}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("a")}, + HTML: &RepositoryRulesetLink{HRef: Ptr("a")}, + }, + }, + Changes: &RepositoryRulesetChanges{ + Conditions: &RepositoryRulesetChangedConditions{ + Updated: []*RepositoryRulesetUpdatedConditions{ + { + Condition: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ + Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, + Exclude: []string{}, + }, + }, + Changes: &RepositoryRulesetUpdatedCondition{ + Include: &RepositoryRulesetChangeSources{ + From: []string{"~ALL"}, + }, + }, + }, + }, + Deleted: []*RepositoryRulesetConditions{}, + }, + Rules: &RepositoryRulesetChangedRules{ + Added: []*RepositoryRule{{Type: RulesetRuleTypeRequiredSignatures}}, + Updated: []*RepositoryRulesetUpdatedRules{ + { + Rule: &RepositoryRule{ + Type: RulesetRuleTypePullRequest, + Parameters: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{ + MergeMethodSquash, + MergeMethodRebase, + }, + DismissStaleReviewsOnPush: false, + RequireCodeOwnerReview: false, + RequireLastPushApproval: false, + RequiredApprovingReviewCount: 2, + RequiredReviewThreadResolution: false, + }, + }, + Changes: &RepositoryRulesetChangedRule{ + Configuration: &RepositoryRulesetChangeSource{ + From: Ptr( + `{\"required_reviewers\":[],\"allowed_merge_methods\":[\"squash\",\"rebase\",\"merge\"],\"require_code_owner_review\":false,\"require_last_push_approval\":false,\"dismiss_stale_reviews_on_push\":false,\"required_approving_review_count\":2,\"authorized_dismissal_actors_only\":false,\"required_review_thread_resolution\":false,\"ignore_approvals_from_contributors\":false,\"automatic_copilot_code_review_enabled\":false}`, + ), + }, + }, + }, + { + Rule: &RepositoryRule{ + Type: RulesetRuleTypeCodeScanning, + Parameters: &CodeScanningRuleParameters{ + CodeScanningTools: []*RuleCodeScanningTool{ + { + AlertsThreshold: CodeScanningAlertsThresholdErrors, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdMediumOrHigher, + Tool: "CodeQL", + }, + }, + }, + }, + Changes: &RepositoryRulesetChangedRule{ + Configuration: &RepositoryRulesetChangeSource{ + From: Ptr( + `{\"code_scanning_tools\":[{\"tool\":\"CodeQL\",\"alerts_threshold\":\"errors\",\"security_alerts_threshold\":\"high_or_higher\"}]}`, + ), + }, + }, + }, + }, + Deleted: []*RepositoryRule{{Type: RulesetRuleTypeRequiredLinearHistory}}, + }, + }, + Repository: repository, + Organization: organization, + Enterprise: enterprise, + Installation: installation, + Sender: sender, + }, + }, + { + "deleted", + fmt.Sprintf( + `{"action":"deleted","repository_ruleset":{"id":1,"name":"r","target":"branch","source_type":"Repository","source":"o/r","enforcement":"active","conditions":{"ref_name":{"exclude":[],"include":["~DEFAULT_BRANCH","refs/heads/dev-*"]}},"rules":[{"type":"deletion"},{"type":"creation"},{"type":"update"},{"type":"required_linear_history"}],"node_id":"n","created_at":%[1]s,"updated_at":%[1]s,"_links":{"self":{"href":"a"},"html":{"href":"a"}}},"repository":{"id":1,"node_id":"n","name":"r","full_name":"o/r"},"organization":{"id":1,"node_id":"n","name":"o"},"enterprise":{"id":1,"node_id":"n","slug":"e","name":"e"},"installation":{"id":1,"node_id":"n","app_id":1,"app_slug":"a"},"sender":{"id":1,"node_id":"n","login":"l"}}`, + referenceTimeStr, + ), + &RepositoryRulesetEvent{ + Action: Ptr("deleted"), + RepositoryRuleset: &RepositoryRuleset{ + ID: Ptr(int64(1)), + Name: "r", + Target: Ptr(RulesetTargetBranch), + SourceType: Ptr(RulesetSourceTypeRepository), + Source: "o/r", + Enforcement: RulesetEnforcementActive, + Conditions: &RepositoryRulesetConditions{ + RefName: &RepositoryRulesetRefConditionParameters{ + Include: []string{"~DEFAULT_BRANCH", "refs/heads/dev-*"}, + Exclude: []string{}, + }, + }, + Rules: &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{}, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + }, + NodeID: Ptr("n"), + CreatedAt: &Timestamp{referenceTime}, + UpdatedAt: &Timestamp{referenceTime}, + Links: &RepositoryRulesetLinks{ + Self: &RepositoryRulesetLink{HRef: Ptr("a")}, + HTML: &RepositoryRulesetLink{HRef: Ptr("a")}, + }, + }, + Repository: repository, + Organization: organization, + Enterprise: enterprise, + Installation: installation, + Sender: sender, + }, + }, } for _, test := range tests { diff --git a/github/rules_test.go b/github/rules_test.go index ea6e4d4f46c..2d51e8bbce3 100644 --- a/github/rules_test.go +++ b/github/rules_test.go @@ -20,10 +20,222 @@ func TestRulesetRules(t *testing.T) { json string }{ {"empty", &RepositoryRulesetRules{}, `[]`}, - {"single_rule_with_empty_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, `[{"type":"creation"}]`}, - {"single_rule_with_required_params", &RepositoryRulesetRules{RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test"}}}, `[{"type":"required_deployments","parameters":{"required_deployment_environments":["test"]}}]`}, - {"all_rules_with_required_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, MergeQueue: &MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}, RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{RequiredStatusChecks: []*RuleStatusCheck{{Context: "test1"}, {Context: "test2"}}, StrictRequiredStatusChecksPolicy: true}, NonFastForward: &EmptyRuleParameters{}, CommitMessagePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitAuthorEmailPattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitterEmailPattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, BranchNamePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, TagNamePattern: &PatternRuleParameters{Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, FilePathRestriction: &FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}, MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}, MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, Workflows: &WorkflowsRuleParameters{Workflows: []*RuleWorkflow{{Path: ".github/workflows/test1.yaml"}, {Path: ".github/workflows/test2.yaml"}}}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}, `[{"type":"creation"},{"type":"update"},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test1"},{"context":"test2"}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"workflows":[{"path":".github/workflows/test1.yaml"},{"path":".github/workflows/test2.yaml"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, - {"all_rules_with_all_params", &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}, Update: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, Deletion: &EmptyRuleParameters{}, RequiredLinearHistory: &EmptyRuleParameters{}, MergeQueue: &MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}, RequiredDeployments: &RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}, RequiredSignatures: &EmptyRuleParameters{}, PullRequest: &PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}, RequiredStatusChecks: &RequiredStatusChecksRuleParameters{DoNotEnforceOnCreate: Ptr(true), RequiredStatusChecks: []*RuleStatusCheck{{Context: "test1", IntegrationID: Ptr(int64(1))}, {Context: "test2", IntegrationID: Ptr(int64(2))}}, StrictRequiredStatusChecksPolicy: true}, NonFastForward: &EmptyRuleParameters{}, CommitMessagePattern: &PatternRuleParameters{Name: Ptr("cmp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitAuthorEmailPattern: &PatternRuleParameters{Name: Ptr("caep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, CommitterEmailPattern: &PatternRuleParameters{Name: Ptr("cep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, BranchNamePattern: &PatternRuleParameters{Name: Ptr("bp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, TagNamePattern: &PatternRuleParameters{Name: Ptr("tp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}, FilePathRestriction: &FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}, MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}, MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, Workflows: &WorkflowsRuleParameters{DoNotEnforceOnCreate: Ptr(true), Workflows: []*RuleWorkflow{{Path: ".github/workflows/test1.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(1)), SHA: Ptr("aaaa")}, {Path: ".github/workflows/test2.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(2)), SHA: Ptr("bbbb")}}}, CodeScanning: &CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}, `[{"type":"creation"},{"type":"update","parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, + { + "single_rule_with_empty_params", + &RepositoryRulesetRules{Creation: &EmptyRuleParameters{}}, + `[{"type":"creation"}]`, + }, + { + "single_rule_with_required_params", + &RepositoryRulesetRules{ + RequiredDeployments: &RequiredDeploymentsRuleParameters{ + RequiredDeploymentEnvironments: []string{"test"}, + }, + }, + `[{"type":"required_deployments","parameters":{"required_deployment_environments":["test"]}}]`, + }, + { + "all_rules_with_required_params", + &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{}, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + MergeQueue: &MergeQueueRuleParameters{ + CheckResponseTimeoutMinutes: 5, + GroupingStrategy: MergeGroupingStrategyAllGreen, + MaxEntriesToBuild: 10, + MaxEntriesToMerge: 20, + MergeMethod: MergeMethodSquash, + MinEntriesToMerge: 1, + MinEntriesToMergeWaitMinutes: 15, + }, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ + RequiredDeploymentEnvironments: []string{"test1", "test2"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{ + MergeMethodSquash, + MergeMethodRebase, + }, + DismissStaleReviewsOnPush: true, + RequireCodeOwnerReview: true, + RequireLastPushApproval: true, + RequiredApprovingReviewCount: 2, + RequiredReviewThreadResolution: true, + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + RequiredStatusChecks: []*RuleStatusCheck{ + {Context: "test1"}, + {Context: "test2"}, + }, + StrictRequiredStatusChecksPolicy: true, + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + CommitterEmailPattern: &PatternRuleParameters{ + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + BranchNamePattern: &PatternRuleParameters{ + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + TagNamePattern: &PatternRuleParameters{ + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + FilePathRestriction: &FilePathRestrictionRuleParameters{ + RestrictedFilePaths: []string{"test1", "test2"}, + }, + MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, + FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{ + RestrictedFileExtensions: []string{".exe", ".pkg"}, + }, + MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, + Workflows: &WorkflowsRuleParameters{ + Workflows: []*RuleWorkflow{ + {Path: ".github/workflows/test1.yaml"}, + {Path: ".github/workflows/test2.yaml"}, + }, + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []*RuleCodeScanningTool{ + { + AlertsThreshold: CodeScanningAlertsThresholdAll, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, + Tool: "test", + }, + { + AlertsThreshold: CodeScanningAlertsThresholdNone, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, + Tool: "test", + }, + }, + }, + }, + `[{"type":"creation"},{"type":"update"},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test1"},{"context":"test2"}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"workflows":[{"path":".github/workflows/test1.yaml"},{"path":".github/workflows/test2.yaml"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`, + }, + { + "all_rules_with_all_params", + &RepositoryRulesetRules{ + Creation: &EmptyRuleParameters{}, + Update: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, + Deletion: &EmptyRuleParameters{}, + RequiredLinearHistory: &EmptyRuleParameters{}, + MergeQueue: &MergeQueueRuleParameters{ + CheckResponseTimeoutMinutes: 5, + GroupingStrategy: MergeGroupingStrategyAllGreen, + MaxEntriesToBuild: 10, + MaxEntriesToMerge: 20, + MergeMethod: MergeMethodSquash, + MinEntriesToMerge: 1, + MinEntriesToMergeWaitMinutes: 15, + }, + RequiredDeployments: &RequiredDeploymentsRuleParameters{ + RequiredDeploymentEnvironments: []string{"test1", "test2"}, + }, + RequiredSignatures: &EmptyRuleParameters{}, + PullRequest: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{ + MergeMethodSquash, + MergeMethodRebase, + }, + DismissStaleReviewsOnPush: true, + RequireCodeOwnerReview: true, + RequireLastPushApproval: true, + RequiredApprovingReviewCount: 2, + RequiredReviewThreadResolution: true, + }, + RequiredStatusChecks: &RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []*RuleStatusCheck{ + {Context: "test1", IntegrationID: Ptr(int64(1))}, + {Context: "test2", IntegrationID: Ptr(int64(2))}, + }, + StrictRequiredStatusChecksPolicy: true, + }, + NonFastForward: &EmptyRuleParameters{}, + CommitMessagePattern: &PatternRuleParameters{ + Name: Ptr("cmp"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + CommitAuthorEmailPattern: &PatternRuleParameters{ + Name: Ptr("caep"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + CommitterEmailPattern: &PatternRuleParameters{ + Name: Ptr("cep"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + BranchNamePattern: &PatternRuleParameters{ + Name: Ptr("bp"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + TagNamePattern: &PatternRuleParameters{ + Name: Ptr("tp"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + FilePathRestriction: &FilePathRestrictionRuleParameters{ + RestrictedFilePaths: []string{"test1", "test2"}, + }, + MaxFilePathLength: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, + FileExtensionRestriction: &FileExtensionRestrictionRuleParameters{ + RestrictedFileExtensions: []string{".exe", ".pkg"}, + }, + MaxFileSize: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, + Workflows: &WorkflowsRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + Workflows: []*RuleWorkflow{ + { + Path: ".github/workflows/test1.yaml", + Ref: Ptr("main"), + RepositoryID: Ptr(int64(1)), + SHA: Ptr("aaaa"), + }, + { + Path: ".github/workflows/test2.yaml", + Ref: Ptr("main"), + RepositoryID: Ptr(int64(2)), + SHA: Ptr("bbbb"), + }, + }, + }, + CodeScanning: &CodeScanningRuleParameters{ + CodeScanningTools: []*RuleCodeScanningTool{ + { + AlertsThreshold: CodeScanningAlertsThresholdAll, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, + Tool: "test", + }, + { + AlertsThreshold: CodeScanningAlertsThresholdNone, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, + Tool: "test", + }, + }, + }, + }, + `[{"type":"creation"},{"type":"update","parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion"},{"type":"required_linear_history"},{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures"},{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward"},{"type":"commit_message_pattern","parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","parameters":{"max_file_size":1024}},{"type":"workflows","parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`, + }, } t.Run("MarshalJSON", func(t *testing.T) { @@ -74,9 +286,321 @@ func TestBranchRules(t *testing.T) { json string }{ {"empty", &BranchRules{}, `[]`}, - {"single_rule_type_single_rule_empty_params", &BranchRules{Creation: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}}, `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1}]`}, - {"single_rule_type_single_rule_with_params", &BranchRules{Update: []*UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}}, `[{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}}]`}, - {"all_rule_types_with_all_parameters", &BranchRules{Creation: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, Update: []*UpdateBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}}}, Deletion: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, RequiredLinearHistory: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, MergeQueue: []*MergeQueueBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MergeQueueRuleParameters{CheckResponseTimeoutMinutes: 5, GroupingStrategy: MergeGroupingStrategyAllGreen, MaxEntriesToBuild: 10, MaxEntriesToMerge: 20, MergeMethod: MergeMethodSquash, MinEntriesToMerge: 1, MinEntriesToMergeWaitMinutes: 15}}}, RequiredDeployments: []*RequiredDeploymentsBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: RequiredDeploymentsRuleParameters{RequiredDeploymentEnvironments: []string{"test1", "test2"}}}}, RequiredSignatures: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, PullRequest: []*PullRequestBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PullRequestRuleParameters{AllowedMergeMethods: []MergeMethod{MergeMethodSquash, MergeMethodRebase}, DismissStaleReviewsOnPush: true, RequireCodeOwnerReview: true, RequireLastPushApproval: true, RequiredApprovingReviewCount: 2, RequiredReviewThreadResolution: true}}}, RequiredStatusChecks: []*RequiredStatusChecksBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: RequiredStatusChecksRuleParameters{DoNotEnforceOnCreate: Ptr(true), RequiredStatusChecks: []*RuleStatusCheck{{Context: "test1", IntegrationID: Ptr(int64(1))}, {Context: "test2", IntegrationID: Ptr(int64(2))}}, StrictRequiredStatusChecksPolicy: true}}}, NonFastForward: []*BranchRuleMetadata{{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}}, CommitMessagePattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("cmp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, CommitAuthorEmailPattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("caep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, CommitterEmailPattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("cep"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, BranchNamePattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("bp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, TagNamePattern: []*PatternBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: PatternRuleParameters{Name: Ptr("tp"), Negate: Ptr(false), Operator: PatternRuleOperatorStartsWith, Pattern: "test"}}}, FilePathRestriction: []*FilePathRestrictionBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: FilePathRestrictionRuleParameters{RestrictedFilePaths: []string{"test1", "test2"}}}}, MaxFilePathLength: []*MaxFilePathLengthBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}}}, FileExtensionRestriction: []*FileExtensionRestrictionBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: FileExtensionRestrictionRuleParameters{RestrictedFileExtensions: []string{".exe", ".pkg"}}}}, MaxFileSize: []*MaxFileSizeBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: MaxFileSizeRuleParameters{MaxFileSize: 1024}}}, Workflows: []*WorkflowsBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: WorkflowsRuleParameters{DoNotEnforceOnCreate: Ptr(true), Workflows: []*RuleWorkflow{{Path: ".github/workflows/test1.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(1)), SHA: Ptr("aaaa")}, {Path: ".github/workflows/test2.yaml", Ref: Ptr("main"), RepositoryID: Ptr(int64(2)), SHA: Ptr("bbbb")}}}}}, CodeScanning: []*CodeScanningBranchRule{{BranchRuleMetadata: BranchRuleMetadata{RulesetSourceType: RulesetSourceTypeRepository, RulesetSource: "test/test", RulesetID: 1}, Parameters: CodeScanningRuleParameters{CodeScanningTools: []*RuleCodeScanningTool{{AlertsThreshold: CodeScanningAlertsThresholdAll, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, Tool: "test"}, {AlertsThreshold: CodeScanningAlertsThresholdNone, SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, Tool: "test"}}}}}}, `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"required_linear_history","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"merge_queue","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"pull_request","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"commit_message_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_size":1024}},{"type":"workflows","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`}, + { + "single_rule_type_single_rule_empty_params", + &BranchRules{ + Creation: []*BranchRuleMetadata{ + { + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + }, + }, + `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1}]`, + }, + { + "single_rule_type_single_rule_with_params", + &BranchRules{ + Update: []*UpdateBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, + }, + }, + }, + `[{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}}]`, + }, + { + "all_rule_types_with_all_parameters", + &BranchRules{ + Creation: []*BranchRuleMetadata{ + { + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + }, + Update: []*UpdateBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, + }, + }, + Deletion: []*BranchRuleMetadata{ + { + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + }, + RequiredLinearHistory: []*BranchRuleMetadata{ + { + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + }, + MergeQueue: []*MergeQueueBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: MergeQueueRuleParameters{ + CheckResponseTimeoutMinutes: 5, + GroupingStrategy: MergeGroupingStrategyAllGreen, + MaxEntriesToBuild: 10, + MaxEntriesToMerge: 20, + MergeMethod: MergeMethodSquash, + MinEntriesToMerge: 1, + MinEntriesToMergeWaitMinutes: 15, + }, + }, + }, + RequiredDeployments: []*RequiredDeploymentsBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: RequiredDeploymentsRuleParameters{ + RequiredDeploymentEnvironments: []string{"test1", "test2"}, + }, + }, + }, + RequiredSignatures: []*BranchRuleMetadata{ + { + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + }, + PullRequest: []*PullRequestBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{ + MergeMethodSquash, + MergeMethodRebase, + }, + DismissStaleReviewsOnPush: true, + RequireCodeOwnerReview: true, + RequireLastPushApproval: true, + RequiredApprovingReviewCount: 2, + RequiredReviewThreadResolution: true, + }, + }, + }, + RequiredStatusChecks: []*RequiredStatusChecksBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: RequiredStatusChecksRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + RequiredStatusChecks: []*RuleStatusCheck{ + {Context: "test1", IntegrationID: Ptr(int64(1))}, + {Context: "test2", IntegrationID: Ptr(int64(2))}, + }, + StrictRequiredStatusChecksPolicy: true, + }, + }, + }, + NonFastForward: []*BranchRuleMetadata{ + { + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + }, + CommitMessagePattern: []*PatternBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: PatternRuleParameters{ + Name: Ptr("cmp"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + }, + CommitAuthorEmailPattern: []*PatternBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: PatternRuleParameters{ + Name: Ptr("caep"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + }, + CommitterEmailPattern: []*PatternBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: PatternRuleParameters{ + Name: Ptr("cep"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + }, + BranchNamePattern: []*PatternBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: PatternRuleParameters{ + Name: Ptr("bp"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + }, + TagNamePattern: []*PatternBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: PatternRuleParameters{ + Name: Ptr("tp"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + }, + FilePathRestriction: []*FilePathRestrictionBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: FilePathRestrictionRuleParameters{ + RestrictedFilePaths: []string{"test1", "test2"}, + }, + }, + }, + MaxFilePathLength: []*MaxFilePathLengthBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, + }, + }, + FileExtensionRestriction: []*FileExtensionRestrictionBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: FileExtensionRestrictionRuleParameters{ + RestrictedFileExtensions: []string{".exe", ".pkg"}, + }, + }, + }, + MaxFileSize: []*MaxFileSizeBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: MaxFileSizeRuleParameters{MaxFileSize: 1024}, + }, + }, + Workflows: []*WorkflowsBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: WorkflowsRuleParameters{ + DoNotEnforceOnCreate: Ptr(true), + Workflows: []*RuleWorkflow{ + { + Path: ".github/workflows/test1.yaml", + Ref: Ptr("main"), + RepositoryID: Ptr(int64(1)), + SHA: Ptr("aaaa"), + }, + { + Path: ".github/workflows/test2.yaml", + Ref: Ptr("main"), + RepositoryID: Ptr(int64(2)), + SHA: Ptr("bbbb"), + }, + }, + }, + }, + }, + CodeScanning: []*CodeScanningBranchRule{ + { + BranchRuleMetadata: BranchRuleMetadata{ + RulesetSourceType: RulesetSourceTypeRepository, + RulesetSource: "test/test", + RulesetID: 1, + }, + Parameters: CodeScanningRuleParameters{ + CodeScanningTools: []*RuleCodeScanningTool{ + { + AlertsThreshold: CodeScanningAlertsThresholdAll, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, + Tool: "test", + }, + { + AlertsThreshold: CodeScanningAlertsThresholdNone, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, + Tool: "test", + }, + }, + }, + }, + }, + }, + `[{"type":"creation","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"update","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"update_allows_fetch_and_merge":true}},{"type":"deletion","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"required_linear_history","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"merge_queue","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}},{"type":"required_deployments","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"required_deployment_environments":["test1","test2"]}},{"type":"required_signatures","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"pull_request","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}},{"type":"required_status_checks","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"required_status_checks":[{"context":"test1","integration_id":1},{"context":"test2","integration_id":2}],"strict_required_status_checks_policy":true}},{"type":"non_fast_forward","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1},{"type":"commit_message_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cmp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"commit_author_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"caep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"committer_email_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"cep","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"branch_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"bp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"tag_name_pattern","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"name":"tp","negate":false,"operator":"starts_with","pattern":"test"}},{"type":"file_path_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_paths":["test1","test2"]}},{"type":"max_file_path_length","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_path_length":512}},{"type":"file_extension_restriction","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"restricted_file_extensions":[".exe",".pkg"]}},{"type":"max_file_size","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"max_file_size":1024}},{"type":"workflows","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"do_not_enforce_on_create":true,"workflows":[{"path":".github/workflows/test1.yaml","ref":"main","repository_id":1,"sha":"aaaa"},{"path":".github/workflows/test2.yaml","ref":"main","repository_id":2,"sha":"bbbb"}]}},{"type":"code_scanning","ruleset_source_type":"Repository","ruleset_source":"test/test","ruleset_id":1,"parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}]`, + }, } t.Run("UnmarshalJSON", func(t *testing.T) { From dffa3303892d6e0710d88a8d7a7d7668fb423953 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Tue, 21 Jan 2025 11:15:33 +0000 Subject: [PATCH 11/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/rules_test.go | 297 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 294 insertions(+), 3 deletions(-) diff --git a/github/rules_test.go b/github/rules_test.go index 2d51e8bbce3..ec58db117df 100644 --- a/github/rules_test.go +++ b/github/rules_test.go @@ -251,7 +251,12 @@ func TestRulesetRules(t *testing.T) { } if diff := cmp.Diff(test.json, string(got)); diff != "" { - t.Errorf("json.Marshal returned:\n%s\nwant:\n%s\ndiff:\n%v", got, test.json, diff) + t.Errorf( + "json.Marshal returned:\n%s\nwant:\n%s\ndiff:\n%v", + got, + test.json, + diff, + ) } }) } @@ -271,7 +276,12 @@ func TestRulesetRules(t *testing.T) { } if diff := cmp.Diff(test.rules, got); diff != "" { - t.Errorf("json.Unmarshal returned:\n%#v\nwant:\n%#v\ndiff:\n%v", got, test.rules, diff) + t.Errorf( + "json.Unmarshal returned:\n%#v\nwant:\n%#v\ndiff:\n%v", + got, + test.rules, + diff, + ) } }) } @@ -617,7 +627,288 @@ func TestBranchRules(t *testing.T) { } if diff := cmp.Diff(test.rules, got); diff != "" { - t.Errorf("json.Unmarshal returned:\n%#v\nwant:\n%#v\ndiff:\n%v", got, test.rules, diff) + t.Errorf( + "json.Unmarshal returned:\n%#v\nwant:\n%#v\ndiff:\n%v", + got, + test.rules, + diff, + ) + } + }) + } + }) +} + +func TestRepositoryRule(t *testing.T) { + t.Parallel() + tests := []struct { + name string + rule *RepositoryRule + json string + }{ + { + "empty", + &RepositoryRule{}, + `{}`, + }, + { + "creation", + &RepositoryRule{Type: RulesetRuleTypeCreation, Parameters: nil}, + `{"type":"creation"}`, + }, + { + "update", + &RepositoryRule{Type: RulesetRuleTypeUpdate, Parameters: &UpdateRuleParameters{}}, + `{"type":"update"}`, + }, + { + "update_params_empty", + &RepositoryRule{Type: RulesetRuleTypeUpdate, Parameters: &UpdateRuleParameters{}}, + `{"type":"update","parameters":{}}`, + }, + { + "update_params_set", + &RepositoryRule{ + Type: RulesetRuleTypeUpdate, + Parameters: &UpdateRuleParameters{UpdateAllowsFetchAndMerge: true}, + }, + `{"type":"update","parameters":{"update_allows_fetch_and_merge":true}}`, + }, + { + "deletion", + &RepositoryRule{Type: RulesetRuleTypeDeletion, Parameters: nil}, + `{"type":"deletion"}`, + }, + { + "required_linear_history", + &RepositoryRule{Type: RulesetRuleTypeRequiredLinearHistory, Parameters: nil}, + `{"type":"required_linear_history"}`, + }, + { + "merge_queue", + &RepositoryRule{ + Type: RulesetRuleTypeMergeQueue, + Parameters: &MergeQueueRuleParameters{ + CheckResponseTimeoutMinutes: 5, + GroupingStrategy: MergeGroupingStrategyAllGreen, + MaxEntriesToBuild: 10, + MaxEntriesToMerge: 20, + MergeMethod: MergeMethodSquash, + MinEntriesToMerge: 1, + MinEntriesToMergeWaitMinutes: 15, + }, + }, + `{"type":"merge_queue","parameters":{"check_response_timeout_minutes":5,"grouping_strategy":"ALLGREEN","max_entries_to_build":10,"max_entries_to_merge":20,"merge_method":"squash","min_entries_to_merge":1,"min_entries_to_merge_wait_minutes":15}}`, + }, + { + "required_deployments", + &RepositoryRule{ + Type: RulesetRuleTypeRequiredDeployments, + Parameters: &RequiredDeploymentsRuleParameters{ + RequiredDeploymentEnvironments: []string{"test1", "test2"}, + }, + }, + `{"type":"required_deployments","parameters":{"required_deployment_environments":["test1","test2"]}}`, + }, + { + "required_signatures", + &RepositoryRule{Type: RulesetRuleTypeRequiredSignatures, Parameters: nil}, + `{"type":"required_signatures"}`, + }, + { + "pull_request", + &RepositoryRule{ + Type: RulesetRuleTypePullRequest, + Parameters: &PullRequestRuleParameters{ + AllowedMergeMethods: []MergeMethod{ + MergeMethodSquash, + MergeMethodRebase, + }, + DismissStaleReviewsOnPush: true, + RequireCodeOwnerReview: true, + RequireLastPushApproval: true, + RequiredApprovingReviewCount: 2, + RequiredReviewThreadResolution: true, + }, + }, + `{"type":"pull_request","parameters":{"allowed_merge_methods":["squash","rebase"],"dismiss_stale_reviews_on_push":true,"require_code_owner_review":true,"require_last_push_approval":true,"required_approving_review_count":2,"required_review_thread_resolution":true}}`, + }, + { + "required_status_checks", + &RepositoryRule{ + Type: RulesetRuleTypeRequiredStatusChecks, + Parameters: &RequiredStatusChecksRuleParameters{ + RequiredStatusChecks: []*RuleStatusCheck{ + {Context: "test1"}, + {Context: "test2"}, + }, + StrictRequiredStatusChecksPolicy: true, + }, + }, + `{"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test1"},{"context":"test2"}],"strict_required_status_checks_policy":true}}`, + }, + { + "non_fast_forward", + &RepositoryRule{Type: RulesetRuleTypeNonFastForward, Parameters: nil}, + `{"type":"non_fast_forward"}`, + }, + { + "commit_message_pattern", + &RepositoryRule{ + Type: RulesetRuleTypeCommitMessagePattern, + Parameters: &PatternRuleParameters{ + Name: Ptr("test"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + `{"type":"commit_message_pattern","parameters":{"name":"test","negate":false,"operator":"starts_with","pattern":"test"}}`, + }, + { + "commit_author_email_pattern", + &RepositoryRule{ + Type: RulesetRuleTypeCommitAuthorEmailPattern, + Parameters: &PatternRuleParameters{ + Name: Ptr("test"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + `{"type":"commit_author_email_pattern","parameters":{"name":"test","negate":false,"operator":"starts_with","pattern":"test"}}`, + }, + { + "committer_email_pattern", + &RepositoryRule{ + Type: RulesetRuleTypeCommitterEmailPattern, + Parameters: &PatternRuleParameters{ + Name: Ptr("test"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + `{"type":"committer_email_pattern","parameters":{"name":"test","negate":false,"operator":"starts_with","pattern":"test"}}`, + }, + { + "branch_name_pattern", + &RepositoryRule{ + Type: RulesetRuleTypeBranchNamePattern, + Parameters: &PatternRuleParameters{ + Name: Ptr("test"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + `{"type":"branch_name_pattern","parameters":{"name":"test","negate":false,"operator":"starts_with","pattern":"test"}}`, + }, + { + "tag_name_pattern", + &RepositoryRule{ + Type: RulesetRuleTypeTagNamePattern, + Parameters: &PatternRuleParameters{ + Name: Ptr("test"), + Negate: Ptr(false), + Operator: PatternRuleOperatorStartsWith, + Pattern: "test", + }, + }, + `{"type":"tag_name_pattern","parameters":{"name":"test","negate":false,"operator":"starts_with","pattern":"test"}}`, + }, + { + "file_path_restriction", + &RepositoryRule{ + Type: RulesetRuleTypeFilePathRestriction, + Parameters: &FilePathRestrictionRuleParameters{ + RestrictedFilePaths: []string{"test1", "test2"}, + }, + }, + `{"type":"file_path_restriction","parameters":{"restricted_file_paths":["test1","test2"]}}`, + }, + { + "max_file_path_length", + &RepositoryRule{ + Type: RulesetRuleTypeMaxFilePathLength, + Parameters: &MaxFilePathLengthRuleParameters{MaxFilePathLength: 512}, + }, + `{"type":"max_file_path_length","parameters":{"max_file_path_length":512}}`, + }, + { + "file_extension_restriction", + &RepositoryRule{ + Type: RulesetRuleTypeFileExtensionRestriction, + Parameters: &FileExtensionRestrictionRuleParameters{ + RestrictedFileExtensions: []string{".exe", ".pkg"}, + }, + }, + `{"type":"file_extension_restriction","parameters":{"restricted_file_extensions":[".exe",".pkg"]}}`, + }, + { + "max_file_size", + &RepositoryRule{ + Type: RulesetRuleTypeMaxFileSize, + Parameters: &MaxFileSizeRuleParameters{MaxFileSize: 1024}, + }, + `{"type":"max_file_size","parameters":{"max_file_size":1024}}`, + }, + { + "workflows", + &RepositoryRule{ + Type: RulesetRuleTypeWorkflows, + Parameters: &WorkflowsRuleParameters{ + Workflows: []*RuleWorkflow{ + {Path: ".github/workflows/test1.yaml"}, + {Path: ".github/workflows/test2.yaml"}, + }, + }, + }, + `{"type":"workflows","parameters":{"workflows":[{"path":".github/workflows/test1.yaml"},{"path":".github/workflows/test2.yaml"}]}}`, + }, + { + "code_scanning", + &RepositoryRule{ + Type: RulesetRuleTypeCodeScanning, + Parameters: &CodeScanningRuleParameters{ + CodeScanningTools: []*RuleCodeScanningTool{ + { + AlertsThreshold: CodeScanningAlertsThresholdAll, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdAll, + Tool: "test", + }, + { + AlertsThreshold: CodeScanningAlertsThresholdNone, + SecurityAlertsThreshold: CodeScanningSecurityAlertsThresholdNone, + Tool: "test", + }, + }, + }, + }, + `{"type":"code_scanning","parameters":{"code_scanning_tools":[{"alerts_threshold":"all","security_alerts_threshold":"all","tool":"test"},{"alerts_threshold":"none","security_alerts_threshold":"none","tool":"test"}]}}`, + }, + } + + t.Run("UnmarshalJSON", func(t *testing.T) { + t.Parallel() + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + got := &RepositoryRule{} + err := json.Unmarshal([]byte(test.json), got) + if err != nil { + t.Errorf("Unable to unmarshal JSON %v: %v", test.json, err) + } + + if diff := cmp.Diff(test.rule, got); diff != "" { + t.Errorf( + "json.Unmarshal returned:\n%#v\nwant:\n%#v\ndiff:\n%v", + got, + test.rule, + diff, + ) } }) } From 81b59ee52f473fe97e27ad5bb26ce83136dea8e3 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Tue, 21 Jan 2025 11:55:07 +0000 Subject: [PATCH 12/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/rules.go | 58 ++++++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/github/rules.go b/github/rules.go index 425a8089a19..a3cb755210d 100644 --- a/github/rules.go +++ b/github/rules.go @@ -480,14 +480,14 @@ type repositoryRulesetRuleWrapper struct { // MarshalJSON is a custom JSON marshaler for RulesetRules. func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { // If new rules are added to RulesetRules the capacity needs increasing - arr := make([]json.RawMessage, 0, 21) + rawRules := make([]json.RawMessage, 0, 21) if r.Creation != nil { bytes, err := marshalRepositoryRulesetRule(RulesetRuleTypeCreation, r.Creation) if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.Update != nil { @@ -495,7 +495,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.Deletion != nil { @@ -503,7 +503,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.RequiredLinearHistory != nil { @@ -511,7 +511,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.MergeQueue != nil { @@ -519,7 +519,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.RequiredDeployments != nil { @@ -527,7 +527,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.RequiredSignatures != nil { @@ -535,7 +535,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.PullRequest != nil { @@ -543,7 +543,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.RequiredStatusChecks != nil { @@ -551,7 +551,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.NonFastForward != nil { @@ -559,7 +559,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.CommitMessagePattern != nil { @@ -567,7 +567,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.CommitAuthorEmailPattern != nil { @@ -575,7 +575,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.CommitterEmailPattern != nil { @@ -583,7 +583,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.BranchNamePattern != nil { @@ -591,7 +591,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.TagNamePattern != nil { @@ -599,7 +599,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.FilePathRestriction != nil { @@ -607,7 +607,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.MaxFilePathLength != nil { @@ -615,7 +615,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.FileExtensionRestriction != nil { @@ -623,7 +623,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.MaxFileSize != nil { @@ -631,7 +631,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.Workflows != nil { @@ -639,7 +639,7 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } if r.CodeScanning != nil { @@ -647,10 +647,10 @@ func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - arr = append(arr, json.RawMessage(bytes)) + rawRules = append(rawRules, json.RawMessage(bytes)) } - return json.Marshal(arr) + return json.Marshal(rawRules) } // marshalRepositoryRulesetRule is a helper function to marshal a ruleset rule. @@ -675,13 +675,13 @@ func marshalRepositoryRulesetRule[T any](t RepositoryRuleType, params T) ([]byte // UnmarshalJSON is a custom JSON unmarshaler for RulesetRules. func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { // If new rules are added to RulesetRules the capacity needs increasing - arr := make([]repositoryRulesetRuleWrapper, 0, 21) + wrappers := make([]repositoryRulesetRuleWrapper, 0, 21) - if err := json.Unmarshal(data, &arr); err != nil { + if err := json.Unmarshal(data, &wrappers); err != nil { return err } - for _, w := range arr { + for _, w := range wrappers { switch w.Type { case RulesetRuleTypeCreation: r.Creation = &EmptyRuleParameters{} @@ -837,13 +837,13 @@ type branchRuleWrapper struct { // UnmarshalJSON is a custom JSON unmarshaler for BranchRules. func (r *BranchRules) UnmarshalJSON(data []byte) error { // If new rules are added to RulesetRules the capacity needs increasing - arr := make([]branchRuleWrapper, 0, 21) + wrappers := make([]branchRuleWrapper, 0, 21) - if err := json.Unmarshal(data, &arr); err != nil { + if err := json.Unmarshal(data, &wrappers); err != nil { return err } - for _, w := range arr { + for _, w := range wrappers { switch w.Type { case RulesetRuleTypeCreation: r.Creation = append(r.Creation, &BranchRuleMetadata{RulesetSourceType: w.RulesetSourceType, RulesetSource: w.RulesetSource, RulesetID: w.RulesetID}) From 49fbce8c2f7e0e64c40adab502cb8f2c5fbecc3d Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Tue, 21 Jan 2025 14:47:42 +0000 Subject: [PATCH 13/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/rules.go | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/github/rules.go b/github/rules.go index a3cb755210d..9616c990a06 100644 --- a/github/rules.go +++ b/github/rules.go @@ -479,7 +479,8 @@ type repositoryRulesetRuleWrapper struct { // MarshalJSON is a custom JSON marshaler for RulesetRules. func (r *RepositoryRulesetRules) MarshalJSON() ([]byte, error) { - // If new rules are added to RulesetRules the capacity needs increasing + // The RepositoryRulesetRules type marshals to between 1 and 21 rules. + // If new rules are added to RepositoryRulesetRules the capacity below needs increasing rawRules := make([]json.RawMessage, 0, 21) if r.Creation != nil { @@ -674,8 +675,7 @@ func marshalRepositoryRulesetRule[T any](t RepositoryRuleType, params T) ([]byte // UnmarshalJSON is a custom JSON unmarshaler for RulesetRules. func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { - // If new rules are added to RulesetRules the capacity needs increasing - wrappers := make([]repositoryRulesetRuleWrapper, 0, 21) + var wrappers []repositoryRulesetRuleWrapper if err := json.Unmarshal(data, &wrappers); err != nil { return err @@ -836,8 +836,7 @@ type branchRuleWrapper struct { // UnmarshalJSON is a custom JSON unmarshaler for BranchRules. func (r *BranchRules) UnmarshalJSON(data []byte) error { - // If new rules are added to RulesetRules the capacity needs increasing - wrappers := make([]branchRuleWrapper, 0, 21) + var wrappers []branchRuleWrapper if err := json.Unmarshal(data, &wrappers); err != nil { return err From 7241f1a6f87be4618962c8c73162ec6224b9dea9 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Tue, 21 Jan 2025 17:00:36 +0000 Subject: [PATCH 14/14] fixup! fix!: Refactored the repository ruleset code Signed-off-by: Steve Hipwell --- github/rules.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/github/rules.go b/github/rules.go index 9616c990a06..8312d95237f 100644 --- a/github/rules.go +++ b/github/rules.go @@ -675,7 +675,7 @@ func marshalRepositoryRulesetRule[T any](t RepositoryRuleType, params T) ([]byte // UnmarshalJSON is a custom JSON unmarshaler for RulesetRules. func (r *RepositoryRulesetRules) UnmarshalJSON(data []byte) error { - var wrappers []repositoryRulesetRuleWrapper + var wrappers []*repositoryRulesetRuleWrapper if err := json.Unmarshal(data, &wrappers); err != nil { return err @@ -836,7 +836,7 @@ type branchRuleWrapper struct { // UnmarshalJSON is a custom JSON unmarshaler for BranchRules. func (r *BranchRules) UnmarshalJSON(data []byte) error { - var wrappers []branchRuleWrapper + var wrappers []*branchRuleWrapper if err := json.Unmarshal(data, &wrappers); err != nil { return err