Skip to main content

ubt_cli/
error.rs

1use thiserror::Error;
2
3/// Unified error type for UBT.
4#[derive(Debug, Error)]
5pub enum UbtError {
6    #[error("Error: {tool} is not installed.{install_guidance}")]
7    ToolNotFound {
8        tool: String,
9        install_guidance: String,
10    },
11
12    #[error("\"{command}\" is not supported by the {plugin} plugin. {hint}")]
13    CommandUnsupported {
14        command: String,
15        plugin: String,
16        hint: String,
17    },
18
19    #[error(
20        "No command configured for \"{command}\". Add it to ubt.toml:\n\n  [commands]\n  \"{command}\" = \"your command here\""
21    )]
22    CommandUnmapped { command: String },
23
24    #[error("{message}")]
25    ConfigError { message: String },
26
27    #[error(
28        "Multiple plugins detected: {plugins}. Set tool in ubt.toml:\n\n  [project]\n  tool = \"{suggested_tool}\""
29    )]
30    PluginConflict {
31        plugins: String,
32        suggested_tool: String,
33    },
34
35    #[error("Could not detect project type. Run \"ubt init\" or create ubt.toml.")]
36    NoPluginMatch,
37
38    #[error("Failed to load plugin \"{name}\": {detail}")]
39    PluginLoadError { name: String, detail: String },
40
41    #[error("Template error: {0}")]
42    TemplateError(String),
43
44    #[error("Execution error: {0}")]
45    ExecutionError(String),
46
47    #[error("Alias \"{alias}\" conflicts with built-in command \"{command}\"")]
48    AliasConflict { alias: String, command: String },
49
50    #[error("Unknown command \"{name}\". Run \"ubt --help\" for available commands.")]
51    UnknownCommand { name: String },
52
53    #[error(transparent)]
54    Io(#[from] std::io::Error),
55}
56
57/// Convenience result type for UBT operations.
58pub type Result<T> = std::result::Result<T, UbtError>;
59
60impl UbtError {
61    /// Create a `ToolNotFound` error with optional install guidance.
62    pub fn tool_not_found(tool: impl Into<String>, install_help: Option<&str>) -> Self {
63        let install_guidance = match install_help {
64            Some(help) => format!("\n\n{help}"),
65            None => String::new(),
66        };
67        UbtError::ToolNotFound {
68            tool: tool.into(),
69            install_guidance,
70        }
71    }
72
73    /// Create a `ConfigError` with optional line number context.
74    pub fn config_error(line: Option<usize>, detail: impl Into<String>) -> Self {
75        let detail = detail.into();
76        let message = match line {
77            Some(n) => format!("Error in ubt.toml [line {n}]: {detail}"),
78            None => format!("Error in ubt.toml: {detail}"),
79        };
80        UbtError::ConfigError { message }
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn tool_not_found_with_install_help() {
90        let err = UbtError::tool_not_found("npm", Some("Install via: https://nodejs.org"));
91        assert_eq!(
92            err.to_string(),
93            "Error: npm is not installed.\n\nInstall via: https://nodejs.org"
94        );
95    }
96
97    #[test]
98    fn tool_not_found_without_install_help() {
99        let err = UbtError::tool_not_found("cargo", None);
100        assert_eq!(err.to_string(), "Error: cargo is not installed.");
101    }
102
103    #[test]
104    fn command_unsupported_formats() {
105        let err = UbtError::CommandUnsupported {
106            command: "lint".into(),
107            plugin: "go".into(),
108            hint: "Try \"ubt run lint\" instead.".into(),
109        };
110        assert_eq!(
111            err.to_string(),
112            "\"lint\" is not supported by the go plugin. Try \"ubt run lint\" instead."
113        );
114    }
115
116    #[test]
117    fn command_unmapped_formats() {
118        let err = UbtError::CommandUnmapped {
119            command: "deploy".into(),
120        };
121        assert_eq!(
122            err.to_string(),
123            "No command configured for \"deploy\". Add it to ubt.toml:\n\n  [commands]\n  \"deploy\" = \"your command here\""
124        );
125    }
126
127    #[test]
128    fn config_error_with_line() {
129        let err = UbtError::config_error(Some(42), "invalid key");
130        assert_eq!(err.to_string(), "Error in ubt.toml [line 42]: invalid key");
131    }
132
133    #[test]
134    fn config_error_without_line() {
135        let err = UbtError::config_error(None, "missing section");
136        assert_eq!(err.to_string(), "Error in ubt.toml: missing section");
137    }
138
139    #[test]
140    fn plugin_conflict_formats() {
141        let err = UbtError::PluginConflict {
142            plugins: "node, bun".into(),
143            suggested_tool: "node".into(),
144        };
145        assert_eq!(
146            err.to_string(),
147            "Multiple plugins detected: node, bun. Set tool in ubt.toml:\n\n  [project]\n  tool = \"node\""
148        );
149    }
150
151    #[test]
152    fn no_plugin_match_formats() {
153        let err = UbtError::NoPluginMatch;
154        assert_eq!(
155            err.to_string(),
156            "Could not detect project type. Run \"ubt init\" or create ubt.toml."
157        );
158    }
159
160    #[test]
161    fn plugin_load_error_formats() {
162        let err = UbtError::PluginLoadError {
163            name: "rust".into(),
164            detail: "file not found".into(),
165        };
166        assert_eq!(
167            err.to_string(),
168            "Failed to load plugin \"rust\": file not found"
169        );
170    }
171
172    #[test]
173    fn template_error_formats() {
174        let err = UbtError::TemplateError("unresolved placeholder".into());
175        assert_eq!(err.to_string(), "Template error: unresolved placeholder");
176    }
177
178    #[test]
179    fn execution_error_formats() {
180        let err = UbtError::ExecutionError("process killed".into());
181        assert_eq!(err.to_string(), "Execution error: process killed");
182    }
183
184    #[test]
185    fn alias_conflict_formats() {
186        let err = UbtError::AliasConflict {
187            alias: "t".into(),
188            command: "test".into(),
189        };
190        assert_eq!(
191            err.to_string(),
192            "Alias \"t\" conflicts with built-in command \"test\""
193        );
194    }
195
196    #[test]
197    fn io_error_from_conversion() {
198        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
199        let ubt_err: UbtError = io_err.into();
200        assert!(matches!(ubt_err, UbtError::Io(_)));
201        assert_eq!(ubt_err.to_string(), "gone");
202    }
203
204    #[test]
205    fn error_is_send_and_sync() {
206        fn assert_send_sync<T: Send + Sync>() {}
207        assert_send_sync::<UbtError>();
208    }
209
210    #[test]
211    fn result_type_alias_works() {
212        fn returns_ok() -> Result<i32> {
213            Ok(42)
214        }
215        fn returns_err() -> Result<i32> {
216            Err(UbtError::NoPluginMatch)
217        }
218        assert_eq!(returns_ok().unwrap(), 42);
219        assert!(returns_err().is_err());
220    }
221}