stout 0.2.1

A fast, Rust-based Homebrew-compatible package manager
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
//! Services command - manage background services
//!
//! This provides basic service management for packages that include
//! launchd plists (macOS) or systemd units (Linux).

use anyhow::{bail, Context, Result};
use clap::{Args as ClapArgs, Subcommand};
use console::style;
use std::path::PathBuf;
use stout_state::{InstalledPackages, Paths};

#[derive(ClapArgs)]
pub struct Args {
    #[command(subcommand)]
    pub command: Option<ServiceCommand>,
}

#[derive(Subcommand)]
pub enum ServiceCommand {
    /// List all managed services
    List,

    /// Start a service
    Start {
        /// Service/formula name
        service: String,
    },

    /// Stop a service
    Stop {
        /// Service/formula name
        service: String,
    },

    /// Restart a service
    Restart {
        /// Service/formula name
        service: String,
    },

    /// Run a service (without registering to launch at login)
    Run {
        /// Service/formula name
        service: String,
    },

    /// Show service info
    Info {
        /// Service/formula name
        service: String,
    },

    /// Clean up unused services
    Cleanup,
}

/// Service status
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(dead_code)]
enum ServiceStatus {
    Running,
    Stopped,
    Error,
    Unknown,
}

impl std::fmt::Display for ServiceStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ServiceStatus::Running => write!(f, "started"),
            ServiceStatus::Stopped => write!(f, "stopped"),
            ServiceStatus::Error => write!(f, "error"),
            ServiceStatus::Unknown => write!(f, "unknown"),
        }
    }
}

pub async fn run(args: Args) -> Result<()> {
    let command = args.command.unwrap_or(ServiceCommand::List);

    match command {
        ServiceCommand::List => list_services().await,
        ServiceCommand::Start { service } => start_service(&service).await,
        ServiceCommand::Stop { service } => stop_service(&service).await,
        ServiceCommand::Restart { service } => restart_service(&service).await,
        ServiceCommand::Run { service } => run_service(&service).await,
        ServiceCommand::Info { service } => info_service(&service).await,
        ServiceCommand::Cleanup => cleanup_services().await,
    }
}

async fn list_services() -> Result<()> {
    let paths = Paths::default();
    let installed = InstalledPackages::load(&paths)?;

    println!("{} Managed services:", style("==>").blue().bold());

    let mut found_services = false;

    for name in installed.names() {
        let pkg = installed
            .get(name)
            .with_context(|| format!("package '{}' is in installed list but not found", name))?;
        let install_path = paths.cellar.join(name).join(&pkg.version);

        // Look for service files
        let service_files = find_service_files(&install_path);

        if !service_files.is_empty() {
            found_services = true;
            let status = get_service_status(name);
            let status_style = match status {
                ServiceStatus::Running => style("started").green(),
                ServiceStatus::Stopped => style("stopped").dim(),
                ServiceStatus::Error => style("error").red(),
                ServiceStatus::Unknown => style("unknown").yellow(),
            };

            println!(
                "  {} {} ({}) - {}",
                style(if status == ServiceStatus::Running {
                    ""
                } else {
                    ""
                })
                .dim(),
                name,
                &pkg.version,
                status_style
            );
        }
    }

    if !found_services {
        println!("  {}", style("No services available").dim());
    }

    Ok(())
}

async fn start_service(name: &str) -> Result<()> {
    let paths = Paths::default();
    let installed = InstalledPackages::load(&paths)?;

    let pkg = installed
        .get(name)
        .ok_or_else(|| anyhow::anyhow!("Formula '{}' is not installed", name))?;

    let install_path = paths.cellar.join(name).join(&pkg.version);
    let service_files = find_service_files(&install_path);

    if service_files.is_empty() {
        bail!("Formula '{}' does not have a service to start", name);
    }

    println!(
        "{} Starting {}...",
        style("==>").blue().bold(),
        style(name).cyan()
    );

    #[cfg(target_os = "macos")]
    {
        for plist in service_files {
            let output = std::process::Command::new("launchctl")
                .args(["load", "-w"])
                .arg(&plist)
                .output()?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                bail!("Failed to start service: {}", stderr);
            }
        }
    }

    #[cfg(target_os = "linux")]
    {
        // For Linux, we'd use systemctl
        println!(
            "{}",
            style("Service management on Linux requires systemd setup").yellow()
        );
    }

    println!("{} Successfully started {}", style("").green(), name);
    Ok(())
}

async fn stop_service(name: &str) -> Result<()> {
    let paths = Paths::default();
    let installed = InstalledPackages::load(&paths)?;

    let pkg = installed
        .get(name)
        .ok_or_else(|| anyhow::anyhow!("Formula '{}' is not installed", name))?;

    let install_path = paths.cellar.join(name).join(&pkg.version);
    let service_files = find_service_files(&install_path);

    if service_files.is_empty() {
        bail!("Formula '{}' does not have a service to stop", name);
    }

    println!(
        "{} Stopping {}...",
        style("==>").blue().bold(),
        style(name).cyan()
    );

    #[cfg(target_os = "macos")]
    {
        for plist in service_files {
            let output = std::process::Command::new("launchctl")
                .args(["unload", "-w"])
                .arg(&plist)
                .output()?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                eprintln!("{} {}", style("Warning:").yellow(), stderr);
            }
        }
    }

    #[cfg(target_os = "linux")]
    {
        println!(
            "{}",
            style("Service management on Linux requires systemd setup").yellow()
        );
    }

    println!("{} Successfully stopped {}", style("").green(), name);
    Ok(())
}

async fn restart_service(name: &str) -> Result<()> {
    stop_service(name).await?;
    start_service(name).await
}

async fn run_service(name: &str) -> Result<()> {
    // Run foreground without registering
    let paths = Paths::default();
    let installed = InstalledPackages::load(&paths)?;

    let pkg = installed
        .get(name)
        .ok_or_else(|| anyhow::anyhow!("Formula '{}' is not installed", name))?;

    let install_path = paths.cellar.join(name).join(&pkg.version);
    let service_files = find_service_files(&install_path);

    if service_files.is_empty() {
        bail!("Formula '{}' does not have a service", name);
    }

    println!(
        "{} Running {} in foreground (Ctrl+C to stop)...",
        style("==>").blue().bold(),
        style(name).cyan()
    );

    #[cfg(target_os = "macos")]
    {
        for plist in &service_files {
            let output = std::process::Command::new("launchctl")
                .args(["start"])
                .arg(plist)
                .output()?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                eprintln!("{} {}", style("Warning:").yellow(), stderr);
            }
        }
    }

    Ok(())
}

async fn info_service(name: &str) -> Result<()> {
    let paths = Paths::default();
    let installed = InstalledPackages::load(&paths)?;

    let pkg = installed
        .get(name)
        .ok_or_else(|| anyhow::anyhow!("Formula '{}' is not installed", name))?;

    let install_path = paths.cellar.join(name).join(&pkg.version);
    let service_files = find_service_files(&install_path);

    println!(
        "{} Service info for {}:",
        style("==>").blue().bold(),
        style(name).cyan()
    );

    println!("  {}: {}", style("Version").dim(), pkg.version);
    println!("  {}: {}", style("Status").dim(), get_service_status(name));

    if service_files.is_empty() {
        println!("  {}: none", style("Service files").dim());
    } else {
        println!("  {}:", style("Service files").dim());
        for file in &service_files {
            println!("    {}", file.display());
        }
    }

    Ok(())
}

async fn cleanup_services() -> Result<()> {
    println!(
        "{} Cleaning up unused services...",
        style("==>").blue().bold()
    );

    // This would remove orphaned plist files
    println!("{}", style("No unused services found.").dim());

    Ok(())
}

/// Find service files (launchd plists or systemd units) for a package
pub fn find_service_files(install_path: &std::path::Path) -> Vec<PathBuf> {
    let mut files = Vec::new();

    // Check for launchd plists
    let _homebrew_dir = install_path.join("homebrew.mxcl.*.plist");
    if let Ok(entries) = glob_simple(install_path, "*.plist") {
        files.extend(entries);
    }

    // Check opt/share for service files
    let share_dir = install_path.join("share");
    if share_dir.exists() {
        if let Ok(entries) = glob_simple(&share_dir, "*.plist") {
            files.extend(entries);
        }
    }

    files
}

/// Stop a running launchd service for a package by unloading its plist files.
/// Returns true if any service was found and stopped.
pub fn stop_package_service(name: &str, install_path: &std::path::Path) -> bool {
    let service_files = find_service_files(install_path);
    if service_files.is_empty() {
        return false;
    }

    #[cfg(target_os = "macos")]
    {
        for plist in &service_files {
            let output = std::process::Command::new("launchctl")
                .args(["unload", "-w"])
                .arg(plist)
                .output();

            match output {
                Ok(o) if o.status.success() => {}
                Ok(o) => {
                    let stderr = String::from_utf8_lossy(&o.stderr);
                    eprintln!("  {} {}", style("Warning:").yellow(), stderr.trim());
                }
                Err(e) => {
                    eprintln!(
                        "  {} Failed to stop service for {}: {}",
                        style("Warning:").yellow(),
                        name,
                        e
                    );
                }
            }
        }
        println!("  {} Stopped service for {}", style("").green(), name);
        true
    }

    #[cfg(not(target_os = "macos"))]
    {
        let _ = (name, service_files);
        false
    }
}

/// Simple glob matching
fn glob_simple(dir: &std::path::Path, pattern: &str) -> Result<Vec<PathBuf>> {
    let mut results = Vec::new();

    if !dir.exists() {
        return Ok(results);
    }

    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let name = entry.file_name().to_string_lossy().to_string();

        if let Some(suffix) = pattern.strip_prefix('*') {
            if name.ends_with(suffix) {
                results.push(entry.path());
            }
        } else if name == pattern {
            results.push(entry.path());
        }
    }

    Ok(results)
}

/// Get service status
fn get_service_status(name: &str) -> ServiceStatus {
    #[cfg(target_os = "macos")]
    {
        let output = std::process::Command::new("launchctl")
            .args(["list"])
            .output();

        if let Ok(output) = output {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.contains(name) {
                return ServiceStatus::Running;
            }
        }
        ServiceStatus::Stopped
    }

    #[cfg(not(target_os = "macos"))]
    {
        let _ = name;
        ServiceStatus::Unknown
    }
}