stout-bundle 0.2.1

Brewfile parsing, bundle management, and environment snapshots
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
//! Brewfile parser
//!
//! Parses Homebrew Brewfile format with two strategies:
//! 1. Ruby parser (full compatibility) - shells out to Ruby
//! 2. Rust parser (fallback) - handles common cases

use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::process::Command;
use tracing::{debug, warn};

/// Parsed Brewfile contents
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Brewfile {
    #[serde(default)]
    pub taps: Vec<TapEntry>,

    #[serde(default)]
    pub brews: Vec<BrewEntry>,

    #[serde(default)]
    pub casks: Vec<CaskEntry>,

    #[serde(default)]
    pub mas: Vec<MasEntry>,

    #[serde(default)]
    pub whalebrew: Vec<WhalebrewEntry>,

    #[serde(default)]
    pub vscode: Vec<VscodeEntry>,
}

/// Tap entry (custom repository)
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct TapEntry {
    pub name: String,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub force_auto_update: Option<bool>,
}

/// Brew entry (formula)
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct BrewEntry {
    pub name: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub link: Option<bool>,
    #[serde(default)]
    pub conflicts_with: Vec<String>,
    #[serde(default)]
    pub restart_service: Option<RestartService>,
    #[serde(default)]
    pub start_service: Option<bool>,
}

/// Restart service option
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RestartService {
    Bool(bool),
    Symbol(String), // :changed, :immediately
}

/// Cask entry (application)
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CaskEntry {
    pub name: String,
    #[serde(default)]
    pub args: CaskArgs,
    #[serde(default)]
    pub greedy: bool,
}

/// Cask installation arguments
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CaskArgs {
    #[serde(default)]
    pub appdir: Option<String>,
    #[serde(default)]
    pub force: bool,
    #[serde(default)]
    pub require_sha: bool,
    #[serde(default)]
    pub no_quarantine: bool,
}

/// Mac App Store entry
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct MasEntry {
    pub name: String,
    pub id: u64,
}

/// Whalebrew entry (Docker-based CLI tools)
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct WhalebrewEntry {
    pub name: String,
}

/// VS Code extension entry
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct VscodeEntry {
    pub name: String,
}

impl Brewfile {
    /// Parse a Brewfile from the given path
    pub fn parse(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Err(Error::BrewfileNotFound(path.display().to_string()));
        }

        // Try Ruby parser first (full compatibility)
        match Self::parse_with_ruby(path) {
            Ok(bf) => {
                debug!("Parsed Brewfile with Ruby parser");
                return Ok(bf);
            }
            Err(e) => {
                debug!("Ruby parser failed: {}, trying Rust parser", e);
            }
        }

        // Fall back to Rust parser
        warn!("Ruby not available, using basic Rust parser (some options may be ignored)");
        Self::parse_with_rust(path)
    }

    /// Parse Brewfile using Ruby for full DSL compatibility
    fn parse_with_ruby(path: &Path) -> Result<Self> {
        const RUBY_SCRIPT: &str = r#"
require 'json'

$e = {
  taps: [],
  brews: [],
  casks: [],
  mas: [],
  whalebrew: [],
  vscode: []
}

def tap(name, url: nil, force_auto_update: nil)
  entry = { name: name }
  entry[:url] = url if url
  entry[:force_auto_update] = force_auto_update unless force_auto_update.nil?
  $e[:taps] << entry
end

def brew(name, args: [], link: nil, conflicts_with: [], restart_service: nil, start_service: nil)
  entry = { name: name }
  entry[:args] = args unless args.empty?
  entry[:link] = link unless link.nil?
  entry[:conflicts_with] = conflicts_with unless conflicts_with.empty?
  entry[:restart_service] = restart_service.to_s if restart_service
  entry[:start_service] = start_service unless start_service.nil?
  $e[:brews] << entry
end

def cask(name, args: {}, greedy: false)
  entry = { name: name }
  entry[:args] = args unless args.empty?
  entry[:greedy] = greedy if greedy
  $e[:casks] << entry
end

def mas(name, id:)
  $e[:mas] << { name: name, id: id }
end

def whalebrew(name)
  $e[:whalebrew] << { name: name }
end

def vscode(name)
  $e[:vscode] << { name: name }
end

# Ignore cask_args (global cask settings)
def cask_args(args = {})
end

begin
  eval(File.read(ARGV[0]))
  puts JSON.generate($e)
rescue => e
  STDERR.puts "Error: #{e.message}"
  exit 1
end
"#;

        let output = Command::new("ruby")
            .arg("-e")
            .arg(RUBY_SCRIPT)
            .arg(path)
            .output()
            .map_err(|e| Error::RubyError(format!("Failed to execute Ruby: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::RubyError(stderr.to_string()));
        }

        let json_str = String::from_utf8_lossy(&output.stdout);
        let brewfile: Brewfile = serde_json::from_str(&json_str)
            .map_err(|e| Error::ParseError(format!("Failed to parse Ruby output: {}", e)))?;

        Ok(brewfile)
    }

    /// Parse Brewfile using Rust (handles common cases)
    fn parse_with_rust(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let mut brewfile = Brewfile::default();

        for line in content.lines() {
            let line = line.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Parse tap entries
            if let Some(rest) = line.strip_prefix("tap ") {
                if let Some(name) = extract_quoted_string(rest) {
                    brewfile.taps.push(TapEntry {
                        name,
                        ..Default::default()
                    });
                }
                continue;
            }

            // Parse brew entries
            if let Some(rest) = line.strip_prefix("brew ") {
                if let Some(name) = extract_quoted_string(rest) {
                    brewfile.brews.push(BrewEntry {
                        name,
                        ..Default::default()
                    });
                }
                continue;
            }

            // Parse cask entries
            if let Some(rest) = line.strip_prefix("cask ") {
                if let Some(name) = extract_quoted_string(rest) {
                    brewfile.casks.push(CaskEntry {
                        name,
                        ..Default::default()
                    });
                }
                continue;
            }

            // Parse mas entries
            if let Some(rest) = line.strip_prefix("mas ") {
                if let Some((name, id)) = parse_mas_entry(rest) {
                    brewfile.mas.push(MasEntry { name, id });
                }
                continue;
            }

            // Parse whalebrew entries
            if let Some(rest) = line.strip_prefix("whalebrew ") {
                if let Some(name) = extract_quoted_string(rest) {
                    brewfile.whalebrew.push(WhalebrewEntry { name });
                }
                continue;
            }

            // Parse vscode entries
            if let Some(rest) = line.strip_prefix("vscode ") {
                if let Some(name) = extract_quoted_string(rest) {
                    brewfile.vscode.push(VscodeEntry { name });
                }
                continue;
            }
        }

        Ok(brewfile)
    }

    /// Generate a Brewfile from the current state
    pub fn generate(
        taps: &[String],
        formulas: &[(String, bool)], // (name, requested)
        casks: &[String],
    ) -> String {
        let mut output = String::new();

        // Taps
        if !taps.is_empty() {
            output.push_str("# Taps\n");
            for tap in taps {
                output.push_str(&format!("tap \"{}\"\n", tap));
            }
            output.push('\n');
        }

        // Formulas (only requested ones by default)
        let requested: Vec<_> = formulas.iter().filter(|(_, r)| *r).collect();
        if !requested.is_empty() {
            output.push_str("# Formulas\n");
            for (name, _) in requested {
                output.push_str(&format!("brew \"{}\"\n", name));
            }
            output.push('\n');
        }

        // Casks
        if !casks.is_empty() {
            output.push_str("# Casks\n");
            for cask in casks {
                output.push_str(&format!("cask \"{}\"\n", cask));
            }
            output.push('\n');
        }

        output
    }

    /// Check if Brewfile is empty
    pub fn is_empty(&self) -> bool {
        self.taps.is_empty()
            && self.brews.is_empty()
            && self.casks.is_empty()
            && self.mas.is_empty()
            && self.whalebrew.is_empty()
            && self.vscode.is_empty()
    }

    /// Get total entry count
    pub fn entry_count(&self) -> usize {
        self.taps.len()
            + self.brews.len()
            + self.casks.len()
            + self.mas.len()
            + self.whalebrew.len()
            + self.vscode.len()
    }
}

/// Extract a quoted string from the start of a line
fn extract_quoted_string(s: &str) -> Option<String> {
    let s = s.trim();

    // Handle double-quoted strings
    if let Some(rest) = s.strip_prefix('"') {
        if let Some(end) = rest.find('"') {
            return Some(rest[..end].to_string());
        }
    }

    // Handle single-quoted strings
    if let Some(rest) = s.strip_prefix('\'') {
        if let Some(end) = rest.find('\'') {
            return Some(rest[..end].to_string());
        }
    }

    None
}

/// Parse a mas entry: mas "Name", id: 123456
fn parse_mas_entry(s: &str) -> Option<(String, u64)> {
    let name = extract_quoted_string(s)?;

    // Find id: after the name
    if let Some(id_pos) = s.find("id:") {
        let id_str = s[id_pos + 3..].trim();
        // Extract digits
        let id_digits: String = id_str.chars().take_while(|c| c.is_ascii_digit()).collect();
        if let Ok(id) = id_digits.parse() {
            return Some((name, id));
        }
    }

    None
}

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

    #[test]
    fn test_extract_quoted_string() {
        assert_eq!(extract_quoted_string("\"jq\""), Some("jq".to_string()));
        assert_eq!(extract_quoted_string("'jq'"), Some("jq".to_string()));
        assert_eq!(
            extract_quoted_string("\"homebrew/cask\""),
            Some("homebrew/cask".to_string())
        );
    }

    #[test]
    fn test_parse_mas_entry() {
        assert_eq!(
            parse_mas_entry("\"Xcode\", id: 497799835"),
            Some(("Xcode".to_string(), 497799835))
        );
    }

    #[test]
    fn test_generate_brewfile() {
        let taps = vec!["homebrew/cask".to_string()];
        let formulas = vec![
            ("jq".to_string(), true),
            ("oniguruma".to_string(), false), // dependency
        ];
        let casks = vec!["firefox".to_string()];

        let output = Brewfile::generate(&taps, &formulas, &casks);

        assert!(output.contains("tap \"homebrew/cask\""));
        assert!(output.contains("brew \"jq\""));
        assert!(!output.contains("brew \"oniguruma\"")); // dependency excluded
        assert!(output.contains("cask \"firefox\""));
    }
}