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
428
429
430
431
432
433
434
435
436
437
438
439
//! Test helpers for dependency binary installation tests.

use crate::dependency_binaries::find_dependency_binary;
#[cfg(any(test, feature = "test-support"))]
use crate::dependency_binaries::{
    DependencyBinary, DependencyBinaryInstallError, DependencyBinaryInstaller,
};
#[cfg(any(test, feature = "test-support"))]
use crate::dirs::BaseDirs;
use crate::error::Result;
#[cfg(any(test, feature = "test-support"))]
use crate::installer_packaging::TargetTriple;
#[cfg(any(test, feature = "test-support"))]
use crate::test_support::env_test_guard;
use crate::test_utils::{ExpectedCall, failure_output, stdout_output, success_output};
#[cfg(any(test, feature = "test-support"))]
use std::fs;
#[cfg(all(any(test, feature = "test-support"), unix))]
use std::os::unix::fs::PermissionsExt;
#[cfg(any(test, feature = "test-support"))]
use std::path::{Path, PathBuf};
use std::process::Output;

/// Repository installer test double that always reports a missing archive.
#[cfg(any(test, feature = "test-support"))]
pub struct AlwaysNotFoundRepositoryInstaller;

#[cfg(any(test, feature = "test-support"))]
impl DependencyBinaryInstaller for AlwaysNotFoundRepositoryInstaller {
    fn install(
        &self,
        dependency: &DependencyBinary,
        target: &TargetTriple,
        _dirs: &dyn BaseDirs,
    ) -> std::result::Result<PathBuf, DependencyBinaryInstallError> {
        Err(DependencyBinaryInstallError::NotFound {
            url: format!(
                "https://example.test/{}-{}-v{}.tgz",
                dependency.package(),
                target,
                dependency.version()
            ),
        })
    }
}

/// Writes a fake binary at `path` that exits successfully.
#[cfg(any(test, feature = "test-support"))]
pub fn write_fake_binary(path: &Path, is_executable: bool) {
    write_fake_binary_with_status(path, is_executable, 0);
}

/// Writes a fake binary at `path` that exits with the supplied status code.
#[cfg(any(test, feature = "test-support"))]
pub fn write_fake_binary_with_status(path: &Path, is_executable: bool, exit_code: i32) {
    fs::write(path, fake_binary_contents(exit_code)).expect("write fake binary");
    #[cfg(unix)]
    {
        let mode = if is_executable { 0o755 } else { 0o644 };
        let mut permissions = fs::metadata(path)
            .expect("read fake binary metadata")
            .permissions();
        permissions.set_mode(mode);
        fs::set_permissions(path, permissions).expect("set fake binary permissions");
    }
    #[cfg(not(unix))]
    let _ = is_executable;
}

#[cfg(any(test, feature = "test-support"))]
fn fake_binary_contents(exit_code: i32) -> Vec<u8> {
    #[cfg(windows)]
    {
        format!("@echo off\r\nexit /b {exit_code}\r\n").into_bytes()
    }
    #[cfg(not(windows))]
    {
        format!("#!/bin/sh\nexit {exit_code}\n").into_bytes()
    }
}

/// Runs a closure with `PATH` pointing at one or more fake directories.
#[cfg(any(test, feature = "test-support"))]
pub fn with_fake_path<T>(setup: impl FnOnce(&[PathBuf]), run: impl FnOnce() -> T) -> T {
    let _guard = env_test_guard();
    let temp_dirs = [
        tempfile::tempdir().expect("create temp dir"),
        tempfile::tempdir().expect("create temp dir"),
    ];
    let path_dirs = temp_dirs
        .iter()
        .map(|dir| dir.path().to_path_buf())
        .collect::<Vec<_>>();
    setup(&path_dirs);
    let path = std::env::join_paths(path_dirs.iter().map(PathBuf::as_path))
        .expect("join fake PATH directories");
    temp_env::with_var("PATH", Some(path), run)
}

/// Runs a closure with `PATH` containing a fake executable in the first entry.
#[cfg(any(test, feature = "test-support"))]
pub fn with_fake_binary_on_path<T>(binary_name: &str, run: impl FnOnce() -> T) -> T {
    with_fake_path(
        |directories| write_fake_binary(&path_binary_location(&directories[0], binary_name), true),
        run,
    )
}

/// Joins `binary_name` onto `directory` with the platform executable suffix,
/// so directly probed fakes are runnable on Windows as well as Unix.
#[cfg(any(test, feature = "test-support"))]
pub fn path_binary_location(directory: &Path, binary_name: &str) -> PathBuf {
    #[cfg(windows)]
    {
        directory.join(format!("{binary_name}.cmd"))
    }
    #[cfg(not(windows))]
    {
        directory.join(binary_name)
    }
}

/// Configuration for generating expected calls in dependency binary tests.
pub struct ExpectedCallConfig<'a> {
    /// Whether cargo-binstall is available.
    pub is_binstall_available: bool,
    /// Whether repository metadata is available to pin cargo fallbacks.
    pub has_repository_context: bool,
    /// Whether the repository failure is a missing asset.
    pub is_repository_asset_missing: bool,
    /// Whether to verify repository installation.
    pub should_verify_repository_install: bool,
    /// Whether repository verification should fail.
    pub is_repository_verification_failing: bool,
    /// Error message for cargo binstall failure (None if succeeds).
    pub cargo_binstall_failure: Option<&'a str>,
    /// Error message for cargo install failure (None if succeeds).
    pub cargo_install_failure: Option<&'a str>,
}

/// Creates an expected call for checking cargo-binstall availability.
pub fn binstall_version_check(is_binstall_available: bool) -> ExpectedCall {
    ExpectedCall {
        cmd: "cargo",
        args: vec!["binstall", "--version"],
        result: if is_binstall_available {
            Ok(success_output())
        } else {
            Ok(failure_output("missing binstall"))
        },
    }
}

/// Creates an expected call for checking cargo-binstall with a fixed result.
pub fn binstall_version_check_with_result(result: Result<Output>) -> ExpectedCall {
    ExpectedCall {
        cmd: "cargo",
        args: vec!["binstall", "--version"],
        result,
    }
}

/// Creates an expected call for installing a tool with cargo-binstall.
pub fn binstall_install(tool: &'static str, result: Result<Output>) -> ExpectedCall {
    let version = dependency_version(tool);
    ExpectedCall {
        cmd: "cargo",
        args: vec!["binstall", "-y", "--version", version, tool],
        result,
    }
}

/// Creates an expected call for installing a tool with cargo install.
pub fn cargo_install(tool: &'static str, result: Result<Output>) -> ExpectedCall {
    ExpectedCall {
        cmd: "cargo",
        args: vec!["install", tool],
        result,
    }
}

fn cargo_source_install(
    tool: &'static str,
    version: &'static str,
    result: Result<Output>,
) -> ExpectedCall {
    ExpectedCall {
        cmd: "cargo",
        args: vec!["install", "--locked", "--version", version, tool],
        result,
    }
}

/// Returns the manifest-pinned version for a dependency tool.
///
/// # Panics
///
/// Panics when the manifest cannot be parsed or the tool is unknown.
pub fn dependency_version(tool: &str) -> &'static str {
    find_dependency_binary(tool)
        .expect("dependency manifest should parse")
        .map(|dependency| dependency.version())
        .unwrap_or_else(|| panic!("unexpected tool: {tool}"))
}

/// Successful `cargo dylint --version` output reporting the manifest version.
pub fn cargo_dylint_version_output() -> Output {
    stdout_output(format!(
        "cargo-dylint {}\n",
        dependency_version("cargo-dylint")
    ))
}

/// Expected `cargo install --list` call reporting the manifest-pinned
/// `dylint-link` version.
pub fn dylint_link_install_list_check() -> ExpectedCall {
    dylint_link_install_list_check_with_version(dependency_version("dylint-link"))
}

/// Expected `cargo install --list` call reporting the given `dylint-link`
/// version.
pub fn dylint_link_install_list_check_with_version(version: &str) -> ExpectedCall {
    ExpectedCall {
        cmd: "cargo",
        args: vec!["install", "--list"],
        result: Ok(stdout_output(format!(
            "dylint-link v{version}:\n    dylint-link\n"
        ))),
    }
}

/// Creates an expected call for verifying repository installation.
pub fn repository_verification_call(tool: &str, verification_fails: bool) -> Option<ExpectedCall> {
    match tool {
        "cargo-dylint" => Some(ExpectedCall {
            cmd: "cargo",
            args: vec!["dylint", "--version"],
            result: if verification_fails {
                Ok(failure_output("still missing"))
            } else {
                Ok(cargo_dylint_version_output())
            },
        }),
        // Repository installs of dylint-link are verified by probing the
        // extracted binary directly, so neither outcome consults the
        // executor.
        "dylint-link" => {
            let _ = verification_fails;
            None
        }
        other => panic!("unexpected tool: {other}"),
    }
}

/// Returns the expected verification call for a given tool.
///
/// Cargo-fallback scenarios in the behaviour suite model `dylint-link` as
/// absent from PATH, so its verification never reaches the executor there.
fn tool_verification_check(tool: &str) -> Option<ExpectedCall> {
    match tool {
        "cargo-dylint" => Some(cargo_dylint_check()),
        "dylint-link" => None,
        other => panic!("unexpected tool: {other}"),
    }
}

/// Configuration for post-primary installation call sequence.
struct PostPrimaryConfig {
    /// The tool name.
    tool: String,
    /// Static tool name for cargo install args.
    tool_static: &'static str,
    /// Whether repository metadata is available to pin cargo fallbacks.
    has_repository_context: bool,
    /// Whether the primary installation succeeded.
    primary_succeeded: bool,
    /// Whether to use binstall (vs cargo install).
    use_binstall: bool,
    /// Error message for cargo install failure (None if succeeds).
    cargo_install_failure: Option<String>,
}

fn repo_aware_cargo_install(
    tool: &'static str,
    has_repository_context: bool,
    result: Result<Output>,
) -> ExpectedCall {
    if has_repository_context {
        cargo_source_install(tool, dependency_version(tool), result)
    } else {
        cargo_install(tool, result)
    }
}

/// Builds the sequence of calls that follow the primary install attempt.
fn post_primary_calls(cfg: &PostPrimaryConfig) -> Vec<ExpectedCall> {
    if cfg.primary_succeeded {
        return tool_verification_check(&cfg.tool).into_iter().collect();
    }
    if !cfg.use_binstall {
        return vec![];
    }
    // binstall failed: check if we should sequence a cargo-install attempt
    if cfg.cargo_install_failure.is_none() {
        // cargo install succeeds after binstall fails
        let cargo_call = repo_aware_cargo_install(
            cfg.tool_static,
            cfg.has_repository_context,
            Ok(success_output()),
        );
        let mut calls = vec![cargo_call];
        calls.extend(tool_verification_check(&cfg.tool));
        return calls;
    }
    // binstall failed and cargo install also fails
    if let Some(message) = cfg.cargo_install_failure.as_deref() {
        let cargo_call = repo_aware_cargo_install(
            cfg.tool_static,
            cfg.has_repository_context,
            Ok(failure_output(message)),
        );
        vec![cargo_call]
    } else {
        vec![]
    }
}

fn source_install_fallback_calls(
    tool: &str,
    tool_static: &'static str,
    config: &ExpectedCallConfig<'_>,
) -> Vec<ExpectedCall> {
    let version = dependency_version(tool);
    let result = config.cargo_install_failure.map_or_else(
        || Ok(success_output()),
        |message| Ok(failure_output(message)),
    );
    let install_call = cargo_source_install(tool_static, version, result);
    if config.cargo_install_failure.is_none() {
        let mut calls = vec![install_call];
        calls.extend(tool_verification_check(tool));
        calls
    } else {
        vec![install_call]
    }
}

fn binstall_args_for_tool(
    tool: &str,
    tool_static: &'static str,
    config: &ExpectedCallConfig<'_>,
) -> Vec<&'static str> {
    if config.has_repository_context {
        let version = dependency_version(tool);
        vec!["binstall", "-y", "--version", version, tool_static]
    } else {
        vec!["binstall", "-y", tool_static]
    }
}

/// Creates expected calls for cargo fallback installation (binstall or install).
pub fn cargo_fallback_calls(tool: &str, config: &ExpectedCallConfig<'_>) -> Vec<ExpectedCall> {
    // Intentional leak in tests to extend lifetime for static string usage;
    // acceptable here as it will not be freed.
    let tool_static: &'static str = Box::leak(tool.to_owned().into_boxed_str());

    if config.is_repository_asset_missing {
        return source_install_fallback_calls(tool, tool_static, config);
    }

    let (use_binstall, failure_message) = if config.is_binstall_available {
        (true, config.cargo_binstall_failure)
    } else {
        (false, config.cargo_install_failure)
    };

    let args = if use_binstall {
        binstall_args_for_tool(tool, tool_static, config)
    } else {
        vec!["install", tool_static]
    };

    let install_call = ExpectedCall {
        cmd: "cargo",
        args,
        result: Ok(match failure_message {
            Some(message) => failure_output(message),
            None => success_output(),
        }),
    };

    let mut calls = vec![install_call];
    let post_config = PostPrimaryConfig {
        tool: tool.to_owned(),
        tool_static,
        has_repository_context: config.has_repository_context,
        primary_succeeded: failure_message.is_none(),
        use_binstall,
        cargo_install_failure: config.cargo_install_failure.map(String::from),
    };
    calls.extend(post_primary_calls(&post_config));
    calls
}

/// Builds the complete list of expected calls for a dependency binary test scenario.
pub fn expected_calls(tool: &str, config: ExpectedCallConfig<'_>) -> Vec<ExpectedCall> {
    let mut calls = vec![binstall_version_check(config.is_binstall_available)];

    if config.should_verify_repository_install {
        calls.extend(repository_verification_call(
            tool,
            config.is_repository_verification_failing,
        ));
        if !config.is_repository_verification_failing {
            return calls;
        }
    }

    calls.extend(cargo_fallback_calls(tool, &config));
    calls
}

/// Creates an expected call for verifying cargo-dylint installation.
pub fn cargo_dylint_check() -> ExpectedCall {
    ExpectedCall {
        cmd: "cargo",
        args: vec!["dylint", "--version"],
        result: Ok(cargo_dylint_version_output()),
    }
}

/// Creates an expected call for verifying cargo-dylint with a fixed result.
pub fn cargo_dylint_check_with_result(result: Result<Output>) -> ExpectedCall {
    ExpectedCall {
        cmd: "cargo",
        args: vec!["dylint", "--version"],
        result,
    }
}