Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
536 changes: 528 additions & 8 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ miette = { version = "7", features = ["fancy"] }
ratatui = "0.30"
serde = { version = "1", features = ["derive"] }
serde_yaml = "0.9"
serde_json = "1"
ureq = "2"
time = { version = "0.3", features = ["formatting"] }
tracing = "0.1"
tracing-subscriber = "0.3"
walkdir = "2"
Expand Down
68 changes: 68 additions & 0 deletions src/compose/down.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,72 @@
use std::path::Path;
use std::process::Command;

use anyhow::{Context, Result};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComposeDownRequest {
pub remove_volumes: bool,
pub remove_orphans: bool,
}

impl Default for ComposeDownRequest {
fn default() -> Self {
Self {
remove_volumes: false,
remove_orphans: true,
}
}
}

/// Execute `docker compose down`.
pub fn execute(request: &ComposeDownRequest, project_root: &Path) -> Result<String> {
let mut args = vec!["compose".to_string(), "down".to_string()];

if request.remove_volumes {
args.push("-v".to_string());
}

if request.remove_orphans {
args.push("--remove-orphans".to_string());
}

let output = Command::new("docker")
.args(&args)
.current_dir(project_root)
.output()
.context("Failed to execute docker compose down")?;

let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);

if output.status.success() {
Ok(format!("{stdout}{stderr}"))
} else {
anyhow::bail!("docker compose down failed: {stderr}")
}
}

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

#[test]
fn compose_down_defaults() {
let request = ComposeDownRequest::default();
assert!(!request.remove_volumes);
assert!(request.remove_orphans);
}

#[test]
fn test_execute() {
crate::utils::test_support::set_mock_path();
let request = ComposeDownRequest {
remove_volumes: true,
remove_orphans: true,
};
let res = execute(&request, Path::new("."));
assert!(res.is_ok());
let output = res.unwrap();
assert!(output.contains("Stopping container"));
}
}
86 changes: 86 additions & 0 deletions src/compose/logs.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,90 @@
use std::path::Path;
use std::process::Command;

use anyhow::{Context, Result};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComposeLogRequest {
pub follow: bool,
pub service: Option<String>,
pub tail: Option<usize>,
}

impl Default for ComposeLogRequest {
fn default() -> Self {
Self {
follow: false,
service: None,
tail: Some(100),
}
}
}

/// Fetch compose logs.
pub fn fetch(request: &ComposeLogRequest, project_root: &Path) -> Result<Vec<String>> {
let mut args = vec!["compose".to_string(), "logs".to_string()];

if request.follow {
args.push("--follow".to_string());
}

if let Some(tail) = request.tail {
args.push("--tail".to_string());
args.push(tail.to_string());
}

if let Some(service) = &request.service {
args.push(service.clone());
}

let output = Command::new("docker")
.args(&args)
.current_dir(project_root)
.output()
.context("Failed to execute docker compose logs")?;

if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
anyhow::bail!("docker compose logs failed: {}", stderr);
}

let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let combined = format!("{stdout}{stderr}");

let lines = combined
.lines()
.filter(|line| !line.is_empty())
.map(|line| line.to_string())
.collect();

Ok(lines)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

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

#[test]
fn compose_log_request_defaults() {
let request = ComposeLogRequest::default();
assert!(!request.follow);
assert!(request.service.is_none());
assert_eq!(request.tail, Some(100));
}

#[test]
fn test_fetch_compose_logs() {
crate::utils::test_support::set_mock_path();
let request = ComposeLogRequest {
follow: false,
service: Some("web".to_string()),
tail: Some(10),
};
let res = fetch(&request, Path::new("."));
assert!(res.is_ok());
let lines = res.unwrap();
assert!(lines.len() >= 2);
assert_eq!(lines[0], "compose log line 1");
}
}
1 change: 1 addition & 0 deletions src/compose/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod down;
pub mod logs;
pub mod restart;
pub mod services;
pub mod up;
58 changes: 58 additions & 0 deletions src/compose/restart.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,62 @@
use std::path::Path;
use std::process::Command;

use anyhow::{Context, Result};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComposeRestartRequest {
pub service: Option<String>,
}

/// Execute `docker compose restart`.
pub fn execute(request: &ComposeRestartRequest, project_root: &Path) -> Result<String> {
let mut args = vec!["compose".to_string(), "restart".to_string()];

if let Some(service) = &request.service {
args.push(service.clone());
}

let output = Command::new("docker")
.args(&args)
.current_dir(project_root)
.output()
.context("Failed to execute docker compose restart")?;

let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);

if output.status.success() {
Ok(format!("{stdout}{stderr}"))
} else {
anyhow::bail!("docker compose restart failed: {stderr}")
}
}

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

#[test]
fn compose_restart_without_service() {
let request = ComposeRestartRequest { service: None };
assert!(request.service.is_none());
}

#[test]
fn compose_restart_with_service() {
let request = ComposeRestartRequest {
service: Some("web".to_string()),
};
assert_eq!(request.service, Some("web".to_string()));
}

#[test]
fn test_execute() {
crate::utils::test_support::set_mock_path();
let request = ComposeRestartRequest {
service: Some("db".to_string()),
};
let res = execute(&request, Path::new("."));
assert!(res.is_ok());
}
}
72 changes: 72 additions & 0 deletions src/compose/services.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use std::path::Path;
use std::process::Command;

use anyhow::{Context, Result};

/// List the services defined in the Compose file.
pub fn list(project_root: &Path) -> Result<Vec<String>> {
let output = Command::new("docker")
.args(["compose", "config", "--services"])
.current_dir(project_root)
.output()
.context("Failed to execute docker compose config --services")?;

if !output.status.success() {
let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
anyhow::bail!("docker compose config --services failed: {err}");
}

let stdout = String::from_utf8_lossy(&output.stdout);
let services = stdout
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| line.trim().to_string())
.collect();

Ok(services)
}

/// Check if any Compose services are currently running.
pub fn running(project_root: &Path) -> Result<Vec<String>> {
let output = Command::new("docker")
.args(["compose", "ps", "--services", "--filter", "status=running"])
.current_dir(project_root)
.output()
.context("Failed to execute docker compose ps --services")?;

if !output.status.success() {
let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
anyhow::bail!("docker compose ps --services failed: {err}");
}

let stdout = String::from_utf8_lossy(&output.stdout);
let services = stdout
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| line.trim().to_string())
.collect();

Ok(services)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

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

#[test]
fn services_module_compiles() {
let _: fn(&std::path::Path) -> anyhow::Result<Vec<String>> = super::list;
}

#[test]
fn test_list_and_running() {
crate::utils::test_support::set_mock_path();
let path = std::path::Path::new(".");

let services = list(path).unwrap();
assert_eq!(services, vec!["service1", "service2"]);

let running_services = running(path).unwrap();
assert_eq!(running_services, vec!["service1"]);
}
}
Loading