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
use cargo_lambda_interactive::{is_stdin_tty, Confirm, Text};
use clap::Args;
use liquid::{model::Value, ParserBuilder};
use miette::{IntoDiagnostic, Result, WrapErr};
use regex::Regex;
use std::{
fs::{copy as copy_file, create_dir_all, read_dir, rename, File},
io::{copy, Cursor},
path::{Path, PathBuf},
};
use tempfile::tempdir;
use walkdir::WalkDir;
use zip::ZipArchive;
mod events;
const DEFAULT_TEMPLATE_URL: &str =
"https://github.com/cargo-lambda/default-template/archive/refs/heads/main.zip";
#[derive(Args, Clone, Debug)]
#[clap(name = "new")]
pub struct New {
#[clap(flatten)]
template_options: TemplateOptions,
#[clap()]
package_name: String,
}
#[derive(Args, Clone, Debug, Default)]
pub struct TemplateOptions {
#[clap(long)]
template: Option<String>,
#[clap(long)]
http: Option<bool>,
#[clap(long)]
function_name: Option<String>,
#[clap(long)]
event_type: Option<String>,
}
impl New {
pub async fn run(&mut self) -> Result<()> {
validate_name(&self.package_name)?;
if self.missing_options() {
if !is_stdin_tty() {
return Err(miette::miette!("missing options: --event-type, --http"));
}
self.ask_template_options()?;
if self.missing_options() {
return Err(miette::miette!("missing options: --event-type, --http"));
}
}
if self.is_http_function() && self.has_event_type() {
return Err(miette::miette!(
"invalid options: --event-type and --http cannot be specified at the same time"
));
}
self.create_package().await
}
fn ask_template_options(&mut self) -> Result<()> {
if let Some(fn_name) = &self.template_options.function_name {
validate_name(fn_name)?;
}
if self.template_options.http.is_none() {
let is_http = Confirm::new("Is this function an HTTP function?")
.with_help_message("type `yes` if the Lambda function is triggered by an API Gateway, Amazon Load Balancer(ALB), or a Lambda URL")
.with_default(false)
.prompt()
.into_diagnostic()?;
if is_http {
self.template_options.http = Some(is_http);
}
}
if self.template_options.http.is_none() {
let event_type = Text::new("AWS Event type that this function receives")
.with_suggester(&suggest_event_type)
.with_validator(&validate_event_type)
.with_help_message("↑↓ to move, tab to auto-complete, enter to submit. Leave it blank if you don't want to use any event from the aws_lambda_events crate")
.prompt()
.into_diagnostic()?;
self.template_options.event_type = Some(event_type);
}
Ok(())
}
fn missing_options(&self) -> bool {
self.template_options.missing_options()
}
fn is_http_function(&self) -> bool {
matches!(self.template_options.http, Some(true))
}
fn has_event_type(&self) -> bool {
matches!(&self.template_options.event_type, Some(s) if !s.is_empty())
}
fn event_type_triple(&self) -> Result<(Value, Value, Value)> {
match &self.template_options.event_type {
Some(s) if !s.is_empty() => {
let import = Value::scalar(format!("aws_lambda_events::event::{}", s));
match s.splitn(2, "::").collect::<Vec<_>>()[..] {
[ev_mod, ev_type] => Ok((
import,
Value::scalar(ev_mod.to_string()),
Value::scalar(ev_type.to_string()),
)),
_ => Err(miette::miette!("unexpected event type")),
}
}
_ => Ok((Value::Nil, Value::Nil, Value::Nil)),
}
}
async fn create_package(&self) -> Result<()> {
let tmp_dir = tempdir().into_diagnostic()?;
let mut template_path = tmp_dir.path().to_path_buf();
match &self.template_options.template {
None => download_template(DEFAULT_TEMPLATE_URL, &template_path).await?,
Some(s) if is_remote_zip_file(s) => download_template(s, &template_path).await?,
Some(s) if is_local_zip_file(s) => unzip_template(PathBuf::from(s), &template_path)?,
Some(s) if is_local_directory(s) => template_path = PathBuf::from(s),
Some(other) => return Err(miette::miette!("invalid template: {}", other)),
};
let parser = ParserBuilder::with_stdlib().build().into_diagnostic()?;
let use_basic_example = !self.is_http_function() && !self.has_event_type();
let (ev_import, ev_feat, ev_type) = self.event_type_triple()?;
let fn_name = match self.template_options.function_name.as_deref() {
Some(fn_name) if fn_name != self.package_name => Value::scalar(fn_name.to_string()),
_ => Value::Nil,
};
let lhv = option_env!("CARGO_LAMBDA_LAMBDA_HTTP_VERSION")
.map(|v| Value::scalar(v.to_string()))
.unwrap_or(Value::Nil);
let lrv = option_env!("CARGO_LAMBDA_LAMBDA_RUNTIME_VERSION")
.map(|v| Value::scalar(v.to_string()))
.unwrap_or(Value::Nil);
let lev = option_env!("CARGO_LAMBDA_LAMBDA_EVENTS_VERSION")
.map(|v| Value::scalar(v.to_string()))
.unwrap_or(Value::Nil);
let globals = liquid::object!({
"project_name": self.package_name,
"function_name": fn_name,
"basic_example": use_basic_example,
"http_function": self.is_http_function(),
"event_type": ev_type,
"event_type_feature": ev_feat,
"event_type_import": ev_import,
"lambda_http_version": lhv,
"lambda_runtime_version": lrv,
"aws_lambda_events_version": lev,
});
let render_dir = tempfile::tempdir().into_diagnostic()?;
let render_path = render_dir.path();
let walk_dir = WalkDir::new(&template_path).follow_links(false);
for entry in walk_dir {
let entry = entry.into_diagnostic()?;
let entry_path = entry.path();
let entry_name = entry_path
.file_name()
.ok_or_else(|| miette::miette!("invalid entry: {:?}", &entry_path))?;
if entry_path.is_dir() {
if entry_name != ".git" {
create_dir_all(&entry_path).into_diagnostic()?;
}
} else if entry_name == "cargo-lambda-template.zip" {
continue;
} else {
let relative = entry_path.strip_prefix(&template_path).into_diagnostic()?;
let new_path = render_path.join(relative);
let parent_name = if let Some(parent) = new_path.parent() {
create_dir_all(parent).into_diagnostic()?;
parent.file_name().and_then(|p| p.to_str())
} else {
None
};
if entry_name == "Cargo.toml"
|| entry_name == "README.md"
|| (entry_name == "main.rs" && parent_name == Some("src"))
{
let template = parser.parse_file(&entry_path).into_diagnostic()?;
let mut file = File::create(&new_path).into_diagnostic()?;
template
.render_to(&mut file, &globals)
.into_diagnostic()
.wrap_err_with(|| {
format!("failed to render template file: {:?}", &new_path)
})?;
} else {
copy_file(&entry_path, &new_path)
.into_diagnostic()
.wrap_err_with(|| {
format!(
"failed to copy file: from {:?} to {:?}",
&entry_path, &new_path
)
})?;
}
}
}
rename(&render_path, &self.package_name)
.into_diagnostic()
.wrap_err_with(|| {
format!(
"failed to move package: from {:?} to {:?}",
&render_path, &self.package_name
)
})?;
Ok(())
}
}
async fn download_template(url: &str, path: &Path) -> Result<()> {
let response = reqwest::get(url).await.into_diagnostic()?;
if response.status() != reqwest::StatusCode::OK {
return Err(miette::miette!(
"error downloading template from {} - {}",
url,
response.text().await.into_diagnostic()?
));
}
let mut bytes = Cursor::new(response.bytes().await.into_diagnostic()?);
let tmp_file = path.join("cargo-lambda-template.zip");
let mut writer = File::create(&tmp_file)
.into_diagnostic()
.wrap_err_with(|| format!("unable to create file: {:?}", &tmp_file))?;
copy(&mut bytes, &mut writer).into_diagnostic()?;
unzip_template(tmp_file, path)
}
impl TemplateOptions {
fn missing_options(&self) -> bool {
self.http.is_none() && self.event_type.is_none()
}
}
fn validate_name(name: &str) -> Result<()> {
let valid_ident = Regex::new(r"^([a-zA-Z][a-zA-Z0-9_-]+)$").into_diagnostic()?;
match valid_ident.is_match(name) {
true => Ok(()),
false => Err(miette::miette!("invalid package name: {}", name)),
}
}
fn validate_event_type(name: &str) -> Result<(), String> {
match name.is_empty() || events::WELL_KNOWN_EVENTS.contains(&name) {
true => Ok(()),
false => Err(format!("invalid event type: {}", name)),
}
}
fn suggest_event_type(text: &str) -> Vec<String> {
events::WELL_KNOWN_EVENTS
.iter()
.filter_map(|s| {
if s.starts_with(text) {
Some(s.to_string())
} else {
None
}
})
.collect()
}
fn is_local_directory(path: &str) -> bool {
let path = Path::new(path);
path.exists() && path.is_dir()
}
fn is_remote_zip_file(path: &str) -> bool {
path.starts_with("https://") && path.ends_with(".zip")
}
fn is_local_zip_file(path: &str) -> bool {
let path = Path::new(path);
path.exists() && path.is_file() && path.extension().unwrap_or_default() == "zip"
}
fn unzip_template(file: PathBuf, path: &Path) -> Result<()> {
let reader = File::open(&file)
.into_diagnostic()
.wrap_err_with(|| format!("unable to open file: {:?}", file))?;
let mut archive = ZipArchive::new(reader).into_diagnostic()?;
archive.extract(path).into_diagnostic()?;
if !path.join("Cargo.toml").exists() {
let mut base_path = None;
let walk_dir = WalkDir::new(path).follow_links(false);
for entry in walk_dir {
let entry = entry.into_diagnostic()?;
let entry_path = entry.path();
if entry_path.is_dir() && entry_path.join("Cargo.toml").exists() {
base_path = Some(entry_path.to_path_buf());
break;
}
}
if let Some(base_path) = base_path {
for entry in read_dir(base_path).into_diagnostic()? {
let entry = entry.into_diagnostic()?;
let entry_path = entry.path();
let entry_name = entry_path
.file_name()
.ok_or_else(|| miette::miette!("invalid entry: {:?}", &entry_path))?;
let new_path = path.join(entry_name);
rename(&entry_path, &new_path)
.into_diagnostic()
.wrap_err_with(|| {
format!(
"failed to move template file: from {:?} to {:?}",
&entry_path, &new_path
)
})?;
}
}
}
Ok(())
}