返回 CodeWhale
feature_registry.rs
根目录 / crates / tui / tests / feature_registry.rs
1 //! Cross-checks `docs/features.toml` (the hand-edited feature registry)
2 //! against the code, and fails on drift.
3 //!
4 //! Checked here: every `[features]` flag in `features.rs` is owned by exactly
5 //! one row, a flag row's status follows the flag's stage and default, and
6 //! every `docs`/`owner` path exists. Not checked yet: slash-command ownership
7 //! and generated docs (later slices of the registry design).
8
9 use std::collections::{BTreeMap, BTreeSet};
10 use std::path::{Path, PathBuf};
11
12 use codewhale_runtime::features::{FEATURES, FeatureSpec, Stage};
13 use serde::Deserialize;
14
15 const STATUSES: &[&str] = &["stable", "experimental", "flagged", "planned"];
16 const SURFACES: &[&str] = &["tui", "desktop", "web", "api"];
17 const SURFACE_STATUSES: &[&str] = &["stable", "preview", "partial", "none", "planned"];
18
19 #[derive(Debug, Deserialize)]
20 #[serde(deny_unknown_fields)]
21 struct Registry {
22 feature: Vec<Row>,
23 }
24
25 #[derive(Debug, Deserialize)]
26 #[serde(deny_unknown_fields)]
27 struct Row {
28 id: String,
29 name: String,
30 summary: String,
31 status: String,
32 #[serde(default)]
33 surfaces: BTreeMap<String, String>,
34 since: Option<String>,
35 flag: Option<String>,
36 docs: Option<String>,
37 owner: Option<String>,
38 }
39
40 fn repo_root() -> PathBuf {
41 Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
42 }
43
44 #[cfg(test)]
45 fn read(root: &Path, rel: &str) -> String {
46 std::fs::read_to_string(root.join(rel)).unwrap_or_else(|err| panic!("read {rel}: {err}"))
47 }
48
49 /// Versions with a `## [x.y.z]` heading in the changelogs.
50 fn released_versions(root: &Path) -> BTreeSet<String> {
51 ["CHANGELOG.md", "docs/CHANGELOG_ARCHIVE.md"]
52 .iter()
53 .flat_map(|file| {
54 read(root, file)
55 .lines()
56 .filter_map(|line| line.strip_prefix("## ["))
57 .filter_map(|rest| rest.split(']').next())
58 .map(str::to_string)
59 .collect::<Vec<_>>()
60 })
61 .collect()
62 }
63
64 /// The registry status a flag implies: off by default is `flagged`; on by
65 /// default is `stable` for Stable flags and `experimental` otherwise.
66 fn status_for_flag(spec: &FeatureSpec) -> &'static str {
67 match (spec.default_enabled, spec.stage) {
68 (false, _) => "flagged",
69 (true, Stage::Stable) => "stable",
70 (true, Stage::Experimental | Stage::Beta) => "experimental",
71 }
72 }
73
74 fn is_kebab(id: &str) -> bool {
75 !id.is_empty()
76 && id.starts_with(|c: char| c.is_ascii_lowercase())
77 && !id.ends_with('-')
78 && !id.contains("--")
79 && id
80 .chars()
81 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
82 }
83
84 fn check(root: &Path, registry: &Registry) -> Vec<String> {
85 let mut errors = Vec::new();
86 let versions = released_versions(root);
87 let mut ids = BTreeSet::new();
88 let mut flag_owners: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
89
90 for row in &registry.feature {
91 let id = row.id.as_str();
92 let mut err = |msg: String| errors.push(format!("{id}: {msg}"));
93
94 if !is_kebab(id) {
95 err("id must be kebab-case".into());
96 }
97 if !ids.insert(id) {
98 err("duplicate id".into());
99 }
100 if row.name.trim().is_empty() {
101 err("name is empty".into());
102 }
103 let summary_len = row.summary.chars().count();
104 if row.summary.trim().is_empty() || summary_len > 120 || row.summary.contains('\n') {
105 err(format!(
106 "summary must be one line of 1-120 characters (has {summary_len})"
107 ));
108 }
109 if !STATUSES.contains(&row.status.as_str()) {
110 err(format!(
111 "status {:?} is not one of {STATUSES:?}",
112 row.status
113 ));
114 }
115 for (surface, value) in &row.surfaces {
116 if !SURFACES.contains(&surface.as_str()) {
117 err(format!(
118 "unknown surface {surface:?}; expected one of {SURFACES:?}"
119 ));
120 }
121 if !SURFACE_STATUSES.contains(&value.as_str()) {
122 err(format!(
123 "surface {surface} = {value:?} is not one of {SURFACE_STATUSES:?}"
124 ));
125 }
126 }
127 if row.status == "planned" && (row.since.is_some() || row.flag.is_some()) {
128 err("a planned row cannot have `since` or `flag`".into());
129 }
130 if let Some(since) = &row.since
131 && since != "unreleased"
132 && !versions.contains(since)
133 {
134 err(format!(
135 "since = {since:?} is neither \"unreleased\" nor a CHANGELOG heading"
136 ));
137 }
138 if let Some(flag) = &row.flag {
139 flag_owners.entry(flag.as_str()).or_default().push(id);
140 match FEATURES.iter().find(|spec| spec.key == flag) {
141 None => err(format!(
142 "flag {flag:?} is not a key in features.rs FEATURES"
143 )),
144 Some(spec) => {
145 let want = status_for_flag(spec);
146 if row.status != want {
147 err(format!(
148 "status {:?} disagrees with flag {flag} (stage {}, default {}): expected {want:?}",
149 row.status,
150 spec.stage,
151 if spec.default_enabled { "on" } else { "off" },
152 ));
153 }
154 }
155 }
156 }
157 if let Some(docs) = &row.docs {
158 let file = docs.split('#').next().unwrap_or_default();
159 if !root.join(file).exists() {
160 err(format!("docs path {file} does not exist"));
161 }
162 }
163 match &row.owner {
164 Some(owner) if !root.join(owner).exists() => {
165 err(format!("owner path {owner} does not exist"));
166 }
167 None if row.status != "planned" => err("a shipped row needs an `owner`".into()),
168 _ => {}
169 }
170 }
171
172 for spec in FEATURES {
173 match flag_owners.get(spec.key).map(Vec::as_slice) {
174 None | Some([]) => errors.push(format!(
175 "flag {} in features.rs has no row in docs/features.toml",
176 spec.key
177 )),
178 Some([_]) => {}
179 Some(many) => errors.push(format!(
180 "flag {} is claimed by several rows: {}",
181 spec.key,
182 many.join(", ")
183 )),
184 }
185 }
186 errors
187 }
188
189 #[test]
190 fn feature_registry_matches_code() {
191 let root = repo_root();
192 let registry: Registry = toml::from_str(&read(&root, "docs/features.toml"))
193 .unwrap_or_else(|err| panic!("docs/features.toml does not parse: {err}"));
194 assert!(
195 !registry.feature.is_empty(),
196 "docs/features.toml has no rows"
197 );
198
199 let errors = check(&root, &registry);
200 assert!(
201 errors.is_empty(),
202 "docs/features.toml has drifted from the code ({} problem(s)); fix the row or the code:\n {}",
203 errors.len(),
204 errors.join("\n ")
205 );
206 }
207
208 #[test]
209 fn feature_registry_checks_catch_drift() {
210 let root = repo_root();
211 let registry: Registry = toml::from_str(
212 r#"
213 [[feature]]
214 id = "Bad_Id"
215 name = "Wrong status"
216 summary = "The vision flag is off by default, so stable is wrong."
217 status = "stable"
218 surfaces = { phone = "stable" }
219 since = "99.0.0"
220 flag = "vision_model"
221 docs = "docs/NOPE.md#anchor"
222 owner = "crates/nope"
223
224 [[feature]]
225 id = "twice"
226 name = "Duplicate flag"
227 summary = "Claims the same flag again."
228 status = "flagged"
229 flag = "vision_model"
230 owner = "crates/tui"
231 "#,
232 )
233 .expect("fixture parses");
234
235 let errors = check(&root, &registry).join("\n");
236 for expected in [
237 "Bad_Id: id must be kebab-case",
238 "unknown surface \"phone\"",
239 "since = \"99.0.0\"",
240 "expected \"flagged\"",
241 "docs path docs/NOPE.md does not exist",
242 "owner path crates/nope does not exist",
243 "flag vision_model is claimed by several rows",
244 "flag shell_tool in features.rs has no row",
245 ] {
246 assert!(
247 errors.contains(expected),
248 "missing {expected:?} in:\n{errors}"
249 );
250 }
251 }
252
252 lines RUST