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
//! Docker Compose ps command implementation using unified trait pattern.

use crate::command::{CommandExecutor, ComposeCommand, ComposeConfig, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};

/// Docker Compose ps command builder
#[derive(Debug, Clone)]
pub struct ComposePsCommand {
    /// Base command executor
    pub executor: CommandExecutor,
    /// Base compose configuration
    pub config: ComposeConfig,
    /// Services to list (empty for all)
    pub services: Vec<String>,
    /// Show all containers (including stopped)
    pub all: bool,
    /// Only display container IDs
    pub quiet: bool,
    /// Show services
    pub show_services: bool,
    /// Filter containers
    pub filter: Vec<String>,
    /// Output format
    pub format: Option<String>,
    /// Only show running containers
    pub status: Option<Vec<ContainerStatus>>,
}

/// Container status filter
#[derive(Debug, Clone, Copy)]
pub enum ContainerStatus {
    /// Paused containers
    Paused,
    /// Restarting containers
    Restarting,
    /// Running containers
    Running,
    /// Stopped containers
    Stopped,
}

impl std::fmt::Display for ContainerStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Paused => write!(f, "paused"),
            Self::Restarting => write!(f, "restarting"),
            Self::Running => write!(f, "running"),
            Self::Stopped => write!(f, "stopped"),
        }
    }
}

/// Container information from compose ps
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComposeContainerInfo {
    /// Container ID
    #[serde(rename = "ID")]
    pub id: String,
    /// Container name
    #[serde(rename = "Name")]
    pub name: String,
    /// Service name
    #[serde(rename = "Service")]
    pub service: String,
    /// Container state
    #[serde(rename = "State")]
    pub state: String,
    /// Health status
    #[serde(rename = "Health")]
    pub health: Option<String>,
    /// Exit code
    #[serde(rename = "ExitCode")]
    pub exit_code: Option<i32>,
    /// Published ports
    #[serde(rename = "Publishers")]
    pub publishers: Option<Vec<PortPublisher>>,
}

/// Port publishing information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PortPublisher {
    /// Target port
    #[serde(rename = "TargetPort")]
    pub target_port: u16,
    /// Published port
    #[serde(rename = "PublishedPort")]
    pub published_port: Option<u16>,
    /// Protocol
    #[serde(rename = "Protocol")]
    pub protocol: String,
}

/// Result from compose ps command
#[derive(Debug, Clone)]
pub struct ComposePsResult {
    /// Raw stdout output
    pub stdout: String,
    /// Raw stderr output
    pub stderr: String,
    /// Success status
    pub success: bool,
    /// Parsed container information (if JSON format)
    pub containers: Vec<ComposeContainerInfo>,
}

impl ComposePsCommand {
    /// Create a new compose ps command
    #[must_use]
    pub fn new() -> Self {
        Self {
            executor: CommandExecutor::new(),
            config: ComposeConfig::new(),
            services: Vec::new(),
            all: false,
            quiet: false,
            show_services: false,
            filter: Vec::new(),
            format: None,
            status: None,
        }
    }

    /// Add a service to list
    #[must_use]
    pub fn service(mut self, service: impl Into<String>) -> Self {
        self.services.push(service.into());
        self
    }

    /// Show all containers (default shows only running)
    #[must_use]
    pub fn all(mut self) -> Self {
        self.all = true;
        self
    }

    /// Only display container IDs
    #[must_use]
    pub fn quiet(mut self) -> Self {
        self.quiet = true;
        self
    }

    /// Display services
    #[must_use]
    pub fn services(mut self) -> Self {
        self.show_services = true;
        self
    }

    /// Add a filter
    #[must_use]
    pub fn filter(mut self, filter: impl Into<String>) -> Self {
        self.filter.push(filter.into());
        self
    }

    /// Set output format
    #[must_use]
    pub fn format(mut self, format: impl Into<String>) -> Self {
        self.format = Some(format.into());
        self
    }

    /// Filter by status
    #[must_use]
    pub fn status(mut self, status: ContainerStatus) -> Self {
        self.status.get_or_insert_with(Vec::new).push(status);
        self
    }

    /// Use JSON output format
    #[must_use]
    pub fn json(mut self) -> Self {
        self.format = Some("json".to_string());
        self
    }

    /// Parse JSON output into container info
    fn parse_json_output(stdout: &str) -> Vec<ComposeContainerInfo> {
        stdout
            .lines()
            .filter(|line| !line.trim().is_empty())
            .filter_map(|line| serde_json::from_str(line).ok())
            .collect()
    }
}

impl Default for ComposePsCommand {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DockerCommand for ComposePsCommand {
    type Output = ComposePsResult;

    fn get_executor(&self) -> &CommandExecutor {
        &self.executor
    }

    fn get_executor_mut(&mut self) -> &mut CommandExecutor {
        &mut self.executor
    }

    fn build_command_args(&self) -> Vec<String> {
        // Use the ComposeCommand implementation explicitly
        <Self as ComposeCommand>::build_command_args(self)
    }

    async fn execute(&self) -> Result<Self::Output> {
        let args = <Self as ComposeCommand>::build_command_args(self);
        let output = self.execute_command(args).await?;

        // Parse JSON output if format is json
        let containers = if self.format.as_deref() == Some("json") {
            Self::parse_json_output(&output.stdout)
        } else {
            Vec::new()
        };

        Ok(ComposePsResult {
            stdout: output.stdout,
            stderr: output.stderr,
            success: output.success,
            containers,
        })
    }
}

impl ComposeCommand for ComposePsCommand {
    fn get_config(&self) -> &ComposeConfig {
        &self.config
    }

    fn get_config_mut(&mut self) -> &mut ComposeConfig {
        &mut self.config
    }

    fn subcommand(&self) -> &'static str {
        "ps"
    }

    fn build_subcommand_args(&self) -> Vec<String> {
        let mut args = Vec::new();

        if self.all {
            args.push("--all".to_string());
        }

        if self.quiet {
            args.push("--quiet".to_string());
        }

        if self.show_services {
            args.push("--services".to_string());
        }

        for filter in &self.filter {
            args.push("--filter".to_string());
            args.push(filter.clone());
        }

        if let Some(ref format) = self.format {
            args.push("--format".to_string());
            args.push(format.clone());
        }

        if let Some(ref statuses) = self.status {
            for status in statuses {
                args.push("--status".to_string());
                args.push(status.to_string());
            }
        }

        // Add service names at the end
        args.extend(self.services.clone());

        args
    }
}

impl ComposePsResult {
    /// Check if the command was successful
    #[must_use]
    pub fn success(&self) -> bool {
        self.success
    }

    /// Get container information
    #[must_use]
    pub fn containers(&self) -> &[ComposeContainerInfo] {
        &self.containers
    }

    /// Get container IDs from output
    #[must_use]
    pub fn container_ids(&self) -> Vec<String> {
        if self.containers.is_empty() {
            // Parse from text output if not JSON
            self.stdout
                .lines()
                .skip(1) // Skip header
                .filter_map(|line| line.split_whitespace().next())
                .map(String::from)
                .collect()
        } else {
            self.containers.iter().map(|c| c.id.clone()).collect()
        }
    }

    /// Get stdout lines
    #[must_use]
    pub fn stdout_lines(&self) -> Vec<&str> {
        self.stdout.lines().collect()
    }
}

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

    #[test]
    fn test_compose_ps_basic() {
        let cmd = ComposePsCommand::new();
        let args = cmd.build_subcommand_args();
        assert!(args.is_empty());

        let full_args = ComposeCommand::build_command_args(&cmd);
        assert_eq!(full_args[0], "compose");
        assert!(full_args.contains(&"ps".to_string()));
    }

    #[test]
    fn test_compose_ps_all() {
        let cmd = ComposePsCommand::new().all();
        let args = cmd.build_subcommand_args();
        assert_eq!(args, vec!["--all"]);
    }

    #[test]
    fn test_compose_ps_with_format() {
        let cmd = ComposePsCommand::new().format("json").all();
        let args = cmd.build_subcommand_args();
        assert_eq!(args, vec!["--all", "--format", "json"]);
    }

    #[test]
    fn test_compose_ps_with_filters() {
        let cmd = ComposePsCommand::new()
            .filter("status=running")
            .quiet()
            .service("web");
        let args = cmd.build_subcommand_args();
        assert_eq!(args, vec!["--quiet", "--filter", "status=running", "web"]);
    }

    #[test]
    fn test_container_status_display() {
        assert_eq!(ContainerStatus::Running.to_string(), "running");
        assert_eq!(ContainerStatus::Stopped.to_string(), "stopped");
        assert_eq!(ContainerStatus::Paused.to_string(), "paused");
        assert_eq!(ContainerStatus::Restarting.to_string(), "restarting");
    }

    #[test]
    fn test_compose_config_integration() {
        let cmd = ComposePsCommand::new()
            .file("docker-compose.yml")
            .project_name("my-project")
            .all();

        let args = ComposeCommand::build_command_args(&cmd);
        assert!(args.contains(&"--file".to_string()));
        assert!(args.contains(&"docker-compose.yml".to_string()));
        assert!(args.contains(&"--project-name".to_string()));
        assert!(args.contains(&"my-project".to_string()));
        assert!(args.contains(&"--all".to_string()));
    }

    /// Regression test for issue #233: `ComposePsCommand` was failing because
    /// the command was being built as "docker docker compose ..." instead of
    /// "docker compose ...". This verifies that `build_command_args` does not
    /// include "docker" since the runtime binary is added separately.
    #[test]
    fn test_compose_args_no_docker_prefix() {
        let cmd = ComposePsCommand::new()
            .file("/path/to/docker-compose.yaml")
            .service("php");

        let args = ComposeCommand::build_command_args(&cmd);

        // Args should start with "compose", not "docker"
        assert_eq!(args[0], "compose");
        // "docker" should not appear anywhere in the args (the runtime binary
        // is added separately by CommandExecutor)
        assert!(
            !args.iter().any(|arg| arg == "docker"),
            "args should not contain 'docker': {args:?}"
        );
    }
}