uv-errors 0.0.91

Common error traits for uv.
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
mod line_wrap;

use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::iter;

use owo_colors::{AnsiColors, DynColor, OwoColorize};

use line_wrap::{get_wrap_width, wrap_text};

/// An error that may carry user-facing hints.
///
/// Implement this on error types that want to surface contextual suggestions
/// (e.g., "try `--prerelease=allow`") to the diagnostics layer. Hints are
/// rendered after the error output, each prefixed with `hint:`.
pub trait Hinted {
    /// Return any hints associated with this error.
    fn hints(&self) -> Hints<'_> {
        Hints::none()
    }
}

/// The display order of a user-facing hint.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum HintOrdering {
    /// Advice that should be shown before other hints.
    First,
    /// Advice with no preferred placement.
    #[default]
    Any,
    /// General advice that should follow more specific hints.
    Last,
}

/// A user-facing hint and its preferred display order.
pub struct Hint<'a> {
    message: Cow<'a, str>,
    ordering: HintOrdering,
}

impl<'a> Hint<'a> {
    /// Create a hint with no preferred placement.
    pub fn new(message: impl Into<Cow<'a, str>>) -> Self {
        Self {
            message: message.into(),
            ordering: HintOrdering::default(),
        }
    }

    /// Set the preferred display order of this hint.
    #[must_use]
    pub fn with_ordering(mut self, ordering: HintOrdering) -> Self {
        self.ordering = ordering;
        self
    }

    /// Convert a borrowed hint to owned, extending its lifetime to `'static`.
    fn into_owned(self) -> Hint<'static> {
        Hint {
            message: Cow::Owned(self.message.into_owned()),
            ordering: self.ordering,
        }
    }
}

impl<'a> From<&'a str> for Hint<'a> {
    fn from(message: &'a str) -> Self {
        Self::new(message)
    }
}

impl From<String> for Hint<'_> {
    fn from(message: String) -> Self {
        Self::new(message)
    }
}

/// A collection of user-facing hint messages.
///
/// Each hint is rendered on its own line, prefixed with the styled `hint:` label.
/// Hints are grouped by [`HintOrdering`], retaining insertion order within each group.
pub struct Hints<'a>(Vec<Hint<'a>>);

impl<'a> Hints<'a> {
    /// No hints.
    pub fn none() -> Self {
        Self(Vec::new())
    }

    /// Add a single hint.
    pub fn push(&mut self, hint: impl Into<Hint<'a>>) {
        self.0.push(hint.into());
    }

    /// Set the display order of every hint in this collection.
    #[must_use]
    pub fn with_ordering(mut self, ordering: HintOrdering) -> Self {
        for hint in &mut self.0 {
            hint.ordering = ordering;
        }
        self
    }

    /// Convert all borrowed hints to owned, extending the lifetime to `'static`.
    pub fn into_owned(self) -> Hints<'static> {
        Hints(self.0.into_iter().map(Hint::into_owned).collect())
    }

    /// Whether the collection is empty.
    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Iterate over hint messages in display order.
    pub fn iter(&self) -> HintsIter<'_, 'a> {
        HintsIter {
            hints: &self.0,
            current: self.0.iter(),
            ordering: HintOrdering::First,
            remaining: [HintOrdering::Any, HintOrdering::Last].into_iter(),
        }
    }

    /// Extend with another set of hints, converting borrowed hints to owned.
    ///
    /// Duplicate messages retain their first insertion position and earliest ordering.
    pub fn extend(&mut self, other: Hints<'_>) {
        for hint in other.0 {
            if let Some(existing) = self
                .0
                .iter_mut()
                .find(|existing| existing.message == hint.message)
            {
                existing.ordering = existing.ordering.min(hint.ordering);
            } else {
                self.0.push(hint.into_owned());
            }
        }
    }
}

/// A borrowed iterator over hint messages in display order.
pub struct HintsIter<'h, 'a> {
    hints: &'h [Hint<'a>],
    current: std::slice::Iter<'h, Hint<'a>>,
    ordering: HintOrdering,
    remaining: std::array::IntoIter<HintOrdering, 2>,
}

impl<'h> Iterator for HintsIter<'h, '_> {
    type Item = &'h str;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(hint) = self.current.find(|hint| hint.ordering == self.ordering) {
                return Some(hint.message.as_ref());
            }
            self.ordering = self.remaining.next()?;
            self.current = self.hints.iter();
        }
    }
}

impl<'h, 'a> IntoIterator for &'h Hints<'a> {
    type Item = &'h str;
    type IntoIter = HintsIter<'h, 'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> IntoIterator for Hints<'a> {
    type Item = Cow<'a, str>;
    type IntoIter = std::iter::Map<std::vec::IntoIter<Hint<'a>>, fn(Hint<'a>) -> Cow<'a, str>>;

    fn into_iter(mut self) -> Self::IntoIter {
        self.0.sort_by_key(|hint| hint.ordering);
        self.0.into_iter().map(|hint| hint.message)
    }
}

/// A display adapter for an error followed by its hints.
///
/// Error renderers line-terminate the error before rendering [`Hints`]. Use
/// this adapter when an error and its hints need to be formatted together.
pub struct ErrorWithHints<'a, E> {
    error: E,
    hints: Hints<'a>,
}

impl<'a, E> ErrorWithHints<'a, E> {
    /// Format an error followed by any hints.
    pub fn new(error: E, hints: Hints<'a>) -> Self {
        Self { error, hints }
    }
}

impl<E: fmt::Display> fmt::Display for ErrorWithHints<'_, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.error)?;
        if !self.hints.is_empty() {
            writeln!(f)?;
            write!(f, "{}", self.hints)?;
        }
        Ok(())
    }
}

impl<'a> From<&'a str> for Hints<'a> {
    fn from(hint: &'a str) -> Self {
        Self::from(Hint::from(hint))
    }
}

impl From<String> for Hints<'_> {
    fn from(hint: String) -> Self {
        Self::from(Hint::from(hint))
    }
}

impl<'a> From<Hint<'a>> for Hints<'a> {
    fn from(hint: Hint<'a>) -> Self {
        Self(vec![hint])
    }
}

impl<'a, T: Into<Hint<'a>>> FromIterator<T> for Hints<'a> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self(iter.into_iter().map(Into::into).collect())
    }
}

impl fmt::Display for Hints<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for hint in self {
            write!(f, "\n{HintPrefix} {hint}")?;
        }
        Ok(())
    }
}

/// A styled `hint:` prefix for use in user-facing messages.
pub struct HintPrefix;

impl fmt::Display for HintPrefix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", "hint".bold().cyan(), ":".bold())
    }
}

/// Options for formatting an error chain.
#[must_use]
pub struct ErrorOptions<'a, C = AnsiColors, W = Stderr> {
    level: Cow<'a, str>,
    color: C,
    width_override: Option<usize>,
    stream: W,
}

/// A standard-error writer for formatted error chains.
#[derive(Debug, Clone, Copy, Default)]
pub struct Stderr;

impl fmt::Write for Stderr {
    fn write_str(&mut self, output: &str) -> fmt::Result {
        anstream::eprint!("{output}");
        Ok(())
    }
}

impl Default for ErrorOptions<'_, AnsiColors, Stderr> {
    fn default() -> Self {
        Self {
            level: Cow::Borrowed("error"),
            color: AnsiColors::Red,
            width_override: None,
            stream: Stderr,
        }
    }
}

impl<'a, C, W> ErrorOptions<'a, C, W> {
    /// Use a custom level prefix, such as `warning`.
    pub fn with_level(mut self, level: impl Into<Cow<'a, str>>) -> Self {
        self.level = level.into();
        self
    }

    /// Use a custom color for the level and cause prefixes.
    pub fn with_color<D>(self, color: D) -> ErrorOptions<'a, D, W> {
        ErrorOptions {
            level: self.level,
            color,
            width_override: self.width_override,
            stream: self.stream,
        }
    }

    /// Override the terminal width used for wrapping.
    ///
    /// This is primarily useful for testing.
    #[cfg(test)]
    fn with_width_override(mut self, width_override: usize) -> Self {
        self.width_override = Some(width_override);
        self
    }

    /// Write the rendered error chain to a custom stream.
    pub fn with_stream<D>(self, stream: D) -> ErrorOptions<'a, C, D> {
        ErrorOptions {
            level: self.level,
            color: self.color,
            width_override: self.width_override,
            stream,
        }
    }
}

/// Format an error chain and explicitly supplied hints to standard error using the default level
/// and color.
pub fn write_error_chain(err: &dyn Error, hints: &Hints<'_>) -> fmt::Result {
    write_error_chain_with_options(err, hints, ErrorOptions::default())
}

/// Format the [`Debug`] representation of every error in an error chain.
pub fn debug_error_chain(err: &dyn Error) -> impl fmt::Display + '_ {
    DebugErrorChain(err)
}

struct DebugErrorChain<'a>(&'a dyn Error);

impl fmt::Display for DebugErrorChain<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (index, error) in iter::successors(Some(self.0), |&error| error.source()).enumerate() {
            if index > 0 {
                formatter.write_str("\n")?;
            }
            write!(formatter, "{index}: {error:?}")?;
        }
        Ok(())
    }
}

/// Formats an error or warning chain with custom options.
///
/// Each hint is rendered on its own line, prefixed with the styled `hint:` label.
pub fn write_error_chain_with_options<C: DynColor + Copy, W: fmt::Write>(
    err: &dyn Error,
    hints: &Hints<'_>,
    options: ErrorOptions<'_, C, W>,
) -> fmt::Result {
    let ErrorOptions {
        level,
        color,
        width_override,
        mut stream,
    } = options;
    let width = get_wrap_width(width_override);

    let main_msg = err.to_string();
    let main_padding = " ".repeat(level.len() + 2);
    let wrapped_main = wrap_text(&main_msg, width, &main_padding, &main_padding, "");
    writeln!(
        &mut stream,
        "{}{} {}",
        level.as_ref().color(color).bold(),
        ":".bold(),
        wrapped_main.trim()
    )?;

    for source in iter::successors(err.source(), |&err| err.source()) {
        let msg = source.to_string();
        // Reserve the display width of the prefix before wrapping the message. Authored lines
        // retain their own indentation beneath it.
        let wrapped = wrap_text(&msg, width.map(|width| width.saturating_sub(9)), "", "", "");

        let mut lines = wrapped.lines();
        if let Some(first) = lines.next() {
            writeln!(
                &mut stream,
                "  {}{} {}",
                "cause".color(color).bold(),
                ":".bold(),
                first.trim()
            )?;
            for line in lines {
                if line.trim().is_empty() {
                    writeln!(&mut stream)?;
                } else {
                    writeln!(&mut stream, "         {line}")?;
                }
            }
        }
    }

    for hint in hints {
        writeln!(&mut stream, "\n{HintPrefix} {hint}")?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use anyhow::anyhow;
    use indoc::indoc;
    use insta::{assert_debug_snapshot, assert_snapshot};
    use owo_colors::AnsiColors;

    use super::{
        ErrorOptions, ErrorWithHints, Hint, HintOrdering, Hints, debug_error_chain,
        write_error_chain_with_options,
    };

    #[test]
    fn extend_deduplicates_matching_hints() {
        let mut hints = Hints::from("same");
        hints.extend(Hints::from("same"));
        hints.extend(Hints::from("other"));

        let hints = hints.iter().collect::<Vec<_>>();
        assert_debug_snapshot!(hints, @r#"
        [
            "same",
            "other",
        ]
        "#);
    }

    #[test]
    fn hint_ordering_retains_insertion_order() {
        let mut hints = Hints::from("any 1");
        hints.push(Hint::new("last 1").with_ordering(HintOrdering::Last));
        hints.push(Hint::new("first 1").with_ordering(HintOrdering::First));
        hints.push("any 2".to_string());
        hints.extend(Hints::from("last 2").with_ordering(HintOrdering::Last));
        hints.extend(Hints::from("first 2").with_ordering(HintOrdering::First));

        assert_snapshot!(anstream::adapter::strip_str(&hints.to_string()), @"
        hint: first 1
        hint: first 2
        hint: any 1
        hint: any 2
        hint: last 1
        hint: last 2
        ");
        assert_debug_snapshot!((&hints).into_iter().collect::<Vec<_>>(), @r#"
        [
            "first 1",
            "first 2",
            "any 1",
            "any 2",
            "last 1",
            "last 2",
        ]
        "#);
        assert_debug_snapshot!(hints.into_iter().collect::<Vec<_>>(), @r#"
        [
            "first 1",
            "first 2",
            "any 1",
            "any 2",
            "last 1",
            "last 2",
        ]
        "#);
    }

    #[test]
    fn changing_ordering_retains_insertion_order() {
        let hints = [
            Hint::new("last").with_ordering(HintOrdering::Last),
            Hint::new("first").with_ordering(HintOrdering::First),
            Hint::new("any"),
        ]
        .into_iter()
        .collect::<Hints<'_>>()
        .with_ordering(HintOrdering::Any);

        assert_debug_snapshot!(hints.iter().collect::<Vec<_>>(), @r#"
        [
            "last",
            "first",
            "any",
        ]
        "#);
    }

    #[test]
    fn duplicate_hints_retain_the_earliest_ordering() {
        let message = String::from("shared");
        let mut hints = Hints::from(message.as_str())
            .with_ordering(HintOrdering::Last)
            .into_owned();
        drop(message);

        hints.extend(Hints::from("first").with_ordering(HintOrdering::First));
        hints.extend(Hints::from("shared").with_ordering(HintOrdering::First));
        hints.extend(Hints::from("shared").with_ordering(HintOrdering::Last));
        hints.extend(Hints::from("any"));

        assert_snapshot!(anstream::adapter::strip_str(&hints.to_string()), @"
        hint: shared
        hint: first
        hint: any
        ");
    }

    #[test]
    fn error_with_hints_separates_hints_from_error() {
        let output = ErrorWithHints::new("error", Hints::from("fix it")).to_string();
        assert_snapshot!(anstream::adapter::strip_str(&output), @"
        error

        hint: fix it
        ");
        assert_snapshot!(ErrorWithHints::new("error", Hints::none()), @"error");
    }

    #[test]
    fn test_error_wrapping_with_columns() {
        #[derive(Debug, thiserror::Error)]
        #[error(
            "Because fiasobfhuasbf was not found in the package registry and you require fiasobfhuasbf, we can conclude that your requirements are unsatisfiable."
        )]
        struct Inner;

        #[derive(Debug, thiserror::Error)]
        #[error("No solution found when resolving dependencies")]
        struct Outer {
            #[source]
            source: Inner,
        }

        let error = Outer { source: Inner };
        let mut output = String::new();
        write_error_chain_with_options(
            &error,
            &Hints::none(),
            ErrorOptions::default()
                .with_width_override(80)
                .with_stream(&mut output),
        )
        .unwrap();
        let output = anstream::adapter::strip_str(&output);

        assert_snapshot!(output, @"
        error: No solution found when resolving dependencies
          cause: Because fiasobfhuasbf was not found in the package registry and you
                 require fiasobfhuasbf, we can conclude that your requirements are
                 unsatisfiable.
        ");
    }

    #[test]
    fn test_error_chain_with_cause() {
        #[derive(Debug, thiserror::Error)]
        #[error("Permission denied")]
        struct Inner;

        #[derive(Debug, thiserror::Error)]
        #[error("Failed to write file")]
        struct Outer {
            #[source]
            source: Inner,
        }

        let error = Outer { source: Inner };
        let mut output = String::new();
        write_error_chain_with_options(
            &error,
            &Hints::none(),
            ErrorOptions::default().with_stream(&mut output),
        )
        .unwrap();
        assert_snapshot!(format!("{output:?}"), @r#""\u{1b}[1m\u{1b}[31merror\u{1b}[39m\u{1b}[0m\u{1b}[1m:\u{1b}[0m Failed to write file\n  \u{1b}[1m\u{1b}[31mcause\u{1b}[39m\u{1b}[0m\u{1b}[1m:\u{1b}[0m Permission denied\n""#);
        let output = anstream::adapter::strip_str(&output);

        assert_snapshot!(output, @"
        error: Failed to write file
          cause: Permission denied
        ");
    }

    #[test]
    fn formats_debug_error_chain() {
        #[derive(Debug, thiserror::Error)]
        #[error("inner error")]
        struct InnerError {
            code: u8,
        }

        #[derive(Debug, thiserror::Error)]
        #[error("outer error")]
        struct OuterError {
            #[source]
            source: InnerError,
        }

        let error = OuterError {
            source: InnerError { code: 42 },
        };

        assert_eq!(
            debug_error_chain(&error).to_string(),
            "0: OuterError { source: InnerError { code: 42 } }\n1: InnerError { code: 42 }"
        );
    }

    #[test]
    fn format_with_custom_level() {
        let error = anyhow!("Failed to create registry entry");
        let mut output = String::new();
        write_error_chain_with_options(
            error.as_ref(),
            &Hints::none(),
            ErrorOptions::default()
                .with_level("warning")
                .with_color(AnsiColors::Yellow)
                .with_stream(&mut output),
        )
        .unwrap();
        let output = anstream::adapter::strip_str(&output);

        assert_snapshot!(output, @"warning: Failed to create registry entry
");
    }

    #[test]
    fn test_no_hyphenation() {
        #[derive(Debug, thiserror::Error)]
        #[error(
            "Failed to download package from https://files.pythonhosted.org/packages/verylongpackagename"
        )]
        struct LongWord;

        let error = LongWord;
        let mut output = String::new();
        write_error_chain_with_options(
            &error,
            &Hints::none(),
            ErrorOptions::default()
                .with_width_override(50)
                .with_stream(&mut output),
        )
        .unwrap();
        let output = anstream::adapter::strip_str(&output);
        assert_snapshot!(output, @r"
        error: Failed to download package from
               https://files.pythonhosted.org/packages/verylongpackagename
        ");
    }

    #[test]
    fn test_long_words_not_broken() {
        #[derive(Debug, thiserror::Error)]
        #[error(
            "The package supercalifragilisticexpialidocious-extraordinarily-long-name was not found"
        )]
        struct VeryLongWord;

        let error = VeryLongWord;
        let mut output = String::new();
        write_error_chain_with_options(
            &error,
            &Hints::none(),
            ErrorOptions::default()
                .with_width_override(40)
                .with_stream(&mut output),
        )
        .unwrap();
        let output = anstream::adapter::strip_str(&output);
        assert_snapshot!(output, @r"
        error: The package
               supercalifragilisticexpialidocious-extraordinarily-long-name
               was not found
        ");
    }

    #[test]
    fn test_multiple_error_sources() {
        #[derive(Debug, thiserror::Error)]
        #[error("Network connection timeout after multiple retry attempts")]
        struct DeepError;

        #[derive(Debug, thiserror::Error)]
        #[error("Failed to fetch package metadata from registry")]
        struct MiddleError {
            #[source]
            source: DeepError,
        }

        #[derive(Debug, thiserror::Error)]
        #[error("Unable to resolve package dependencies")]
        struct TopError {
            #[source]
            source: MiddleError,
        }

        let error = TopError {
            source: MiddleError { source: DeepError },
        };
        let mut output = String::new();
        write_error_chain_with_options(
            &error,
            &Hints::none(),
            ErrorOptions::default()
                .with_width_override(40)
                .with_stream(&mut output),
        )
        .unwrap();
        let output = anstream::adapter::strip_str(&output);
        assert_snapshot!(output, @"
        error: Unable to resolve package
               dependencies
          cause: Failed to fetch package
                 metadata from registry
          cause: Network connection timeout
                 after multiple retry attempts
        ");
    }

    #[test]
    fn format_cause_with_narrow_width() {
        let error = anyhow!("one two").context("root");
        let mut output = String::new();
        write_error_chain_with_options(
            error.as_ref(),
            &Hints::none(),
            ErrorOptions::default()
                .with_width_override(4)
                .with_stream(&mut output),
        )
        .unwrap();
        let output = anstream::adapter::strip_str(&output);

        assert_snapshot!(output, @"
        error: root
          cause: one
                 two
        ");
    }

    #[test]
    fn test_multiline_main_message_wraps_each_line() {
        #[derive(Debug, thiserror::Error)]
        #[error(
            "There is no command `foobar` for `uv`. Did you mean one of:\n    auth\n    run\n    init"
        )]
        struct Suggestions;

        let error = Suggestions;
        let mut output = String::new();
        write_error_chain_with_options(
            &error,
            &Hints::none(),
            ErrorOptions::default()
                .with_width_override(50)
                .with_stream(&mut output),
        )
        .unwrap();
        let output = anstream::adapter::strip_str(&output);

        assert_snapshot!(output, @r"
        error: There is no command `foobar` for `uv`. Did
               you mean one of:
            auth
            run
            init
        ");
    }

    #[test]
    fn test_wrap_only_on_ascii_space() {
        #[derive(Debug, thiserror::Error)]
        #[error("Path /usr/local/lib/python3.12/site-packages not found in filesystem hierarchy")]
        struct SpecialChars;

        let error = SpecialChars;
        let mut output = String::new();
        write_error_chain_with_options(
            &error,
            &Hints::none(),
            ErrorOptions::default()
                .with_width_override(50)
                .with_stream(&mut output),
        )
        .unwrap();
        let output = anstream::adapter::strip_str(&output);
        assert_snapshot!(output, @r"
        error: Path /usr/local/lib/python3.12/site-packages
               not found in filesystem hierarchy
        ");
    }

    #[test]
    fn format_with_hints() {
        let err = anyhow!("Permission denied").context("Failed to fetch package");

        let hints = [
            "Try running with `--verbose` for more information.".to_string(),
            "Try running without --offline.".to_string(),
        ]
        .into_iter()
        .collect();

        let mut rendered = String::new();
        write_error_chain_with_options(
            err.as_ref(),
            &hints,
            ErrorOptions::default().with_stream(&mut rendered),
        )
        .unwrap();
        let rendered = anstream::adapter::strip_str(&rendered);

        assert_snapshot!(rendered, @"
        error: Failed to fetch package
          cause: Permission denied

        hint: Try running with `--verbose` for more information.

        hint: Try running without --offline.
        ");
    }

    #[test]
    fn format_multiline_message() {
        let err_middle = indoc! {"Failed to fetch https://example.com/upload/python3.13.tar.zst
        Server says: This endpoint only support POST requests.

        For downloads, please refer to https://example.com/download/python3.13.tar.zst"};
        let err = anyhow!("Caused By: HTTP Error 400")
            .context(err_middle)
            .context("Failed to download Python 3.12");

        let mut rendered = String::new();
        write_error_chain_with_options(
            err.as_ref(),
            &Hints::none(),
            ErrorOptions::default().with_stream(&mut rendered),
        )
        .unwrap();
        let rendered = anstream::adapter::strip_str(&rendered);

        assert_snapshot!(rendered, @"
        error: Failed to download Python 3.12
          cause: Failed to fetch https://example.com/upload/python3.13.tar.zst
                 Server says: This endpoint only support POST requests.

                 For downloads, please refer to https://example.com/download/python3.13.tar.zst
          cause: Caused By: HTTP Error 400
        ");
    }
}