diff --git a/github/repos_rules.go b/github/repos_rules.go index 4e6f5f13474..38d4255a9aa 100644 --- a/github/repos_rules.go +++ b/github/repos_rules.go @@ -118,6 +118,10 @@ func (r *RepositoryRule) UnmarshalJSON(data []byte) error { case "creation", "deletion", "required_linear_history", "required_signatures", "non_fast_forward": 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 @@ -127,6 +131,7 @@ func (r *RepositoryRule) UnmarshalJSON(data []byte) error { rawParams := json.RawMessage(bytes) r.Parameters = &rawParams + case "required_deployments": params := RequiredDeploymentEnvironmentsRuleParameters{} if err := json.Unmarshal(*RepositoryRule.Parameters, ¶ms); err != nil { @@ -185,13 +190,18 @@ func NewCreationRule() (rule *RepositoryRule) { // NewUpdateRule creates a rule to only allow users with bypass permission to update matching refs. func NewUpdateRule(params *UpdateAllowsFetchAndMergeRuleParameters) (rule *RepositoryRule) { - bytes, _ := json.Marshal(params) + if params != nil { + bytes, _ := json.Marshal(params) - rawParams := json.RawMessage(bytes) + rawParams := json.RawMessage(bytes) + return &RepositoryRule{ + Type: "update", + Parameters: &rawParams, + } + } return &RepositoryRule{ - Type: "update", - Parameters: &rawParams, + Type: "update", } } diff --git a/github/repos_rules_test.go b/github/repos_rules_test.go index 582ec89245b..a57137c688d 100644 --- a/github/repos_rules_test.go +++ b/github/repos_rules_test.go @@ -292,6 +292,45 @@ func TestRepositoriesService_GetRulesForBranch(t *testing.T) { }) } +func TestRepositoriesService_GetRulesForBranchEmptyUpdateRule(t *testing.T) { + client, mux, _, teardown := setup() + defer teardown() + + 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) + } + + updateRule := NewUpdateRule(nil) + + want := []*RepositoryRule{ + updateRule, + } + if !cmp.Equal(rules, want) { + t.Errorf("Repositories.GetRulesForBranch returned %+v, want %+v", Stringify(rules), Stringify(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_GetAllRulesets(t *testing.T) { client, mux, _, teardown := setup() defer teardown()