-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbuild.rs
More file actions
272 lines (237 loc) · 7.66 KB
/
build.rs
File metadata and controls
272 lines (237 loc) · 7.66 KB
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
//! Docker builder build command
//!
//! Alternative interface to start a build (similar to `docker build`)
use crate::command::build::{BuildCommand, BuildOutput};
use crate::command::{CommandExecutor, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;
/// `docker builder build` command - alternative interface to docker build
///
/// This is essentially the same as `docker build` but accessed through
/// the builder subcommand interface.
///
/// # Example
/// ```no_run
/// use docker_wrapper::command::builder::BuilderBuildCommand;
/// use docker_wrapper::DockerCommand;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let result = BuilderBuildCommand::new(".")
/// .tag("myapp:latest")
/// .no_cache()
/// .execute()
/// .await?;
///
/// if let Some(id) = result.image_id {
/// println!("Built image: {}", id);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct BuilderBuildCommand {
/// Underlying build command
inner: BuildCommand,
}
impl BuilderBuildCommand {
/// Create a new builder build command
///
/// # Arguments
/// * `context` - Build context path (e.g., ".", "/path/to/dir")
pub fn new(context: impl Into<String>) -> Self {
Self {
inner: BuildCommand::new(context),
}
}
/// Set the Dockerfile to use
#[must_use]
pub fn dockerfile(mut self, path: impl Into<String>) -> Self {
self.inner = self.inner.file(path.into());
self
}
/// Tag the image
#[must_use]
pub fn tag(mut self, tag: impl Into<String>) -> Self {
self.inner = self.inner.tag(tag);
self
}
/// Do not use cache when building
#[must_use]
pub fn no_cache(mut self) -> Self {
self.inner = self.inner.no_cache();
self
}
/// Set build-time variables
#[must_use]
pub fn build_arg(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.inner = self.inner.build_arg(key, value);
self
}
/// Set target build stage
#[must_use]
pub fn target(mut self, target: impl Into<String>) -> Self {
self.inner = self.inner.target(target);
self
}
/// Set platform for multi-platform builds
#[must_use]
pub fn platform(mut self, platform: impl Into<String>) -> Self {
self.inner = self.inner.platform(platform);
self
}
/// Enable `BuildKit` backend
#[must_use]
pub fn buildkit(mut self) -> Self {
// This would normally set DOCKER_BUILDKIT=1 environment variable
// For now, we'll add it as a raw arg (in practice, this would be an env var)
self.inner
.executor
.raw_args
.push("DOCKER_BUILDKIT=1".to_string());
self
}
/// Enable quiet mode
#[must_use]
pub fn quiet(mut self) -> Self {
self.inner = self.inner.quiet();
self
}
/// Always remove intermediate containers
#[must_use]
pub fn force_rm(mut self) -> Self {
self.inner = self.inner.force_rm();
self
}
/// Remove intermediate containers after successful build (default)
#[must_use]
pub fn rm(self) -> Self {
// rm is the default behavior, this is a no-op
self
}
/// Do not remove intermediate containers after build
#[must_use]
pub fn no_rm(mut self) -> Self {
self.inner = self.inner.no_rm();
self
}
/// Always attempt to pull newer version of base image
#[must_use]
pub fn pull(mut self) -> Self {
self.inner = self.inner.pull();
self
}
}
#[async_trait]
impl DockerCommand for BuilderBuildCommand {
type Output = BuildOutput;
fn get_executor(&self) -> &CommandExecutor {
&self.inner.executor
}
fn get_executor_mut(&mut self) -> &mut CommandExecutor {
&mut self.inner.executor
}
fn build_command_args(&self) -> Vec<String> {
// Get the args from the inner build command
let mut inner_args = self.inner.build_command_args();
// Replace "build" with "builder build"
if !inner_args.is_empty() && inner_args[0] == "build" {
inner_args[0] = "builder".to_string();
inner_args.insert(1, "build".to_string());
}
inner_args
}
async fn execute(&self) -> Result<Self::Output> {
// The builder build command has the same output as regular build
let args = self.build_command_args();
let output = self.execute_command(args).await?;
// Extract image ID from output
let image_id = extract_image_id(&output.stdout);
Ok(BuildOutput {
stdout: output.stdout,
stderr: output.stderr,
exit_code: output.exit_code,
image_id,
})
}
}
/// Extract image ID from build output
fn extract_image_id(stdout: &str) -> Option<String> {
// Look for "Successfully built <id>" or "writing image sha256:<id>"
for line in stdout.lines().rev() {
if line.contains("Successfully built") {
return line.split_whitespace().last().map(String::from);
}
if line.contains("writing image sha256:") {
if let Some(id) = line.split("sha256:").nth(1) {
return Some(format!(
"sha256:{}",
id.split_whitespace()
.next()?
.trim_end_matches('"')
.trim_end_matches('}')
));
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_builder_build_basic() {
let cmd = BuilderBuildCommand::new(".");
let args = cmd.build_command_args();
assert_eq!(&args[0..2], &["builder", "build"]);
assert!(args.contains(&".".to_string()));
}
#[test]
fn test_builder_build_with_options() {
let cmd = BuilderBuildCommand::new("/app")
.tag("myapp:latest")
.dockerfile("custom.Dockerfile")
.no_cache()
.build_arg("VERSION", "1.0");
let args = cmd.build_command_args();
assert_eq!(&args[0..2], &["builder", "build"]);
assert!(args.contains(&"--tag".to_string()));
assert!(args.contains(&"myapp:latest".to_string()));
assert!(args.contains(&"--file".to_string()));
assert!(args.contains(&"custom.Dockerfile".to_string()));
assert!(args.contains(&"--no-cache".to_string()));
assert!(args.contains(&"--build-arg".to_string()));
assert!(args.contains(&"VERSION=1.0".to_string()));
}
#[test]
fn test_builder_build_buildkit() {
let mut cmd = BuilderBuildCommand::new(".");
cmd = cmd.buildkit();
// Check that DOCKER_BUILDKIT was added as a raw arg
assert!(cmd
.inner
.executor
.raw_args
.contains(&"DOCKER_BUILDKIT=1".to_string()));
}
#[test]
fn test_builder_build_platform() {
let cmd = BuilderBuildCommand::new(".")
.platform("linux/amd64")
.target("production");
let args = cmd.build_command_args();
assert!(args.contains(&"--platform".to_string()));
assert!(args.contains(&"linux/amd64".to_string()));
assert!(args.contains(&"--target".to_string()));
assert!(args.contains(&"production".to_string()));
}
#[test]
fn test_builder_build_extensibility() {
let mut cmd = BuilderBuildCommand::new(".");
cmd.inner
.executor
.raw_args
.push("--custom-flag".to_string());
let args = cmd.build_command_args();
assert!(args.contains(&"--custom-flag".to_string()));
}
}