ferrotype 0.1.3

An opinionated wrapper for insta.rs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
#![doc = include_str!("../readme.md")]
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

/// Get the output directory for snapshots based on the configured feature.
///
/// Returns `.snapshots` when the `dot_snapshots` feature is enabled,
/// otherwise returns `snapshots`.
pub fn get_output_dir() -> &'static str {
  if cfg!(feature = "dot_snapshots") {
    ".snapshots"
  } else {
    "snapshots"
  }
}

/// A snapshot builder for creating structured test snapshots with [insta](https://insta.rs).
///
/// `Ferrotype` allows you to build up a snapshot consisting of multiple named
/// sections, each containing different types of content (debug output,
/// formatted code, hex dumps, etc.). The final snapshot can then be asserted
/// using the `ferrotype::assert!` macro.
///
/// # Examples
///
/// ```rust,no_run
/// use ferrotype::Ferrotype;
///
/// let mut snapshot = Ferrotype::new();
/// snapshot.add("Input", "Hello, world!".to_string());
/// snapshot.add_debug("Data", vec![1, 2, 3]);
/// ferrotype::assert!(snapshot);
/// ```
#[derive(Clone, Debug)]
pub struct Ferrotype<S: ?Sized = ()> {
  expect_errors: bool,

  filter_memory_addresses: bool,

  filter_uuids: bool,

  filter_type_ids: bool,

  filter_hashes: bool,

  // Vector of report sections
  sections: Vec<(
    // Heading
    String,
    // Body
    String,
  )>,

  // External state threaded into stateful bluegum sections. Boxed so the
  // snapshot stays `Sized` even when `S` is an unsized trait object (e.g.
  // `dyn SourceResolver`).
  state: Box<S>,
}

impl Ferrotype<()> {
  /// Create a new `Ferrotype` snapshot builder.
  ///
  /// Pair this with the `ferrotype::assert!` macro to generate a snapshot.
  ///
  /// ```rust,no_run
  /// use ferrotype::Ferrotype;
  ///
  /// let mut snapshot = Ferrotype::new();
  /// snapshot.add("Input", "Hello, world!".to_string());
  /// ferrotype::assert!(snapshot);
  /// ```
  pub fn new() -> Self {
    Self::new_with_state(Box::new(()))
  }
}

impl<S: ?Sized> Ferrotype<S> {
  /// Create a new `Ferrotype` snapshot builder carrying external `state`.
  ///
  /// The state is threaded into every node rendered by
  /// [`add_bluegum`](Self::add_bluegum), so stateful bluegum nodes can resolve
  /// external data (e.g. interned idents via a source resolver) while printing.
  ///
  /// `state` is boxed so it can be an unsized trait object, e.g.
  /// `Ferrotype::new_with_state(Box::new(reader) as Box<dyn SourceResolver>)`.
  pub fn new_with_state(state: Box<S>) -> Self {
    Self {
      expect_errors: false,
      filter_memory_addresses: true,
      filter_uuids: true,
      filter_type_ids: true,
      filter_hashes: true,
      sections: Vec::new(),
      state,
    }
  }

  /// Get whether this snapshot expects errors to occur.
  ///
  /// When `true`, the test is expected to have errors and they won't cause test
  /// failure.
  pub fn expects_errors(&mut self) -> bool {
    self.expect_errors
  }

  /// Set whether this snapshot expects errors to occur.
  ///
  /// When `true`, the test is expected to have errors and they won't cause test
  /// failure. Returns `self` for method chaining.
  pub fn set_expect_errors(&mut self, expect: bool) -> &mut Self {
    self.expect_errors = expect;
    self
  }

  /// Get whether memory addresses should be filtered from the snapshot.
  ///
  /// When `true`, memory addresses (like `0x7fff5fbff710`) are replaced with
  /// `[Redacted::Pointer]` to make snapshots deterministic across runs.
  pub fn filter_memory_addresses(&self) -> bool {
    self.filter_memory_addresses
  }

  /// Set whether memory addresses should be filtered from the snapshot.
  ///
  /// When `true`, memory addresses (like `0x7fff5fbff710`) are replaced with
  /// `[Redacted::Pointer]` to make snapshots deterministic across runs.
  /// Returns `self` for method chaining.
  pub fn set_filter_memory_addresses(&mut self, to: bool) -> &mut Self {
    self.filter_memory_addresses = to;
    self
  }

  /// Get whether UUIDs should be filtered from the snapshot.
  ///
  /// When `true`, UUIDs (like `550e8400-e29b-41d4-a716-446655440000`) are
  /// replaced with `[Redacted::UUID]` to make snapshots deterministic across
  /// runs.
  pub fn filter_uuids(&self) -> bool {
    self.filter_uuids
  }

  /// Set whether UUIDs should be filtered from the snapshot.
  ///
  /// When `true`, UUIDs (like `550e8400-e29b-41d4-a716-446655440000`) are
  /// replaced with `[Redacted::UUID]` to make snapshots deterministic across
  /// runs. Returns `self` for method chaining.
  pub fn set_filter_uuids(&mut self, to: bool) -> &mut Self {
    self.filter_uuids = to;
    self
  }

  /// Get whether TypeIds should be filtered from the snapshot.
  ///
  /// When `true`, TypeIds (like `TypeId { t: 12345 }`) are replaced with
  /// `[Redacted::TypeId]` to make snapshots deterministic across runs.
  pub fn filter_type_ids(&self) -> bool {
    self.filter_type_ids
  }

  /// Set whether TypeIds should be filtered from the snapshot.
  ///
  /// When `true`, TypeIds (like `TypeId { t: 12345 }`) are replaced with
  /// `[Redacted::TypeId]` to make snapshots deterministic across runs.
  /// Returns `self` for method chaining.
  pub fn set_filter_type_ids(&mut self, to: bool) -> &mut Self {
    self.filter_type_ids = to;
    self
  }

  /// Get whether hashes should be filtered from the snapshot.
  ///
  /// When `true`, hash values (like `hash: 12345,`) are replaced with
  /// `hash: [Redacted::Hash],` to make snapshots deterministic across runs.
  pub fn filter_hashes(&self) -> bool {
    self.filter_hashes
  }

  /// Set whether hashes should be filtered from the snapshot.
  ///
  /// When `true`, hash values (like `hash: 12345,`) are replaced with
  /// `hash: [Redacted::Hash],` to make snapshots deterministic across runs.
  /// Returns `self` for method chaining.
  pub fn set_filter_hashes(&mut self, to: bool) -> &mut Self {
    self.filter_hashes = to;
    self
  }

  /// Set filtering for all random IDs (memory addresses, UUIDs, etc.).
  ///
  /// This is a convenience method that enables filtering for:
  /// - Memory addresses (like `0x7fff5fbff710`)
  /// - UUIDs (like `550e8400-e29b-41d4-a716-446655440000`)
  /// - TypeIds (like `TypeId { t: 12345 }`)
  /// - Hash values (like `hash: 12345,`)
  /// - Any other random identifiers added in the future
  ///
  /// Returns `self` for method chaining.
  pub fn set_filter_random_ids(&mut self, to: bool) -> &mut Self {
    self.filter_memory_addresses = to;
    self.filter_uuids = to;
    self.filter_type_ids = to;
    self.filter_hashes = to;
    self
  }
}

impl Default for Ferrotype<()> {
  fn default() -> Self {
    Self::new()
  }
}

impl<S: ?Sized> Ferrotype<S> {
  /// Add a new section to the snapshot with the given title and body.
  pub fn add(&mut self, title: &str, body: String) {
    self.sections.push((title.to_owned(), body));
  }

  /// Add a new section to the snapshot with debug-formatted content.
  ///
  /// The body will be formatted using `{:#?}` (pretty-printed debug format).
  pub fn add_debug<T: std::fmt::Debug>(&mut self, title: &str, body: T) {
    self.sections.push((title.to_owned(), format!("{body:#?}")));
  }

  /// Format a title by converting snake_case to PascalCase.
  ///
  /// This is adapted from the paste crate to provide consistent title
  /// formatting. For example, "parse_result" becomes "ParseResult".
  fn format_title(title: &str) -> String {
    // adapted from the paste crate https://docs.rs/paste/latest/src/paste/segment.rs.html#195
    let mut acc = String::new();
    let mut prev = '_';
    for ch in title.chars() {
      if ch != '_' {
        if prev == '_' {
          for chu in ch.to_uppercase() {
            acc.push(chu);
          }
        } else if prev.is_uppercase() {
          for chl in ch.to_lowercase() {
            acc.push(chl);
          }
        } else {
          acc.push(ch);
        }
      }
      prev = ch;
    }

    acc
  }

  /// Convert the snapshot to its string representation.
  ///
  /// Each section is formatted with a title followed by indented content:
  /// ```text
  /// SectionTitle: >
  ///   section content
  ///   indented by 2 spaces
  /// ```
  pub fn as_string(&self) -> String {
    self
      .sections
      .iter()
      .map(|(title, body)| {
        format!(
          "{}: >\n{}",
          Self::format_title(title),
          // print the section with an indent
          body
            .lines()
            .map(|l| format!("  {l}"))
            .collect::<Vec<String>>()
            .join("\n")
        )
      })
      .collect::<Vec<String>>()
      .join("\n\n")
  }

  /// Print the snapshot content to stdout.
  ///
  /// This prints just the snapshot content without any headers or separators.
  /// For debugging purposes, consider using `print_stdout()` instead.
  pub fn print(&self) {
    println!("{}", self.as_string());
  }

  /// Print the snapshot to stdout with decorative headers.
  ///
  /// This prints the snapshot content surrounded by headers and footers
  /// to make it easily identifiable in test output.
  pub fn print_stdout(&self) {
    println!("====== Ferrotype Snapshot ======");
    println!("{}\n", self.as_string());
    println!("--------------------------------");
  }

  /// Print the snapshot to stderr with decorative headers.
  ///
  /// This prints the snapshot content surrounded by headers and footers
  /// to stderr, useful for error reporting or debugging.
  pub fn print_stderr(&self) {
    eprintln!("====== Ferrotype Snapshot ======");
    eprintln!("{}\n", self.as_string());
    eprintln!("--------------------------------");
  }
}

impl<S: ?Sized> std::fmt::Display for Ferrotype<S> {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    if cfg!(feature = "anstream") {
      write!(
        f,
        "{}",
        anstream::adapter::strip_str(&self.as_string()).to_string(),
      )
    } else {
      write!(f, "{}", self.as_string())
    }
  }
}

/// Assert a snapshot using insta with ferrotype-specific configuration.
///
/// This macro takes a `Ferrotype` snapshot and asserts it using insta.rs with
/// pre-configured settings for deterministic snapshots. It automatically:
///
/// - Filters memory addresses when enabled
/// - Redacts TypeIds and hash values
/// - Sets up appropriate snapshot paths
/// - Configures insta settings for consistent output
///
/// # Examples
///
/// ```rust,no_run
/// use ferrotype::Ferrotype;
///
/// let mut snapshot = Ferrotype::new();
/// snapshot.add("Test", "Hello world".to_string());
/// ferrotype::assert!(snapshot);
/// ```
///
/// You can also specify a custom snapshot folder:
///
/// ```rust,ignore
/// # use ferrotype::Ferrotype;
/// # let mut snapshot = Ferrotype::new();
/// ferrotype::assert!(
///   #[use_folder(custom, subfolder)]
///   snapshot
/// );
/// ```
#[macro_export]
macro_rules! assert {
  // @ferrotype_name sub-macro -------------------------------------------------
  //
  // This sub-macro gets the function name of the caller
  // This expects only one snapshot per function
  (@ferrotype_name) => {{
    fn f() {}
    fn type_name_of<T>(_: T) -> &'static str {
      std::any::type_name::<T>()
    }

    type_name_of(f).rsplit("::")
      .find(|&part| part != "f" && part != "{{closure}}")
      .expect("Short function name")
  }};
  // @use_folder sub-macro -----------------------------------------------------
  //
  // This sub-macro gets the directory of the caller
  (@use_folder use_folder( $( $folder:ident ),+ )) => {{
    let mut p = std::path::PathBuf::from($crate::get_output_dir());
    $(
      p.push(stringify!($folder));
    )+

    p
  }};
  // default to the output directory
  (@use_folder) => {
    std::path::PathBuf::from($crate::get_output_dir())
  };


  // main ----------------------------------------------------------------------

  ( $(#[ use_folder( $( $folder:ident ),+ ) ])? $snapshot:expr ) => {

    let snapshot = { $snapshot };
    let mut settings = insta::Settings::clone_current();

    // These configure insta to work with our snapshot format
    settings.set_sort_maps(true);
    settings.set_omit_expression(false);
    settings.set_prepend_module_to_snapshot(false);
    settings.remove_description();

    let mut filters = vec![];
    // We need to set a few filters to redact non-deterministic data

      // the following are redacted, because the will change between runs
      // but checking for the presence of them, as well as keeping them in debug output
      // is easier this way

      if snapshot.filter_memory_addresses() {
        // Redact Memory Addresses, as they are non-deterministic
        filters.push((r"\s*(0x[\da-fA-F]+)", " [Redacted::Pointer]"));
      }

      if snapshot.filter_uuids() {
        // Redact UUIDs, as they are non-deterministic
        filters.push((r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", "[Redacted::UUID]"));
      }

      if snapshot.filter_type_ids() {
        // Redact TypeId's
        filters.push((r"\s*TypeId\s*\{\s*t:\s*(\d+)\s*,\s*}", " [Redacted::TypeId]"));
      }

      if snapshot.filter_hashes() {
        // hash's need to be redacted and they contain the TypeId which is non-deterministic
        filters.push((r"hash:\s(\d+),", "hash: [Redacted::Hash], "));
      }


    settings.set_filters(filters);

    #[allow(unused_labels)]
    'set_snapshot_path: {
      let folder = $crate::assert!(@use_folder $( use_folder( $( $folder ),+ ) )? );

      // if this module is anywhere under a `tests` (or `test`) directory,
      // use the snapshot folder directly. Otherwise, place it under `tests/`.
      {
        let file_path = std::path::PathBuf::from(file!());
        let in_tests_dir = {
          let mut p = file_path.as_path();
          let mut found = false;
          while let Some(parent) = p.parent() {
            if let Some(name) = parent.file_name() {
              if name == "tests" || name == "test" {
                found = true;
                break;
              }
            }
            p = parent;
          }
          found
        };

        settings.set_snapshot_path(if in_tests_dir {
          folder
        } else if file_path.parent().is_none() {
          // no parent dir, keep original behavior
          folder
        } else {
          // not inside a `tests` dir, write under `tests/`
          std::path::Path::new("tests").join(folder)
        });
      }
    }

    // Now, assert the snapshot with out settings
      settings.bind(|| {
        insta::assert_snapshot!(
          // snapshot name
          format!(
            "{}_{}",
            module_path!()
              .split("::")
              .last()
              .unwrap(),
              $crate::assert!(@ferrotype_name),
            ),
          // serialise the snapshot
          snapshot.to_string(),
          // expression
          // we're setting this to a mock import, as we print the full source as a section
          format!("use {}::{}",
            module_path!(),
            $crate::assert!(@ferrotype_name),
          ).to_string().as_str()
        );

    });
  };
}

#[cfg(feature = "bluegum")]
impl<S: ?Sized> Ferrotype<S> {
  /// Add a section containing a bluegum tree rendered with the snapshot's
  /// stored state.
  ///
  /// Renders the tree through [`bluegum::BluegumWithState`], threading the
  /// state passed to [`new_with_state`](Self::new_with_state) through every
  /// node so stateful nodes can resolve external data (e.g. interned idents
  /// via a source resolver, symbol tables) while printing.
  ///
  /// ```rust,ignore
  /// let mut snapshot = Ferrotype::new_with_state(source_resolver);
  /// snapshot.add_bluegum("Records", &records);
  /// ```
  pub fn add_bluegum<T>(&mut self, title: &str, tree: &T)
  where
    T: bluegum::BluegumWithState<S>,
    T: bluegum::Bluegum,
  {
    let builder = bluegum::Builder::render_with_state(tree, &*self.state);
    let mut p = bluegum::Printer::default();
    p.render_builder(builder);

    self
      .sections
      .push((title.to_owned(), p.with_color().to_owned()));
  }

  /// Add a section containing a bluegum tree rendered with an explicitly
  /// supplied state, independent of the snapshot's stored state.
  ///
  /// Use this when the state is only available at the call site (e.g. a
  /// `Ferrotype<()>` created without state). For the common case where the
  /// snapshot already carries the state, prefer
  /// [`add_bluegum`](Self::add_bluegum).
  ///
  /// ```rust,ignore
  /// snapshot.add_bluegum_with_external_state("Records", &records, &resolver);
  /// ```
  pub fn add_bluegum_with_external_state<St, T>(
    &mut self,
    title: &str,
    tree: &T,
    state: &St,
  ) where
    St: ?Sized,
    T: bluegum::BluegumWithState<St>,
  {
    let builder = bluegum::Builder::render_with_state(tree, state);
    let mut p = bluegum::Printer::default();
    p.render_builder(builder);

    self
      .sections
      .push((title.to_owned(), p.with_color().to_owned()));
  }

  /// Add a section containing a rendered bluegum builder.
  ///
  /// This renders a pre-constructed bluegum builder and adds it as a section.
  pub fn add_bluegum_builder(
    &mut self,
    title: &str,
    builder: bluegum::Builder,
  ) {
    let mut p = bluegum::Printer::default();
    p.render_builder(builder);

    self
      .sections
      .push((title.to_owned(), p.with_color().to_owned()));
  }

  /// Add a section containing a bluegum tree built with a closure.
  ///
  /// This creates a new bluegum builder, passes it to the provided closure
  /// for configuration, then renders and adds the result as a section.
  ///
  /// ```rust,ignore
  /// snapshot.add_bluegum_builder_with("Tree", |b| {
  ///     b.name("Root").field("child", &"Child");
  /// });
  /// ```
  pub fn add_bluegum_builder_with<F>(&mut self, title: &str, builder: F)
  where
    F: FnOnce(&mut bluegum::Builder),
  {
    let mut p = bluegum::Printer::default();
    p.render_builder_with(builder);

    self
      .sections
      .push((title.to_owned(), p.with_color().to_owned()));
  }

  /// Add a section containing a bluegum tree rendered with custom styles.
  ///
  /// This renders the tree using a bluegum printer configured with the
  /// provided styles instead of the default ones.
  pub fn add_bluegum_with<T>(
    &mut self,
    title: &str,
    tree: &T,
    styles: bluegum::Styles,
  ) where
    T: bluegum::Bluegum,
    T: std::fmt::Debug,
  {
    let mut p = bluegum::Printer::new(styles);

    p.render(tree);

    self
      .sections
      .push((title.to_owned(), p.with_color().to_owned()));
  }
}

#[cfg(feature = "tokenstream")]
impl<S: ?Sized> Ferrotype<S> {
  /// Add a section containing a formatted Rust token stream.
  ///
  /// This parses the token stream as a Rust file and formats it using
  /// `prettyplease` for readable output. If parsing fails, this will panic.
  ///
  /// Panics if the token stream cannot be parsed as valid Rust syntax.
  /// ```rust,ignore
  /// use quote::quote;
  ///
  /// let tokens = quote! {
  ///     fn hello() {
  ///         println!("Hello, world!");
  ///     }
  /// };
  /// snapshot.add_token_stream("Generated Code", &tokens);
  /// ```
  pub fn add_token_stream(
    &mut self,
    title: &str,
    ts: &proc_macro2::TokenStream,
  ) {
    // TODO: if self.expect_errors we should catch the error here, and print
    // the unformatted token stream (and error) (gold-5pv)
    let file = syn::parse_file(&ts.to_string()).unwrap();
    self.add(title, prettyplease::unparse(&file));
  }
}

#[cfg(feature = "anstream")]
impl<S: ?Sized> Ferrotype<S> {
  /// Add a section with terminal color and control codes stripped.
  ///
  /// This uses the anstream adapter to remove ANSI escape sequences,
  /// color codes, and other terminal control characters from the content
  /// to ensure clean, readable snapshots.
  pub fn add_strip_str(&mut self, title: &str, body: String) {
    self.sections.push((
      title.to_owned(),
      anstream::adapter::strip_str(&body).to_string(),
    ));
  }
}

#[cfg(feature = "hex")]
impl<S: ?Sized> Ferrotype<S> {
  /// Add a section with binary data formatted as a hex dump.
  ///
  /// This creates a readable hex dump of the provided bytes using
  /// the `pretty_hex` crate, showing both hex values and ASCII representation.
  ///
  /// ```rust,ignore
  /// let data = b"Hello, world!";
  /// snapshot.add_hex("Binary Data", data);
  /// ```
  pub fn add_hex(&mut self, title: &str, body: &[u8]) {
    use pretty_hex::*;
    self
      .sections
      .push((title.to_owned(), format!("{:?}", body.hex_dump())));
  }
}

#[cfg(test)]
mod tests;