-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.rs
More file actions
321 lines (289 loc) · 9.91 KB
/
cli.rs
File metadata and controls
321 lines (289 loc) · 9.91 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
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
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use ctor::ctor;
use edgezero_adapter::cli_support::{
find_manifest_upwards, find_workspace_root, path_distance, read_package_name,
};
use edgezero_adapter::scaffold::{
register_adapter_blueprint, AdapterBlueprint, AdapterFileSpec, CommandTemplates,
DependencySpec, LoggingDefaults, ManifestSpec, ReadmeInfo, TemplateRegistration,
};
use edgezero_adapter::{register_adapter, Adapter, AdapterAction};
use walkdir::WalkDir;
const TARGET_TRIPLE: &str = "wasm32-unknown-unknown";
pub fn build() -> Result<PathBuf, String> {
let manifest = find_wrangler_manifest(
std::env::current_dir()
.map_err(|e| e.to_string())?
.as_path(),
)?;
let manifest_dir = manifest
.parent()
.ok_or_else(|| "wrangler manifest has no parent directory".to_string())?;
let cargo_manifest = manifest_dir.join("Cargo.toml");
let crate_name = read_package_name(&cargo_manifest)?;
let status = Command::new("cargo")
.args([
"build",
"--release",
"--target",
TARGET_TRIPLE,
"--manifest-path",
cargo_manifest
.to_str()
.ok_or("invalid Cargo manifest path")?,
])
.status()
.map_err(|e| format!("failed to run cargo build: {e}"))?;
if !status.success() {
return Err(format!("cargo build failed with status {status}"));
}
let workspace_root = find_workspace_root(manifest_dir);
let artifact = locate_artifact(&workspace_root, manifest_dir, &crate_name)?;
let pkg_dir = workspace_root.join("pkg");
fs::create_dir_all(&pkg_dir)
.map_err(|e| format!("failed to create {}: {e}", pkg_dir.display()))?;
let dest = pkg_dir.join(format!("{}.wasm", crate_name.replace('-', "_")));
fs::copy(&artifact, &dest)
.map_err(|e| format!("failed to copy artifact to {}: {e}", dest.display()))?;
Ok(dest)
}
pub fn deploy(extra_args: &[String]) -> Result<(), String> {
let manifest = find_wrangler_manifest(
std::env::current_dir()
.map_err(|e| e.to_string())?
.as_path(),
)?;
let manifest_dir = manifest
.parent()
.ok_or_else(|| "wrangler manifest has no parent directory".to_string())?;
let config = manifest
.to_str()
.ok_or_else(|| "invalid wrangler config path".to_string())?;
let status = Command::new("wrangler")
.args(["deploy", "--config", config])
.args(extra_args)
.current_dir(manifest_dir)
.status()
.map_err(|e| format!("failed to run wrangler CLI: {e}"))?;
if !status.success() {
return Err(format!("wrangler deploy failed with status {status}"));
}
Ok(())
}
pub fn serve(extra_args: &[String]) -> Result<(), String> {
let manifest = find_wrangler_manifest(
std::env::current_dir()
.map_err(|e| e.to_string())?
.as_path(),
)?;
let manifest_dir = manifest
.parent()
.ok_or_else(|| "wrangler manifest has no parent directory".to_string())?;
let config = manifest
.to_str()
.ok_or_else(|| "invalid wrangler config path".to_string())?;
let status = Command::new("wrangler")
.args(["dev", "--config", config])
.args(extra_args)
.current_dir(manifest_dir)
.status()
.map_err(|e| format!("failed to run wrangler CLI: {e}"))?;
if !status.success() {
return Err(format!("wrangler dev failed with status {status}"));
}
Ok(())
}
struct CloudflareCliAdapter;
static CLOUDFLARE_TEMPLATE_REGISTRATIONS: &[TemplateRegistration] = &[
TemplateRegistration {
name: "cf_Cargo_toml",
contents: include_str!("templates/Cargo.toml.hbs"),
},
TemplateRegistration {
name: "cf_src_lib_rs",
contents: include_str!("templates/src/lib.rs.hbs"),
},
TemplateRegistration {
name: "cf_src_main_rs",
contents: include_str!("templates/src/main.rs.hbs"),
},
TemplateRegistration {
name: "cf_cargo_config_toml",
contents: include_str!("templates/.cargo/config.toml.hbs"),
},
TemplateRegistration {
name: "cf_wrangler_toml",
contents: include_str!("templates/wrangler.toml.hbs"),
},
];
static CLOUDFLARE_FILE_SPECS: &[AdapterFileSpec] = &[
AdapterFileSpec {
template: "cf_Cargo_toml",
output: "Cargo.toml",
},
AdapterFileSpec {
template: "cf_src_lib_rs",
output: "src/lib.rs",
},
AdapterFileSpec {
template: "cf_src_main_rs",
output: "src/main.rs",
},
AdapterFileSpec {
template: "cf_cargo_config_toml",
output: ".cargo/config.toml",
},
AdapterFileSpec {
template: "cf_wrangler_toml",
output: "wrangler.toml",
},
];
static CLOUDFLARE_DEPENDENCIES: &[DependencySpec] = &[
DependencySpec {
key: "dep_edgezero_core_cloudflare",
repo_crate: "crates/edgezero-core",
fallback: "edgezero-core = { git = \"https://git@github.com/stackpop/edgezero.git\", package = \"edgezero-core\", default-features = false }",
features: &[],
},
DependencySpec {
key: "dep_edgezero_adapter_cloudflare",
repo_crate: "crates/edgezero-adapter-cloudflare",
fallback:
"edgezero-adapter-cloudflare = { git = \"https://git@github.com/stackpop/edgezero.git\", package = \"edgezero-adapter-cloudflare\", default-features = false }",
features: &[],
},
DependencySpec {
key: "dep_edgezero_adapter_cloudflare_wasm",
repo_crate: "crates/edgezero-adapter-cloudflare",
fallback:
"edgezero-adapter-cloudflare = { git = \"https://git@github.com/stackpop/edgezero.git\", package = \"edgezero-adapter-cloudflare\", default-features = false, features = [\"cloudflare\"] }",
features: &["cloudflare"],
},
];
static CLOUDFLARE_BLUEPRINT: AdapterBlueprint = AdapterBlueprint {
id: "cloudflare",
display_name: "Cloudflare Workers",
crate_suffix: "adapter-cloudflare",
dependency_crate: "edgezero-adapter-cloudflare",
dependency_repo_path: "crates/edgezero-adapter-cloudflare",
template_registrations: CLOUDFLARE_TEMPLATE_REGISTRATIONS,
files: CLOUDFLARE_FILE_SPECS,
extra_dirs: &["src", ".cargo"],
dependencies: CLOUDFLARE_DEPENDENCIES,
manifest: ManifestSpec {
manifest_filename: "wrangler.toml",
build_target: "wasm32-unknown-unknown",
build_profile: "release",
build_features: &["cloudflare"],
},
commands: CommandTemplates {
build: "wrangler build --cwd {crate_dir}",
deploy: "wrangler deploy --cwd {crate_dir}",
serve: "wrangler dev --cwd {crate_dir}",
},
logging: LoggingDefaults {
endpoint: None,
level: "info",
echo_stdout: None,
},
readme: ReadmeInfo {
description: "{display} entrypoint.",
dev_heading: "{display} (local)",
dev_steps: &["`edgezero-cli serve --adapter cloudflare`"],
},
run_module: "edgezero_adapter_cloudflare",
};
static CLOUDFLARE_ADAPTER: CloudflareCliAdapter = CloudflareCliAdapter;
impl Adapter for CloudflareCliAdapter {
fn name(&self) -> &'static str {
"cloudflare"
}
fn execute(&self, action: AdapterAction, args: &[String]) -> Result<(), String> {
match action {
AdapterAction::Build => build().map(|artifact| {
println!(
"[edgezero] Cloudflare build artifact -> {}",
artifact.display()
);
}),
AdapterAction::Deploy => deploy(args),
AdapterAction::Serve => serve(args),
}
}
}
pub fn register() {
register_adapter(&CLOUDFLARE_ADAPTER);
register_adapter_blueprint(&CLOUDFLARE_BLUEPRINT);
}
#[ctor]
fn register_ctor() {
register();
}
fn find_wrangler_manifest(start: &Path) -> Result<PathBuf, String> {
if let Some(found) = find_manifest_upwards(start, "wrangler.toml") {
return Ok(found);
}
let root = find_workspace_root(start);
let mut candidates: Vec<PathBuf> = WalkDir::new(&root)
.follow_links(true)
.max_depth(8)
.into_iter()
.filter_map(Result::ok)
.map(|entry| entry.path().to_path_buf())
.filter(|path| {
path.file_name()
.map(|n| n == "wrangler.toml")
.unwrap_or(false)
&& path
.parent()
.map(|dir| dir.join("Cargo.toml").exists())
.unwrap_or(false)
})
.collect();
if candidates.is_empty() {
return Err("could not locate wrangler.toml".to_string());
}
candidates.sort_by_key(|path| {
let parent = path.parent().unwrap_or(Path::new(""));
path_distance(start, parent)
});
Ok(candidates.remove(0))
}
fn locate_artifact(
workspace_root: &Path,
manifest_dir: &Path,
crate_name: &str,
) -> Result<PathBuf, String> {
let release_name = format!("{}.wasm", crate_name.replace('-', "_"));
if let Some(custom) = std::env::var_os("CARGO_TARGET_DIR") {
let candidate = PathBuf::from(custom)
.join(TARGET_TRIPLE)
.join("release")
.join(&release_name);
if candidate.exists() {
return Ok(candidate);
}
}
let manifest_target = manifest_dir
.join("target")
.join(TARGET_TRIPLE)
.join("release")
.join(&release_name);
if manifest_target.exists() {
return Ok(manifest_target);
}
let workspace_target = workspace_root
.join("target")
.join(TARGET_TRIPLE)
.join("release")
.join(&release_name);
if workspace_target.exists() {
return Ok(workspace_target);
}
Err(format!(
"compiled artifact not found for {} (looked in manifest and workspace target directories)",
crate_name
))
}