1use std::collections::BTreeMap;
4
5use async_trait::async_trait;
6use interprex::{ModelError, ProviderError, Repository, Result, SourceCodeConfigurationProvider};
7use octocrab::Page;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11use crate::{
12 GithubProvider,
13 client::{authenticated_external, read_error},
14};
15
16const WRITABLE_RULE_TYPES: &[&str] = &[
17 "creation",
18 "update",
19 "deletion",
20 "required_linear_history",
21 "merge_queue",
22 "required_deployments",
23 "required_signatures",
24 "pull_request",
25 "required_status_checks",
26 "non_fast_forward",
27 "commit_message_pattern",
28 "commit_author_email_pattern",
29 "committer_email_pattern",
30 "branch_name_pattern",
31 "tag_name_pattern",
32 "workflows",
33 "code_scanning",
34 "copilot_code_review",
35 "license_compliance_scanning",
36 "file_path_restriction",
37 "max_file_path_length",
38 "file_extension_restriction",
39 "max_file_size",
40];
41
42const READ_ONLY_RULESET_FIELDS: &[&str] = &[
43 "node_id",
44 "_links",
45 "current_user_can_bypass",
46 "created_at",
47 "updated_at",
48];
49
50#[derive(Deserialize)]
51struct GithubRulesetSummary {
52 id: u64,
53 name: String,
54 #[serde(default)]
55 target: Option<String>,
56 source_type: String,
57 source: String,
58 enforcement: String,
59}
60
61#[derive(Serialize)]
62struct RulesetListQuery {
63 per_page: u8,
64 includes_parents: bool,
65}
66
67#[derive(Serialize)]
68struct IncludesParents {
69 includes_parents: bool,
70}
71
72#[derive(Deserialize)]
73struct RulesetWriteReceipt {
74 id: u64,
75}
76
77#[derive(Serialize)]
78struct GithubRulesetWrite<'a> {
79 name: &'a str,
80 target: &'a str,
81 enforcement: &'a str,
82 bypass_actors: &'a [GithubRulesetBypassActor],
83 #[serde(skip_serializing_if = "Option::is_none")]
84 conditions: Option<&'a GithubRulesetConditions>,
85 rules: &'a [GithubRulesetRule],
86}
87
88#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
97pub struct GithubRuleset {
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub id: Option<u64>,
100 pub name: String,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub target: Option<String>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub source_type: Option<String>,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub source: Option<String>,
107 pub enforcement: String,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub bypass_actors: Option<Vec<GithubRulesetBypassActor>>,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
111 pub conditions: Option<GithubRulesetConditions>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub rules: Option<Vec<GithubRulesetRule>>,
114 #[serde(flatten)]
115 pub additional: BTreeMap<String, Value>,
116}
117
118impl GithubRuleset {
119 pub fn validate(&self) -> std::result::Result<(), ModelError> {
125 non_empty(&self.name, "GitHub ruleset name")?;
126 non_empty(&self.enforcement, "GitHub ruleset enforcement")?;
127 if self.id == Some(0) {
128 return Err(ModelError::InvalidNumber);
129 }
130 for (value, field) in [
131 (self.target.as_deref(), "GitHub ruleset target"),
132 (self.source_type.as_deref(), "GitHub ruleset source type"),
133 (self.source.as_deref(), "GitHub ruleset source"),
134 ] {
135 if let Some(value) = value {
136 non_empty(value, field)?;
137 }
138 }
139 if let Some(actors) = &self.bypass_actors {
140 for actor in actors {
141 actor.validate()?;
142 }
143 }
144 if let Some(rules) = &self.rules {
145 for rule in rules {
146 rule.validate()?;
147 }
148 }
149 Ok(())
150 }
151}
152
153#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
159pub struct GithubRulesetConditions {
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub ref_name: Option<GithubRefNameCondition>,
162 #[serde(flatten)]
163 pub additional: BTreeMap<String, Value>,
164}
165
166#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
171pub struct GithubRefNameCondition {
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub include: Option<Vec<String>>,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub exclude: Option<Vec<String>>,
176 #[serde(flatten)]
177 pub additional: BTreeMap<String, Value>,
178}
179
180#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
186pub struct GithubRulesetBypassActor {
187 pub actor_type: String,
188 #[serde(flatten)]
189 pub fields: BTreeMap<String, Value>,
190}
191
192impl GithubRulesetBypassActor {
193 fn validate(&self) -> std::result::Result<(), ModelError> {
194 non_empty(&self.actor_type, "GitHub bypass actor type")?;
195 if self.fields.get("actor_id").and_then(Value::as_u64) == Some(0) {
196 return Err(ModelError::InvalidNumber);
197 }
198 if let Some(mode) = self.fields.get("bypass_mode").and_then(Value::as_str) {
199 non_empty(mode, "GitHub bypass mode")?;
200 }
201 Ok(())
202 }
203
204 #[must_use]
206 pub fn actor_id(&self) -> Option<&Value> {
207 self.fields.get("actor_id")
208 }
209
210 #[must_use]
212 pub fn bypass_mode(&self) -> Option<&Value> {
213 self.fields.get("bypass_mode")
214 }
215}
216
217#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
224pub struct GithubRulesetRule {
225 #[serde(rename = "type")]
226 pub rule_type: String,
227 #[serde(flatten)]
228 pub fields: BTreeMap<String, Value>,
229}
230
231impl GithubRulesetRule {
232 fn validate(&self) -> std::result::Result<(), ModelError> {
233 non_empty(&self.rule_type, "GitHub rule type")
234 }
235
236 #[must_use]
238 pub fn parameters(&self) -> Option<&Value> {
239 self.fields.get("parameters")
240 }
241}
242
243#[async_trait]
244impl SourceCodeConfigurationProvider for GithubProvider {
245 type Ruleset = GithubRuleset;
246
247 #[tracing::instrument(
251 name = "interprex.provider.source_code_configuration.read_rulesets",
252 skip_all,
253 fields(interprex.provider.name = "github")
254 )]
255 async fn read_rulesets(&self, repository: &Repository) -> Result<Vec<Self::Ruleset>> {
256 let page: Page<Value> = self
257 .user()?
258 .get(
259 format!("/repos/{repository}/rulesets"),
260 Some(&RulesetListQuery {
261 per_page: 100,
262 includes_parents: true,
263 }),
264 )
265 .await
266 .map_err(|error| {
267 read_error(
268 "list source rulesets",
269 format!("source rulesets for {repository}"),
270 error,
271 )
272 })?;
273 let mut summaries = self
274 .user()?
275 .all_pages(page)
276 .await
277 .map_err(|error| {
278 read_error(
279 "list source rulesets",
280 format!("source rulesets for {repository}"),
281 error,
282 )
283 })?
284 .into_iter()
285 .map(parse_summary)
286 .collect::<Result<Vec<_>>>()?;
287 summaries.sort_by(|left, right| {
288 (&left.source_type, &left.source, left.id).cmp(&(
289 &right.source_type,
290 &right.source,
291 right.id,
292 ))
293 });
294
295 let mut rulesets = Vec::with_capacity(summaries.len());
296 for summary in summaries {
297 rulesets.push(self.read_ruleset_detail(repository, &summary).await?);
298 }
299 Ok(rulesets)
300 }
301
302 #[tracing::instrument(
303 name = "interprex.provider.source_code_configuration.apply_ruleset",
304 skip_all,
305 fields(interprex.provider.name = "github")
306 )]
307 async fn apply_ruleset(
308 &self,
309 repository: &Repository,
310 ruleset: &Self::Ruleset,
311 ) -> Result<Self::Ruleset> {
312 let desired = writable_ruleset(repository, ruleset)?;
313 let desired_value = serde_json::to_value(&desired).map_err(|error| {
314 invalid_input(format!("ruleset cannot be serialized for GitHub: {error}"))
315 })?;
316 let id = match ruleset.id {
317 Some(id) => {
318 let _: Value = self
319 .streaming_user()?
320 .put(
321 format!("/repos/{repository}/rulesets/{id}"),
322 Some(&desired_value),
323 )
324 .await
325 .map_err(|error| write_error("update source ruleset", Some(id), error))?;
326 id
327 }
328 None => {
329 let response: Value = self
330 .streaming_user()?
331 .post(
332 format!("/repos/{repository}/rulesets"),
333 Some(&desired_value),
334 )
335 .await
336 .map_err(|error| write_error("create source ruleset", None, error))?;
337 parse_receipt(response)?
338 }
339 };
340
341 let summary = GithubRulesetSummary {
342 id,
343 name: desired.name.to_owned(),
344 target: Some(desired.target.to_owned()),
345 source_type: "Repository".to_owned(),
346 source: repository.to_string(),
347 enforcement: desired.enforcement.to_owned(),
348 };
349 let observed = self.read_ruleset_detail(repository, &summary).await?;
350 let observed_value = serde_json::to_value(writable_ruleset(repository, &observed)?)
351 .map_err(|error| {
352 unrepresentable(format!("accepted ruleset cannot be read: {error}"))
353 })?;
354 if observed_value != desired_value {
355 return Err(unrepresentable(format!(
356 "ruleset {id} writable configuration changed between apply and verification"
357 )));
358 }
359 Ok(observed)
360 }
361}
362
363impl GithubProvider {
364 async fn read_ruleset_detail(
365 &self,
366 repository: &Repository,
367 summary: &GithubRulesetSummary,
368 ) -> Result<GithubRuleset> {
369 let response: Value = self
370 .user()?
371 .get(
372 format!("/repos/{repository}/rulesets/{}", summary.id),
373 Some(&IncludesParents {
374 includes_parents: true,
375 }),
376 )
377 .await
378 .map_err(|error| {
379 read_error(
380 "read source ruleset detail",
381 format!("source ruleset {} for {repository}", summary.id),
382 error,
383 )
384 })?;
385 let ruleset: GithubRuleset = serde_json::from_value(response).map_err(|error| {
386 unrepresentable(format!(
387 "source ruleset {} detail is unreadable: {error}",
388 summary.id
389 ))
390 })?;
391 validate_detail(repository, summary, &ruleset)?;
392 Ok(ruleset)
393 }
394}
395
396fn parse_summary(value: Value) -> Result<GithubRulesetSummary> {
397 let summary: GithubRulesetSummary = serde_json::from_value(value).map_err(|error| {
398 unrepresentable(format!("source ruleset summary is unreadable: {error}"))
399 })?;
400 if summary.id == 0 {
401 return Err(unrepresentable("source ruleset summary has a zero id"));
402 }
403 for (value, fact) in [
404 (&summary.name, "name"),
405 (&summary.source_type, "source type"),
406 (&summary.source, "source"),
407 (&summary.enforcement, "enforcement"),
408 ] {
409 if value.is_empty() {
410 return Err(unrepresentable(format!(
411 "source ruleset {} summary has an empty {fact}",
412 summary.id
413 )));
414 }
415 }
416 if summary.target.as_deref() == Some("") {
417 return Err(unrepresentable(format!(
418 "source ruleset {} summary has an empty target",
419 summary.id
420 )));
421 }
422 Ok(summary)
423}
424
425fn validate_detail(
426 repository: &Repository,
427 summary: &GithubRulesetSummary,
428 ruleset: &GithubRuleset,
429) -> Result<()> {
430 ruleset.validate().map_err(|error| {
431 unrepresentable(format!(
432 "source ruleset {} detail is invalid: {error}",
433 summary.id
434 ))
435 })?;
436 if ruleset.id != Some(summary.id) {
437 return Err(unrepresentable(format!(
438 "source ruleset {} detail identifies {:?}",
439 summary.id, ruleset.id
440 )));
441 }
442 let target = ruleset
443 .target
444 .as_deref()
445 .ok_or_else(|| unrepresentable(format!("source ruleset {} has no target", summary.id)))?;
446 if !matches!(target, "branch" | "tag" | "push" | "repository") {
447 return Err(unsupported("read an unknown ruleset target"));
448 }
449 let source_type = ruleset.source_type.as_deref().ok_or_else(|| {
450 unrepresentable(format!("source ruleset {} has no source type", summary.id))
451 })?;
452 if !matches!(source_type, "Repository" | "Organization" | "Enterprise") {
453 return Err(unsupported("read an unknown ruleset source type"));
454 }
455 let source = ruleset
456 .source
457 .as_deref()
458 .ok_or_else(|| unrepresentable(format!("source ruleset {} has no source", summary.id)))?;
459 if ruleset.source_type.as_deref() != Some(summary.source_type.as_str())
460 || ruleset.source.as_deref() != Some(summary.source.as_str())
461 {
462 return Err(unrepresentable(format!(
463 "source ruleset {} detail has a different source identity",
464 summary.id
465 )));
466 }
467 if source_type == "Repository" && source != repository.to_string() {
468 return Err(unrepresentable(format!(
469 "source ruleset {} belongs to repository {source}, not {repository}",
470 summary.id
471 )));
472 }
473 if ruleset.bypass_actors.is_none() {
474 return Err(unsupported(
475 "read complete rulesets without bypass-actor access",
476 ));
477 }
478 if ruleset.rules.is_none() {
479 return Err(unrepresentable(format!(
480 "source ruleset {} detail has no rules",
481 summary.id
482 )));
483 }
484 Ok(())
485}
486
487fn writable_ruleset<'a>(
488 repository: &Repository,
489 ruleset: &'a GithubRuleset,
490) -> Result<GithubRulesetWrite<'a>> {
491 ruleset
492 .validate()
493 .map_err(|error| invalid_input(error.to_string()))?;
494 let target = ruleset
495 .target
496 .as_deref()
497 .ok_or_else(|| invalid_input("ruleset target must be explicit"))?;
498 if target == "repository" {
499 return Err(unsupported(
500 "apply repository-target rulesets through a repository endpoint",
501 ));
502 }
503 if !matches!(target, "branch" | "tag" | "push") {
504 return Err(unsupported("apply an unknown ruleset target"));
505 }
506 if !matches!(
507 ruleset.enforcement.as_str(),
508 "disabled" | "active" | "evaluate"
509 ) {
510 return Err(unsupported("apply an unknown ruleset enforcement value"));
511 }
512 validate_write_source(repository, ruleset)?;
513 validate_write_fields(ruleset)?;
514 let bypass_actors = ruleset
515 .bypass_actors
516 .as_deref()
517 .ok_or_else(|| invalid_input("complete ruleset requires bypass_actors, including empty"))?;
518 let rules = ruleset
519 .rules
520 .as_deref()
521 .ok_or_else(|| invalid_input("complete ruleset requires rules, including empty"))?;
522 Ok(GithubRulesetWrite {
523 name: &ruleset.name,
524 target,
525 enforcement: &ruleset.enforcement,
526 bypass_actors,
527 conditions: ruleset.conditions.as_ref(),
528 rules,
529 })
530}
531
532fn validate_write_source(repository: &Repository, ruleset: &GithubRuleset) -> Result<()> {
533 match ruleset.id {
534 Some(_) => match (ruleset.source_type.as_deref(), ruleset.source.as_deref()) {
535 (Some("Repository"), Some(source)) if source == repository.to_string() => Ok(()),
536 (Some("Repository"), Some(_)) => Err(invalid_input(
537 "ruleset repository source does not match the destination repository",
538 )),
539 (Some("Organization"), Some(_)) | (Some("Enterprise"), Some(_)) => Err(unsupported(
540 "apply an inherited ruleset through a repository endpoint",
541 )),
542 (Some(_), Some(_)) => Err(unsupported("apply an unknown ruleset source type")),
543 _ => Err(invalid_input(
544 "existing ruleset requires its repository source identity",
545 )),
546 },
547 None if ruleset.source_type.is_some() || ruleset.source.is_some() => Err(invalid_input(
548 "new ruleset must not carry read-only source identity",
549 )),
550 None => Ok(()),
551 }
552}
553
554fn validate_write_fields(ruleset: &GithubRuleset) -> Result<()> {
555 if ruleset
556 .additional
557 .keys()
558 .any(|field| !READ_ONLY_RULESET_FIELDS.contains(&field.as_str()))
559 {
560 return Err(unsupported(
561 "apply a ruleset with an unknown top-level field",
562 ));
563 }
564 if ruleset.id.is_none() && !ruleset.additional.is_empty() {
565 return Err(invalid_input(
566 "new ruleset must not carry read-only provider metadata",
567 ));
568 }
569 if let Some(conditions) = &ruleset.conditions
570 && (!conditions.additional.is_empty()
571 || conditions
572 .ref_name
573 .as_ref()
574 .is_some_and(|condition| !condition.additional.is_empty()))
575 {
576 return Err(unsupported("apply a ruleset with an unknown condition"));
577 }
578 if let Some(ref_name) = ruleset
579 .conditions
580 .as_ref()
581 .and_then(|conditions| conditions.ref_name.as_ref())
582 && (ref_name.include.is_none() || ref_name.exclude.is_none())
583 {
584 return Err(invalid_input(
585 "a ref-name condition requires explicit include and exclude collections",
586 ));
587 }
588 if let Some(actors) = &ruleset.bypass_actors {
589 for actor in actors {
590 if actor
591 .fields
592 .keys()
593 .any(|field| !matches!(field.as_str(), "actor_id" | "bypass_mode"))
594 {
595 return Err(unsupported("apply a ruleset with an unknown bypass field"));
596 }
597 if !matches!(
598 actor.actor_type.as_str(),
599 "Integration"
600 | "OrganizationAdmin"
601 | "RepositoryRole"
602 | "Team"
603 | "DeployKey"
604 | "User"
605 ) {
606 return Err(unsupported(
607 "apply a ruleset with an unknown bypass actor type",
608 ));
609 }
610 match actor.actor_id() {
611 Some(Value::Null) => {}
612 Some(Value::Number(id)) if id.as_u64().is_some_and(|id| id > 0) => {}
613 _ => {
614 return Err(invalid_input(
615 "a bypass actor requires an explicit null or positive integer actor_id",
616 ));
617 }
618 }
619 let mode = actor
620 .bypass_mode()
621 .and_then(Value::as_str)
622 .ok_or_else(|| invalid_input("a bypass actor requires a string bypass_mode"))?;
623 if !matches!(mode, "always" | "pull_request" | "exempt") {
624 return Err(unsupported("apply a ruleset with an unknown bypass mode"));
625 }
626 }
627 }
628 if let Some(rules) = &ruleset.rules {
629 for rule in rules {
630 if !WRITABLE_RULE_TYPES.contains(&rule.rule_type.as_str()) {
631 return Err(unsupported("apply an unknown ruleset rule"));
632 }
633 if rule
634 .fields
635 .keys()
636 .any(|field| field.as_str() != "parameters")
637 {
638 return Err(unsupported("apply a ruleset rule with an unknown field"));
639 }
640 }
641 }
642 Ok(())
643}
644
645fn parse_receipt(value: Value) -> Result<u64> {
646 let receipt: RulesetWriteReceipt = serde_json::from_value(value)
647 .map_err(|error| unrepresentable(format!("created ruleset has no readable id: {error}")))?;
648 if receipt.id == 0 {
649 Err(unrepresentable("created ruleset has a zero id"))
650 } else {
651 Ok(receipt.id)
652 }
653}
654
655fn write_error(
656 operation: &'static str,
657 ruleset_id: Option<u64>,
658 error: octocrab::Error,
659) -> ProviderError {
660 if matches!(
661 &error,
662 octocrab::Error::GitHub { source, .. } if source.status_code.as_u16() == 404
663 ) {
664 return ProviderError::NotFound {
665 entity: ruleset_id.map_or_else(
666 || "repository rulesets".to_owned(),
667 |id| format!("source ruleset {id}"),
668 ),
669 };
670 }
671 if let octocrab::Error::GitHub { source, .. } = &error
672 && source.status_code.as_u16() == 422
673 && let Some(errors) = source.errors.as_deref()
674 && !errors.is_empty()
675 && let Some(mut fields) = errors
676 .iter()
677 .map(ruleset_validation_field)
678 .collect::<Option<Vec<_>>>()
679 {
680 fields.sort_unstable();
681 fields.dedup();
682 return invalid_input(format!(
683 "GitHub rejected these ruleset fields: {}",
684 fields.join(", ")
685 ));
686 }
687 authenticated_external(operation, &error)
688}
689
690fn ruleset_validation_field(error: &Value) -> Option<&'static str> {
691 let field = error.get("field")?.as_str()?;
692 let code = error.get("code")?.as_str()?;
693 if !matches!(
694 code,
695 "custom" | "invalid" | "missing" | "missing_field" | "unprocessable"
696 ) {
697 return None;
698 }
699 match field {
700 "name" => Some("name"),
701 "target" => Some("target"),
702 "enforcement" => Some("enforcement"),
703 "bypass_actors" => Some("bypass_actors"),
704 "conditions" => Some("conditions"),
705 "rules" => Some("rules"),
706 _ => None,
707 }
708}
709
710fn invalid_input(fact: impl Into<String>) -> ProviderError {
711 ProviderError::InvalidInput {
712 provider: "github",
713 fact: fact.into(),
714 }
715}
716
717fn unrepresentable(fact: impl Into<String>) -> ProviderError {
718 ProviderError::Unrepresentable {
719 provider: "github",
720 fact: fact.into(),
721 }
722}
723
724fn unsupported(operation: &'static str) -> ProviderError {
725 ProviderError::Unsupported {
726 provider: "github",
727 operation,
728 }
729}
730
731fn non_empty(value: &str, field: &'static str) -> std::result::Result<(), ModelError> {
732 if value.is_empty() {
733 Err(ModelError::Empty { field })
734 } else {
735 Ok(())
736 }
737}
738
739#[cfg(test)]
740mod tests {
741 use super::*;
742
743 #[test]
744 fn complete_ruleset_round_trips_known_and_unknown_native_fields() {
745 let fixture = serde_json::json!({
746 "id": 7,
747 "name": "pull requests",
748 "target": "branch",
749 "source_type": "Repository",
750 "source": "civitas-forge/interprex",
751 "enforcement": "evaluate",
752 "bypass_actors": [
753 {"actor_id": 15368, "actor_type": "Integration", "bypass_mode": "pull_request"},
754 {"actor_id": null, "actor_type": "FutureActor", "bypass_mode": "future_mode", "future": true}
755 ],
756 "conditions": {
757 "ref_name": {"include": ["~DEFAULT_BRANCH"], "exclude": ["refs/heads/release/*"]},
758 "repository_name": {"include": ["important-*"], "exclude": ["archive-*"], "protected": true}
759 },
760 "rules": [
761 {"type": "required_status_checks", "parameters": {
762 "strict_required_status_checks_policy": true,
763 "do_not_enforce_on_create": false,
764 "required_status_checks": [{"context": "quality", "integration_id": 15368}]
765 }},
766 {"type": "required_signatures"},
767 {"type": "future_rule", "parameters": {"new_option": true}, "future": "retained"}
768 ],
769 "current_user_can_bypass": "never",
770 "future_top_level": {"retained": true}
771 });
772
773 let ruleset: GithubRuleset =
774 serde_json::from_value(fixture.clone()).expect("deserialize complete ruleset");
775 ruleset.validate().expect("valid ruleset");
776 assert_eq!(
777 ruleset
778 .conditions
779 .as_ref()
780 .and_then(|conditions| conditions.ref_name.as_ref())
781 .and_then(|condition| condition.exclude.as_ref()),
782 Some(&vec!["refs/heads/release/*".to_owned()])
783 );
784 assert_eq!(
785 ruleset.rules.as_ref().expect("rules")[0].parameters(),
786 Some(&fixture["rules"][0]["parameters"])
787 );
788 assert_eq!(
789 serde_json::to_value(ruleset).expect("serialize complete ruleset"),
790 fixture
791 );
792 }
793
794 #[test]
795 fn ruleset_validation_rejects_empty_native_identities() {
796 let ruleset: GithubRuleset = serde_json::from_value(serde_json::json!({
797 "id": 7,
798 "name": "pull requests",
799 "enforcement": "active",
800 "rules": [{"type": ""}]
801 }))
802 .expect("deserialize ruleset");
803 assert_eq!(
804 ruleset.validate(),
805 Err(ModelError::Empty {
806 field: "GitHub rule type"
807 })
808 );
809 }
810
811 #[test]
812 fn every_current_writable_rule_kind_retains_its_complete_fields() {
813 let kinds = [
814 "creation",
815 "update",
816 "deletion",
817 "required_linear_history",
818 "merge_queue",
819 "required_deployments",
820 "required_signatures",
821 "pull_request",
822 "required_status_checks",
823 "non_fast_forward",
824 "commit_message_pattern",
825 "commit_author_email_pattern",
826 "committer_email_pattern",
827 "branch_name_pattern",
828 "tag_name_pattern",
829 "workflows",
830 "code_scanning",
831 "copilot_code_review",
832 "license_compliance_scanning",
833 "file_path_restriction",
834 "max_file_path_length",
835 "file_extension_restriction",
836 "max_file_size",
837 ];
838 for kind in kinds {
839 let fixture = serde_json::json!({
840 "type": kind,
841 "parameters": {"provider_owned": [true, 7, "value"]},
842 "future_field": {"retained": true}
843 });
844 let rule: GithubRulesetRule =
845 serde_json::from_value(fixture.clone()).expect("deserialize rule");
846 assert_eq!(serde_json::to_value(rule).expect("serialize rule"), fixture);
847 }
848 }
849}