cargo-rail 0.13.4

Graph-aware testing, dependency unification, and crate extraction for Rust monorepos
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
//! TOML formatting utilities
//!
//! Provides consistent, opinionated formatting for all TOML output.
//! Uses template strings + toml_edit parsing (hybrid approach).

use crate::error::{RailError, RailResult};
use toml_edit::DocumentMut;

/// Formatting rules and utilities
#[derive(Debug, Clone)]
pub struct TomlFormatter {
  /// Number of items before breaking array into multiple lines
  pub inline_array_threshold: usize,
  /// Number of features before breaking into multiple lines
  pub inline_feature_threshold: usize,
  /// Indentation string (usually 2 spaces)
  pub indent: &'static str,
  /// Whether to sort dependencies alphabetically (true) or preserve order (false)
  pub sort_dependencies: bool,
}

impl Default for TomlFormatter {
  fn default() -> Self {
    Self {
      inline_array_threshold: 4,
      inline_feature_threshold: 10,
      indent: "  ",
      sort_dependencies: true,
    }
  }
}

impl TomlFormatter {
  /// Create a new formatter with default settings
  pub fn new() -> Self {
    Self::default()
  }

  /// Format string array with optional grouping
  pub fn array_string(&self, items: &[String], groups: Option<Vec<Group>>) -> String {
    if items.is_empty() {
      return "[]".to_string();
    }

    // If we have groups, always use multiline
    if let Some(groups) = groups {
      let mut output = String::from("[\n");
      for group in groups {
        if !group.items.is_empty() {
          output.push_str(&format!("{}# {}\n", self.indent, group.name));
          for item in &group.items {
            output.push_str(&format!("{}\"{}\",\n", self.indent, item));
          }
        }
      }
      output.push(']');
      return output;
    }

    // Check if we should inline
    if items.len() <= self.inline_array_threshold {
      let content = join_quoted(items.iter().map(String::as_str));
      return format!("[{}]", content);
    }

    // Multiline default
    let mut output = String::from("[\n");
    for item in items {
      output.push_str(&format!("{}\"{}\",\n", self.indent, item));
    }
    output.push(']');
    output
  }

  /// Format features array (for Cargo.toml dependencies)
  pub fn array_features(&self, features: &[String]) -> String {
    if features.is_empty() {
      return "[]".to_string();
    }

    if features.len() > self.inline_feature_threshold {
      let mut output = String::from("[\n");
      for feature in features {
        output.push_str(&format!("{}\"{}\",\n", self.indent, feature));
      }
      output.push(']');
      output
    } else {
      let content = join_quoted(features.iter().map(String::as_str));
      format!("[{}]", content)
    }
  }

  /// Format target array with tier grouping
  pub fn array_targets(&self, targets: &[String]) -> String {
    let groups = group_targets(targets);

    // Convert to generic groups
    let generic_groups = groups.into_iter().map(|(name, items)| Group { name, items }).collect();

    self.array_string(targets, Some(generic_groups))
  }

  /// Format array without grouping (simple multiline for readability)
  pub fn array_simple(&self, items: &[String]) -> String {
    if items.is_empty() {
      return "[]".to_string();
    }
    if items.len() <= self.inline_array_threshold {
      let content = join_quoted(items.iter().map(String::as_str));
      return format!("[{}]", content);
    }
    let mut output = String::from("[\n");
    for item in items {
      output.push_str(&format!("{}\"{}\",\n", self.indent, item));
    }
    output.push(']');
    output
  }

  /// Format section header with box comment
  pub fn section_header(&self, title: &str, description: &str) -> String {
    format!("# {}\n# {}\n[{}]\n", title.to_uppercase(), description, title)
  }

  /// Format inline table
  pub fn inline_table(&self, pairs: &[(String, TomlValue)]) -> String {
    if pairs.is_empty() {
      return "{}".to_string();
    }

    let content = pairs
      .iter()
      .map(|(k, v)| format!("{} = {}", k, v))
      .collect::<Vec<_>>()
      .join(", ");

    format!("{{ {} }}", content)
  }

  /// Validate TOML string parses correctly
  pub fn validate(&self, toml: &str) -> RailResult<()> {
    toml
      .parse::<DocumentMut>()
      .map(|_| ())
      .map_err(|e| RailError::message(format!("Invalid TOML generated: {}", e)))
  }

  /// Format a Cargo.toml document in-place
  ///
  /// Applies standard formatting rules:
  /// 1. Sorts dependencies (if dependency_sort is Alphabetical)
  /// 2. Standardizes table format (inline vs block)
  pub fn format_manifest(&self, doc: &mut DocumentMut) -> RailResult<()> {
    // 1. Sort dependencies (only if configured to sort alphabetically)
    self.sort_deps(doc);

    // 2. Standardize table formatting (inline vs block)
    self.standardize_tables(doc);

    Ok(())
  }

  /// Sort dependencies in all dependency sections
  ///
  /// Only sorts if `sort_dependencies` is true.
  /// When false, existing order is maintained.
  fn sort_deps(&self, doc: &mut DocumentMut) {
    // Skip sorting if configured to preserve existing order
    if !self.sort_dependencies {
      return;
    }

    let sections = [
      "dependencies",
      "dev-dependencies",
      "build-dependencies",
      "workspace.dependencies",
    ];

    for section in sections {
      if let Some(table) = self.get_table_mut(doc, section) {
        table.sort_values();
      }
    }

    // Also handle target-specific dependencies
    // [target.'cfg(...)'.dependencies]
    if let Some(target_table) = doc.get_mut("target").and_then(|t| t.as_table_mut()) {
      for (_, cfg_item) in target_table.iter_mut() {
        if let Some(cfg_table) = cfg_item.as_table_mut() {
          for section in ["dependencies", "dev-dependencies", "build-dependencies"] {
            if let Some(deps) = cfg_table.get_mut(section).and_then(|d| d.as_table_mut()) {
              deps.sort_values();
            }
          }
        }
      }
    }
  }

  /// Standardize table formatting
  /// - Simple dependencies (version only or path only) -> Inline
  /// - Complex dependencies -> Inline if possible
  fn standardize_tables(&self, doc: &mut DocumentMut) {
    let sections = [
      "dependencies",
      "dev-dependencies",
      "build-dependencies",
      "workspace.dependencies",
    ];

    for section in sections {
      if let Some(table) = self.get_table_mut(doc, section) {
        for (_, item) in table.iter_mut() {
          if let Some(inline) = item.as_inline_table_mut() {
            // Ensure it stays inline
            inline.fmt();
          } else if let Some(t) = item.as_table_mut() {
            // Convert standard table to inline if it's a dependency
            // But only if it doesn't have sub-tables (which deps shouldn't have usually)
            t.set_implicit(true);
          }
        }
      }
    }
  }

  /// Helper to get a mutable table reference from a dotted path
  fn get_table_mut<'a>(&self, doc: &'a mut DocumentMut, path: &str) -> Option<&'a mut toml_edit::Table> {
    let parts: Vec<&str> = path.split('.').collect();
    let mut current = doc.as_item_mut();

    for part in parts {
      if let Some(table) = current.as_table_mut() {
        if let Some(next) = table.get_mut(part) {
          current = next;
        } else {
          return None;
        }
      } else {
        return None;
      }
    }

    current.as_table_mut()
  }
}

/// Target tier classification
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum TargetTier {
  /// Tier 1: Guaranteed to work
  Tier1,
  /// Tier 2: Guaranteed to build
  Tier2,
  /// Tier 3: No guarantees
  Tier3,
  /// Other/Unknown
  Other,
}

/// Classify a target triple into a tier
pub fn classify_target_tier(target: &str) -> TargetTier {
  match target {
    "x86_64-unknown-linux-gnu" | "aarch64-unknown-linux-gnu" | "x86_64-pc-windows-msvc" | "aarch64-apple-darwin" => {
      TargetTier::Tier1
    }
    "aarch64-pc-windows-msvc" => TargetTier::Tier2,
    t if t.contains("musl") || t.contains("wasm") => TargetTier::Tier2,
    _ => TargetTier::Other,
  }
}

/// Group targets by tier
pub fn group_targets(targets: &[String]) -> Vec<(String, Vec<String>)> {
  // Pre-allocate based on expected distribution (most targets are Tier 1/2)
  let mut tier1 = Vec::with_capacity(targets.len() / 2);
  let mut tier2 = Vec::with_capacity(targets.len() / 2);
  let mut other = Vec::new();

  // Build indices per tier to avoid cloning during classification
  let mut tier1_idx = Vec::with_capacity(targets.len() / 2);
  let mut tier2_idx = Vec::with_capacity(targets.len() / 2);
  let mut other_idx = Vec::new();

  for (idx, target) in targets.iter().enumerate() {
    match classify_target_tier(target) {
      TargetTier::Tier1 => tier1_idx.push(idx),
      TargetTier::Tier2 => tier2_idx.push(idx),
      _ => other_idx.push(idx),
    }
  }

  // Sort indices by target name, then clone only the sorted targets
  tier1_idx.sort_by(|&a, &b| targets[a].cmp(&targets[b]));
  tier2_idx.sort_by(|&a, &b| targets[a].cmp(&targets[b]));
  other_idx.sort_by(|&a, &b| targets[a].cmp(&targets[b]));

  tier1.extend(tier1_idx.iter().map(|&i| targets[i].clone()));
  tier2.extend(tier2_idx.iter().map(|&i| targets[i].clone()));
  other.extend(other_idx.iter().map(|&i| targets[i].clone()));

  let mut groups = Vec::with_capacity(3);
  if !tier1.is_empty() {
    groups.push(("Tier 1 (Guaranteed)".to_string(), tier1));
  }
  if !tier2.is_empty() {
    groups.push(("Tier 2 (Common)".to_string(), tier2));
  }
  if !other.is_empty() {
    groups.push(("Other".to_string(), other));
  }

  groups
}

/// Value types for inline tables
#[derive(Debug, Clone)]
pub enum TomlValue {
  /// String value
  String(String),
  /// Boolean value
  Bool(bool),
  /// Integer value
  Integer(i64),
  /// Array of strings
  Array(Vec<String>),
}

impl std::fmt::Display for TomlValue {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      TomlValue::String(s) => write!(f, "\"{}\"", s),
      TomlValue::Bool(b) => write!(f, "{}", b),
      TomlValue::Integer(i) => write!(f, "{}", i),
      TomlValue::Array(arr) => {
        let content = join_quoted(arr.iter().map(String::as_str));
        write!(f, "[{}]", content)
      }
    }
  }
}

fn join_quoted<'a, I>(items: I) -> String
where
  I: IntoIterator<Item = &'a str>,
{
  let mut out = String::new();
  for (idx, item) in items.into_iter().enumerate() {
    if idx > 0 {
      out.push_str(", ");
    }
    out.push('"');
    out.push_str(item);
    out.push('"');
  }
  out
}

/// A named group of items for array formatting
#[derive(Debug, Clone)]
pub struct Group {
  /// Name of the group (displayed in comment)
  pub name: String,
  /// Items in the group
  pub items: Vec<String>,
}

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

  #[test]
  fn test_inline_array() {
    let formatter = TomlFormatter::new();
    let items = vec!["a".to_string(), "b".to_string()];
    assert_eq!(formatter.array_string(&items, None), "[\"a\", \"b\"]");
  }

  #[test]
  fn test_multiline_array() {
    let formatter = TomlFormatter::new();
    let items = vec![
      "a".to_string(),
      "b".to_string(),
      "c".to_string(),
      "d".to_string(),
      "e".to_string(),
    ];
    let output = formatter.array_string(&items, None);
    assert!(output.contains("\n"));
    assert!(output.contains("  \"a\","));
  }

  #[test]
  fn test_grouped_targets() {
    let formatter = TomlFormatter::new();
    let targets = vec![
      "x86_64-unknown-linux-gnu".to_string(),
      "wasm32-unknown-unknown".to_string(),
    ];
    let output = formatter.array_targets(&targets);
    assert!(output.contains("# Tier 1"));
    assert!(output.contains("# Tier 2"));
  }

  #[test]
  fn test_inline_table() {
    let formatter = TomlFormatter::new();
    let pairs = vec![
      ("version".to_string(), TomlValue::String("1.0".to_string())),
      ("features".to_string(), TomlValue::Array(vec!["a".to_string()])),
    ];
    let output = formatter.inline_table(&pairs);
    assert_eq!(output, "{ version = \"1.0\", features = [\"a\"] }");
  }
}