whitaker-installer 0.2.7

Installer CLI for Whitaker Dylint lint libraries
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
//! List command implementation.
//!
//! This module provides the `run_list` command handler and supporting functions
//! for querying and displaying installed lint libraries.

use camino::{Utf8Path, Utf8PathBuf};
use log::trace;
use std::io::Write;

use crate::cli::ListArgs;
use crate::dirs::{BaseDirs, SystemBaseDirs};
use crate::error::{InstallerError, Result};
use crate::list_output::{format_human, format_json};
use crate::scanner::{InstalledLints, scan_installed};
use crate::stager::default_target_dir;
use crate::toolchain::Toolchain;

/// Lists installed lint libraries and their associated lints.
///
/// Scans the staging directory for installed libraries, detects the active
/// toolchain from `rust-toolchain.toml` in the current directory (if present),
/// and formats the output for display.
///
/// Output is written to stdout (human-readable by default, JSON with `--json`).
///
/// # Errors
///
/// Returns an error if:
/// - The staging directory cannot be scanned
/// - Writing to stdout fails
pub fn run_list(args: &ListArgs, stdout: &mut dyn Write) -> Result<()> {
    run_list_with(args, stdout, detect_active_toolchain)
}

/// Internal implementation with injectable toolchain detection for testability.
fn run_list_with<F>(args: &ListArgs, stdout: &mut dyn Write, detect_toolchain: F) -> Result<()>
where
    F: FnOnce() -> Option<String>,
{
    let scan_roots = determine_scan_roots(args.target_dir.as_deref())?;
    let mut installed = InstalledLints::default();
    for root in scan_roots {
        let discovered =
            scan_installed(&root).map_err(|e| InstallerError::ScanFailed { source: e })?;
        merge_installed(&mut installed, discovered);
    }
    sort_installed_libraries(&mut installed);

    let active_toolchain = detect_toolchain();

    let output = if args.json {
        format_json(&installed, active_toolchain.as_deref())
    } else {
        format_human(&installed, active_toolchain.as_deref())
    };

    writeln!(stdout, "{output}").map_err(|e| InstallerError::WriteFailed { source: e })?;

    Ok(())
}

fn merge_installed(target: &mut InstalledLints, discovered: InstalledLints) {
    for (toolchain, mut libraries) in discovered.by_toolchain {
        let entry = target.by_toolchain.entry(toolchain).or_default();
        entry.append(&mut libraries);
    }
}

fn sort_installed_libraries(installed: &mut InstalledLints) {
    for libraries in installed.by_toolchain.values_mut() {
        libraries.sort_by(|left, right| left.crate_name.as_str().cmp(right.crate_name.as_str()));
    }
}

fn default_prebuilt_target_dir() -> Option<Utf8PathBuf> {
    SystemBaseDirs::new()
        .and_then(|dirs| dirs.whitaker_data_dir())
        .and_then(|path| Utf8PathBuf::from_path_buf(path).ok())
        .map(|path| path.join("lints"))
}

fn determine_scan_roots(cli_target: Option<&Utf8Path>) -> Result<Vec<Utf8PathBuf>> {
    if let Some(target) = cli_target {
        return Ok(vec![target.to_owned()]);
    }

    let mut roots = Vec::new();
    if let Some(default) = default_target_dir() {
        roots.push(default);
    }
    if let Some(prebuilt) = default_prebuilt_target_dir()
        && !roots.iter().any(|root| root == &prebuilt)
    {
        roots.push(prebuilt);
    }

    if roots.is_empty() {
        return Err(InstallerError::StagingFailed {
            reason: "could not determine any scan roots".to_owned(),
        });
    }
    Ok(roots)
}

/// Detect the active toolchain from `rust-toolchain.toml` in the current directory.
///
/// Returns `None` if:
/// - The current directory cannot be determined
/// - The path is not valid UTF-8
/// - No `rust-toolchain.toml` file exists
/// - The toolchain file cannot be parsed
pub fn detect_active_toolchain() -> Option<String> {
    let cwd = match std::env::current_dir() {
        Ok(path) => path,
        Err(e) => {
            trace!("detect_active_toolchain: failed to get current dir: {e}");
            return None;
        }
    };

    let utf8_cwd = match Utf8PathBuf::try_from(cwd) {
        Ok(path) => path,
        Err(e) => {
            trace!("detect_active_toolchain: current dir is not valid UTF-8: {e}");
            return None;
        }
    };

    detect_active_toolchain_in(&utf8_cwd)
}

/// Detect the active toolchain from `rust-toolchain.toml` in the given directory.
///
/// This is the internal implementation that accepts a path for testability.
/// Use [`detect_active_toolchain`] for production code.
///
/// Returns `None` if:
/// - No `rust-toolchain.toml` file exists in the directory
/// - The toolchain file cannot be parsed
pub(crate) fn detect_active_toolchain_in(dir: &Utf8Path) -> Option<String> {
    match Toolchain::detect(dir) {
        Ok(tc) => Some(tc.channel().to_owned()),
        Err(e) => {
            trace!("detect_active_toolchain_in: toolchain detection failed: {e}");
            None
        }
    }
}

/// Determines the target directory from CLI or falls back to the default.
///
/// If a target directory is provided via CLI, it is used directly. Otherwise,
/// the default staging directory from [`crate::stager::default_target_dir`] is
/// used.
///
/// # Errors
///
/// Returns [`InstallerError::StagingFailed`] if no target directory can be
/// determined (neither provided nor default available).
pub fn determine_target_dir(cli_target: Option<&Utf8Path>) -> Result<Utf8PathBuf> {
    determine_target_dir_with(cli_target, default_target_dir)
}

/// Internal implementation with injectable default provider for testability.
fn determine_target_dir_with<F>(cli_target: Option<&Utf8Path>, default_fn: F) -> Result<Utf8PathBuf>
where
    F: FnOnce() -> Option<Utf8PathBuf>,
{
    cli_target
        .map(Utf8Path::to_owned)
        .or_else(default_fn)
        .ok_or_else(|| InstallerError::StagingFailed {
            reason: "could not determine default target directory".to_owned(),
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::{fixture, rstest};
    use std::fs;
    use tempfile::TempDir;

    // -------------------------------------------------------------------------
    // Fixtures
    // -------------------------------------------------------------------------

    /// A temporary directory converted to a UTF-8 path for test isolation.
    struct TempTarget {
        _temp: TempDir,
        path: Utf8PathBuf,
    }

    #[fixture]
    fn temp_target() -> TempTarget {
        let temp = TempDir::new().expect("failed to create temp dir");
        let path = Utf8PathBuf::try_from(temp.path().to_owned()).expect("non-UTF8 temp path");
        TempTarget { _temp: temp, path }
    }

    /// A Write implementation that always fails, for testing error paths.
    struct FailingWriter;

    impl std::io::Write for FailingWriter {
        fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
            Err(std::io::Error::other("simulated write failure"))
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Err(std::io::Error::other("simulated flush failure"))
        }
    }

    // -------------------------------------------------------------------------
    // Helpers
    // -------------------------------------------------------------------------

    #[derive(Debug, Clone, Copy)]
    enum MockLibraryKind {
        Local,
        Prebuilt { target: &'static str },
    }

    impl MockLibraryKind {
        fn library_dir(&self, target_dir: &Utf8Path, toolchain: &str) -> Utf8PathBuf {
            match self {
                Self::Local => target_dir.join(toolchain).join("release"),
                Self::Prebuilt { target } => target_dir.join(toolchain).join(target).join("lib"),
            }
        }

        fn content(&self) -> &'static [u8] {
            match self {
                Self::Local => b"mock library",
                Self::Prebuilt { .. } => b"mock prebuilt library",
            }
        }
    }

    fn create_mock_library_internal(target_dir: &Utf8Path, toolchain: &str, kind: MockLibraryKind) {
        use crate::builder::{library_extension, library_prefix};

        let lib_dir = kind.library_dir(target_dir, toolchain);
        fs::create_dir_all(&lib_dir).expect("failed to create target library directory");

        let filename = format!(
            "{}whitaker_suite@{toolchain}{}",
            library_prefix(),
            library_extension()
        );

        let error_msg = match kind {
            MockLibraryKind::Local => "failed to create mock library",
            MockLibraryKind::Prebuilt { .. } => "failed to create prebuilt mock library",
        };
        fs::write(lib_dir.join(filename), kind.content()).expect(error_msg);
    }

    /// Helper to create a mock installed library in the target directory for tests.
    fn create_mock_library(target_dir: &Utf8Path, toolchain: &str) {
        create_mock_library_internal(target_dir, toolchain, MockLibraryKind::Local);
    }

    fn create_mock_prebuilt_library(target_dir: &Utf8Path, toolchain: &str, target: &'static str) {
        create_mock_library_internal(target_dir, toolchain, MockLibraryKind::Prebuilt { target });
    }

    // -------------------------------------------------------------------------
    // run_list tests
    // -------------------------------------------------------------------------

    #[rstest]
    fn run_list_outputs_human_readable_format(temp_target: TempTarget) {
        let args = ListArgs {
            json: false,
            target_dir: Some(temp_target.path.clone()),
        };
        let mut stdout = Vec::new();

        let result = run_list_with(&args, &mut stdout, || None);

        assert!(result.is_ok(), "expected success, got: {result:?}");
        let output = String::from_utf8_lossy(&stdout);
        assert!(output.contains("No lints installed"), "got: {output}");
    }

    #[rstest]
    #[case::json_format(true, &["toolchains", "\"active\""])]
    #[case::human_format(false, &["nightly-2026-05-28", "whitaker_suite"])]
    fn run_list_with_installed_library_includes_expected_output(
        temp_target: TempTarget,
        #[case] json: bool,
        #[case] expected: &[&str],
    ) {
        create_mock_library(&temp_target.path, "nightly-2026-05-28");
        let args = ListArgs {
            json,
            target_dir: Some(temp_target.path.clone()),
        };
        let mut stdout = Vec::new();

        let result = run_list_with(&args, &mut stdout, || Some("nightly-2026-05-28".to_owned()));

        assert!(result.is_ok(), "expected success, got: {result:?}");
        let output = String::from_utf8_lossy(&stdout);
        for needle in expected {
            assert!(
                output.contains(needle),
                "expected '{needle}' in output: {output}"
            );
        }
    }

    #[rstest]
    fn run_list_finds_prebuilt_layout_libraries(temp_target: TempTarget) {
        create_mock_prebuilt_library(
            &temp_target.path,
            "nightly-2026-05-28",
            "x86_64-unknown-linux-gnu",
        );
        let args = ListArgs {
            json: false,
            target_dir: Some(temp_target.path.clone()),
        };
        let mut stdout = Vec::new();

        let result = run_list_with(&args, &mut stdout, || Some("nightly-2026-05-28".to_owned()));

        assert!(result.is_ok(), "expected success, got: {result:?}");
        let output = String::from_utf8_lossy(&stdout);
        assert!(output.contains("nightly-2026-05-28"), "got: {output}");
        assert!(output.contains("whitaker_suite"), "got: {output}");
    }

    #[rstest]
    fn run_list_returns_write_failed_on_stdout_error(temp_target: TempTarget) {
        let args = ListArgs {
            json: false,
            target_dir: Some(temp_target.path.clone()),
        };
        let mut failing_stdout = FailingWriter;

        let result = run_list_with(&args, &mut failing_stdout, || None);

        let err = result.expect_err("expected error on write failure");
        assert!(
            matches!(err, InstallerError::WriteFailed { .. }),
            "expected WriteFailed error, got: {err:?}"
        );
    }

    // -------------------------------------------------------------------------
    // detect_active_toolchain_in tests
    // -------------------------------------------------------------------------

    #[rstest]
    fn detect_active_toolchain_in_returns_none_when_no_toolchain_file(temp_target: TempTarget) {
        let result = detect_active_toolchain_in(&temp_target.path);
        assert!(
            result.is_none(),
            "expected None for directory without rust-toolchain.toml"
        );
    }

    #[rstest]
    fn detect_active_toolchain_in_returns_channel_when_toolchain_file_exists(
        temp_target: TempTarget,
    ) {
        // Create a rust-toolchain.toml file
        let toolchain_content = r#"[toolchain]
channel = "nightly-2026-05-28"
"#;
        fs::write(
            temp_target.path.join("rust-toolchain.toml"),
            toolchain_content,
        )
        .expect("failed to write rust-toolchain.toml");

        let result = detect_active_toolchain_in(&temp_target.path);

        assert_eq!(result, Some("nightly-2026-05-28".to_owned()));
    }

    // -------------------------------------------------------------------------
    // determine_target_dir tests
    // -------------------------------------------------------------------------

    #[rstest]
    fn determine_target_dir_returns_cli_value_when_provided(temp_target: TempTarget) {
        let result = determine_target_dir_with(Some(&temp_target.path), || None);

        assert!(result.is_ok(), "expected success, got: {result:?}");
        assert_eq!(result.expect("already checked"), temp_target.path);
    }

    #[rstest]
    fn determine_target_dir_falls_back_to_default_when_cli_is_none(temp_target: TempTarget) {
        let default_path = temp_target.path.clone();

        let result = determine_target_dir_with(None, || Some(default_path.clone()));

        assert!(result.is_ok(), "expected success, got: {result:?}");
        assert_eq!(result.expect("already checked"), default_path);
    }

    #[test]
    fn determine_target_dir_returns_error_when_no_default_available() {
        let result = determine_target_dir_with(None, || None);

        let err = result.expect_err("expected error when no default");
        assert!(
            matches!(err, InstallerError::StagingFailed { .. }),
            "expected StagingFailed error, got: {err:?}"
        );
    }

    #[rstest]
    fn determine_target_dir_prefers_cli_over_default(temp_target: TempTarget) {
        let cli_path = temp_target.path.clone();
        let default_path = temp_target.path.join("should_not_be_used");

        let result = determine_target_dir_with(Some(&cli_path), || Some(default_path));

        assert!(result.is_ok(), "expected success, got: {result:?}");
        assert_eq!(result.expect("already checked"), cli_path);
    }
}