use std::fmt;
macro_rules! rule_ids {
($($variant:ident => $id:literal,)+) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RuleId {
$(
#[doc = $id]
$variant,
)+
}
impl RuleId {
pub const ALL: &'static [Self] = &[$(Self::$variant),+];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
$(Self::$variant => $id),+
}
}
#[must_use]
pub fn parse(id: &str) -> Option<Self> {
match id {
$($id => Some(Self::$variant),)+
_ => None,
}
}
}
impl serde::Serialize for RuleId {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> serde::Deserialize<'de> for RuleId {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Self, D::Error> {
let id = <std::borrow::Cow<'_, str> as serde::Deserialize>::deserialize(
deserializer,
)?;
Self::parse(&id).ok_or_else(|| {
serde::de::Error::custom(format!("no spec defines the rule {id}"))
})
}
}
};
}
rule_ids! {
FragmentNamesTheVenueForm => "acquisition:a-fragment-names-the-venue-form",
HostInstallIsARecordedDecision => "acquisition:a-host-install-is-a-recorded-decision",
PinMoveNamesTheSkillRoute => "acquisition:a-pin-move-names-the-skill-route",
CleanRemovesOnlyANamedLeftover => "acquisition:clean-removes-only-a-named-leftover",
CleanSwapsTheRetiredLine => "acquisition:clean-swaps-the-retired-line",
EveryPairCarriesAVerdict => "acquisition:every-pair-carries-a-verdict",
EveryReportNamesAPendingMove => "acquisition:every-report-names-a-pending-move",
OneTargetRunsOneMechanism => "acquisition:one-target-runs-one-mechanism",
StatusReportsAndNeverJudges => "acquisition:status-reports-and-never-judges",
SyncIsTheOperatorsAct => "acquisition:sync-is-the-operators-act",
SyncAdvisesTheFollowsLinesAndWritesNone => "acquisition:sync-advises-the-follows-lines-and-writes-none",
TheCheckRefreshesWeeklyAndRetriesHourly => "acquisition:the-check-refreshes-weekly-and-retries-hourly",
TheCheckWarnsAndWritesOnlyItsCache => "acquisition:the-check-warns-and-writes-only-its-cache",
TheOffSwitchStopsTheCheckAlone => "acquisition:the-off-switch-stops-the-check-alone",
TheOperatorCallerReportsEveryOutcome => "acquisition:the-operator-caller-reports-every-outcome",
ThePinMovesInOneTransaction => "acquisition:the-pin-moves-in-one-transaction",
TheSetupPathOffersTheWire => "acquisition:the-setup-path-offers-the-wire",
TheSyncLeavesADiffNobodyCommitted => "acquisition:the-sync-leaves-a-diff-nobody-committed",
TheToolServesAndDoesNotEdit => "acquisition:the-tool-serves-and-does-not-edit",
RecordedDimensionOnlyShrinks => "budget-debt:a-recorded-dimension-only-shrinks",
DebtIsCreatedByAnExplicitAct => "budget-debt:debt-is-created-by-an-explicit-act",
CellCarriesOneReference => "comparison-docs:a-cell-carries-one-reference",
ComparisonCarriesALegend => "comparison-docs:a-comparison-carries-a-legend",
VerdictCarriesItsWord => "comparison-docs:a-verdict-carries-its-word",
EveryTableIsDated => "comparison-docs:every-table-is-dated",
TablePipesAreEscaped => "comparison-docs:table-pipes-are-escaped",
CitationResolvesToARule => "decision-records:a-citation-resolves-to-a-rule",
RecordFollowsTheHeadingShape => "decision-records:a-record-follows-the-heading-shape",
BodyStaysWithinWordCap => "decision-records:body-stays-within-350-words",
FilenameCarriesNoDigit => "decision-records:filename-carries-no-digit",
MergedRecordIsPermanent => "decision-records:merged-record-is-permanent",
RecordIsNotRevised => "decision-records:record-is-not-revised",
DeclaredLocationIsNamedByItsVariable => "distribution:a-declared-location-is-named-by-its-variable",
DeliveredConfigurationServesADeliveredRule => "distribution:a-delivered-configuration-serves-a-delivered-rule",
LandingClassifiesItsTargetFirst => "distribution:a-landing-classifies-its-target-first",
SeededRuleRunsNoCanonCommand => "distribution:a-seeded-rule-runs-no-canon-command",
SkillChecksItsHostBeforeItPlans => "distribution:a-skill-checks-its-host-before-it-plans",
SkillHasOneOwner => "distribution:a-skill-has-one-owner",
SkillIsReadableBeforeAnInstance => "distribution:a-skill-is-readable-before-an-instance",
SkillObeysThePortableFormat => "distribution:a-skill-obeys-the-portable-format",
SkillPlansBeforeItActs => "distribution:a-skill-plans-before-it-acts",
InitializationPreservesProjectContent => "distribution:initialization-preserves-project-content",
InstanceCarriesTheSkills => "distribution:an-instance-carries-the-skills",
UnattributedSkillFolderIsNeverReplaced => "distribution:an-unattributed-skill-folder-is-never-replaced",
InstancesOperateOffline => "distribution:instances-operate-offline",
ManifestIdentifiesEveryOwnedFile => "distribution:manifest-identifies-every-owned-file",
DeclarationIsSeededOnceAndThenOwned => "distribution:the-declaration-is-seeded-once-and-then-owned",
SkillPackageIsSelfContained => "distribution:a-skill-package-is-self-contained",
SkillUninstallRemovesOnlyWhatItWrote => "distribution:skill-uninstall-removes-only-what-it-wrote",
SkillsArePartOfThePayload => "distribution:skills-are-part-of-the-payload",
TheDoctorNamesAShadowingUserCopy => "distribution:the-doctor-names-a-shadowing-user-copy",
ThePayloadNamesNoOtherProject => "distribution:the-payload-names-no-other-project",
ThePayloadRootsAreDeclaredOnce => "distribution:the-payload-roots-are-declared-once",
UpgradeConflictsAreAtomic => "distribution:upgrade-conflicts-are-atomic",
MachineScopeRecipeDropsASessionVariable => "release:a-machine-scope-recipe-drops-a-session-variable",
BinaryBuildsForEveryDeclaredTarget => "release:the-binary-builds-for-every-declared-target",
OneCatalogDescribesEveryServedDocument => "docs-discovery:one-catalog-describes-every-served-document",
InstanceIsRoutedToTheIndex => "docs-discovery:an-instance-is-routed-to-the-index",
AuthorInstructionsStayWithinBudget => "docs-format:author-instructions-stay-within-budget",
ChapterStaysWithinLineCap => "docs-format:chapter-stays-within-200-lines",
DocumentStatesThePresent => "docs-format:document-states-the-present",
DocumentUsesStructuralMarkdownOnly => "docs-format:document-uses-structural-markdown-only",
EveryBudgetCarriesAGate => "docs-format:every-budget-carries-a-gate",
FenceDeclaresALanguage => "docs-format:fence-declares-a-language",
ProseStaysUnwrapped => "docs-format:prose-stays-unwrapped",
DocumentCarriesNoPersonalPath => "docs-foundations:a-document-carries-no-personal-path",
DocumentDirectoryExplainsItself => "docs-foundations:a-document-directory-explains-itself",
DocumentOwnsWhatItGoverns => "docs-foundations:a-document-owns-what-it-governs",
KindPrefixCarriesASlug => "docs-foundations:a-kind-prefix-carries-a-slug",
ArtifactFilenamesCarryAKindPrefix => "docs-foundations:artifact-filenames-carry-a-kind-prefix",
CompanionArtifactsShareTheSpecName => "docs-foundations:companion-artifacts-share-the-spec-name",
SpecStatesThePresent => "docs-foundations:spec-states-the-present",
SpecWinsOverRecord => "docs-foundations:spec-wins-over-record",
SpecsAreCentralized => "docs-foundations:specs-are-centralized",
SpecFollowsTheHeadingShape => "docs-specs:a-spec-follows-the-heading-shape",
ProhibitionsAreCapped => "docs-specs:prohibitions-are-capped",
RequirementCarriesAVerification => "docs-specs:requirement-carries-a-verification",
RequirementCarriesFiveParts => "docs-specs:requirement-carries-five-parts",
RuleIdIsUniqueAndSlugged => "docs-specs:rule-id-is-unique-and-slugged",
RuleIdOutlivesItsSentence => "docs-specs:rule-id-outlives-its-sentence",
SpecStaysWithinLineCap => "docs-specs:spec-stays-within-300-lines",
StatementUsesAnEarsPattern => "docs-specs:statement-uses-an-ears-pattern",
UnenforcedRulesAreDeclared => "docs-specs:unenforced-rules-are-declared",
VerificationNamesALiveHook => "docs-specs:verification-names-a-live-hook",
DivergentResultNamesItsDestination => "guides:a-divergent-result-names-its-destination",
ManualStepEnumeratesItsInteraction => "guides:a-manual-step-enumerates-its-interaction",
StepFollowsItsProducers => "guides:a-step-follows-its-producers",
StepIsOneImperativeAction => "guides:a-step-is-one-imperative-action",
ExternalFactIsVerifiedUpstream => "guides:an-external-fact-is-verified-upstream",
CitationsLiveInTheReferenceZone => "guides:citations-live-in-the-reference-zone",
EveryStepCarriesItsCheck => "guides:every-step-carries-its-check",
PreconditionsOpenAndVerificationCloses => "guides:preconditions-open-and-verification-closes",
TheManifestStaysReadable => "instance:the-manifest-stays-readable",
LintConfigurationComposes => "instance:the-lint-configuration-composes",
AgentsBlockStaysManaged => "instance:the-agents-block-stays-managed",
TrackingRegistryStaysValid => "instance:the-tracking-registry-stays-valid",
ProjectDeclaresWhatItsGatesJudge => "instance:the-project-declares-what-its-gates-judge",
ManagedBlockAgreesWithTheDeclaration => "instance:the-managed-block-agrees-with-the-declaration",
RootLintConfigurationLoadsRelativeLinks => "instance:the-root-lint-configuration-loads-relative-links",
BugzillaReportBodyFitsReportWidth => "known-issues:a-bugzilla-report-body-fits-in-79-columns",
FiledRecordCarriesItsReport => "known-issues:a-filed-record-carries-its-report",
RecordCarriesItsRetirementCondition => "known-issues:a-record-carries-its-retirement-condition",
RecordCarriesOneFilingState => "known-issues:a-record-carries-one-filing-state",
RecordCarriesOneState => "known-issues:a-record-carries-one-state",
RecordRecordsItsLastCheck => "known-issues:a-record-records-its-last-check",
RecordWalksTheMechanism => "known-issues:a-record-walks-the-mechanism",
CaseIdIsASlug => "known-issues:case-id-is-a-slug",
CanonGateIsNotDelivered => "release:a-canon-gate-is-not-delivered",
DeliveredGateReadsWhatTheConventionOwns => "release:a-delivered-gate-reads-what-the-convention-owns",
ReleasedVersionIsNotReAuthored => "release:a-released-version-is-not-re-authored",
TagDerivesFromTheVersionFile => "release:a-tag-derives-from-the-version-file",
EveryReleaseDeclaresWhatItAsks => "release:every-release-declares-what-it-asks",
LicenseDeclaresBothHalves => "release:license-declares-both-halves",
CanonIsAnOrdinaryInstance => "release:the-canon-is-an-ordinary-instance",
CanonRunsItsPreviousRelease => "release:the-canon-runs-its-previous-release",
PayloadRecordDescribesItsTree => "release:the-payload-record-describes-its-tree",
RkPinHasTwoFactsAndOneMover => "release:the-rk-pin-has-two-facts-and-one-mover",
DeliveredGateSetIsDeclaredOnce => "release:the-delivered-gate-set-is-declared-once",
DevshellSuppliesEveryProjectTool => "release:the-devshell-supplies-every-project-tool",
LocalHooksRunEveryCheckOfCi => "release:the-local-hooks-run-every-check-of-ci",
ThirdPartyNoticesTravelWithThePayload => "release:third-party-notices-travel-with-the-payload",
VersionsAreSemanticAndAligned => "release:versions-are-semantic-and-aligned",
ChoiceOffersOneDefault => "skill-format:a-choice-offers-one-default",
FactLivesInOneFile => "skill-format:a-fact-lives-in-one-file",
HardRuleIsACheckNotCapitals => "skill-format:a-hard-rule-is-a-check-not-capitals",
ManualStaysWithinItsCharacterCap => "skill-format:a-manual-stays-within-12000-characters",
PackageHoldsTheManualAndItsReferences => "skill-format:a-package-holds-the-manual-and-its-references",
ReferenceStaysWithinItsCharacterCap => "skill-format:a-reference-stays-within-32000-characters",
ReferenceLinkCarriesItsCondition => "skill-format:a-reference-link-carries-its-condition",
InstructionIsOneCheckableAction => "skill-format:an-instruction-is-one-checkable-action",
EveryLinePassesTheDeletionTest => "skill-format:every-line-passes-the-deletion-test",
OneTermNamesOneConcept => "skill-format:one-term-names-one-concept",
ProseIsOnlyAReasonThatChangesBehavior => "skill-format:prose-is-only-a-reason-that-changes-behavior",
SharedContentIsAuthoredOnce => "skill-format:shared-content-is-authored-once",
DescriptionSaysWhatThenWhen => "skill-format:the-description-says-what-then-when",
ManualFollowsTheStageOrder => "skill-format:the-manual-follows-the-stage-order",
ManualIsTheControlPlane => "skill-format:the-manual-is-the-control-plane",
ManualLinksEveryReferenceDirectly => "skill-format:the-manual-links-every-reference-directly",
RuleThatMattersMostComesFirst => "skill-format:the-rule-that-matters-most-comes-first",
StructureFollowsTheContent => "skill-format:the-structure-follows-the-content",
CommentCitesTheRule => "spec-to-code:a-comment-cites-the-rule",
CommentNamesNoRecord => "spec-to-code:a-comment-names-no-record",
GateMessageCitesTheRule => "spec-to-code:a-gate-message-cites-the-rule",
SpecMayLeadItsCode => "spec-to-code:a-spec-may-lead-its-code",
SuppressionNamesItsCase => "spec-to-code:a-suppression-names-its-case",
EnvReportsTheLoaderAndEachItem => "setup:env-reports-the-loader-and-each-item",
EnvWritesOneItemThroughTheRecordedLoader => "setup:env-writes-one-item-through-the-recorded-loader",
GatedCommandNamesItsFix => "setup:a-gated-command-names-its-fix",
EveryCommandHasAGateClass => "setup:every-command-has-a-gate-class",
LintReportsEachFindingWithItsRule => "setup:lint-reports-each-finding-with-its-rule",
InventoryListsEveryDocument => "setup:inventory-lists-every-document",
ArchiveMovesOnlyCommittedDocuments => "setup:an-archive-moves-only-committed-documents",
ArchiveRebuildsFromGit => "setup:an-archive-rebuilds-from-git",
MarkAppendsAndNeverRewrites => "setup:mark-appends-and-never-rewrites",
CloseRefusesAnUnfinishedSource => "setup:close-refuses-an-unfinished-source",
OpenMigrationIsDeclared => "setup:an-open-migration-is-declared",
IncrementalLandingIsNamed => "setup:an-incremental-landing-is-named",
StatusReportsWhatAnOlderReleaseLeft => "setup:status-reports-what-an-older-release-left",
LandingTakesTheChoicesItsStageRecorded => "staging:a-landing-takes-the-choices-its-stage-recorded",
ReplacementKeepsTheBytesItReplaces => "staging:a-replacement-keeps-the-bytes-it-replaces",
StageTakesTheRecordedChoices => "staging:a-stage-takes-the-recorded-choices",
UpgradeListsEveryRetiredCitationFirst => "staging:an-upgrade-lists-every-retired-citation-first",
UpgradeFromAnOlderReleaseNamesTheSkillRoute => "staging:an-upgrade-from-an-older-release-names-the-skill-route",
CompareReportsEveryDestination => "staging:compare-reports-every-destination-the-stage-carries",
PartialFailureReportsWhatItCompleted => "staging:a-partial-failure-reports-what-it-completed",
SeedLandsRenderedForItsRoot => "staging:a-seed-lands-rendered-for-its-root",
StageCarriesTheWholeCandidate => "staging:a-stage-carries-the-whole-candidate",
StagePersistsUntilItIsCleaned => "staging:a-stage-persists-until-it-is-cleaned",
StageWritesOnlyTheStage => "staging:a-stage-writes-only-the-stage",
UnattributedCollisionRefusesFirst => "staging:an-unattributed-collision-refuses-first",
EveryPathStaysUnderTheTarget => "staging:every-path-stays-under-the-target",
OneDocumentationRootServesTheRun => "staging:one-documentation-root-serves-the-run",
OneWriterHoldsTheTarget => "staging:one-writer-holds-the-target",
OwnerOnlyStateIsCheckedOnLinux => "staging:owner-only-state-is-checked-on-linux",
ProductionReadsNoStagedByte => "staging:production-reads-no-staged-byte",
ManifestAttributesEveryRefresh => "staging:the-manifest-attributes-every-refresh",
ManifestIsWrittenLast => "staging:the-manifest-is-written-last",
OperatorOwnsAcquisition => "staging:the-operator-owns-acquisition",
DeclaredDependentExists => "tracking:a-declared-dependent-exists",
PerishableSourceIsRegistered => "tracking:a-perishable-source-is-registered",
EntryDeclaresHowToRevalidate => "tracking:an-entry-declares-how-to-revalidate",
OverdueEntryBlocks => "tracking:an-overdue-entry-blocks",
UpstreamCheckDoesNotEditTheTree => "tracking:an-upstream-check-does-not-edit-the-tree",
UpstreamDerivationPinsARevision => "tracking:an-upstream-derivation-pins-a-revision",
RegistryHasOneReadableShape => "tracking:the-registry-has-one-readable-shape",
ValidatorChecksWhatTheSchemaCannot => "tracking:the-validator-checks-what-the-schema-cannot",
ExistingDocumentConvertsWhenEdited => "writing-style:an-existing-document-converts-when-edited",
NoDeliveredGateJudgesProse => "writing-style:no-delivered-gate-judges-prose",
SourcesNameTheRevisionRead => "writing-style:sources-name-the-revision-read",
DocumentationBlockRoutesToTheStyle => "writing-style:the-documentation-block-routes-to-the-style",
StyleLivesInOneDocument => "writing-style:the-style-lives-in-one-document",
NoneImposesNoObligation => "writing-policy:none-imposes-no-obligation",
ProjectSelectsOneSource => "writing-policy:the-project-selects-one-source",
}
impl fmt::Display for RuleId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugs_are_well_formed_and_unique() {
let mut seen = std::collections::BTreeSet::new();
for rule in RuleId::ALL {
let id = rule.as_str();
let (domain, name) = id.split_once(':').unwrap();
let assert_slug = |part: &str| {
assert!(!part.is_empty(), "{id} has an empty half");
assert!(
part.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'),
"{id} is not a slug pair"
);
};
assert_slug(domain);
assert_slug(name);
assert!(seen.insert(id), "{id} is duplicated");
}
}
#[test]
fn display_renders_the_slug_pair() {
assert_eq!(
RuleId::ChapterStaysWithinLineCap.to_string(),
"docs-format:chapter-stays-within-200-lines"
);
}
}