shellcomp 0.1.13

Shell completion installation and activation helpers for Rust CLI tools
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
use std::error::Error as StdError;
use std::fmt::{Display, Formatter};
use std::io;
use std::path::{Path, PathBuf};

use crate::Shell;
use crate::model::FailureReport;

/// Convenience result type used by all public `shellcomp` APIs.
pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
/// Errors returned by `shellcomp` operations.
///
/// Recoverable operational failures that callers are expected to render are wrapped as
/// [`Error::Failure`] with a [`crate::FailureReport`]. Lower-level variants represent immediate
/// input validation or filesystem problems.
pub enum Error {
    /// The requested program name was empty.
    EmptyProgramName,
    /// The requested program name contains unsupported path separators or reserved values.
    InvalidProgramName {
        /// The rejected program name.
        program_name: String,
    },
    /// `HOME` could not be resolved for an operation that requires it.
    MissingHome,
    /// The requested shell is known to the API but not implemented yet.
    UnsupportedShell(Shell),
    /// A target path did not contain a parent directory.
    PathHasNoParent {
        /// The invalid path.
        path: PathBuf,
    },
    /// A target path failed explicit validation for security or correctness reasons.
    InvalidTargetPath {
        /// The rejected path.
        path: PathBuf,
        /// Stable reason for failure classification.
        reason: &'static str,
    },
    /// A path could not be represented as UTF-8 for shell wiring purposes.
    NonUtf8Path {
        /// The path that could not be encoded.
        path: PathBuf,
    },
    /// A managed text file contained invalid UTF-8.
    InvalidUtf8File {
        /// The unreadable file path.
        path: PathBuf,
    },
    /// A managed block start marker was found without its matching end marker.
    ManagedBlockMissingEnd {
        /// The file containing the broken managed block.
        path: PathBuf,
        /// The expected start marker.
        start_marker: String,
        /// The expected end marker.
        end_marker: String,
    },
    /// A structured recoverable failure report intended for callers.
    ///
    /// Match this variant when you need stable failure kinds, affected paths, or caller-facing
    /// recovery guidance without parsing a display string.
    Failure(Box<FailureReport>),
    /// A filesystem operation failed.
    ///
    /// Most user-facing operational I/O failures are mapped to [`Error::Failure`] by the public
    /// APIs. This variant is still exposed because low-level helpers and validation paths may
    /// surface it directly.
    Io {
        /// The operation being attempted.
        action: &'static str,
        /// The path involved in the operation.
        path: PathBuf,
        /// The underlying I/O error.
        source: io::Error,
    },
}

impl Error {
    /// Returns a stable machine-readable error code.
    pub fn error_code(&self) -> &'static str {
        match self {
            Self::EmptyProgramName => "shellcomp.empty_program_name",
            Self::InvalidProgramName { .. } => "shellcomp.invalid_program_name",
            Self::MissingHome => "shellcomp.missing_home",
            Self::UnsupportedShell(_) => "shellcomp.unsupported_shell",
            Self::PathHasNoParent { .. } => "shellcomp.invalid_target_path",
            Self::InvalidTargetPath { .. } => "shellcomp.invalid_target_path",
            Self::NonUtf8Path { .. } => "shellcomp.invalid_target_path",
            Self::InvalidUtf8File { .. } => "shellcomp.invalid_target_file",
            Self::ManagedBlockMissingEnd { .. } => "shellcomp.profile_corrupted",
            Self::Failure(report) => report.error_code(),
            Self::Io { .. } => "shellcomp.io_error",
        }
    }

    /// Returns whether a retry may succeed with changed environment or timing.
    pub const fn is_retryable(&self) -> bool {
        match self {
            Self::Failure(report) => report.is_retryable(),
            Self::Io { .. } => true,
            _ => false,
        }
    }

    /// Returns the operation-scoped trace id when this is a structured failure.
    pub fn trace_id(&self) -> Option<u64> {
        match self {
            Self::Failure(report) => Some(report.trace_id),
            _ => None,
        }
    }

    pub(crate) fn io(action: &'static str, path: impl Into<PathBuf>, source: io::Error) -> Self {
        Self::Io {
            action,
            path: path.into(),
            source,
        }
    }

    pub(crate) fn failure(report: FailureReport) -> Self {
        Self::Failure(Box::new(report))
    }

    /// Returns `Some` when the error is [`Error::Failure`].
    pub fn as_failure(&self) -> Option<&FailureReport> {
        match self {
            Self::Failure(report) => Some(report),
            _ => None,
        }
    }

    /// Converts a [`Error::Failure`] into a plain [`FailureReport`].
    ///
    /// This is useful when callers need stable, structured failure data and prefer not to
    /// branch on internals in each match arm.
    pub fn into_failure(self) -> Option<FailureReport> {
        match self {
            Self::Failure(report) => Some(*report),
            _ => None,
        }
    }

    /// Returns the most relevant filesystem location for this error, when one exists.
    ///
    /// For [`Error::Failure`], this returns the report's primary `target_path`. Use
    /// [`crate::FailureReport::affected_locations`] when you need the full set of related paths.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use shellcomp::Error;
    ///
    /// let error = Error::InvalidProgramName {
    ///     program_name: "bad/name".to_owned(),
    /// };
    ///
    /// assert_eq!(error.location(), None);
    /// ```
    pub fn location(&self) -> Option<&Path> {
        match self {
            Self::PathHasNoParent { path }
            | Self::InvalidTargetPath { path, .. }
            | Self::NonUtf8Path { path }
            | Self::InvalidUtf8File { path }
            | Self::Io { path, .. } => Some(path.as_path()),
            Self::ManagedBlockMissingEnd { path, .. } => Some(path.as_path()),
            Self::Failure(report) => report.target_path.as_deref(),
            Self::EmptyProgramName
            | Self::InvalidProgramName { .. }
            | Self::MissingHome
            | Self::UnsupportedShell(_) => None,
        }
    }

    /// Returns a human-readable failure reason intended for caller-side rendering.
    ///
    /// This is suitable for logs or CLI output, but callers that need stable branching should
    /// prefer matching [`Error::Failure`] and reading [`crate::FailureReport::kind`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use shellcomp::Error;
    ///
    /// let error = Error::MissingHome;
    /// assert!(error.reason().is_some());
    /// ```
    pub fn reason(&self) -> Option<&str> {
        match self {
            Self::Failure(report) => Some(report.reason.as_str()),
            Self::EmptyProgramName => Some("Program name must not be empty."),
            Self::InvalidProgramName { .. } => Some(
                "Program names must use a safe portable character set: ASCII letters, digits, `.`, `_`, and `-`.",
            ),
            Self::MissingHome => Some(
                "The operation requires a user home directory because the default shell-managed path could not be resolved.",
            ),
            Self::UnsupportedShell(_) => Some(
                "This shell is modelled in the API but not implemented in the production support set yet.",
            ),
            Self::PathHasNoParent { .. } => {
                Some("The provided path does not have a parent directory.")
            }
            Self::InvalidTargetPath { reason, .. } => Some(reason),
            Self::NonUtf8Path { .. } => Some(
                "The path cannot be represented safely in shell startup wiring because it is not valid UTF-8.",
            ),
            Self::InvalidUtf8File { .. } => Some(
                "The managed file could not be parsed as UTF-8, so shellcomp cannot safely update it.",
            ),
            Self::ManagedBlockMissingEnd { .. } => {
                Some("A managed shell block is malformed because its closing marker is missing.")
            }
            Self::Io { .. } => None,
        }
    }

    /// Returns a suggested next step for this error, when one exists.
    ///
    /// This is primarily intended for CLI or UI layers that want to surface actionable guidance
    /// without inventing shell-specific recovery text themselves.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use shellcomp::Error;
    ///
    /// let error = Error::PathHasNoParent {
    ///     path: "/".into(),
    /// };
    ///
    /// assert!(error.next_step().is_some());
    /// ```
    pub fn next_step(&self) -> Option<&str> {
        match self {
            Self::Failure(report) => report.next_step.as_deref(),
            Self::MissingHome => Some(
                "Set HOME or the relevant shell-specific home variable for the current process, or pass `path_override` so the library does not need a default managed path.",
            ),
            Self::PathHasNoParent { .. } => Some(
                "Pass a file path with a real parent directory, or create the parent directory before calling shellcomp.",
            ),
            Self::InvalidTargetPath { reason, .. } if *reason == "target path must be absolute" => {
                Some("Pass an absolute path so shellcomp can apply safe path validation reliably.")
            }
            Self::InvalidTargetPath { reason, .. }
                if *reason == "target path must not be a symbolic link" =>
            {
                Some(
                    "Choose a path in a non-symlink directory and avoid symlink completion targets.",
                )
            }
            Self::InvalidTargetPath { reason, .. } => Some(match *reason {
                "target path must be normalized" => {
                    "Pass a normalized absolute path without `.` or `..` segments."
                }
                "target path parent must be an existing directory" => {
                    "Create the parent directory before calling shellcomp."
                }
                _ => "Use an explicit non-relative, non-symlink target path.",
            }),
            Self::InvalidProgramName { .. } => Some(
                "Rename the binary or pass a sanitized program name that only uses ASCII letters, digits, `.`, `_`, and `-`.",
            ),
            _ => None,
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EmptyProgramName => write!(f, "program name must not be empty"),
            Self::InvalidProgramName { program_name } => {
                write!(
                    f,
                    "program name `{program_name}` contains unsupported characters"
                )
            }
            Self::MissingHome => write!(
                f,
                "no supported home-directory environment variable is set and no fallback path can be resolved"
            ),
            Self::UnsupportedShell(shell) => write!(f, "shell `{shell}` is not supported yet"),
            Self::PathHasNoParent { path } => {
                write!(
                    f,
                    "path `{}` does not have a parent directory",
                    path.display()
                )
            }
            Self::InvalidTargetPath { path, reason } => {
                write!(f, "target path `{}` is invalid: {reason}", path.display())
            }
            Self::NonUtf8Path { path } => {
                write!(
                    f,
                    "path `{}` cannot be represented as UTF-8",
                    path.display()
                )
            }
            Self::InvalidUtf8File { path } => {
                write!(f, "file `{}` is not valid UTF-8", path.display())
            }
            Self::ManagedBlockMissingEnd {
                path,
                start_marker,
                end_marker,
            } => write!(
                f,
                "managed block `{start_marker}` in `{}` is missing closing marker `{end_marker}`",
                path.display()
            ),
            Self::Failure(report) => write!(f, "{}", report.reason),
            Self::Io {
                action,
                path,
                source,
            } => write!(f, "failed to {action} `{}`: {source}", path.display()),
        }
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::Error;
    use crate::model::{
        ActivationMode, ActivationReport, Availability, FailureKind, FailureReport, Operation,
        Shell,
    };

    #[test]
    fn failure_helpers_forward_report_context() {
        let error = Error::failure(FailureReport {
            operation: Operation::Install,
            shell: Shell::Bash,
            target_path: Some(PathBuf::from("/tmp/tool")),
            affected_locations: vec![PathBuf::from("/tmp/tool"), PathBuf::from("/tmp/.bashrc")],
            kind: FailureKind::ProfileUnavailable,
            file_change: Some(crate::FileChange::Created),
            activation: Some(ActivationReport {
                mode: ActivationMode::Manual,
                availability: Availability::ManualActionRequired,
                location: Some(PathBuf::from("/tmp/.bashrc")),
                reason: Some("profile update failed".to_owned()),
                next_step: Some("edit your shell profile manually".to_owned()),
            }),
            cleanup: None,
            reason: "Could not update the managed Bash startup block.".to_owned(),
            next_step: Some("edit your shell profile manually".to_owned()),
            trace_id: 123,
        });

        assert_eq!(error.location(), Some(PathBuf::from("/tmp/tool").as_path()));
        assert_eq!(
            error.reason(),
            Some("Could not update the managed Bash startup block.")
        );
        assert_eq!(error.next_step(), Some("edit your shell profile manually"));
        assert_eq!(error.as_failure().unwrap().trace_id, 123);
    }

    #[test]
    fn builtin_error_helpers_return_actionable_context() {
        let error = Error::InvalidProgramName {
            program_name: "bad/name".to_owned(),
        };

        assert_eq!(
            error.reason(),
            Some(
                "Program names must use a safe portable character set: ASCII letters, digits, `.`, `_`, and `-`."
            )
        );
        assert_eq!(
            error.next_step(),
            Some(
                "Rename the binary or pass a sanitized program name that only uses ASCII letters, digits, `.`, `_`, and `-`."
            )
        );
        assert_eq!(error.location(), None);
    }

    #[test]
    fn error_helpers_expose_stable_code_retryability_and_trace() {
        let report = FailureReport {
            operation: Operation::Install,
            shell: Shell::Bash,
            target_path: Some(PathBuf::from("/tmp/tool")),
            affected_locations: vec![PathBuf::from("/tmp/tool")],
            kind: FailureKind::CompletionFileUnreadable,
            file_change: None,
            activation: None,
            cleanup: None,
            reason: "write failure".to_owned(),
            next_step: Some("retry after fixing permissions".to_owned()),
            trace_id: 99,
        };

        let error = Error::failure(report);

        assert_eq!(
            error.error_code(),
            FailureKind::CompletionFileUnreadable.code()
        );
        assert!(error.is_retryable());
        assert_eq!(error.trace_id(), Some(99));

        let invalid_path = Error::InvalidTargetPath {
            path: PathBuf::from("relative"),
            reason: "target path must be absolute",
        };

        assert_eq!(invalid_path.error_code(), "shellcomp.invalid_target_path");
        assert!(!invalid_path.is_retryable());
        assert_eq!(invalid_path.trace_id(), None);
    }

    #[test]
    fn missing_home_helpers_use_generic_home_directory_guidance() {
        let error = Error::MissingHome;

        assert_eq!(
            error.reason(),
            Some(
                "The operation requires a user home directory because the default shell-managed path could not be resolved."
            )
        );
        assert_eq!(
            error.next_step(),
            Some(
                "Set HOME or the relevant shell-specific home variable for the current process, or pass `path_override` so the library does not need a default managed path."
            )
        );
        assert_eq!(
            error.to_string(),
            "no supported home-directory environment variable is set and no fallback path can be resolved"
        );
    }
}