rattler_build_core 0.2.4

The core engine of rattler-build, providing recipe rendering, source fetching, script execution, package building, testing, and publishing
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! Migration from deprecated `cache:` format to `staging:` outputs.
//!
//! This module provides functionality to detect and migrate recipes that use the
//! old `cache:` top-level key to the new `staging:` output format.

use std::path::Path;

use fs_err as fs;
use serde_yaml::Value as YamlValue;
use thiserror::Error;

/// Errors that can occur during recipe migration.
#[derive(Debug, Error)]
pub enum MigrateRecipeError {
    /// I/O error reading/writing recipe file
    #[error("I/O error: {0}")]
    IoError(#[from] std::io::Error),

    /// Failed to parse YAML
    #[error("Failed to parse YAML: {0}")]
    YamlParse(String),

    /// Recipe does not contain a `cache:` key
    #[error("Recipe does not contain a top-level 'cache:' key — nothing to migrate")]
    NoCacheKey,

    /// Failed to serialize YAML
    #[error("Failed to serialize YAML: {0}")]
    SerializeError(String),
}

/// Check whether raw YAML content contains a top-level `cache:` key.
///
/// Uses `serde_yaml::Value` for a lightweight structural check (not just a
/// regex), so it won't false-positive on comments or nested keys.
pub fn has_cache_key(content: &str) -> bool {
    serde_yaml::from_str::<YamlValue>(content)
        .ok()
        .and_then(|v| v.as_mapping().cloned())
        .is_some_and(|m| m.contains_key(YamlValue::String("cache".to_string())))
}

/// Migrate a recipe file from `cache:` format to `staging:` outputs.
///
/// If `dry_run` is true, prints the migrated content to stdout without writing.
/// Returns the migrated content.
pub fn migrate_recipe(path: &Path, dry_run: bool) -> Result<String, MigrateRecipeError> {
    let content = fs::read_to_string(path)?;
    let migrated = migrate_cache_to_staging(&content)?;

    if dry_run {
        println!("{migrated}");
    } else {
        fs::write(path, &migrated)?;
        tracing::info!("Migrated recipe: {}", path.display());
    }

    Ok(migrated)
}

/// Core migration: transform recipe text from `cache:` to `staging:` format.
pub fn migrate_cache_to_staging(content: &str) -> Result<String, MigrateRecipeError> {
    let yaml: YamlValue =
        serde_yaml::from_str(content).map_err(|e| MigrateRecipeError::YamlParse(e.to_string()))?;

    let mapping = yaml
        .as_mapping()
        .ok_or_else(|| MigrateRecipeError::YamlParse("expected top-level mapping".to_string()))?;

    let cache = mapping
        .get(YamlValue::String("cache".to_string()))
        .ok_or(MigrateRecipeError::NoCacheKey)?;

    let staging_name = derive_staging_name(&yaml);
    let staging_text = build_staging_text(&staging_name, cache);

    // Remove the cache section from the text
    let mut content = remove_cache_section(content);
    content = insert_staging_output(&content, &staging_text);
    content = insert_inherit(&content, &staging_name);

    Ok(content)
}

/// Derive a staging output name from the recipe.
///
/// Uses `recipe.name` + `-build` if available, otherwise falls back to
/// `"build-cache"`.
fn derive_staging_name(yaml: &YamlValue) -> String {
    yaml.get("recipe")
        .and_then(|r| r.get("name"))
        .and_then(|n| n.as_str())
        .map(|name| format!("{name}-build"))
        .unwrap_or_else(|| "build-cache".to_string())
}

/// Find the line range of a top-level YAML section (key at column 0).
///
/// Returns `Some((start_line, end_line))` where the range is exclusive on end.
/// `start_line` is the line containing `key:`, and `end_line` is the first line
/// of the *next* top-level section (or the total line count).
fn find_section_range(lines: &[&str], key: &str) -> Option<(usize, usize)> {
    let prefix = format!("{key}:");
    let start = lines.iter().position(|line| {
        let trimmed = line.trim_start();
        // Must be at column 0 (no leading whitespace) and start with `key:`
        trimmed.len() == line.len()
            && (trimmed == prefix || trimmed.starts_with(&format!("{key}: ")))
    })?;

    // Find the end: next non-blank, non-comment line at column 0
    let mut end = start + 1;
    while end < lines.len() {
        let line = lines[end];
        if line.is_empty() || line.chars().all(|c| c.is_whitespace()) {
            end += 1;
            continue;
        }
        let trimmed = line.trim_start();
        if trimmed.starts_with('#') {
            // Comment line — could belong to cache or next section.
            // Check if the *next* non-blank, non-comment line is indented.
            // If it is, this comment belongs to the cache section.
            let mut lookahead = end + 1;
            while lookahead < lines.len() {
                let la = lines[lookahead];
                if la.is_empty()
                    || la.chars().all(|c| c.is_whitespace())
                    || la.trim_start().starts_with('#')
                {
                    lookahead += 1;
                    continue;
                }
                break;
            }
            if lookahead < lines.len() && lines[lookahead].starts_with(|c: char| c.is_whitespace())
            {
                // Next content line is indented → comment belongs to cache section
                end += 1;
                continue;
            }
            // Comment is at top level → belongs to next section
            break;
        }
        // Non-blank, non-comment line
        if line.starts_with(|c: char| c.is_whitespace()) {
            // Indented → still part of the current section
            end += 1;
        } else {
            // At column 0 → next top-level section
            break;
        }
    }

    Some((start, end))
}

/// Remove the `cache:` section from the recipe text.
fn remove_cache_section(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let Some((start, end)) = find_section_range(&lines, "cache") else {
        return content.to_string();
    };

    let mut result_lines: Vec<&str> = Vec::new();
    result_lines.extend_from_slice(&lines[..start]);
    // Skip trailing blank lines after the removed section
    let mut rest_start = end;
    while rest_start < lines.len()
        && (lines[rest_start].is_empty() || lines[rest_start].chars().all(|c| c.is_whitespace()))
    {
        rest_start += 1;
    }
    result_lines.extend_from_slice(&lines[rest_start..]);

    let mut result = result_lines.join("\n");
    // Preserve trailing newline if original had one
    if content.ends_with('\n') && !result.ends_with('\n') {
        result.push('\n');
    }
    result
}

/// Build the YAML text for a staging output from parsed cache data.
fn build_staging_text(name: &str, cache: &YamlValue) -> String {
    let mut lines = Vec::new();
    lines.push("  - staging:".to_string());
    lines.push(format!("      name: {name}"));

    let Some(cache_map) = cache.as_mapping() else {
        return lines.join("\n");
    };

    // Process `build:` section
    if let Some(build) = cache_map.get(YamlValue::String("build".to_string())) {
        lines.push("    build:".to_string());
        append_yaml_indented(&mut lines, build, 6);
    }

    // Process `requirements:` section
    if let Some(reqs) = cache_map.get(YamlValue::String("requirements".to_string())) {
        lines.push("    requirements:".to_string());
        append_yaml_indented(&mut lines, reqs, 6);
    }

    // Process `source:` section
    if let Some(source) = cache_map.get(YamlValue::String("source".to_string())) {
        lines.push("    source:".to_string());
        append_yaml_indented(&mut lines, source, 6);
    }

    lines.join("\n")
}

/// Append a YAML value as indented text lines.
fn append_yaml_indented(lines: &mut Vec<String>, value: &YamlValue, base_indent: usize) {
    let yaml_str = serde_yaml::to_string(value)
        .unwrap_or_default()
        .trim_end()
        .to_string();

    let indent = " ".repeat(base_indent);
    for line in yaml_str.lines() {
        lines.push(format!("{indent}{line}"));
    }
}

/// Insert the staging output text as the first item under `outputs:`.
fn insert_staging_output(content: &str, staging_text: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();

    // Find the `outputs:` line
    let Some(outputs_line_idx) = lines.iter().position(|line| {
        let trimmed = line.trim();
        trimmed == "outputs:" || trimmed.starts_with("outputs: ")
    }) else {
        return content.to_string();
    };

    // Find the first `- ` item under outputs
    let mut first_item_idx = None;
    for (i, line) in lines.iter().enumerate().skip(outputs_line_idx + 1) {
        if line.is_empty() || line.chars().all(|c| c.is_whitespace()) {
            continue;
        }
        let trimmed = line.trim_start();
        if trimmed.starts_with('#') {
            continue;
        }
        if trimmed.starts_with("- ") {
            first_item_idx = Some(i);
            break;
        }
        // Non-list content under outputs — unexpected
        break;
    }

    let mut result_lines: Vec<String> = lines[..=outputs_line_idx]
        .iter()
        .map(|s| s.to_string())
        .collect();

    result_lines.push(staging_text.to_string());
    // Add blank line between staging and first package output
    result_lines.push(String::new());

    if let Some(idx) = first_item_idx {
        for line in &lines[idx..] {
            result_lines.push(line.to_string());
        }
    }

    let mut result = result_lines.join("\n");
    if content.ends_with('\n') && !result.ends_with('\n') {
        result.push('\n');
    }
    result
}

/// Add `inherit: <staging_name>` to each `- package:` output that doesn't
/// already have one.
fn insert_inherit(content: &str, staging_name: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let mut result_lines: Vec<String> = Vec::new();
    let mut i = 0;

    while i < lines.len() {
        let line = lines[i];
        result_lines.push(line.to_string());

        // Detect `  - package:` lines
        let trimmed = line.trim_start();
        let leading_spaces = line.len() - trimmed.len();

        if trimmed.starts_with("- package:") && leading_spaces > 0 {
            let item_indent = leading_spaces;
            let content_indent = item_indent + 2;

            // Scan the entire output block to check for existing `inherit:`
            let mut has_inherit = false;
            let mut j = i + 1;
            while j < lines.len() {
                let next_line = lines[j];
                let next_trimmed = next_line.trim_start();
                let next_indent = next_line.len() - next_trimmed.len();

                if next_line.is_empty() || next_trimmed.is_empty() {
                    j += 1;
                    continue;
                }
                if next_trimmed.starts_with("- ") && next_indent <= item_indent {
                    break;
                }
                if next_indent == 0 && !next_trimmed.starts_with('#') {
                    break;
                }
                if next_indent == content_indent && next_trimmed.starts_with("inherit:") {
                    has_inherit = true;
                }
                j += 1;
            }

            if !has_inherit {
                let inherit_line = format!("{}inherit: {staging_name}", " ".repeat(content_indent));

                // Find the end of the `package:` sub-block (lines deeper than
                // content_indent). Stop at blank lines or lines at
                // content_indent or less.
                let mut pkg_end = i + 1;
                while pkg_end < lines.len() {
                    let pl = lines[pkg_end];
                    let pt = pl.trim_start();
                    let pindent = pl.len() - pt.len();

                    if pl.is_empty() || pt.is_empty() {
                        break;
                    }
                    if pindent > content_indent {
                        pkg_end += 1;
                        continue;
                    }
                    break;
                }

                // Push package sub-block lines, then inherit
                for line in lines.iter().take(pkg_end).skip(i + 1) {
                    result_lines.push(line.to_string());
                }
                result_lines.push(inherit_line);
                i = pkg_end;
                continue;
            }
        }

        i += 1;
    }

    let mut result = result_lines.join("\n");
    if content.ends_with('\n') && !result.ends_with('\n') {
        result.push('\n');
    }
    result
}

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

    #[test]
    fn test_has_cache_key_positive() {
        let content = "\
cache:
  build:
    script:
      - echo hello
outputs:
  - package:
      name: foo
";
        assert!(has_cache_key(content));
    }

    #[test]
    fn test_has_cache_key_negative() {
        let content = "\
outputs:
  - package:
      name: foo
";
        assert!(!has_cache_key(content));
    }

    #[test]
    fn test_has_cache_key_nested_not_toplevel() {
        let content = "\
something:
  cache:
    build: true
";
        assert!(!has_cache_key(content));
    }

    #[test]
    fn test_migrate_no_cache_key_errors() {
        let content = "\
outputs:
  - package:
      name: foo
";
        let err = migrate_cache_to_staging(content).unwrap_err();
        assert!(matches!(err, MigrateRecipeError::NoCacheKey));
    }

    #[test]
    fn test_migrate_basic_cache() {
        let content = "\
context:
  version: 0.1.0
  build_num: 0

recipe:
  name: cache-installation
  version: ${{ version }}

build:
  number: ${{ build_num }}

cache:
  requirements:
    build:
      - cmake
  build:
    script:
      - cmake --version

outputs:
  - package:
      name: check-1

  - package:
      name: check-2
";
        let result = migrate_cache_to_staging(content).unwrap();
        insta::assert_snapshot!(result, @r###"
        context:
          version: 0.1.0
          build_num: 0

        recipe:
          name: cache-installation
          version: ${{ version }}

        build:
          number: ${{ build_num }}

        outputs:
          - staging:
              name: cache-installation-build
            build:
              script:
              - cmake --version
            requirements:
              build:
              - cmake

          - package:
              name: check-1
            inherit: cache-installation-build

          - package:
              name: check-2
            inherit: cache-installation-build
        "###);
    }

    #[test]
    fn test_migrate_cache_with_compiler() {
        let content = "\
# test for issue https://github.com/prefix-dev/rattler-build/issues/1290
recipe:
  name: foo
  version: 0.1.0

cache:
  build:
    script:
      - mkdir -p $PREFIX/lib
      - mkdir -p $PREFIX/include
      - touch $PREFIX/include/test.h
      - touch $PREFIX/lib/libdav1d.so.7.0.0
      - ln -s $PREFIX/lib/libdav1d.so.7.0.0 $PREFIX/lib/libdav1d.so.7
      - ln -s $PREFIX/lib/libdav1d.so.7 $PREFIX/lib/libdav1d.so

  requirements:
    build:
      - ${{ compiler('c') }}

outputs:
  - package:
      name: testlib-so-version
      version: 2.1.4

    build:
      files:
        include:
          - lib/*.so.*
";
        let result = migrate_cache_to_staging(content).unwrap();
        insta::assert_snapshot!(result, @r###"
        # test for issue https://github.com/prefix-dev/rattler-build/issues/1290
        recipe:
          name: foo
          version: 0.1.0

        outputs:
          - staging:
              name: foo-build
            build:
              script:
              - mkdir -p $PREFIX/lib
              - mkdir -p $PREFIX/include
              - touch $PREFIX/include/test.h
              - touch $PREFIX/lib/libdav1d.so.7.0.0
              - ln -s $PREFIX/lib/libdav1d.so.7.0.0 $PREFIX/lib/libdav1d.so.7
              - ln -s $PREFIX/lib/libdav1d.so.7 $PREFIX/lib/libdav1d.so
            requirements:
              build:
              - ${{ compiler('c') }}

          - package:
              name: testlib-so-version
              version: 2.1.4
            inherit: foo-build

            build:
              files:
                include:
                  - lib/*.so.*
        "###);
    }

    #[test]
    fn test_migrate_cache_without_recipe_name() {
        let content = "\
cache:
  build:
    script:
      - echo hello

outputs:
  - package:
      name: my-pkg
";
        let result = migrate_cache_to_staging(content).unwrap();
        insta::assert_snapshot!(result, @r###"
        outputs:
          - staging:
              name: build-cache
            build:
              script:
              - echo hello

          - package:
              name: my-pkg
            inherit: build-cache
        "###);
    }

    #[test]
    fn test_migrate_cache_with_source() {
        let content = "\
recipe:
  name: my-lib
  version: 1.0.0

cache:
  source:
    url: https://example.com/source.tar.gz
    sha256: abc123
  build:
    script:
      - make install

outputs:
  - package:
      name: my-lib-bin
";
        let result = migrate_cache_to_staging(content).unwrap();
        insta::assert_snapshot!(result, @r###"
        recipe:
          name: my-lib
          version: 1.0.0

        outputs:
          - staging:
              name: my-lib-build
            build:
              script:
              - make install
            source:
              url: https://example.com/source.tar.gz
              sha256: abc123

          - package:
              name: my-lib-bin
            inherit: my-lib-build
        "###);
    }

    #[test]
    fn test_migrate_cache_symlinks() {
        let content = "\
recipe:
  name: cache-symlinks
  version: 1.0.0

cache:
  build:
    script: |
      mkdir -p $PREFIX/bin
      touch $PREFIX/bin/exe
      ln -s $PREFIX/bin/exe $PREFIX/bin/exe-symlink
      ln -s $PREFIX/bin/exe $PREFIX/bin/absolute-exe-symlink
      touch $PREFIX/foo.txt
      ln -s $PREFIX/foo.txt $PREFIX/foo-symlink.txt
      ln -s $PREFIX/foo.txt $PREFIX/absolute-symlink.txt
      ln -s $PREFIX/non-existent-file $PREFIX/broken-symlink.txt
      ln -s ./foo.txt $PREFIX/relative-symlink.txt
      echo ${{ PREFIX }} > $PREFIX/prefix.txt

outputs:
  - package:
      name: cache-symlinks
    build:
      files:
        include:
          - \"**/*\"
        exclude:
          - \"absolute-symlink.txt\"
          - \"bin/absolute-exe-symlink\"
  - package:
      name: absolute-cache-symlinks
    build:
      files:
        - \"absolute-symlink.txt\"
        - \"bin/absolute-exe-symlink\"
";
        let result = migrate_cache_to_staging(content).unwrap();
        insta::assert_snapshot!(result, @r###"
        recipe:
          name: cache-symlinks
          version: 1.0.0

        outputs:
          - staging:
              name: cache-symlinks-build
            build:
              script: |
                mkdir -p $PREFIX/bin
                touch $PREFIX/bin/exe
                ln -s $PREFIX/bin/exe $PREFIX/bin/exe-symlink
                ln -s $PREFIX/bin/exe $PREFIX/bin/absolute-exe-symlink
                touch $PREFIX/foo.txt
                ln -s $PREFIX/foo.txt $PREFIX/foo-symlink.txt
                ln -s $PREFIX/foo.txt $PREFIX/absolute-symlink.txt
                ln -s $PREFIX/non-existent-file $PREFIX/broken-symlink.txt
                ln -s ./foo.txt $PREFIX/relative-symlink.txt
                echo ${{ PREFIX }} > $PREFIX/prefix.txt

          - package:
              name: cache-symlinks
            inherit: cache-symlinks-build
            build:
              files:
                include:
                  - "**/*"
                exclude:
                  - "absolute-symlink.txt"
                  - "bin/absolute-exe-symlink"
          - package:
              name: absolute-cache-symlinks
            inherit: cache-symlinks-build
            build:
              files:
                - "absolute-symlink.txt"
                - "bin/absolute-exe-symlink"
        "###);
    }

    #[test]
    fn test_comments_outside_cache_preserved() {
        let content = "\
# This is a top-level comment
recipe:
  name: foo
  version: 1.0.0

cache:
  build:
    script:
      - echo hello

# This comment should be preserved
outputs:
  - package:
      name: bar
";
        let result = migrate_cache_to_staging(content).unwrap();
        assert!(result.contains("# This is a top-level comment"));
        assert!(result.contains("# This comment should be preserved"));
    }

    #[test]
    fn test_existing_inherit_not_duplicated() {
        let content = "\
recipe:
  name: foo
  version: 1.0.0

cache:
  build:
    script:
      - echo hello

outputs:
  - package:
      name: bar
    inherit: something-else
";
        let result = migrate_cache_to_staging(content).unwrap();
        // Should not add a second inherit
        assert_eq!(
            result.matches("inherit:").count(),
            1,
            "should not duplicate inherit"
        );
    }
}