zlayer-builder 0.10.76

Dockerfile parsing and buildah-based container image building
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
//! `ZPipeline` types - YAML-based multi-image build pipeline format
//!
//! This module defines all serde-deserializable types for the `ZPipeline` format,
//! which coordinates building multiple container images from a single manifest.
//! The format supports:
//!
//! - **Global variables** - Template substitution via `${VAR}` syntax
//! - **Default settings** - Shared configuration inherited by all images
//! - **Dependency ordering** - `depends_on` declares build order constraints
//! - **Coordinated push** - Push all images after successful builds

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Top-level ZPipeline
// ---------------------------------------------------------------------------

/// Top-level ZPipeline.yaml representation.
///
/// A pipeline coordinates building multiple container images with dependency
/// ordering, shared configuration, and coordinated push operations.
///
/// # YAML Example
///
/// ```yaml
/// version: "1"
///
/// vars:
///   VERSION: "1.0.0"
///   REGISTRY: "ghcr.io/myorg"
///
/// defaults:
///   format: oci
///   build_args:
///     RUST_VERSION: "1.90"
///
/// images:
///   base:
///     file: images/Dockerfile.base
///     tags:
///       - "${REGISTRY}/base:${VERSION}"
///   app:
///     file: images/Dockerfile.app
///     depends_on: [base]
///     tags:
///       - "${REGISTRY}/app:${VERSION}"
///
/// push:
///   after_all: true
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ZPipeline {
    /// Pipeline format version (currently "1")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,

    /// Global variables for template substitution.
    /// Referenced in tags and other string fields as `${VAR_NAME}`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub vars: HashMap<String, String>,

    /// Default settings inherited by all images.
    /// Individual image settings override these defaults.
    #[serde(default)]
    pub defaults: PipelineDefaults,

    /// Named images to build. Order is preserved (`IndexMap`).
    /// Keys are image names used for `depends_on` references.
    pub images: IndexMap<String, PipelineImage>,

    /// Cache configuration for storing built image layers.
    /// Enables pipeline-built images to be used as bases by downstream images.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache: Option<PipelineCacheConfig>,

    /// Push configuration.
    #[serde(default)]
    pub push: PushConfig,
}

// ---------------------------------------------------------------------------
// Pipeline defaults
// ---------------------------------------------------------------------------

/// Default settings applied to all images in the pipeline.
///
/// Individual image settings take precedence over these defaults.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PipelineDefaults {
    /// Default output format: "oci" or "docker"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,

    /// Default build arguments passed to all image builds
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub build_args: HashMap<String, String>,

    /// Whether to skip cache by default
    #[serde(default, skip_serializing_if = "is_false")]
    pub no_cache: bool,

    /// Default cache mounts applied to all RUN steps in all images.
    /// Individual `ZImagefile` step-level cache mounts are additive.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cache_mounts: Vec<crate::zimage::types::ZCacheMount>,

    /// Default retry count for failed RUN steps (0 = no retries)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retries: Option<u32>,

    /// Default target platforms for multi-arch builds (e.g., `linux/amd64`, `linux/arm64`).
    /// When set, each image is built once per platform and a manifest list is created.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub platforms: Vec<String>,
}

// ---------------------------------------------------------------------------
// Pipeline image
// ---------------------------------------------------------------------------

/// Configuration for a single image in the pipeline.
///
/// # YAML Example
///
/// ```yaml
/// zlayer-app:
///   file: images/ZImagefile.app
///   context: "."
///   tags:
///     - "${REGISTRY}/app:${VERSION}"
///     - "${REGISTRY}/app:latest"
///   depends_on: [zlayer-base]
///   build_args:
///     EXTRA_ARG: "value"
///   no_cache: false
///   format: oci
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PipelineImage {
    /// Path to the build file (Dockerfile, `ZImagefile`, etc.)
    pub file: PathBuf,

    /// Build context directory. Defaults to "."
    #[serde(
        default = "default_context",
        skip_serializing_if = "is_default_context"
    )]
    pub context: PathBuf,

    /// Image tags to apply. Supports variable substitution.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,

    /// Build arguments specific to this image.
    /// Merged with (and overrides) `defaults.build_args`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub build_args: HashMap<String, String>,

    /// Names of images that must be built before this one.
    /// Creates a dependency graph for build ordering.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub depends_on: Vec<String>,

    /// Override `no_cache` setting for this image.
    /// If None, inherits from defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub no_cache: Option<bool>,

    /// Override output format for this image.
    /// If None, inherits from defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,

    /// Cache mounts for this image's RUN steps, merged with defaults
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cache_mounts: Vec<crate::zimage::types::ZCacheMount>,

    /// Override retry count for this image
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retries: Option<u32>,

    /// Target platforms for this image (overrides defaults.platforms).
    /// If empty, inherits from defaults.platforms.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub platforms: Vec<String>,
}

// ---------------------------------------------------------------------------
// Push configuration
// ---------------------------------------------------------------------------

/// Configuration for pushing built images to registries.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PushConfig {
    /// If true, push all images only after all builds succeed.
    /// If false (default), images are not pushed automatically.
    #[serde(default, skip_serializing_if = "is_false")]
    pub after_all: bool,
}

// ---------------------------------------------------------------------------
// Cache configuration
// ---------------------------------------------------------------------------

/// Cache backend configuration for the build pipeline.
///
/// Controls how built image layers are stored between pipeline stages.
/// When set, pipeline-built images are registered in a local OCI registry
/// so downstream images can reference them as base images.
///
/// # YAML Example
///
/// ```yaml
/// cache:
///   type: persistent
///   path: ~/.zlayer/cache
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PipelineCacheConfig {
    /// Cache type: "memory", "persistent", or "s3"
    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
    pub cache_type: Option<String>,

    /// Path for persistent cache (only used when type is "persistent")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,

    /// S3 bucket name (only used when type is "s3")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bucket: Option<String>,

    /// S3 region
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,

    /// S3 endpoint URL
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,

    /// S3 key prefix for cache objects
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Default build context directory.
fn default_context() -> PathBuf {
    PathBuf::from(".")
}

/// Check if path is the default context.
fn is_default_context(path: &Path) -> bool {
    path.as_os_str() == "."
}

/// Helper for `skip_serializing_if` on boolean fields.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(v: &bool) -> bool {
    !v
}

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

    #[test]
    fn test_pipeline_image_defaults() {
        let yaml = r"
file: Dockerfile
";
        let img: PipelineImage = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(img.file, PathBuf::from("Dockerfile"));
        assert_eq!(img.context, PathBuf::from("."));
        assert!(img.tags.is_empty());
        assert!(img.build_args.is_empty());
        assert!(img.depends_on.is_empty());
        assert!(img.no_cache.is_none());
        assert!(img.format.is_none());
        assert!(img.cache_mounts.is_empty());
        assert!(img.retries.is_none());
        assert!(img.platforms.is_empty());
    }

    #[test]
    fn test_pipeline_defaults_empty() {
        let yaml = "{}";
        let defaults: PipelineDefaults = serde_yaml::from_str(yaml).unwrap();
        assert!(defaults.format.is_none());
        assert!(defaults.build_args.is_empty());
        assert!(!defaults.no_cache);
        assert!(defaults.cache_mounts.is_empty());
        assert!(defaults.retries.is_none());
        assert!(defaults.platforms.is_empty());
    }

    #[test]
    fn test_pipeline_defaults_full() {
        let yaml = r#"
format: oci
build_args:
  RUST_VERSION: "1.90"
no_cache: true
"#;
        let defaults: PipelineDefaults = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(defaults.format, Some("oci".to_string()));
        assert_eq!(
            defaults.build_args.get("RUST_VERSION"),
            Some(&"1.90".to_string())
        );
        assert!(defaults.no_cache);
    }

    #[test]
    fn test_push_config_defaults() {
        let yaml = "{}";
        let push: PushConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(!push.after_all);
    }

    #[test]
    fn test_push_config_after_all() {
        let yaml = "after_all: true";
        let push: PushConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(push.after_all);
    }

    #[test]
    fn test_pipeline_cache_config() {
        let yaml = r"
version: '1'
cache:
  type: persistent
  path: /tmp/test-cache
images:
  test:
    file: Dockerfile
";
        let pipeline: ZPipeline = serde_yaml::from_str(yaml).unwrap();
        let cache = pipeline.cache.unwrap();
        assert_eq!(cache.cache_type.as_deref(), Some("persistent"));
        assert_eq!(cache.path, Some(PathBuf::from("/tmp/test-cache")));
    }

    #[test]
    fn test_deny_unknown_fields_pipeline_image() {
        let yaml = r#"
file: Dockerfile
unknown_field: "should fail"
"#;
        let result: Result<PipelineImage, _> = serde_yaml::from_str(yaml);
        assert!(result.is_err(), "Should reject unknown fields");
    }

    #[test]
    fn test_deny_unknown_fields_pipeline_defaults() {
        let yaml = r#"
format: oci
bogus: "nope"
"#;
        let result: Result<PipelineDefaults, _> = serde_yaml::from_str(yaml);
        assert!(result.is_err(), "Should reject unknown fields");
    }

    #[test]
    fn test_cache_mounts_and_retries_deserialize_defaults() {
        let yaml = r"
format: oci
no_cache: true
cache_mounts:
  - target: /root/.cargo/registry
    id: cargo-registry
    sharing: shared
  - target: /root/.cache/pip
retries: 3
";
        let defaults: PipelineDefaults = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(defaults.cache_mounts.len(), 2);
        assert_eq!(defaults.cache_mounts[0].target, "/root/.cargo/registry");
        assert_eq!(
            defaults.cache_mounts[0].id,
            Some("cargo-registry".to_string())
        );
        assert_eq!(defaults.cache_mounts[0].sharing, Some("shared".to_string()));
        assert_eq!(defaults.cache_mounts[1].target, "/root/.cache/pip");
        assert!(defaults.cache_mounts[1].id.is_none());
        assert_eq!(defaults.retries, Some(3));
    }

    #[test]
    fn test_cache_mounts_and_retries_deserialize_image() {
        let yaml = r"
file: Dockerfile
cache_mounts:
  - target: /tmp/build-cache
    readonly: true
retries: 5
";
        let img: PipelineImage = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(img.cache_mounts.len(), 1);
        assert_eq!(img.cache_mounts[0].target, "/tmp/build-cache");
        assert!(img.cache_mounts[0].readonly);
        assert_eq!(img.retries, Some(5));
    }

    #[test]
    fn test_deny_unknown_fields_push_config() {
        let yaml = r#"
after_all: true
extra: "bad"
"#;
        let result: Result<PushConfig, _> = serde_yaml::from_str(yaml);
        assert!(result.is_err(), "Should reject unknown fields");
    }

    #[test]
    fn test_serialization_skips_defaults() {
        let img = PipelineImage {
            file: PathBuf::from("Dockerfile"),
            context: PathBuf::from("."),
            tags: vec![],
            build_args: HashMap::new(),
            depends_on: vec![],
            no_cache: None,
            format: None,
            cache_mounts: vec![],
            retries: None,
            platforms: vec![],
        };
        let serialized = serde_yaml::to_string(&img).unwrap();
        // Should only contain "file" since everything else is default/empty
        assert!(serialized.contains("file:"));
        assert!(!serialized.contains("context:"));
        assert!(!serialized.contains("tags:"));
        assert!(!serialized.contains("build_args:"));
        assert!(!serialized.contains("depends_on:"));
        assert!(!serialized.contains("no_cache:"));
        assert!(!serialized.contains("format:"));
        assert!(!serialized.contains("cache_mounts:"));
        assert!(!serialized.contains("retries:"));
        assert!(!serialized.contains("platforms:"));
    }

    #[test]
    fn test_serialization_includes_non_defaults() {
        let img = PipelineImage {
            file: PathBuf::from("Dockerfile"),
            context: PathBuf::from("./subdir"),
            tags: vec!["myimage:latest".to_string()],
            build_args: HashMap::from([("KEY".to_string(), "value".to_string())]),
            depends_on: vec!["base".to_string()],
            no_cache: Some(true),
            format: Some("docker".to_string()),
            cache_mounts: vec![crate::zimage::types::ZCacheMount {
                target: "/root/.cache".to_string(),
                id: Some("mycache".to_string()),
                sharing: None,
                readonly: false,
            }],
            retries: Some(3),
            platforms: vec!["linux/amd64".to_string(), "linux/arm64".to_string()],
        };
        let serialized = serde_yaml::to_string(&img).unwrap();
        assert!(serialized.contains("context:"));
        assert!(serialized.contains("tags:"));
        assert!(serialized.contains("build_args:"));
        assert!(serialized.contains("depends_on:"));
        assert!(serialized.contains("no_cache:"));
        assert!(serialized.contains("format:"));
        assert!(serialized.contains("cache_mounts:"));
        assert!(serialized.contains("retries:"));
        assert!(serialized.contains("platforms:"));
    }
}