podup 0.4.0

Translate and run docker-compose files on rootless Podman
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
//! Image build and pull operations.
//!
//! [`Engine::pull_image`] fetches a pre-built image from a registry.
//! [`Engine::build_service`] compiles a build context tar, passes it to the
//! Podman/Docker API, and applies any extra tags. Inline Dockerfiles and
//! multi-stage `--target` trimming are handled before the tar is assembled.

use std::path::Path;

use bollard::body_full;
use bollard::query_parameters::{BuildImageOptions, CreateImageOptions, TagImageOptions};
use bytes::Bytes;
use flate2::write::GzEncoder;
use flate2::Compression;
use futures::StreamExt;
use tracing::{debug, info, warn};
use walkdir::WalkDir;

use crate::compose::types::{BuildConfig, Service};
use crate::error::{ComposeError, Result};
use crate::size;

use super::Engine;

impl Engine {
	pub(super) async fn pull_image(&self, service: &Service) -> Result<()> {
		let image = match &service.image {
			Some(img) => img.clone(),
			None => return Ok(()),
		};

		info!("pulling {image}");

		let mut stream = self.docker.create_image(
			Some(CreateImageOptions {
				from_image: Some(image.clone()),
				platform: service.platform.clone().unwrap_or_default(),
				..Default::default()
			}),
			None,
			None,
		);

		while let Some(result) = stream.next().await {
			match result {
				Ok(info) => {
					if let Some(status) = info.status {
						debug!("{status}");
					}
				}
				Err(e) => warn!("pull warning: {e}"),
			}
		}

		Ok(())
	}

	pub(super) async fn build_service(&self, service_name: &str, service: &Service) -> Result<()> {
		let build = match &service.build {
			Some(b) => b,
			None => return Ok(()),
		};

		let context_path = self.base_dir.join(build.context());
		let tag = service
			.image
			.clone()
			.unwrap_or_else(|| format!("{}:latest", service_name));

		info!("building {tag} from {}", context_path.display());

		let (tar_bytes, dockerfile_name) = if let Some(inline) = build.dockerfile_inline() {
			build_context_tar_with_inline(&context_path, inline)?
		} else {
			let df = build.dockerfile().unwrap_or("Dockerfile");
			if let Some(target) = build.target() {
				build_context_tar_with_target(&context_path, df, target)?
			} else {
				(build_context_tar(&context_path, df)?, df.to_string())
			}
		};

		let arg_map = build.args().to_map();
		let mut build_args: std::collections::HashMap<String, String> =
			std::collections::HashMap::new();
		for (k, v) in arg_map {
			let value = match v {
				Some(val) => val,
				None => std::env::var(&k).unwrap_or_default(),
			};
			build_args.insert(k, value);
		}

		let mut labels: std::collections::HashMap<String, String> =
			std::collections::HashMap::new();
		if let BuildConfig::Config { labels: l, .. } = build {
			labels.extend(l.to_map());
		}

		let network_owned = if let BuildConfig::Config {
			network: Some(n), ..
		} = build
		{
			n.clone()
		} else {
			String::new()
		};
		let platform_owned = if let BuildConfig::Config { platforms, .. } = build {
			platforms.first().cloned().unwrap_or_default()
		} else {
			String::new()
		};
		let shmsize = build
			.shm_size()
			.and_then(size::parse_memory)
			.map(|s| s as u64)
			.unwrap_or(0);
		let extrahosts = build.extra_hosts().join(",");

		let options = BuildImageOptions {
			dockerfile: dockerfile_name,
			t: Some(tag.clone()),
			rm: true,
			nocache: build.no_cache(),
			pull: if build.pull() {
				Some("1".to_string())
			} else {
				None
			},
			buildargs: if build_args.is_empty() {
				None
			} else {
				Some(build_args)
			},
			labels: if labels.is_empty() {
				None
			} else {
				Some(labels)
			},
			networkmode: if network_owned.is_empty() {
				None
			} else {
				Some(network_owned)
			},
			platform: platform_owned,
			shmsize: if shmsize > 0 {
				Some(shmsize as i32)
			} else {
				None
			},
			extrahosts: if extrahosts.is_empty() {
				None
			} else {
				Some(extrahosts)
			},
			cachefrom: if build.cache_from().is_empty() {
				None
			} else {
				Some(build.cache_from().to_vec())
			},
			..Default::default()
		};

		let body = Bytes::from(tar_bytes);
		let mut stream = self
			.docker
			.build_image(options, None, Some(body_full(body)));

		while let Some(result) = stream.next().await {
			match result {
				Ok(info) => {
					if let Some(stream_msg) = info.stream {
						print!("{stream_msg}");
					}
					if let Some(err) = info.error_detail.and_then(|e| e.message) {
						return Err(ComposeError::Build(err));
					}
				}
				Err(e) => return Err(ComposeError::Podman(e)),
			}
		}

		// Apply additional tags.
		for extra_tag in build.tags() {
			let (repo, tag_str) = extra_tag
				.rsplit_once(':')
				.map(|(r, t)| (r.to_string(), t.to_string()))
				.unwrap_or_else(|| (extra_tag.clone(), "latest".to_string()));
			if let Err(e) = self
				.docker
				.tag_image(
					&tag,
					Some(TagImageOptions {
						repo: Some(repo),
						tag: Some(tag_str),
					}),
				)
				.await
			{
				warn!("failed to apply extra tag {extra_tag}: {e}");
			}
		}

		Ok(())
	}
}

// ---------------------------------------------------------------------------
// Build context tar
// ---------------------------------------------------------------------------

/// Write inline Dockerfile content into the context tar as `.dockerfile-inline`.
fn build_context_tar_with_inline(context: &Path, inline: &str) -> Result<(Vec<u8>, String)> {
	let inline_name = ".dockerfile-inline";
	let ignore_patterns = read_dockerignore(context);

	let encoder = GzEncoder::new(Vec::new(), Compression::default());
	let mut tar = tar::Builder::new(encoder);

	// Inline Dockerfile first.
	let mut header = tar::Header::new_gnu();
	header.set_size(inline.len() as u64);
	header.set_mode(0o644);
	header.set_cksum();
	tar.append_data(&mut header, inline_name, inline.as_bytes())
		.map_err(|e| ComposeError::Build(e.to_string()))?;

	for entry in WalkDir::new(context).follow_links(false) {
		let entry = entry.map_err(|e| ComposeError::Io(e.into()))?;
		let abs = entry.path();
		let rel = abs
			.strip_prefix(context)
			.map_err(|_| ComposeError::Build("path strip error".into()))?;
		if rel.as_os_str().is_empty() {
			continue;
		}
		let rel_str = rel.to_string_lossy();
		if is_ignored(&rel_str, &ignore_patterns) {
			continue;
		}
		if abs.is_dir() {
			tar.append_dir(rel, abs)
				.map_err(|e| ComposeError::Build(e.to_string()))?;
		} else {
			tar.append_path_with_name(abs, rel)
				.map_err(|e| ComposeError::Build(e.to_string()))?;
		}
	}

	let gz = tar
		.into_inner()
		.map_err(|e| ComposeError::Build(e.to_string()))?;
	let bytes = gz
		.finish()
		.map_err(|e| ComposeError::Build(e.to_string()))?;
	Ok((bytes, inline_name.to_string()))
}

pub(crate) fn build_context_tar(context: &Path, _dockerfile: &str) -> Result<Vec<u8>> {
	let ignore_patterns = read_dockerignore(context);

	let encoder = GzEncoder::new(Vec::new(), Compression::default());
	let mut tar = tar::Builder::new(encoder);

	for entry in WalkDir::new(context).follow_links(false) {
		let entry = entry.map_err(|e| ComposeError::Io(e.into()))?;
		let abs = entry.path();
		let rel = abs
			.strip_prefix(context)
			.map_err(|_| ComposeError::Build("path strip error".into()))?;

		if rel.as_os_str().is_empty() {
			continue;
		}

		let rel_str = rel.to_string_lossy();
		if is_ignored(&rel_str, &ignore_patterns) {
			continue;
		}

		if abs.is_dir() {
			tar.append_dir(rel, abs)
				.map_err(|e| ComposeError::Build(e.to_string()))?;
		} else {
			tar.append_path_with_name(abs, rel)
				.map_err(|e| ComposeError::Build(e.to_string()))?;
		}
	}

	let gz = tar
		.into_inner()
		.map_err(|e| ComposeError::Build(e.to_string()))?;
	let bytes = gz
		.finish()
		.map_err(|e| ComposeError::Build(e.to_string()))?;

	Ok(bytes)
}

/// Build a context tar with the Dockerfile truncated to stages up to `target`.
///
/// Achieves the same result as `docker build --target=<target>` without requiring
/// bollard API support for the target parameter.
fn build_context_tar_with_target(
	context: &Path,
	dockerfile: &str,
	target: &str,
) -> Result<(Vec<u8>, String)> {
	let df_path = context.join(dockerfile);
	let df_content = std::fs::read_to_string(&df_path).map_err(ComposeError::Io)?;
	let truncated = truncate_dockerfile_to_target(&df_content, target);

	let ignore_patterns = read_dockerignore(context);
	let encoder = GzEncoder::new(Vec::new(), Compression::default());
	let mut tar = tar::Builder::new(encoder);

	// Write truncated Dockerfile first.
	let df_bytes = truncated.as_bytes();
	let mut header = tar::Header::new_gnu();
	header.set_size(df_bytes.len() as u64);
	header.set_mode(0o644);
	header.set_cksum();
	tar.append_data(&mut header, dockerfile, df_bytes)
		.map_err(|e| ComposeError::Build(e.to_string()))?;

	// Add context, skipping the original Dockerfile (already wrote truncated version).
	for entry in WalkDir::new(context).follow_links(false) {
		let entry = entry.map_err(|e| ComposeError::Io(e.into()))?;
		let abs = entry.path();
		let rel = abs
			.strip_prefix(context)
			.map_err(|_| ComposeError::Build("path strip error".into()))?;
		if rel.as_os_str().is_empty() {
			continue;
		}
		let rel_str = rel.to_string_lossy();
		if is_ignored(&rel_str, &ignore_patterns) {
			continue;
		}
		if rel_str == dockerfile {
			continue; // Replaced by truncated version above.
		}
		if abs.is_dir() {
			tar.append_dir(rel, abs)
				.map_err(|e| ComposeError::Build(e.to_string()))?;
		} else {
			tar.append_path_with_name(abs, rel)
				.map_err(|e| ComposeError::Build(e.to_string()))?;
		}
	}

	let gz = tar
		.into_inner()
		.map_err(|e| ComposeError::Build(e.to_string()))?;
	let bytes = gz
		.finish()
		.map_err(|e| ComposeError::Build(e.to_string()))?;
	Ok((bytes, dockerfile.to_string()))
}

/// Truncate a Dockerfile to only include stages up to and including `target`.
///
/// Stages after `target` are dropped, making the target stage the effective
/// final output — equivalent to `docker build --target=<target>`.
pub(crate) fn truncate_dockerfile_to_target(content: &str, target: &str) -> String {
	let target_lower = target.to_lowercase();
	let mut lines: Vec<&str> = Vec::new();
	let mut found_target = false;

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

		if trimmed.starts_with("from ") {
			if found_target {
				// First FROM after our target stage — stop here.
				break;
			}
			lines.push(line);
			if let Some(as_idx) = trimmed.find(" as ") {
				let stage = trimmed[as_idx + 4..].trim().to_string();
				if stage == target_lower {
					found_target = true;
				}
			}
		} else {
			lines.push(line);
		}
	}

	if !found_target {
		tracing::warn!(
            "build.target '{target}' not found as a named stage in Dockerfile — using full Dockerfile"
        );
		return content.to_string();
	}

	lines.join("\n")
}

fn read_dockerignore(context: &Path) -> Vec<String> {
	let path = context.join(".dockerignore");
	let Ok(content) = std::fs::read_to_string(path) else {
		return Vec::new();
	};
	content
		.lines()
		.map(|l| l.trim().to_string())
		.filter(|l| !l.is_empty() && !l.starts_with('#'))
		.collect()
}

fn is_ignored(path: &str, patterns: &[String]) -> bool {
	for pattern in patterns {
		if pattern.ends_with('/') {
			if path.starts_with(pattern.as_str()) {
				return true;
			}
		} else if path == pattern.as_str()
			|| (path.starts_with(pattern.as_str())
				&& path.as_bytes().get(pattern.len()) == Some(&b'/'))
		{
			return true;
		}
	}
	false
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

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

	#[test]
	fn truncate_drops_stages_after_target() {
		let df = "FROM base AS builder\nRUN build\nFROM builder AS production\nRUN run\nFROM production AS final\nRUN finalize\n";
		let result = truncate_dockerfile_to_target(df, "production");
		assert!(result.contains("FROM base AS builder"));
		assert!(result.contains("FROM builder AS production"));
		assert!(!result.contains("FROM production AS final"));
	}

	#[test]
	fn truncate_unknown_target_returns_full() {
		let df = "FROM alpine\nRUN echo hi\n";
		let result = truncate_dockerfile_to_target(df, "nonexistent");
		assert_eq!(result, df);
	}

	#[test]
	fn truncate_case_insensitive_target() {
		let df = "FROM base AS Builder\nRUN step\nFROM Builder AS Next\nRUN other\n";
		let result = truncate_dockerfile_to_target(df, "builder");
		assert!(result.contains("AS Builder"));
		assert!(!result.contains("AS Next"));
	}

	#[test]
	fn truncate_single_stage_target() {
		let df = "FROM alpine AS app\nRUN echo done\n";
		let result = truncate_dockerfile_to_target(df, "app");
		assert!(result.contains("FROM alpine AS app"));
		assert!(result.contains("echo done"));
	}
}