conf 0.4.5

A derive-based config parser for CLI args, env, and structured config files
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
use crate::{ConfValueSource, FlattenedOptionalDebugInfo, ProgramOption};
use clap::{Command, Error as ClapError, builder::Styles, error::ErrorKind};
use std::{ffi::OsString, fmt, fmt::Write};

/// An error which occurs when a `Conf::parse` function is called.
/// This may conceptually represent many underlying errors of several different types.
//
// Note: For now this is a thin wrapper around clap::Error just so that we can control our public
// API independently of clap. We may eventually need to make it contain an enum which is either a
// clap::Error or a collection of InnerError or something like this, but this approach is working
// adequately for now.
#[derive(Debug)]
pub struct Error(ClapError);

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.0.source()
    }
}

impl Error {
    /// Print formatted and colored error text to stderr or stdout as appropriate (as clap does)
    pub fn print(&self) -> Result<(), std::io::Error> {
        self.0.print()
    }

    /// Exit the program, printing an error message to stderr or stdout as appropriate (as clap
    /// does)
    pub fn exit(&self) -> ! {
        self.0.exit()
    }

    /// The exit code this error will exit the program with
    pub fn exit_code(&self) -> i32 {
        self.0.exit_code()
    }

    // An error reported during program options generation
    #[doc(hidden)]
    pub fn skip_short_not_found(
        not_found_chars: Vec<char>,
        field_name: &'static str,
        field_type_name: &'static str,
    ) -> Self {
        let buf = format!(
            "Internal error (invalid skip short)\n  When flattening {field_type_name} at {field_name}, these short options were not found: {not_found_chars:?}\n  To fix this error, remove them from the skip_short attribute list."
        );
        ClapError::raw(ErrorKind::UnknownArgument, buf).into()
    }

    // An error reported when positional arguments are used in flatten optional
    #[doc(hidden)]
    pub fn positional_in_flatten_optional(
        field_name: &str,
        field_type_name: &str,
        option_id: &str,
    ) -> Self {
        let buf = format!(
            "Cannot use flatten optional with struct '{field_type_name}' at field '{field_name}' because it contains positional argument '{option_id}'. Positional arguments are not supported in flatten optional structs (but are supported in regular flatten)."
        );
        ClapError::raw(ErrorKind::ArgumentConflict, buf).into()
    }
}

impl From<ClapError> for Error {
    fn from(src: ClapError) -> Error {
        Error(src)
    }
}

impl From<fmt::Error> for Error {
    fn from(src: fmt::Error) -> Error {
        ClapError::from(src).into()
    }
}

/// A single problem that occurs when a Conf attempts to parse env, or run a value parser, or run a
/// validation predicate
#[doc(hidden)]
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum InnerError {
    /// Missing a required parameter
    // (missing program option, optional reason it is required, serde source is present)
    MissingRequiredParameter(
        Box<ProgramOption>,
        Option<Box<OwnedFlattenedOptionalDebugInfo>>,
        bool,
    ),
    /// Invalid parameter value
    // (source, value string, program option, error message)
    InvalidParameterValue(ConfValueSource<String>, String, Box<ProgramOption>, String),
    /// Too Few Arguments
    // (struct name, instance id prefix, single options, flattened fields, optional reason this is
    // required, serde source is present)
    TooFewArguments(
        String,
        String,
        Vec<ProgramOption>,
        Vec<String>,
        Option<Box<OwnedFlattenedOptionalDebugInfo>>,
        bool,
    ),
    /// Too many arguments
    // (struct name, instance id prefix, single options, flattened fields (field name, option which
    // appeared))
    TooManyArguments(
        String,
        String,
        Vec<(ProgramOption, ConfValueSource<String>)>,
        Vec<(String, ProgramOption, ConfValueSource<String>)>,
    ),
    /// Validation failed
    // (struct name, instance id_prefix, error message)
    ValidationFailed(String, String, String),
    /// Invalid UTF-8 in env
    // (value omitted if it is secret)
    InvalidUtf8Env(String, Box<ProgramOption>, Option<OsString>),
    /// Missing required subcommand
    // struct name, field name, subcommands
    MissingRequiredSubcommand(String, String, Vec<String>),
    /// Parsing (document)
    // document name, field name, error
    Serde(String, String, String),
}

impl InnerError {
    /// Helper which makes InvalidParameterValue
    pub fn invalid_value(
        conf_value_source: ConfValueSource<&str>,
        value_str: &str,
        program_option: &ProgramOption,
        err: impl fmt::Display,
    ) -> Self {
        let program_option = Box::new(program_option.clone());
        Self::InvalidParameterValue(
            conf_value_source.into_owned(),
            value_str.to_owned(),
            program_option,
            err.to_string(),
        )
    }

    /// Helper which makes InvalidParameterValue from an OsStr value
    pub fn invalid_value_os(
        conf_value_source: ConfValueSource<&str>,
        value_os: &std::ffi::OsStr,
        program_option: &ProgramOption,
        err: impl fmt::Display,
    ) -> Self {
        let program_option = Box::new(program_option.clone());
        Self::InvalidParameterValue(
            conf_value_source.into_owned(),
            value_os.to_string_lossy().into_owned(),
            program_option,
            err.to_string(),
        )
    }

    /// Helper which makes MissingRequiredParameter
    pub(crate) fn missing_required_parameter(
        opt: &ProgramOption,
        flattened_optional_debug_info: Option<FlattenedOptionalDebugInfo<'_>>,
        serde_source_is_present: bool,
    ) -> Self {
        Self::MissingRequiredParameter(
            Box::new(opt.clone()),
            flattened_optional_debug_info.map(Into::into).map(Box::new),
            serde_source_is_present,
        )
    }

    /// Helper which makes TooFewArguments
    pub(crate) fn too_few_arguments<'a>(
        struct_name: &'static str,
        instance_id_prefix: &str,
        constraint_single_options: impl AsRef<[&'a ProgramOption]>,
        constraint_flattened_ids: impl AsRef<[&'a str]>,
        flattened_optional_debug_info: Option<FlattenedOptionalDebugInfo<'a>>,
        serde_source_is_present: bool,
    ) -> Self {
        let constraint_single_options = constraint_single_options
            .as_ref()
            .iter()
            .map(|opt| (*opt).clone())
            .collect::<Vec<_>>();
        let constraint_flattened_ids = constraint_flattened_ids
            .as_ref()
            .iter()
            .map(|id| (*id).to_owned())
            .collect::<Vec<_>>();
        let flattened_optional_debug_info =
            flattened_optional_debug_info.map(Into::into).map(Box::new);
        Self::TooFewArguments(
            struct_name.to_owned(),
            instance_id_prefix.to_owned(),
            constraint_single_options,
            constraint_flattened_ids,
            flattened_optional_debug_info,
            serde_source_is_present,
        )
    }

    /// Helper which makes TooManyArguments
    // Constraint flattened data is (field name, option which appeared)
    pub(crate) fn too_many_arguments<'a>(
        struct_name: &'static str,
        instance_id_prefix: &'a str,
        constraint_single_options: impl AsRef<[(&'a ProgramOption, ConfValueSource<&'a str>)]>,
        constraint_flattened_data: impl AsRef<[(&'a str, &'a ProgramOption, ConfValueSource<&'a str>)]>,
    ) -> Self {
        let constraint_single_options = constraint_single_options
            .as_ref()
            .iter()
            .map(|(opt, src)| ((*opt).clone(), (*src).into_owned()))
            .collect::<Vec<_>>();
        let constraint_flattened_data = constraint_flattened_data
            .as_ref()
            .iter()
            .map(|(field_name, opt, src)| {
                (
                    (*field_name).to_owned(),
                    (*opt).clone(),
                    (*src).into_owned(),
                )
            })
            .collect::<Vec<_>>();
        Self::TooManyArguments(
            struct_name.to_owned(),
            instance_id_prefix.to_owned(),
            constraint_single_options,
            constraint_flattened_data,
        )
    }

    /// Helper which makes ValidationFailed
    pub fn validation(
        struct_name: &'static str,
        instance_id_prefix: &str,
        err: impl fmt::Display,
    ) -> Self {
        Self::ValidationFailed(
            struct_name.to_owned(),
            instance_id_prefix.to_owned(),
            err.to_string(),
        )
    }

    /// Helper which makes InvalidUtf8Env
    pub(crate) fn invalid_utf8_env(
        env_var: &str,
        program_option: &ProgramOption,
        val: Option<&OsString>,
    ) -> Self {
        Self::InvalidUtf8Env(
            env_var.to_owned(),
            Box::new(program_option.clone()),
            val.cloned(),
        )
    }

    /// Helper which makes MissingRequiredSubcommand
    pub fn missing_required_subcommand(
        struct_name: &str,
        field_name: &str,
        subcommand_names: &'static [&'static str],
    ) -> Self {
        Self::MissingRequiredSubcommand(
            struct_name.to_owned(),
            field_name.to_owned(),
            subcommand_names.iter().map(|x| (*x).to_owned()).collect(),
        )
    }

    /// Helper which makes Serde
    pub fn serde(document_name: &str, field_name: &str, err: impl fmt::Display) -> Self {
        Self::Serde(
            document_name.to_owned(),
            field_name.to_owned(),
            err.to_string(),
        )
    }

    // A short (one-line) description of the problem
    fn title(&self) -> &'static str {
        match self {
            Self::InvalidUtf8Env(..) => "An env var contained invalid UTF8",
            Self::MissingRequiredParameter(..) => "A required value was not provided",
            Self::TooFewArguments(..) => "Too few arguments",
            Self::TooManyArguments(..) => "Too many arguments",
            Self::ValidationFailed(..) => "Validation failed",
            Self::InvalidParameterValue(..) => "Invalid value",
            Self::MissingRequiredSubcommand(..) => "Missing required subcommand",
            Self::Serde(..) => "Parsing document",
        }
    }

    // convert to clap error kind
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidUtf8Env(..) => ErrorKind::InvalidValue,
            Self::MissingRequiredParameter(..) => ErrorKind::MissingRequiredArgument,
            Self::TooFewArguments(..) => ErrorKind::TooFewValues,
            Self::TooManyArguments(..) => ErrorKind::TooManyValues,
            Self::ValidationFailed(..) => ErrorKind::ValueValidation,
            Self::InvalidParameterValue(..) => ErrorKind::InvalidValue,
            Self::MissingRequiredSubcommand(..) => ErrorKind::MissingSubcommand,
            Self::Serde(..) => ErrorKind::InvalidValue,
        }
    }

    // get program option associated to this error, if any
    // when only one error occurs, we print associated help text
    fn get_program_option(&self) -> Option<&ProgramOption> {
        match self {
            Self::InvalidUtf8Env(_, opt, _) => Some(opt),
            Self::MissingRequiredParameter(opt, ..) => Some(opt),
            Self::InvalidParameterValue(_src, _val_str, opt, _err) => Some(opt),
            Self::TooFewArguments(..) => None,
            Self::TooManyArguments(..) => None,
            Self::ValidationFailed(..) => None,
            Self::MissingRequiredSubcommand(..) => None,
            Self::Serde(..) => None,
        }
    }

    // Print this error in a form for when it is the only error
    fn print_solo(
        &self,
        stream: &mut impl std::fmt::Write,
        styles: &Styles,
    ) -> Result<(), std::fmt::Error> {
        writeln!(stream, "{}", self.title())?;

        self.print_body(stream, styles)?;

        // Print the opt.print help text as well
        if let Some(opt) = self.get_program_option() {
            writeln!(stream)?;
            writeln!(stream, "Help:")?;
            opt.print(stream, None)?;
        }

        Ok(())
    }

    // Print indented details of this error (but not the opt.print text)
    fn print_body(
        &self,
        stream: &mut impl std::fmt::Write,
        styles: &Styles,
    ) -> Result<(), std::fmt::Error> {
        // Styling based on examples in clap like here:
        // https://docs.rs/clap_builder/4.5.9/src/clap_builder/error/mod.rs.html#790
        let invalid = styles.get_invalid();

        match self {
            Self::InvalidUtf8Env(name, opt, maybe_val) => {
                let lossy_val = maybe_val
                    .as_ref()
                    .and_then(|val| {
                        if opt.is_secret() {
                            None
                        } else {
                            Some(val.to_string_lossy())
                        }
                    })
                    .unwrap_or_else(|| "***secret***".into());

                writeln!(
                    stream,
                    "  {name}: {}'{lossy_val}'{}",
                    invalid.render(),
                    invalid.render_reset()
                )?;
            }
            Self::MissingRequiredParameter(
                opt,
                maybe_flatten_optional_debug_info,
                serde_source_is_present,
            ) => {
                print_opt_requirements(stream, opt, "must be provided", *serde_source_is_present)?;
                if let Some(flatten_optional) = maybe_flatten_optional_debug_info.as_ref() {
                    // Indent 4 spaces
                    write!(stream, "    ")?;
                    flatten_optional.print_required_opt_context(stream)?;
                }
            }
            Self::InvalidParameterValue(value_source, value_str, opt, err) => {
                let context = format!(
                    "  when parsing {} value",
                    render_provided_opt(opt, value_source)
                );
                let mut estimated_len = context.len();
                write!(stream, "{context}")?;
                if !opt.is_secret() {
                    write!(
                        stream,
                        " {}'{value_str}'{}",
                        invalid.render(),
                        invalid.render_reset()
                    )?;
                    estimated_len += 3 + value_str.len();
                }
                writeln!(
                    stream,
                    ": {err_str}",
                    err_str = Self::format_err_str(err, estimated_len + 2)
                )?;
            }
            Self::TooFewArguments(
                struct_name,
                instance_id_prefix,
                single_opts,
                flattened_opts,
                maybe_flatten_optional_debug_info,
                serde_source_is_present,
            ) => {
                let mut instance_id_prefix = instance_id_prefix.to_owned();
                if !instance_id_prefix.is_empty() {
                    instance_id_prefix.insert_str(0, " @ .");
                    remove_trailing_dot(&mut instance_id_prefix);
                }
                writeln!(
                    stream,
                    "  One of these must be provided: (constraint on {struct_name}{instance_id_prefix}): "
                )?;
                for opt in single_opts {
                    write!(stream, "  ")?;
                    print_opt_requirements(stream, opt, "", *serde_source_is_present)?;
                }
                for field_name in flattened_opts {
                    writeln!(stream, "    Argument group '{field_name}'")?;
                }
                if let Some(flatten_optional) = maybe_flatten_optional_debug_info.as_ref() {
                    write!(stream, "  ")?;
                    flatten_optional.print_required_opt_context(stream)?;
                }
            }
            Self::TooManyArguments(
                struct_name,
                instance_id_prefix,
                single_opts,
                flattened_opts,
            ) => {
                let mut instance_id_prefix = instance_id_prefix.to_owned();
                if !instance_id_prefix.is_empty() {
                    instance_id_prefix.insert_str(0, " @ .");
                    remove_trailing_dot(&mut instance_id_prefix);
                }
                writeln!(
                    stream,
                    "  Too many arguments, provide at most one of these: (constraint on {struct_name}{instance_id_prefix}): "
                )?;
                for (opt, source) in single_opts {
                    let provided_opt = render_provided_opt(opt, source);
                    writeln!(stream, "    {provided_opt}")?;
                }
                for (field_name, opt, source) in flattened_opts {
                    let provided_opt = render_provided_opt(opt, source);
                    writeln!(
                        stream,
                        "    {provided_opt} (part of argument group '{field_name}')"
                    )?;
                }
            }
            Self::ValidationFailed(struct_name, instance_id_prefix, err) => {
                let mut context = format!("  {struct_name} value was invalid");
                if !instance_id_prefix.is_empty() {
                    context += &format!(" (@ .{instance_id_prefix})");
                }
                let estimated_len = context.len();
                writeln!(
                    stream,
                    "{context}: {err_str}",
                    err_str = Self::format_err_str(err, estimated_len + 2)
                )?;
            }
            Self::MissingRequiredSubcommand(struct_name, field_name, subcommand_names) => {
                writeln!(
                    stream,
                    "  A subcommand must be selected ({struct_name}::{field_name}):"
                )?;
                for name in subcommand_names {
                    writeln!(stream, "    {name}")?;
                }
            }
            Self::Serde(document_name, field_name, err) => {
                let context = format!("  Parsing {document_name} (@ {field_name})");
                let estimated_len = context.len();
                writeln!(
                    stream,
                    "{context}: {err_str}",
                    err_str = Self::format_err_str(err, estimated_len + 2)
                )?;
            }
        }
        Ok(())
    }

    // Formats an error string to look nicely indented if it has line breaks and starting with a
    // line break if the error is long.
    fn format_err_str(err_str: &str, estimated_line_length_so_far: usize) -> String {
        const TARGET_LINE_LENGTH: usize = 100;
        const INDENTATION: usize = 4;

        let mut err_str = err_str.to_owned();
        if err_str.len() + estimated_line_length_so_far > TARGET_LINE_LENGTH
            || err_str.contains('\n')
        {
            err_str.insert(0, '\n');
        }

        let indented_newline = "\n".to_owned() + &" ".repeat(INDENTATION);
        err_str.replace('\n', &indented_newline)
    }
}

// Print one line describing a missing required option, showing all the ways it can be provided
// The line is indented two spaces
fn print_opt_requirements(
    stream: &mut impl std::fmt::Write,
    opt: &ProgramOption,
    trailing_text: &str,
    serde_source_is_present: bool,
) -> fmt::Result {
    let mut ways_to_provide = vec![];

    // Check for env form
    if let Some(name) = opt.env_form.as_deref() {
        ways_to_provide.push(format!("env '{name}'"));
    }

    // Check for positional argument
    if opt.is_positional {
        let pos_name = format!("<{}>", opt.id);
        ways_to_provide.push(format!("'{pos_name}'"));
    }
    // Check for switch (if not positional)
    else if let Some(switch) = render_help_switch(opt) {
        ways_to_provide.push(format!("'{switch}'"));
    }

    // Check for serde source
    if opt.has_serde_source && serde_source_is_present {
        ways_to_provide.push(format!("'{}' in config file", opt.id));
    }

    // Build the final line
    if ways_to_provide.is_empty() {
        writeln!(stream, "  Required value '{}' cannot be provided", opt.id)?;
    } else {
        let joined = ways_to_provide.join(", or ");
        if trailing_text.is_empty() {
            writeln!(stream, "  {joined}")?;
        } else if ways_to_provide.len() == 1 {
            // When there's only one way to provide, don't add a comma before trailing text
            writeln!(stream, "  {joined} {trailing_text}")?;
        } else {
            writeln!(stream, "  {joined}, {trailing_text}")?;
        }
    }

    Ok(())
}

fn render_provided_opt(opt: &ProgramOption, value_source: &ConfValueSource<String>) -> String {
    match value_source {
        ConfValueSource::Args => {
            // If we have both a long and a short form, prefer to display the long form in this help
            // message
            let switch = render_help_switch(opt).unwrap_or_default();
            format!("'{switch}'")
        }
        ConfValueSource::Default => "default value".into(),
        ConfValueSource::Env(name) => {
            format!("env '{name}'")
        }
        ConfValueSource::Document(name) => {
            format!("document '{name}'")
        }
    }
}

fn render_help_switch(opt: &ProgramOption) -> Option<String> {
    // If we have both a long and a short form, prefer to display the long form in this help message
    opt.long_form
        .as_deref()
        .map(|l| format!("--{l}"))
        .or_else(|| opt.short_form.map(|s| format!("-{s}")))
}

fn remove_trailing_dot(string: &mut String) {
    if let Some(c) = string.pop() {
        if c != '.' {
            string.push(c);
        }
    }
}

/// A version of FlattenedOptionalDebugInfo that owns its data
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct OwnedFlattenedOptionalDebugInfo {
    pub struct_name: &'static str,
    pub id_prefix: String,
    pub option_appeared: Box<ProgramOption>,
    pub value_source: ConfValueSource<String>,
}

impl<'a> From<FlattenedOptionalDebugInfo<'a>> for OwnedFlattenedOptionalDebugInfo {
    fn from(src: FlattenedOptionalDebugInfo<'a>) -> Self {
        Self {
            struct_name: src.struct_name,
            id_prefix: src.id_prefix,
            option_appeared: Box::new(src.option_appeared.clone()),
            value_source: src.value_source.into_owned(),
        }
    }
}

impl OwnedFlattenedOptionalDebugInfo {
    /// Print context about why an option is required, if it is part of an flatten optional group.
    /// Prints one line with no indentation, add indentation first if needed
    fn print_required_opt_context(&self, stream: &mut impl std::fmt::Write) -> fmt::Result {
        let provided_opt = render_provided_opt(&self.option_appeared, &self.value_source);
        let mut context = self.struct_name.to_owned();
        if !self.id_prefix.is_empty() {
            context += " @ .";
            context += &self.id_prefix;
            remove_trailing_dot(&mut context);
        }

        writeln!(
            stream,
            "because {provided_opt} was provided (enabling argument group {context})"
        )
    }
}

impl fmt::Display for InnerError {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self.title())
    }
}

impl InnerError {
    pub(crate) fn into_clap_error(self, command: &Command) -> Error {
        let mut buf = String::new();

        self.print_solo(&mut buf, command.get_styles()).unwrap();
        ClapError::raw(self.error_kind(), buf)
            .with_cmd(command)
            .into()
    }

    pub(crate) fn vec_to_clap_error(mut src: Vec<InnerError>, command: &Command) -> Error {
        assert!(!src.is_empty());
        if src.len() == 1 {
            return src.remove(0).into_clap_error(command);
        }

        src.sort();
        let last_error_kind = src.last().unwrap().error_kind();

        let styles = command.get_styles();
        let error_sty = styles.get_error();

        let mut buf = String::new();

        let mut last_title = "";
        for err in src {
            if err.title() != last_title {
                if !last_title.is_empty() {
                    write!(
                        &mut buf,
                        "{}error: {}",
                        error_sty.render(),
                        error_sty.render_reset()
                    )
                    .unwrap();
                }
                writeln!(&mut buf, "{}", err.title()).unwrap();
                last_title = err.title();
            }
            err.print_body(&mut buf, styles).unwrap();
        }
        ClapError::raw(last_error_kind, buf)
            .with_cmd(command)
            .into()
    }
}