rch-common 1.0.26

Shared types and utilities for Remote Compilation Helper
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Rust toolchain information types.
//!
//! Types for representing Rust toolchain information used in the RCH protocol
//! for toolchain synchronization between local and remote workers.

use serde::{Deserialize, Serialize};

/// Detected Rust toolchain information.
///
/// Contains the channel, optional date, and full version string needed
/// to ensure worker uses the same toolchain as the local project.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolchainInfo {
    /// The channel: "stable", "beta", "nightly", or specific version like "1.75.0".
    pub channel: String,
    /// Optional date for nightly/beta: "2024-01-15".
    pub date: Option<String>,
    /// Full version string from rustc --version.
    pub full_version: String,
}

impl ToolchainInfo {
    /// Create a new ToolchainInfo.
    pub fn new(
        channel: impl Into<String>,
        date: Option<String>,
        full_version: impl Into<String>,
    ) -> Self {
        Self {
            channel: channel.into(),
            date,
            full_version: full_version.into(),
        }
    }

    /// Format for rustup run command.
    ///
    /// Returns the toolchain identifier suitable for `rustup run <toolchain>`.
    pub fn rustup_toolchain(&self) -> String {
        match &self.date {
            Some(date) => format!("{}-{}", self.channel, date),
            None => self.channel.clone(),
        }
    }

    /// Check if this is a nightly toolchain.
    pub fn is_nightly(&self) -> bool {
        self.channel == "nightly"
    }

    /// Check if this is a beta toolchain.
    pub fn is_beta(&self) -> bool {
        self.channel == "beta"
    }

    /// Check if this is a stable toolchain.
    pub fn is_stable(&self) -> bool {
        self.channel == "stable"
    }
}

impl std::fmt::Display for ToolchainInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.rustup_toolchain())
    }
}

/// Wrap a command to run with a specific toolchain.
///
/// If toolchain is provided, wraps the command with `rustup run <toolchain>`.
/// Otherwise returns the original command unchanged.
pub fn wrap_command_with_toolchain(command: &str, toolchain: Option<&ToolchainInfo>) -> String {
    match toolchain {
        Some(tc) => format!("rustup run {} {}", tc.rustup_toolchain(), command),
        None => command.to_string(),
    }
}

use crate::types::ColorMode;

/// Wrap a command with environment variables to force color output.
///
/// Remote SSH connections typically don't allocate a PTY, which causes tools
/// like cargo, rustc, and bun to detect a non-TTY and disable color output.
/// This function adds environment variables that force color output regardless
/// of terminal detection.
///
/// # Environment Variables Set
///
/// - `CARGO_TERM_COLOR=always` - Forces cargo to output ANSI colors
/// - `RUST_LOG_STYLE=always` - Forces env_logger/tracing to use colors
/// - `CLICOLOR_FORCE=1` - Standard env var for forcing color output
/// - `FORCE_COLOR=1` - Used by many Node.js/JS tools including Bun
///
/// # Arguments
///
/// * `command` - The command to wrap
/// * `color_mode` - The color mode configuration
///
/// # Returns
///
/// The command prefixed with color-forcing environment variables,
/// or the original command if color mode is Auto or Never.
pub fn wrap_command_with_color(command: &str, color_mode: ColorMode) -> String {
    match color_mode {
        ColorMode::Always => {
            // Environment variables that force color output across different tools:
            // - CARGO_TERM_COLOR: cargo's native color setting
            // - RUST_LOG_STYLE: env_logger and tracing-subscriber color setting
            // - CLICOLOR_FORCE: de facto standard for forcing colors (clicolors.org)
            // - FORCE_COLOR: Node.js/JS ecosystem standard (used by Bun, chalk, etc.)
            // - NO_COLOR: Ensure it's unset (some tools check this first)
            format!(
                "env -u NO_COLOR CARGO_TERM_COLOR=always RUST_LOG_STYLE=always CLICOLOR_FORCE=1 FORCE_COLOR=1 {}",
                command
            )
        }
        ColorMode::Auto => {
            // Let the remote command auto-detect (default behavior)
            command.to_string()
        }
        ColorMode::Never => {
            // Explicitly disable colors
            format!("env NO_COLOR=1 CARGO_TERM_COLOR=never {}", command)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_toolchain_info_new() {
        let tc = ToolchainInfo::new(
            "nightly",
            Some("2024-01-15".to_string()),
            "rustc 1.76.0-nightly",
        );
        assert_eq!(tc.channel, "nightly");
        assert_eq!(tc.date, Some("2024-01-15".to_string()));
    }

    #[test]
    fn test_rustup_toolchain_with_date() {
        let tc = ToolchainInfo {
            channel: "nightly".to_string(),
            date: Some("2024-01-15".to_string()),
            full_version: "".to_string(),
        };
        assert_eq!(tc.rustup_toolchain(), "nightly-2024-01-15");
    }

    #[test]
    fn test_rustup_toolchain_without_date() {
        let tc = ToolchainInfo {
            channel: "stable".to_string(),
            date: None,
            full_version: "".to_string(),
        };
        assert_eq!(tc.rustup_toolchain(), "stable");
    }

    #[test]
    fn test_toolchain_info_display() {
        let tc = ToolchainInfo {
            channel: "nightly".to_string(),
            date: Some("2024-01-15".to_string()),
            full_version: "".to_string(),
        };
        assert_eq!(tc.to_string(), "nightly-2024-01-15");
    }

    #[test]
    fn test_is_nightly() {
        let tc = ToolchainInfo::new("nightly", None, "");
        assert!(tc.is_nightly());
        assert!(!tc.is_stable());
        assert!(!tc.is_beta());
    }

    #[test]
    fn test_is_stable() {
        let tc = ToolchainInfo::new("stable", None, "");
        assert!(tc.is_stable());
        assert!(!tc.is_nightly());
        assert!(!tc.is_beta());
    }

    #[test]
    fn test_serialization_roundtrip() {
        let tc = ToolchainInfo {
            channel: "nightly".to_string(),
            date: Some("2024-01-15".to_string()),
            full_version: "rustc 1.76.0-nightly (abc123 2024-01-15)".to_string(),
        };
        let json = serde_json::to_string(&tc).unwrap();
        let parsed: ToolchainInfo = serde_json::from_str(&json).unwrap();
        assert_eq!(tc, parsed);
    }

    #[test]
    fn test_wrap_command_with_toolchain() {
        let tc = ToolchainInfo::new("nightly", Some("2024-01-15".to_string()), "");
        let wrapped = wrap_command_with_toolchain("cargo build", Some(&tc));
        assert_eq!(wrapped, "rustup run nightly-2024-01-15 cargo build");
    }

    #[test]
    fn test_wrap_command_no_toolchain() {
        let wrapped = wrap_command_with_toolchain("cargo build", None);
        assert_eq!(wrapped, "cargo build");
    }

    #[test]
    fn test_wrap_command_stable_toolchain() {
        let tc = ToolchainInfo::new("stable", None, "");
        let wrapped = wrap_command_with_toolchain("cargo test", Some(&tc));
        assert_eq!(wrapped, "rustup run stable cargo test");
    }

    // === Additional command wrapping tests for toolchain synchronization ===

    #[test]
    fn test_is_beta() {
        let tc = ToolchainInfo::new("beta", None, "");
        assert!(tc.is_beta());
        assert!(!tc.is_stable());
        assert!(!tc.is_nightly());
    }

    #[test]
    fn test_wrap_command_beta_with_date() {
        let tc = ToolchainInfo::new("beta", Some("2024-02-01".to_string()), "");
        let wrapped = wrap_command_with_toolchain("cargo check", Some(&tc));
        assert_eq!(wrapped, "rustup run beta-2024-02-01 cargo check");
    }

    #[test]
    fn test_wrap_command_specific_version() {
        // Specific version like "1.75.0" without date
        let tc = ToolchainInfo::new("1.75.0", None, "rustc 1.75.0");
        let wrapped = wrap_command_with_toolchain("cargo build --release", Some(&tc));
        assert_eq!(wrapped, "rustup run 1.75.0 cargo build --release");
    }

    #[test]
    fn test_wrap_command_with_complex_args() {
        let tc = ToolchainInfo::new("nightly", None, "");
        let cmd = "cargo build --features \"feature1,feature2\" --target x86_64-unknown-linux-gnu";
        let wrapped = wrap_command_with_toolchain(cmd, Some(&tc));
        assert_eq!(
            wrapped,
            "rustup run nightly cargo build --features \"feature1,feature2\" --target x86_64-unknown-linux-gnu"
        );
    }

    #[test]
    fn test_wrap_command_with_path_spaces() {
        let tc = ToolchainInfo::new("stable", None, "");
        let cmd = "cargo build --manifest-path \"/path/with spaces/Cargo.toml\"";
        let wrapped = wrap_command_with_toolchain(cmd, Some(&tc));
        assert_eq!(
            wrapped,
            "rustup run stable cargo build --manifest-path \"/path/with spaces/Cargo.toml\""
        );
    }

    #[test]
    fn test_wrap_command_empty_string() {
        let tc = ToolchainInfo::new("stable", None, "");
        let wrapped = wrap_command_with_toolchain("", Some(&tc));
        assert_eq!(wrapped, "rustup run stable ");
    }

    #[test]
    fn test_wrap_command_empty_string_no_toolchain() {
        let wrapped = wrap_command_with_toolchain("", None);
        assert_eq!(wrapped, "");
    }

    #[test]
    fn test_wrap_command_clippy() {
        let tc = ToolchainInfo::new("nightly", Some("2024-03-15".to_string()), "");
        let wrapped = wrap_command_with_toolchain("cargo clippy -- -D warnings", Some(&tc));
        assert_eq!(
            wrapped,
            "rustup run nightly-2024-03-15 cargo clippy -- -D warnings"
        );
    }

    #[test]
    fn test_wrap_command_rustfmt() {
        let tc = ToolchainInfo::new("nightly", None, "");
        let wrapped = wrap_command_with_toolchain("cargo fmt --check", Some(&tc));
        assert_eq!(wrapped, "rustup run nightly cargo fmt --check");
    }

    #[test]
    fn test_wrap_command_test_with_filter() {
        let tc = ToolchainInfo::new("stable", None, "");
        let wrapped = wrap_command_with_toolchain("cargo test test_name -- --nocapture", Some(&tc));
        assert_eq!(
            wrapped,
            "rustup run stable cargo test test_name -- --nocapture"
        );
    }

    #[test]
    fn test_rustup_toolchain_beta_with_date() {
        let tc = ToolchainInfo {
            channel: "beta".to_string(),
            date: Some("2024-02-01".to_string()),
            full_version: "".to_string(),
        };
        assert_eq!(tc.rustup_toolchain(), "beta-2024-02-01");
    }

    #[test]
    fn test_rustup_toolchain_specific_version() {
        let tc = ToolchainInfo {
            channel: "1.75.0".to_string(),
            date: None,
            full_version: "rustc 1.75.0".to_string(),
        };
        assert_eq!(tc.rustup_toolchain(), "1.75.0");
    }

    #[test]
    fn test_display_stable() {
        let tc = ToolchainInfo::new("stable", None, "");
        assert_eq!(tc.to_string(), "stable");
    }

    #[test]
    fn test_display_beta_with_date() {
        let tc = ToolchainInfo::new("beta", Some("2024-02-01".to_string()), "");
        assert_eq!(tc.to_string(), "beta-2024-02-01");
    }

    #[test]
    fn test_serialization_stable() {
        let tc = ToolchainInfo::new("stable", None, "rustc 1.75.0 (hash 2024-01-01)");
        let json = serde_json::to_string(&tc).unwrap();
        assert!(json.contains("\"channel\":\"stable\""));
        assert!(json.contains("\"date\":null"));
        let parsed: ToolchainInfo = serde_json::from_str(&json).unwrap();
        assert_eq!(tc, parsed);
    }

    #[test]
    fn test_serialization_beta_with_date() {
        let tc = ToolchainInfo::new("beta", Some("2024-02-01".to_string()), "rustc 1.76.0-beta");
        let json = serde_json::to_string(&tc).unwrap();
        let parsed: ToolchainInfo = serde_json::from_str(&json).unwrap();
        assert_eq!(tc, parsed);
        assert_eq!(parsed.date, Some("2024-02-01".to_string()));
    }

    #[test]
    fn test_toolchain_info_clone() {
        let tc = ToolchainInfo::new("nightly", Some("2024-01-15".to_string()), "rustc 1.76.0");
        let cloned = tc.clone();
        assert_eq!(tc, cloned);
        assert_eq!(tc.channel, cloned.channel);
        assert_eq!(tc.date, cloned.date);
        assert_eq!(tc.full_version, cloned.full_version);
    }

    #[test]
    fn test_toolchain_info_equality() {
        let tc1 = ToolchainInfo::new("nightly", Some("2024-01-15".to_string()), "rustc 1.76.0");
        let tc2 = ToolchainInfo::new("nightly", Some("2024-01-15".to_string()), "rustc 1.76.0");
        let tc3 = ToolchainInfo::new("nightly", Some("2024-01-16".to_string()), "rustc 1.76.0");
        assert_eq!(tc1, tc2);
        assert_ne!(tc1, tc3);
    }

    #[test]
    fn test_channel_detection_methods_consistency() {
        // Only one of the is_* methods should return true for a given toolchain
        for channel in &["stable", "beta", "nightly", "1.75.0", "custom"] {
            let tc = ToolchainInfo::new(*channel, None, "");
            let count = [tc.is_stable(), tc.is_beta(), tc.is_nightly()]
                .iter()
                .filter(|&&b| b)
                .count();
            // Should have at most one true (custom channels have none)
            assert!(count <= 1, "Multiple channel types for: {}", channel);
        }
    }

    // === Color wrapping tests ===

    #[test]
    fn test_wrap_command_with_color_always() {
        let wrapped = wrap_command_with_color("cargo test", ColorMode::Always);
        assert!(wrapped.contains("CARGO_TERM_COLOR=always"));
        assert!(wrapped.contains("RUST_LOG_STYLE=always"));
        assert!(wrapped.contains("CLICOLOR_FORCE=1"));
        assert!(wrapped.contains("FORCE_COLOR=1"));
        assert!(wrapped.contains("env -u NO_COLOR"));
        assert!(wrapped.contains("cargo test"));
    }

    #[test]
    fn test_wrap_command_with_color_auto() {
        let wrapped = wrap_command_with_color("cargo test", ColorMode::Auto);
        // Auto mode should not modify the command
        assert_eq!(wrapped, "cargo test");
    }

    #[test]
    fn test_wrap_command_with_color_never() {
        let wrapped = wrap_command_with_color("cargo test", ColorMode::Never);
        assert!(wrapped.starts_with("env "));
        assert!(wrapped.contains("NO_COLOR=1"));
        assert!(wrapped.contains("CARGO_TERM_COLOR=never"));
        assert!(wrapped.contains("cargo test"));
    }

    #[test]
    fn test_wrap_command_with_color_never_is_timeout_safe() {
        let wrapped = wrap_command_with_color("sh -c 'exit 43'", ColorMode::Never);
        let status = std::process::Command::new("sh")
            .arg("-c")
            .arg(format!(
                "timeout --foreground --preserve-status 5 {}",
                wrapped
            ))
            .status()
            .expect("timeout-wrapped color-disabled command should execute");

        assert_eq!(
            status.code(),
            Some(43),
            "timeout must execute env, not an environment assignment argv"
        );
    }

    #[test]
    fn test_wrap_command_with_color_preserves_complex_command() {
        let cmd = "cargo test --release -- --test-threads=4";
        let wrapped = wrap_command_with_color(cmd, ColorMode::Always);
        assert!(wrapped.contains(cmd));
    }

    #[test]
    fn test_wrap_command_with_color_bun_commands() {
        // Verify Bun commands work with color wrapping (uses FORCE_COLOR)
        let wrapped = wrap_command_with_color("bun test", ColorMode::Always);
        assert!(wrapped.contains("FORCE_COLOR=1"));
        assert!(wrapped.contains("bun test"));
    }

    #[test]
    fn test_color_mode_display() {
        assert_eq!(ColorMode::Always.to_string(), "always");
        assert_eq!(ColorMode::Auto.to_string(), "auto");
        assert_eq!(ColorMode::Never.to_string(), "never");
    }

    #[test]
    fn test_color_mode_from_str() {
        assert_eq!("always".parse::<ColorMode>(), Ok(ColorMode::Always));
        assert_eq!("force".parse::<ColorMode>(), Ok(ColorMode::Always));
        assert_eq!("auto".parse::<ColorMode>(), Ok(ColorMode::Auto));
        assert_eq!("never".parse::<ColorMode>(), Ok(ColorMode::Never));
        assert_eq!("no".parse::<ColorMode>(), Ok(ColorMode::Never));
        assert!("invalid".parse::<ColorMode>().is_err());
    }

    #[test]
    fn test_color_mode_default() {
        // Default should be Always to preserve colors in remote SSH
        assert_eq!(ColorMode::default(), ColorMode::Always);
    }
}