Skip to main content

nu_protocol/errors/
shell_warning.rs

1#![allow(unused_assignments)]
2use crate::Span;
3use miette::Diagnostic;
4use std::hash::Hash;
5use thiserror::Error;
6
7use crate::{ConfigWarning, ReportMode, Reportable};
8
9#[derive(Clone, Debug, Error, Diagnostic)]
10#[diagnostic(severity(Warning))]
11pub enum ShellWarning {
12    /// Running jobs (without auto-kill) prevented interactive shell from exiting.
13    #[error("Running background jobs that won't be killed automatically: {job_count}.")]
14    #[diagnostic(
15        code(nu::shell::background_jobs_running),
16        help(
17            "Run `exit` again to kill all jobs.\nUse `job spawn --auto-kill` when spawning thread jobs to exclude them from this warning."
18        )
19    )]
20    BackgroundJobsRunning { job_count: usize },
21    /// A parse-time deprecation. Indicates that something will be removed in a future release.
22    ///
23    /// Use [`ParseWarning::Deprecated`](crate::ParseWarning::Deprecated) if this is a deprecation
24    /// which is detectable at parse-time.
25    #[error("{dep_type} deprecated.")]
26    #[diagnostic(code(nu::shell::deprecated))]
27    Deprecated {
28        dep_type: String,
29        label: String,
30        #[label("{label}")]
31        span: Span,
32        #[help]
33        help: Option<String>,
34        report_mode: ReportMode,
35    },
36    /// Warnings reported while updating the config
37    #[error("Encountered {} warnings(s) when updating config", warnings.len())]
38    #[diagnostic(code(nu::shell::invalid_config))]
39    InvalidConfig {
40        #[related]
41        warnings: Vec<ConfigWarning>,
42    },
43    /// The interactive last-result value was truncated to fit `max_last_result_size`.
44    ///
45    /// Once-per-store is controlled by a stack flag; use [`ReportMode::EveryUse`] so the
46    /// engine report log does not permanently suppress later truncations at the same limit.
47    #[error(
48        "Last result was truncated to fit $env.config.max_last_result_size ({limit_bytes} bytes by Value::memory_size)."
49    )]
50    #[diagnostic(code(nu::shell::last_result_truncated))]
51    LastResultTruncated {
52        /// Access site span (not used as a source label — truncation is a state warning).
53        span: Span,
54        limit_bytes: usize,
55        #[help]
56        help: Option<String>,
57        report_mode: ReportMode,
58    },
59}
60
61impl Reportable for ShellWarning {
62    fn report_mode(&self) -> ReportMode {
63        match self {
64            ShellWarning::Deprecated { report_mode, .. }
65            | ShellWarning::LastResultTruncated { report_mode, .. } => *report_mode,
66            ShellWarning::InvalidConfig { .. } => ReportMode::FirstUse,
67            ShellWarning::BackgroundJobsRunning { .. } => ReportMode::EveryUse,
68        }
69    }
70}
71
72// To keep track of reported warnings
73impl Hash for ShellWarning {
74    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
75        match self {
76            ShellWarning::BackgroundJobsRunning { job_count } => job_count.hash(state),
77            ShellWarning::Deprecated {
78                dep_type, label, ..
79            } => {
80                dep_type.hash(state);
81                label.hash(state);
82            }
83            // Hash the contents so FirstUse dedups per warning batch, not
84            // once for all config warnings in the session.
85            ShellWarning::InvalidConfig { warnings } => warnings.hash(state),
86            // EveryUse — hash unused for suppression; include fields for completeness
87            ShellWarning::LastResultTruncated { limit_bytes, .. } => {
88                limit_bytes.hash(state);
89            }
90        }
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use crate::ConfigWarning;
98
99    fn hash_of(warning: &ShellWarning) -> u64 {
100        let mut hasher = std::hash::DefaultHasher::new();
101        warning.hash(&mut hasher);
102        std::hash::Hasher::finish(&hasher)
103    }
104
105    fn incompatible_batch(label: &'static str) -> ShellWarning {
106        ShellWarning::InvalidConfig {
107            warnings: vec![ConfigWarning::IncompatibleOptions {
108                label,
109                span: Span::test_data(),
110                help: "",
111            }],
112        }
113    }
114
115    /// `report_mode` is `FirstUse`, which dedups by this hash; a constant hash
116    /// would suppress every config warning after the first batch of a session.
117    #[test]
118    fn different_config_warning_batches_hash_differently() {
119        assert_ne!(
120            hash_of(&incompatible_batch("history")),
121            hash_of(&incompatible_batch("other")),
122        );
123    }
124
125    /// The same batch re-reported (e.g. a re-sourced config) stays suppressed.
126    #[test]
127    fn an_identical_config_warning_batch_hashes_the_same() {
128        assert_eq!(
129            hash_of(&incompatible_batch("history")),
130            hash_of(&incompatible_batch("history")),
131        );
132    }
133}