docker-wrapper 0.11.1

A Docker CLI wrapper for Rust
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
//! Platform detection and runtime abstraction for Docker environments.

use crate::error::{Error, Result};
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Represents the detected container runtime
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Runtime {
    /// Docker runtime
    Docker,
    /// Podman runtime (Docker-compatible)
    Podman,
    /// Colima runtime (Docker-compatible on macOS)
    Colima,
    /// Rancher Desktop runtime
    RancherDesktop,
    /// `OrbStack` runtime (macOS)
    OrbStack,
    /// Docker Desktop
    DockerDesktop,
}

impl Runtime {
    /// Get the command name for this runtime
    #[must_use]
    pub fn command(&self) -> &str {
        match self {
            Runtime::Docker
            | Runtime::Colima
            | Runtime::RancherDesktop
            | Runtime::OrbStack
            | Runtime::DockerDesktop => "docker",
            Runtime::Podman => "podman",
        }
    }

    /// Check if this runtime supports Docker Compose
    #[must_use]
    pub fn supports_compose(&self) -> bool {
        matches!(
            self,
            Runtime::Docker
                | Runtime::DockerDesktop
                | Runtime::Colima
                | Runtime::RancherDesktop
                | Runtime::OrbStack
        )
    }

    /// Get compose command for this runtime
    #[must_use]
    pub fn compose_command(&self) -> Vec<String> {
        match self {
            Runtime::Podman => vec!["podman-compose".to_string()],
            Runtime::Docker
            | Runtime::DockerDesktop
            | Runtime::Colima
            | Runtime::RancherDesktop
            | Runtime::OrbStack => {
                vec!["docker".to_string(), "compose".to_string()]
            }
        }
    }
}

impl std::fmt::Display for Runtime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Runtime::Docker => write!(f, "Docker"),
            Runtime::Podman => write!(f, "Podman"),
            Runtime::Colima => write!(f, "Colima"),
            Runtime::RancherDesktop => write!(f, "Rancher Desktop"),
            Runtime::OrbStack => write!(f, "OrbStack"),
            Runtime::DockerDesktop => write!(f, "Docker Desktop"),
        }
    }
}

/// Operating system platform
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Platform {
    /// Linux
    Linux,
    /// macOS
    MacOS,
    /// Windows
    Windows,
    /// FreeBSD
    FreeBSD,
    /// Other/Unknown
    Other(String),
}

impl Platform {
    /// Detect the current platform
    #[must_use]
    pub fn detect() -> Self {
        match env::consts::OS {
            "linux" => Platform::Linux,
            "macos" | "darwin" => Platform::MacOS,
            "windows" => Platform::Windows,
            "freebsd" => Platform::FreeBSD,
            other => Platform::Other(other.to_string()),
        }
    }

    /// Check if running inside WSL
    #[must_use]
    pub fn is_wsl(&self) -> bool {
        if !matches!(self, Platform::Linux) {
            return false;
        }

        // Check for WSL-specific files/environment
        Path::new("/proc/sys/fs/binfmt_misc/WSLInterop").exists()
            || env::var("WSL_DISTRO_NAME").is_ok()
            || env::var("WSL_INTEROP").is_ok()
    }

    /// Get the default Docker socket path for this platform
    #[must_use]
    pub fn default_socket_path(&self) -> PathBuf {
        match self {
            Platform::MacOS => {
                // Check for various Docker socket locations on macOS
                let locations = [
                    "/var/run/docker.sock",
                    "/Users/$USER/.docker/run/docker.sock",
                    "/Users/$USER/.colima/docker.sock",
                    "/Users/$USER/.orbstack/run/docker.sock",
                ];

                for location in &locations {
                    let path = if location.contains("$USER") {
                        let user = env::var("USER").unwrap_or_else(|_| "unknown".to_string());
                        PathBuf::from(location.replace("$USER", &user))
                    } else {
                        PathBuf::from(location)
                    };

                    if path.exists() {
                        return path;
                    }
                }

                PathBuf::from("/var/run/docker.sock")
            }
            Platform::Windows => PathBuf::from("//./pipe/docker_engine"),
            Platform::Linux | Platform::FreeBSD | Platform::Other(_) => {
                PathBuf::from("/var/run/docker.sock")
            }
        }
    }
}

impl std::fmt::Display for Platform {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Platform::Linux => write!(f, "Linux"),
            Platform::MacOS => write!(f, "macOS"),
            Platform::Windows => write!(f, "Windows"),
            Platform::FreeBSD => write!(f, "FreeBSD"),
            Platform::Other(s) => write!(f, "{s}"),
        }
    }
}

/// Platform and runtime detection
#[derive(Debug, Clone)]
pub struct PlatformInfo {
    /// Operating system platform
    pub platform: Platform,
    /// Container runtime
    pub runtime: Runtime,
    /// Docker/runtime version
    pub version: String,
    /// Whether running in WSL
    pub is_wsl: bool,
    /// Docker socket path
    pub socket_path: PathBuf,
}

impl PlatformInfo {
    /// Detect platform and runtime information
    ///
    /// # Errors
    ///
    /// Returns an error if no container runtime is detected
    pub fn detect() -> Result<Self> {
        let platform = Platform::detect();
        let is_wsl = platform.is_wsl();
        let socket_path = Self::find_socket_path(&platform);

        // Detect runtime
        let runtime = Self::detect_runtime()?;
        let version = Self::get_runtime_version(&runtime)?;

        Ok(Self {
            platform,
            runtime,
            version,
            is_wsl,
            socket_path,
        })
    }

    /// Find the Docker socket path
    fn find_socket_path(platform: &Platform) -> PathBuf {
        // Check DOCKER_HOST environment variable first
        if let Ok(docker_host) = env::var("DOCKER_HOST") {
            if docker_host.starts_with("unix://") {
                return PathBuf::from(docker_host.trim_start_matches("unix://"));
            }
        }

        platform.default_socket_path()
    }

    /// Detect the container runtime
    fn detect_runtime() -> Result<Runtime> {
        // Check for specific runtime environment variables
        if env::var("ORBSTACK_HOME").is_ok() {
            return Ok(Runtime::OrbStack);
        }

        if env::var("COLIMA_HOME").is_ok() {
            return Ok(Runtime::Colima);
        }

        // Try to detect by checking version output
        if let Ok(output) = Command::new("docker").arg("version").output() {
            let version_str = String::from_utf8_lossy(&output.stdout);

            if version_str.contains("Docker Desktop") {
                return Ok(Runtime::DockerDesktop);
            }

            if version_str.contains("Rancher Desktop") {
                return Ok(Runtime::RancherDesktop);
            }

            if version_str.contains("podman") {
                return Ok(Runtime::Podman);
            }

            if version_str.contains("colima") {
                return Ok(Runtime::Colima);
            }

            if version_str.contains("OrbStack") {
                return Ok(Runtime::OrbStack);
            }

            // Generic Docker
            if version_str.contains("Docker") {
                return Ok(Runtime::Docker);
            }
        }

        // Try podman as fallback
        if Command::new("podman").arg("version").output().is_ok() {
            return Ok(Runtime::Podman);
        }

        Err(Error::DockerNotFound)
    }

    /// Get runtime version
    fn get_runtime_version(runtime: &Runtime) -> Result<String> {
        let output = Command::new(runtime.command())
            .arg("version")
            .arg("--format")
            .arg("{{.Server.Version}}")
            .output()
            .map_err(|e| {
                Error::command_failed(
                    format!("{} version", runtime.command()),
                    -1,
                    "",
                    e.to_string(),
                )
            })?;

        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            // Fallback to parsing regular version output
            let output = Command::new(runtime.command())
                .arg("version")
                .output()
                .map_err(|e| {
                    Error::command_failed(
                        format!("{} version", runtime.command()),
                        -1,
                        "",
                        e.to_string(),
                    )
                })?;

            let version_str = String::from_utf8_lossy(&output.stdout);
            Ok(Self::parse_version(&version_str))
        }
    }

    /// Parse version from version string
    fn parse_version(version_str: &str) -> String {
        // Look for version patterns
        for line in version_str.lines() {
            if line.contains("Version:") {
                if let Some(version) = line.split(':').nth(1) {
                    return version.trim().to_string();
                }
            }
        }

        "unknown".to_string()
    }

    /// Check if the runtime is available and working
    ///
    /// # Errors
    ///
    /// Returns an error if the runtime is not found or not running
    pub fn check_runtime(&self) -> Result<()> {
        let output = Command::new(self.runtime.command())
            .arg("info")
            .output()
            .map_err(|_| Error::DockerNotFound)?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("Cannot connect to the Docker daemon") {
                return Err(Error::DaemonNotRunning);
            }
            return Err(Error::command_failed(
                format!("{} info", self.runtime.command()),
                -1,
                "",
                stderr,
            ));
        }

        Ok(())
    }

    /// Get runtime-specific environment variables
    #[must_use]
    pub fn environment_vars(&self) -> Vec<(String, String)> {
        let mut vars = Vec::new();

        // Add socket path if needed
        if self.socket_path.exists() {
            vars.push((
                "DOCKER_HOST".to_string(),
                format!("unix://{}", self.socket_path.display()),
            ));
        }

        // Add runtime-specific vars
        match self.runtime {
            Runtime::Podman => {
                vars.push(("DOCKER_BUILDKIT".to_string(), "0".to_string()));
            }
            Runtime::DockerDesktop | Runtime::Docker => {
                vars.push(("DOCKER_BUILDKIT".to_string(), "1".to_string()));
            }
            _ => {}
        }

        vars
    }
}

impl std::fmt::Display for PlatformInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} on {} (version: {})",
            self.runtime, self.platform, self.version
        )?;
        if self.is_wsl {
            write!(f, " [WSL]")?;
        }
        Ok(())
    }
}

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

    #[test]
    fn test_platform_detection() {
        let platform = Platform::detect();
        // Should detect something
        assert!(matches!(
            platform,
            Platform::Linux
                | Platform::MacOS
                | Platform::Windows
                | Platform::FreeBSD
                | Platform::Other(_)
        ));
    }

    #[test]
    fn test_runtime_command() {
        assert_eq!(Runtime::Docker.command(), "docker");
        assert_eq!(Runtime::Podman.command(), "podman");
        assert_eq!(Runtime::Colima.command(), "docker");
    }

    #[test]
    fn test_runtime_compose_support() {
        assert!(Runtime::Docker.supports_compose());
        assert!(Runtime::DockerDesktop.supports_compose());
        assert!(Runtime::Colima.supports_compose());
        assert!(!Runtime::Podman.supports_compose());
    }

    #[test]
    fn test_platform_display() {
        assert_eq!(Platform::Linux.to_string(), "Linux");
        assert_eq!(Platform::MacOS.to_string(), "macOS");
        assert_eq!(Platform::Windows.to_string(), "Windows");
    }

    #[test]
    fn test_runtime_display() {
        assert_eq!(Runtime::Docker.to_string(), "Docker");
        assert_eq!(Runtime::Podman.to_string(), "Podman");
        assert_eq!(Runtime::OrbStack.to_string(), "OrbStack");
    }
}