1use std::io::Read;
15use std::path::Path;
16
17use fallow_types::flag_retirement::{
18 FlagSiteRole, RetirementEvidence, RetirementFlag, RetirementFlagKind, RetirementReason,
19 RetirementVendor, RetirementVendorState, VendorFlagState,
20};
21use rustc_hash::{FxHashMap, FxHashSet};
22use serde::Deserialize;
23
24const FLAG_STATE_SCHEMA_VERSION: u32 = 1;
26
27pub const MAX_FLAG_STATE_BYTES: u64 = 16 * 1024 * 1024;
29
30pub const STALE_EXPORT_DAYS: u64 = 30;
32
33const SECS_PER_DAY: u64 = 86_400;
35
36const FLAG_STATE_HELP: &str = "See https://fallow.tools/docs/cli/flags/#vendor-flag-state for the schema and a jq recipe for each vendor.";
38
39#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct FlagStateError {
42 pub message: String,
44 pub help: &'static str,
46}
47
48impl FlagStateError {
49 fn new(message: impl Into<String>) -> Self {
50 Self {
51 message: message.into(),
52 help: FLAG_STATE_HELP,
53 }
54 }
55}
56
57#[derive(Debug, Deserialize)]
58#[serde(deny_unknown_fields)]
59struct FlagStateFile {
60 schema_version: u32,
61 source: String,
62 exported_at: String,
63 flags: Vec<FlagStateEntry>,
64}
65
66#[derive(Debug, Deserialize)]
67#[serde(deny_unknown_fields)]
68struct FlagStateEntry {
69 key: String,
70 state: VendorFlagState,
71 #[serde(default)]
72 serves_single_variation: Option<bool>,
73 #[serde(default)]
74 created_at: Option<String>,
75 #[serde(default)]
76 last_evaluated_at: Option<String>,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct VendorFlag {
82 pub state: RetirementVendor,
84 pub line: u32,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct VendorExport {
91 pub source: String,
93 pub exported_at: String,
95 pub display_path: String,
98 pub flags: Vec<VendorFlag>,
100}
101
102pub fn load_flag_state(path: &Path, root: &Path) -> Result<VendorExport, FlagStateError> {
109 let file = std::fs::File::open(path).map_err(|error| {
110 FlagStateError::new(format!(
111 "cannot read the flag state file {}: {error}",
112 path.display()
113 ))
114 })?;
115 let mut bytes = Vec::new();
116 file.take(MAX_FLAG_STATE_BYTES + 1)
117 .read_to_end(&mut bytes)
118 .map_err(|error| {
119 FlagStateError::new(format!(
120 "cannot read the flag state file {}: {error}",
121 path.display()
122 ))
123 })?;
124 if bytes.len() as u64 > MAX_FLAG_STATE_BYTES {
125 return Err(FlagStateError::new(format!(
126 "the flag state file {} is larger than {} MiB",
127 path.display(),
128 MAX_FLAG_STATE_BYTES / (1024 * 1024)
129 )));
130 }
131 parse_flag_state(&bytes, display_path(path, root))
132}
133
134fn display_path(path: &Path, root: &Path) -> String {
140 let canonical_path = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
141 let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
142 let shown = match canonical_path.strip_prefix(&canonical_root) {
143 Ok(relative) => relative.to_path_buf(),
144 Err(_) => canonical_path
145 .file_name()
146 .map_or_else(|| path.to_path_buf(), std::path::PathBuf::from),
147 };
148 shown.to_string_lossy().replace('\\', "/")
149}
150
151fn parse_flag_state(bytes: &[u8], display_path: String) -> Result<VendorExport, FlagStateError> {
159 let text = std::str::from_utf8(bytes)
160 .map_err(|_| FlagStateError::new(format!("{display_path} is not UTF-8 text")))?;
161 let file: FlagStateFile = serde_json::from_str(text)
162 .map_err(|error| FlagStateError::new(format!("{display_path} is not valid: {error}")))?;
163 if file.schema_version != FLAG_STATE_SCHEMA_VERSION {
164 return Err(FlagStateError::new(format!(
165 "{display_path} has schema_version {}, but this build reads schema_version {FLAG_STATE_SCHEMA_VERSION}",
166 file.schema_version
167 )));
168 }
169 if file.source.trim().is_empty() {
170 return Err(FlagStateError::new(format!(
171 "{display_path} has an empty source"
172 )));
173 }
174 if date_epoch(&file.exported_at).is_none() {
175 return Err(FlagStateError::new(format!(
176 "{display_path} has exported_at {:?}, which does not start with a YYYY-MM-DD date",
177 file.exported_at
178 )));
179 }
180 let lines = key_lines(text);
181 let mut seen: FxHashSet<&str> = FxHashSet::default();
182 for entry in &file.flags {
183 if entry.key.is_empty() {
184 return Err(FlagStateError::new(format!(
185 "{display_path} has a flag with an empty key"
186 )));
187 }
188 if !seen.insert(entry.key.as_str()) {
189 return Err(FlagStateError::new(format!(
190 "{display_path} has the key {:?} more than one time",
191 entry.key
192 )));
193 }
194 }
195 let flags = file
196 .flags
197 .into_iter()
198 .map(|entry| VendorFlag {
199 line: lines.get(entry.key.as_str()).copied().unwrap_or(1),
200 state: RetirementVendor {
201 key: entry.key,
202 state: entry.state,
203 serves_single_variation: entry.serves_single_variation,
204 created_at: entry.created_at,
205 last_evaluated_at: entry.last_evaluated_at,
206 },
207 })
208 .collect();
209 Ok(VendorExport {
210 source: file.source,
211 exported_at: file.exported_at,
212 display_path,
213 flags,
214 })
215}
216
217fn key_lines(text: &str) -> FxHashMap<String, u32> {
219 const KEY_TOKEN: &str = "\"key\"";
220 let mut lines = FxHashMap::default();
221 let mut from = 0;
222 while let Some(offset) = text[from..].find(KEY_TOKEN) {
223 let start = from + offset;
224 from = start + KEY_TOKEN.len();
225 let rest = text[from..].trim_start();
226 let Some(value) = rest.strip_prefix(':') else {
227 continue;
228 };
229 let mut values =
230 serde_json::Deserializer::from_str(value.trim_start()).into_iter::<String>();
231 let Some(Ok(key)) = values.next() else {
232 continue;
233 };
234 let line = u32::try_from(text[..start].matches('\n').count() + 1).unwrap_or(u32::MAX);
235 lines.entry(key).or_insert(line);
236 }
237 lines
238}
239
240fn date_epoch(text: &str) -> Option<u64> {
242 crate::clock::utc_midnight_epoch(text.get(..10)?)
243}
244
245pub(crate) type SiteLocation = (String, u32, u32);
247
248pub struct VendorMatch<'a> {
250 pub export: &'a VendorExport,
252 pub key_prefix: Option<&'a str>,
255 pub code_flag_names: &'a FxHashSet<String>,
257 pub project_sdk_labels: &'a FxHashSet<String>,
260 pub hidden_sdk_labels: &'a FxHashMap<SiteLocation, String>,
263 pub add_vendor_only: bool,
266 pub clock_epoch_secs: u64,
268}
269
270pub(crate) fn apply_vendor_state(
280 rows: &mut Vec<RetirementFlag>,
281 input: &VendorMatch<'_>,
282) -> RetirementVendorState {
283 let export = input.export;
284 let by_name: FxHashMap<&str, &VendorFlag> = export
285 .flags
286 .iter()
287 .map(|flag| (code_name(&flag.state.key, input.key_prefix), flag))
288 .collect();
289 let source = normalize_label(&export.source);
290 let source_is_project_sdk = input
291 .project_sdk_labels
292 .iter()
293 .any(|sdk| label_matches_source(sdk, &source));
294 for row in rows.iter_mut() {
295 if row.kind != RetirementFlagKind::SdkCall
296 || (source_is_project_sdk && !row_matches_source(row, &source, input.hidden_sdk_labels))
297 {
298 continue;
299 }
300 match by_name.get(row.flag_name.as_str()) {
301 Some(flag) => add_state_reasons(row, flag, export),
302 None => add_missing_reason(row, export),
303 }
304 }
305 if input.add_vendor_only {
306 for flag in &export.flags {
307 let name = code_name(&flag.state.key, input.key_prefix);
308 if !input.code_flag_names.contains(name) {
309 rows.push(vendor_only_row(name, flag, export));
310 }
311 }
312 }
313 RetirementVendorState {
314 source: export.source.clone(),
315 exported_at: export.exported_at.clone(),
316 export_age_days: date_epoch(&export.exported_at)
317 .map(|epoch| input.clock_epoch_secs.saturating_sub(epoch) / SECS_PER_DAY),
318 flags: export.flags.len(),
319 }
320}
321
322fn code_name<'k>(key: &'k str, prefix: Option<&str>) -> &'k str {
324 prefix
325 .filter(|prefix| !prefix.is_empty())
326 .and_then(|prefix| key.strip_prefix(prefix))
327 .filter(|name| !name.is_empty())
328 .unwrap_or(key)
329}
330
331fn normalize_label(label: &str) -> String {
334 label
335 .chars()
336 .filter(char::is_ascii_alphanumeric)
337 .map(|c| c.to_ascii_lowercase())
338 .collect()
339}
340
341fn row_matches_source(
345 row: &RetirementFlag,
346 source: &str,
347 hidden: &FxHashMap<SiteLocation, String>,
348) -> bool {
349 if let Some(sdk) = row.sdk_name.as_deref() {
350 return label_matches_source(sdk, source);
351 }
352 row.sites.iter().any(|site| {
353 hidden
354 .get(&(site.path.clone(), site.line, site.col))
355 .is_none_or(|sdk| label_matches_source(sdk, source))
356 })
357}
358
359fn label_matches_source(sdk: &str, source: &str) -> bool {
362 if source.is_empty() {
363 return false;
364 }
365 let sdk = normalize_label(sdk);
366 !sdk.is_empty() && (sdk.starts_with(source) || source.starts_with(&sdk))
367}
368
369fn evidence_site(row: &RetirementFlag) -> Option<(String, u32)> {
372 row.sites
373 .iter()
374 .find(|site| site.role == FlagSiteRole::Read)
375 .or_else(|| row.sites.first())
376 .map(|site| (site.path.clone(), site.line))
377}
378
379fn add_state_reasons(row: &mut RetirementFlag, flag: &VendorFlag, export: &VendorExport) {
380 row.vendor = Some(flag.state.clone());
381 let Some((path, line)) = evidence_site(row) else {
382 return;
383 };
384 let state = &flag.state;
385 let single = state.serves_single_variation == Some(true);
386 if state.state == VendorFlagState::RolledOut || single {
387 let mut detail = format!("{} state {}", export.source, state_code(state.state));
388 if single {
389 detail.push_str(", serves one variation");
390 }
391 push_reason(row, RetirementReason::FullyRolledOut, &path, line, detail);
392 }
393 if state.state == VendorFlagState::Archived {
394 let detail = format!("{} state archived", export.source);
395 push_reason(row, RetirementReason::ArchivedInVendor, &path, line, detail);
396 }
397}
398
399fn add_missing_reason(row: &mut RetirementFlag, export: &VendorExport) {
400 let Some((path, line)) = evidence_site(row) else {
401 return;
402 };
403 let detail = format!(
404 "the key is not in the {} export ({})",
405 export.source, export.display_path
406 );
407 push_reason(row, RetirementReason::MissingInVendor, &path, line, detail);
408}
409
410fn push_reason(
411 row: &mut RetirementFlag,
412 reason: RetirementReason,
413 path: &str,
414 line: u32,
415 detail: String,
416) {
417 if !row.reasons.contains(&reason) {
418 row.reasons.push(reason);
419 }
420 row.evidence.push(RetirementEvidence {
421 reason,
422 path: path.to_string(),
423 line,
424 detail,
425 });
426}
427
428fn vendor_only_row(name: &str, flag: &VendorFlag, export: &VendorExport) -> RetirementFlag {
429 RetirementFlag {
430 flag_name: name.to_string(),
431 kind: RetirementFlagKind::VendorExport,
432 sdk_name: None,
433 workspace: None,
434 sites: Vec::new(),
435 read_sites: 0,
436 test_only: false,
437 first_seen: None,
438 oldest_surviving_site: None,
439 last_touched: None,
440 age_days: None,
441 reasons: vec![RetirementReason::VendorOnly],
442 evidence: vec![RetirementEvidence {
443 reason: RetirementReason::VendorOnly,
444 path: export.display_path.clone(),
445 line: flag.line,
446 detail: format!(
447 "the key is in the {} export, but no code reads it",
448 export.source
449 ),
450 }],
451 actions: Vec::new(),
452 vendor: Some(flag.state.clone()),
453 }
454}
455
456const fn state_code(state: VendorFlagState) -> &'static str {
457 match state {
458 VendorFlagState::On => "on",
459 VendorFlagState::Off => "off",
460 VendorFlagState::RolledOut => "rolled_out",
461 VendorFlagState::Archived => "archived",
462 VendorFlagState::Experiment => "experiment",
463 }
464}
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469 use fallow_types::flag_retirement::RetirementSite;
470
471 const EXPORT: &str = r#"{
472 "schema_version": 1,
473 "source": "launchdarkly",
474 "exported_at": "2026-09-20T00:00:00Z",
475 "flags": [
476 { "key": "web.rolled", "state": "rolled_out" },
477 { "key": "web.single", "state": "off", "serves_single_variation": true },
478 { "key": "web.archived", "state": "archived" },
479 { "key": "web.live", "state": "on", "serves_single_variation": false },
480 { "key": "web.orphan", "state": "on" }
481 ]
482}"#;
483
484 const CLOCK: u64 = 1_790_294_400;
486
487 fn export() -> VendorExport {
488 parse_flag_state(EXPORT.as_bytes(), "flag-state.json".to_string()).expect("valid export")
489 }
490
491 fn sdk_row(name: &str, sdk: Option<&str>) -> RetirementFlag {
492 RetirementFlag {
493 flag_name: name.to_string(),
494 kind: RetirementFlagKind::SdkCall,
495 sdk_name: sdk.map(str::to_string),
496 workspace: None,
497 sites: vec![RetirementSite {
498 path: "src/app.ts".to_string(),
499 line: 3,
500 col: 2,
501 role: FlagSiteRole::Read,
502 in_test: false,
503 }],
504 read_sites: 1,
505 test_only: false,
506 first_seen: None,
507 oldest_surviving_site: None,
508 last_touched: None,
509 age_days: None,
510 reasons: Vec::new(),
511 evidence: Vec::new(),
512 actions: Vec::new(),
513 vendor: None,
514 }
515 }
516
517 fn apply(rows: &mut Vec<RetirementFlag>, add_vendor_only: bool) -> RetirementVendorState {
518 let labels: FxHashSet<String> =
519 rows.iter().filter_map(|row| row.sdk_name.clone()).collect();
520 apply_with_labels(rows, add_vendor_only, &labels)
521 }
522
523 fn apply_with_labels(
524 rows: &mut Vec<RetirementFlag>,
525 add_vendor_only: bool,
526 labels: &FxHashSet<String>,
527 ) -> RetirementVendorState {
528 let export = export();
529 let names: FxHashSet<String> = rows.iter().map(|row| row.flag_name.clone()).collect();
530 apply_vendor_state(
531 rows,
532 &VendorMatch {
533 export: &export,
534 key_prefix: Some("web."),
535 code_flag_names: &names,
536 project_sdk_labels: labels,
537 hidden_sdk_labels: &FxHashMap::default(),
538 add_vendor_only,
539 clock_epoch_secs: CLOCK,
540 },
541 )
542 }
543
544 fn reasons_of<'r>(rows: &'r [RetirementFlag], name: &str) -> &'r [RetirementReason] {
545 &rows
546 .iter()
547 .find(|row| row.flag_name == name)
548 .unwrap_or_else(|| panic!("no row {name}"))
549 .reasons
550 }
551
552 #[test]
553 fn vendor_states_give_the_vendor_reasons() {
554 let mut rows = vec![
555 sdk_row("rolled", Some("LaunchDarkly")),
556 sdk_row("single", Some("LaunchDarkly")),
557 sdk_row("archived", Some("LaunchDarkly")),
558 sdk_row("live", Some("LaunchDarkly")),
559 sdk_row("typo", Some("LaunchDarkly")),
560 ];
561 let state = apply(&mut rows, true);
562 assert_eq!(
563 reasons_of(&rows, "rolled"),
564 [RetirementReason::FullyRolledOut]
565 );
566 assert_eq!(
567 reasons_of(&rows, "single"),
568 [RetirementReason::FullyRolledOut]
569 );
570 assert_eq!(
571 reasons_of(&rows, "archived"),
572 [RetirementReason::ArchivedInVendor]
573 );
574 assert!(reasons_of(&rows, "live").is_empty());
575 assert_eq!(
576 reasons_of(&rows, "typo"),
577 [RetirementReason::MissingInVendor]
578 );
579 assert_eq!(reasons_of(&rows, "orphan"), [RetirementReason::VendorOnly]);
580
581 let single = rows
582 .iter()
583 .find(|row| row.flag_name == "single")
584 .expect("row");
585 assert_eq!(
586 single.evidence[0].detail,
587 "launchdarkly state off, serves one variation"
588 );
589 assert_eq!(
590 single.vendor.as_ref().map(|v| v.key.as_str()),
591 Some("web.single")
592 );
593
594 let orphan = rows
595 .iter()
596 .find(|row| row.flag_name == "orphan")
597 .expect("row");
598 assert_eq!(orphan.kind, RetirementFlagKind::VendorExport);
599 assert!(orphan.sites.is_empty());
600 assert_eq!(orphan.evidence[0].path, "flag-state.json");
601 assert_eq!(orphan.evidence[0].line, 10, "the line of the orphan key");
602
603 assert_eq!(state.source, "launchdarkly");
604 assert_eq!(state.flags, 5);
605 assert_eq!(state.export_age_days, Some(5));
606 }
607
608 #[test]
609 fn a_narrowed_run_adds_no_vendor_only_rows() {
610 let mut rows = vec![sdk_row("rolled", Some("LaunchDarkly"))];
611 apply(&mut rows, false);
612 assert_eq!(rows.len(), 1);
613 }
614
615 #[test]
616 fn a_key_that_the_code_reads_under_another_kind_is_not_vendor_only() {
617 let mut rows = vec![RetirementFlag {
618 kind: RetirementFlagKind::EnvironmentVariable,
619 ..sdk_row("orphan", None)
620 }];
621 apply(&mut rows, true);
622 assert_eq!(
623 rows.len(),
624 1 + 4,
625 "the env row and four keys that no code reads"
626 );
627 assert!(
628 reasons_of(&rows, "orphan").is_empty(),
629 "an env row never matches the export"
630 );
631 }
632
633 #[test]
634 fn an_export_of_one_vendor_leaves_other_sdks_alone() {
635 let mut rows = vec![
636 sdk_row("typo", Some("LaunchDarkly")),
637 sdk_row("other", Some("Statsig")),
638 sdk_row("custom", None),
639 ];
640 apply(&mut rows, false);
641 assert_eq!(
642 reasons_of(&rows, "typo"),
643 [RetirementReason::MissingInVendor]
644 );
645 assert!(reasons_of(&rows, "other").is_empty());
646 assert_eq!(
647 reasons_of(&rows, "custom"),
648 [RetirementReason::MissingInVendor],
649 "an SDK row without a label can belong to the vendor"
650 );
651 }
652
653 #[test]
654 fn a_row_without_a_name_uses_the_default_provider_of_its_calls() {
655 let mut hidden_row = sdk_row("hidden", None);
659 hidden_row.sites[0].line = 7;
660 let mut mixed_row = sdk_row("mixed", None);
661 mixed_row.sites[0].line = 8;
662 let mut second = mixed_row.sites[0].clone();
663 second.line = 9;
664 mixed_row.sites.push(second);
665 let mut rows = vec![hidden_row, mixed_row];
666 let hidden: FxHashMap<SiteLocation, String> = [
667 (("src/app.ts".to_string(), 7, 2), "Statsig".to_string()),
668 (("src/app.ts".to_string(), 8, 2), "Statsig".to_string()),
669 (("src/app.ts".to_string(), 9, 2), "LaunchDarkly".to_string()),
670 ]
671 .into_iter()
672 .collect();
673 let labels: FxHashSet<String> = ["Statsig", "LaunchDarkly"]
674 .into_iter()
675 .map(str::to_string)
676 .collect();
677 let export = export();
678 let names: FxHashSet<String> = rows.iter().map(|row| row.flag_name.clone()).collect();
679 apply_vendor_state(
680 &mut rows,
681 &VendorMatch {
682 export: &export,
683 key_prefix: Some("web."),
684 code_flag_names: &names,
685 project_sdk_labels: &labels,
686 hidden_sdk_labels: &hidden,
687 add_vendor_only: false,
688 clock_epoch_secs: CLOCK,
689 },
690 );
691 assert!(reasons_of(&rows, "hidden").is_empty());
692 assert_eq!(
693 reasons_of(&rows, "mixed"),
694 [RetirementReason::MissingInVendor]
695 );
696 }
697
698 #[test]
699 fn a_narrowed_run_reads_the_sdk_labels_of_the_whole_project() {
700 let mut rows = vec![sdk_row("other", Some("Statsig"))];
703 let labels: FxHashSet<String> = ["Statsig", "LaunchDarkly"]
704 .into_iter()
705 .map(str::to_string)
706 .collect();
707 apply_with_labels(&mut rows, false, &labels);
708 assert!(
709 reasons_of(&rows, "other").is_empty(),
710 "{:?}",
711 rows[0].reasons
712 );
713 }
714
715 #[test]
716 fn an_export_of_an_unknown_vendor_matches_every_sdk_row() {
717 let mut rows = vec![sdk_row("typo", Some("Statsig"))];
718 let export = parse_flag_state(
719 br#"{"schema_version":1,"source":"in-house","exported_at":"2026-09-20","flags":[]}"#,
720 "state.json".to_string(),
721 )
722 .expect("valid");
723 apply_vendor_state(
724 &mut rows,
725 &VendorMatch {
726 export: &export,
727 key_prefix: None,
728 code_flag_names: &FxHashSet::default(),
729 project_sdk_labels: &std::iter::once("Statsig".to_string()).collect(),
730 hidden_sdk_labels: &FxHashMap::default(),
731 add_vendor_only: true,
732 clock_epoch_secs: CLOCK,
733 },
734 );
735 assert_eq!(
736 reasons_of(&rows, "typo"),
737 [RetirementReason::MissingInVendor]
738 );
739 }
740
741 #[test]
742 fn invalid_exports_are_rejected() {
743 let cases: [(&str, &str); 6] = [
744 ("not json", "is not valid"),
745 (
746 r#"{"schema_version":2,"source":"x","exported_at":"2026-01-01","flags":[]}"#,
747 "schema_version 2",
748 ),
749 (
750 r#"{"schema_version":1,"source":"x","exported_at":"yesterday","flags":[]}"#,
751 "YYYY-MM-DD",
752 ),
753 (
754 r#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"a","state":"paused"}]}"#,
755 "unknown variant",
756 ),
757 (
758 r#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"a","state":"on"},{"key":"a","state":"off"}]}"#,
759 "more than one time",
760 ),
761 (
762 r#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"a","state":"on","enabled":true}]}"#,
763 "unknown field",
764 ),
765 ];
766 for (input, expected) in cases {
767 let error =
768 parse_flag_state(input.as_bytes(), "state.json".to_string()).expect_err(input);
769 assert!(
770 error.message.contains(expected),
771 "{input}: {}",
772 error.message
773 );
774 }
775 }
776
777 #[test]
778 fn an_oversized_export_is_rejected_before_parse() {
779 let dir = tempfile::tempdir().expect("temp dir");
780 let path = dir.path().join("state.json");
781 let file = std::fs::File::create(&path).expect("create");
782 file.set_len(MAX_FLAG_STATE_BYTES + 1).expect("grow");
783 let error = load_flag_state(&path, dir.path()).expect_err("too large");
784 assert!(
785 error.message.contains("larger than 16 MiB"),
786 "{}",
787 error.message
788 );
789 }
790
791 #[test]
792 fn the_display_path_is_relative_to_the_root_only_inside_it() {
793 let dir = tempfile::tempdir().expect("temp dir");
794 let inside = dir.path().join("state.json");
795 std::fs::write(&inside, "{}").expect("write");
796 assert_eq!(display_path(&inside, dir.path()), "state.json");
797 let other = tempfile::tempdir().expect("temp dir");
798 let outside = other.path().join("state.json");
799 std::fs::write(&outside, "{}").expect("write");
800 assert_eq!(
801 display_path(&outside, dir.path()),
802 "state.json",
803 "a file outside the root shows its file name only"
804 );
805 }
806
807 #[test]
808 fn a_prefix_that_is_the_whole_key_keeps_the_key() {
809 assert_eq!(code_name("web.", Some("web.")), "web.");
810 assert_eq!(code_name("web.a", Some("")), "web.a");
811 assert_eq!(code_name("app.a", Some("web.")), "app.a");
812 }
813}