-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmod.rs
More file actions
181 lines (144 loc) · 5.85 KB
/
mod.rs
File metadata and controls
181 lines (144 loc) · 5.85 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
use std::collections::HashMap;
use anyhow::{Context as _, anyhow};
use camino_tempfile::tempdir;
use clap::Parser;
use futures::{StreamExt, stream::FuturesOrdered};
use icp::{
canister::build::{BuildError, Params},
fs::read,
};
use crate::{commands::Context, progress::ProgressManager};
#[derive(Parser, Debug)]
pub struct Cmd {
/// The names of the canisters within the current project
pub names: Vec<String>,
}
#[derive(Debug, thiserror::Error)]
pub enum CommandError {
#[error("project does not contain a canister named '{name}'")]
CanisterNotFound { name: String },
#[error(transparent)]
Build(#[from] BuildError),
#[error("build did not result in output")]
MissingOutput,
#[error("failed to read output wasm artifact")]
ReadOutput,
#[error("failed to store build artifact")]
ArtifactStore,
#[error("failed to join build output")]
JoinError(#[from] tokio::task::JoinError),
#[error(transparent)]
Unexpected(#[from] anyhow::Error),
}
/// Executes the build command, compiling canisters defined in the project manifest.
pub async fn exec(ctx: &Context, cmd: Cmd) -> Result<(), CommandError> {
// Load the project manifest, which defines the canisters to be built.
let p = ctx.project.load().await.context("failed to load project")?;
// Choose canisters to build
let cnames = match cmd.names.is_empty() {
// No canisters specified
true => p.canisters.keys().cloned().collect(),
// Individual canisters specified
false => cmd.names.clone(),
};
for name in &cnames {
if !p.canisters.contains_key(name) {
return Err(CommandError::CanisterNotFound {
name: name.to_owned(),
});
}
}
let cs = p
.canisters
.iter()
.filter(|(k, _)| cnames.contains(k))
.collect::<HashMap<_, _>>();
// Prepare a futures set for concurrent canister builds
let mut futs = FuturesOrdered::new();
let progress_manager = ProgressManager::new();
// Iterate through each resolved canister and trigger its build process.
for (_, (canister_path, c)) in cs {
// Create progress bar with standard configuration
let mut pb = progress_manager.create_multi_step_progress_bar(&c.name);
// Create an async closure that handles the build process for this specific canister
let fut = {
let c = c.clone();
async move {
// Define the build logic
let build_result = async {
// Create a temporary directory for build artifacts
let build_dir =
tempdir().context("failed to create a temporary build directory")?;
// Prepare a path for our output wasm
let wasm_output_path = build_dir.path().join("out.wasm");
let step_count = c.build.steps.len();
for (i, step) in c.build.steps.iter().enumerate() {
// Indicate to user the current step being executed
let current_step = i + 1;
let pb_hdr = format!("\nBuilding: {step} {current_step} of {step_count}");
let tx = pb.begin_step(pb_hdr);
// Perform build step
let build_result = ctx
.builder
.build(
step, // step
&Params {
path: canister_path.to_owned(),
output: wasm_output_path.to_owned(),
},
tx,
)
.await;
// Ensure background receiver drains all messages
pb.end_step().await;
if let Err(e) = build_result {
return Err(CommandError::Build(e));
}
}
// Verify a file exists in the wasm output path
if !wasm_output_path.exists() {
return Err(CommandError::MissingOutput);
}
// Load wasm output
let wasm = read(&wasm_output_path).context(CommandError::ReadOutput)?;
// TODO(or.ricon): Verify wasm output is valid wasm (consider using wasmparser)
// Save the wasm artifact
ctx.artifacts
.save(&c.name, &wasm)
.context(CommandError::ArtifactStore)?;
Ok::<_, CommandError>(())
}
.await;
// If build failed, dump the output to terminal
if let Err(e) = &build_result {
pb.dump_output(ctx);
let _ = ctx
.term
.write_line(&format!("Failed to build canister: {e}"));
}
// Execute with progress tracking for final state
ProgressManager::execute_with_progress(
pb,
async { build_result },
|| "Built successfully".to_string(),
|err| format!("Failed to build canister: {err}"),
)
.await
}
};
futs.push_back(fut);
}
// Consume the set of futures and abort if an error occurs
let mut found_error = false;
while let Some(res) = futs.next().await {
if let Err(_) = res {
found_error = true;
}
}
if found_error {
return Err(CommandError::Unexpected(anyhow!(
"One or more canisters failed to build"
)));
}
Ok(())
}