1use serde::Serialize;
4
5use crate::source_fingerprint::SourceFingerprint;
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
9#[serde(rename_all = "snake_case")]
10pub enum AuditContextPathState {
11 Missing,
13 Present,
15 Unreadable(String),
17}
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
21pub struct AuditContextFileFingerprint {
22 pub path: String,
24 pub state: AuditContextPathState,
26 pub source: Option<SourceFingerprint>,
28 pub content_hash: Option<String>,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
34pub struct AuditContextDirectoryFingerprint {
35 pub name: String,
37 pub state: AuditContextPathState,
39 pub canonical_path: Option<String>,
41 pub source: Option<SourceFingerprint>,
43 pub markers: Vec<AuditContextFileFingerprint>,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
49pub struct AuditMaterializedContextFingerprint {
50 pub lockfiles: Vec<AuditContextFileFingerprint>,
52 pub directories: Vec<AuditContextDirectoryFingerprint>,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
58pub struct AuditConfigFingerprint {
59 pub path: Option<String>,
61 pub resolved_hash: Option<String>,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
67pub struct AuditCoverageFingerprint {
68 pub path: String,
70 pub files: Vec<AuditCoverageFileFingerprint>,
73 #[serde(skip_serializing_if = "Option::is_none")]
75 pub error: Option<String>,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
80pub struct AuditCoverageFileFingerprint {
81 pub path: String,
83 #[serde(skip_serializing_if = "Option::is_none")]
85 pub source: Option<SourceFingerprint>,
86 #[serde(skip_serializing_if = "Option::is_none")]
88 pub content_hash: Option<String>,
89 #[serde(skip_serializing_if = "Option::is_none")]
91 pub len: Option<usize>,
92 #[serde(skip_serializing_if = "Option::is_none")]
94 pub error: Option<String>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
100pub struct AuditTypeAwareFingerprint {
101 pub projects: Vec<String>,
103 pub require: String,
105}
106
107#[derive(Debug, Clone, PartialEq, Serialize)]
109pub struct AuditCacheKeyPayload {
110 pub cache_version: u8,
112 pub cli_version: String,
114 pub base_sha: String,
116 pub config_file: AuditConfigFingerprint,
118 pub changed_files: Vec<String>,
120 pub materialized_context: AuditMaterializedContextFingerprint,
122 pub production: bool,
124 pub production_dead_code: Option<bool>,
126 pub production_health: Option<bool>,
128 pub production_dupes: Option<bool>,
130 pub workspace: Option<Vec<String>>,
132 pub changed_workspaces: Option<String>,
134 pub group_by: Option<String>,
136 pub include_entry_exports: bool,
138 pub show_cascade: bool,
140 pub brief: bool,
143 pub max_crap: Option<f64>,
145 pub coverage: Option<AuditCoverageFingerprint>,
147 pub coverage_root: Option<String>,
149 pub dead_code: bool,
151 pub health: bool,
153 pub dupes: bool,
155 pub architecture: String,
158 pub css: bool,
160 pub css_deep: bool,
162 #[serde(skip_serializing_if = "Option::is_none")]
165 pub type_aware_backend: Option<String>,
166 #[serde(skip_serializing_if = "Option::is_none")]
169 pub type_aware: Option<AuditTypeAwareFingerprint>,
170}
171
172#[derive(Debug, Clone)]
174pub struct AuditCacheKeyBuilder {
175 payload: AuditCacheKeyPayload,
176}
177
178impl AuditCacheKeyBuilder {
179 #[must_use]
181 pub fn new(
182 cache_version: u8,
183 cli_version: impl Into<String>,
184 base_sha: impl Into<String>,
185 config_file: AuditConfigFingerprint,
186 changed_files: Vec<String>,
187 materialized_context: AuditMaterializedContextFingerprint,
188 ) -> Self {
189 Self {
190 payload: AuditCacheKeyPayload {
191 cache_version,
192 cli_version: cli_version.into(),
193 base_sha: base_sha.into(),
194 config_file,
195 changed_files,
196 materialized_context,
197 production: false,
198 production_dead_code: None,
199 production_health: None,
200 production_dupes: None,
201 workspace: None,
202 changed_workspaces: None,
203 group_by: None,
204 include_entry_exports: false,
205 show_cascade: false,
206 brief: false,
207 max_crap: None,
208 coverage: None,
209 coverage_root: None,
210 dead_code: true,
211 health: true,
212 dupes: true,
213 architecture: "all".to_string(),
214 css: false,
215 css_deep: false,
216 type_aware_backend: None,
217 type_aware: None,
218 },
219 }
220 }
221
222 #[must_use]
224 pub const fn production(
225 mut self,
226 production: bool,
227 dead_code: Option<bool>,
228 health: Option<bool>,
229 dupes: Option<bool>,
230 ) -> Self {
231 self.payload.production = production;
232 self.payload.production_dead_code = dead_code;
233 self.payload.production_health = health;
234 self.payload.production_dupes = dupes;
235 self
236 }
237
238 #[must_use]
240 pub fn scope(
241 mut self,
242 workspace: Option<Vec<String>>,
243 changed_workspaces: Option<String>,
244 group_by: Option<String>,
245 include_entry_exports: bool,
246 ) -> Self {
247 self.payload.workspace = workspace;
248 self.payload.changed_workspaces = changed_workspaces;
249 self.payload.group_by = group_by;
250 self.payload.include_entry_exports = include_entry_exports;
251 self
252 }
253
254 #[must_use]
257 pub const fn show_cascade(mut self, show_cascade: bool) -> Self {
258 self.payload.show_cascade = show_cascade;
259 self
260 }
261
262 #[must_use]
264 pub const fn brief(mut self, brief: bool) -> Self {
265 self.payload.brief = brief;
266 self
267 }
268
269 #[must_use]
271 pub fn health(
272 mut self,
273 max_crap: Option<f64>,
274 coverage: Option<AuditCoverageFingerprint>,
275 coverage_root: Option<String>,
276 ) -> Self {
277 self.payload.max_crap = max_crap;
278 self.payload.coverage = coverage;
279 self.payload.coverage_root = coverage_root;
280 self
281 }
282
283 #[must_use]
286 pub fn analyses(
287 mut self,
288 dead_code: bool,
289 health: bool,
290 dupes: bool,
291 architecture: impl Into<String>,
292 ) -> Self {
293 self.payload.dead_code = dead_code;
294 self.payload.health = health;
295 self.payload.dupes = dupes;
296 self.payload.architecture = architecture.into();
297 self
298 }
299
300 #[must_use]
302 pub const fn styling(mut self, css: bool, css_deep: bool) -> Self {
303 self.payload.css = css;
304 self.payload.css_deep = css_deep;
305 self
306 }
307
308 #[must_use]
310 pub fn type_aware_backend(mut self, backend: Option<String>) -> Self {
311 self.payload.type_aware_backend = backend;
312 self
313 }
314
315 #[must_use]
317 pub fn type_aware(mut self, selection: Option<AuditTypeAwareFingerprint>) -> Self {
318 self.payload.type_aware = selection;
319 self
320 }
321
322 #[must_use]
324 pub const fn payload(&self) -> &AuditCacheKeyPayload {
325 &self.payload
326 }
327
328 pub fn to_json_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
334 serde_json::to_vec(&self.payload)
335 }
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 fn config() -> AuditConfigFingerprint {
343 AuditConfigFingerprint {
344 path: Some("fallow.toml".to_string()),
345 resolved_hash: Some("abc".to_string()),
346 }
347 }
348
349 fn context() -> AuditMaterializedContextFingerprint {
350 AuditMaterializedContextFingerprint {
351 lockfiles: Vec::new(),
352 directories: Vec::new(),
353 }
354 }
355
356 #[test]
357 fn audit_cache_key_builder_preserves_typed_fields() {
358 let coverage = AuditCoverageFingerprint {
359 path: "coverage".to_string(),
360 files: vec![AuditCoverageFileFingerprint {
361 path: "coverage/coverage-final.json".to_string(),
362 source: Some(SourceFingerprint::new(12, 34)),
363 content_hash: Some("hash".to_string()),
364 len: Some(34),
365 error: None,
366 }],
367 error: None,
368 };
369
370 let builder = AuditCacheKeyBuilder::new(
371 3,
372 "1.2.3",
373 "abc123",
374 config(),
375 vec!["src/a.ts".to_string()],
376 context(),
377 )
378 .production(true, Some(false), Some(true), None)
379 .scope(
380 Some(vec!["web".to_string()]),
381 Some("main".to_string()),
382 Some("Package".to_string()),
383 true,
384 )
385 .health(Some(42.0), Some(coverage), Some("/workspace".to_string()))
386 .styling(true, true);
387
388 let payload = builder.payload();
389 assert_eq!(payload.cache_version, 3);
390 assert_eq!(payload.base_sha, "abc123");
391 assert_eq!(payload.workspace.as_deref(), Some(&["web".to_string()][..]));
392 assert!(payload.include_entry_exports);
393 assert!(payload.css);
394 assert!(payload.css_deep);
395 assert_eq!(payload.coverage.as_ref().map(|c| c.files.len()), Some(1));
396 assert_eq!(
397 payload
398 .coverage
399 .as_ref()
400 .and_then(|c| c.files.first())
401 .and_then(|f| f.source),
402 Some(SourceFingerprint::new(12, 34))
403 );
404 }
405
406 #[test]
407 fn audit_cache_key_bytes_reflect_changed_file_order() {
408 let first = AuditCacheKeyBuilder::new(
409 1,
410 "1.0.0",
411 "base",
412 config(),
413 vec!["src/a.ts".to_string(), "src/b.ts".to_string()],
414 context(),
415 )
416 .to_json_bytes()
417 .expect("payload should serialize");
418 let second = AuditCacheKeyBuilder::new(
419 1,
420 "1.0.0",
421 "base",
422 config(),
423 vec!["src/b.ts".to_string(), "src/a.ts".to_string()],
424 context(),
425 )
426 .to_json_bytes()
427 .expect("payload should serialize");
428
429 assert_ne!(first, second);
430 }
431
432 #[test]
433 fn audit_cache_key_bytes_include_the_analysis_selection() {
434 let build = |dead_code, health, dupes, architecture: &str| {
435 AuditCacheKeyBuilder::new(
436 1,
437 "1.0.0",
438 "base",
439 config(),
440 vec!["src/a.ts".to_string()],
441 context(),
442 )
443 .analyses(dead_code, health, dupes, architecture)
444 .to_json_bytes()
445 .expect("payload should serialize")
446 };
447
448 let all = build(true, true, true, "all");
449 assert_ne!(all, build(false, true, true, "all"));
450 assert_ne!(all, build(true, false, true, "all"));
451 assert_ne!(all, build(true, true, false, "all"));
452 assert_ne!(all, build(true, true, true, "exclude"));
453 }
454
455 #[test]
456 fn audit_cache_key_bytes_include_only_a_selected_type_aware_backend() {
457 let build = |backend: Option<&str>| {
458 AuditCacheKeyBuilder::new(1, "1.0.0", "base", config(), Vec::new(), context())
459 .type_aware_backend(backend.map(str::to_string))
460 .to_json_bytes()
461 .expect("payload should serialize")
462 };
463
464 let default = build(None);
465 assert!(!String::from_utf8_lossy(&default).contains("type_aware_backend"));
466 assert_ne!(default, build(Some("tsrs")));
467 }
468
469 #[test]
470 fn audit_cache_key_bytes_include_only_an_enabled_type_aware_selection() {
471 let build = |selection: Option<AuditTypeAwareFingerprint>| {
472 AuditCacheKeyBuilder::new(1, "1.0.0", "base", config(), Vec::new(), context())
473 .type_aware(selection)
474 .to_json_bytes()
475 .expect("payload should serialize")
476 };
477 let selection = |projects: &[&str]| AuditTypeAwareFingerprint {
478 projects: projects.iter().map(|p| (*p).to_string()).collect(),
479 require: "BestEffort".to_string(),
480 };
481
482 let syntactic = build(None);
483 assert!(!String::from_utf8_lossy(&syntactic).contains("\"type_aware\""));
484 let default_projects = build(Some(selection(&[])));
485 assert_ne!(syntactic, default_projects);
486 assert_ne!(
487 default_projects,
488 build(Some(selection(&["tsconfig.app.json"])))
489 );
490 }
491
492 #[test]
493 fn audit_cache_key_bytes_include_materialized_context() {
494 let missing = context();
495 let present = AuditMaterializedContextFingerprint {
496 lockfiles: vec![AuditContextFileFingerprint {
497 path: "pnpm-lock.yaml".to_string(),
498 state: AuditContextPathState::Present,
499 source: Some(SourceFingerprint::new(1, 10)),
500 content_hash: Some("lock-hash".to_string()),
501 }],
502 directories: Vec::new(),
503 };
504 let build = |materialized_context| {
505 AuditCacheKeyBuilder::new(
506 5,
507 "1.0.0",
508 "base",
509 config(),
510 vec!["src/a.ts".to_string()],
511 materialized_context,
512 )
513 .to_json_bytes()
514 .expect("payload should serialize")
515 };
516
517 let missing_json = build(missing);
518 let present_json = build(present);
519
520 assert_ne!(missing_json, present_json);
521 assert!(
522 String::from_utf8(present_json)
523 .expect("utf8 json")
524 .contains("pnpm-lock.yaml")
525 );
526 }
527}