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
use cargo_lambda_interactive::{command::silent_command, is_user_cancellation_error};
use cargo_lambda_metadata::fs::rename;
use clap::Args;
use liquid::{model::Value, Object, ParserBuilder};
use miette::{IntoDiagnostic, Result, WrapErr};
use regex::Regex;
use std::{
collections::HashMap,
env,
fs::{copy as copy_file, create_dir_all, File},
path::{Path, PathBuf},
};
use walkdir::WalkDir;
use crate::template::TemplateSource;
mod error;
use error::CreateError;
mod events;
mod extensions;
mod functions;
mod template;
#[derive(Args, Clone, Debug)]
#[command(name = "new")]
#[group(skip)]
pub struct New {
#[arg(long)]
template: Option<String>,
#[arg(long)]
extension: bool,
#[command(flatten)]
function_options: functions::Options,
#[command(flatten)]
extension_options: extensions::Options,
#[arg(short, long)]
open: bool,
#[arg(long, alias = "function-name")]
bin_name: Option<String>,
#[arg(long)]
no_interactive: bool,
#[arg(long)]
render_file: Option<Vec<PathBuf>>,
#[arg(long)]
render_var: Option<Vec<String>>,
#[arg(long)]
ignore_file: Option<Vec<PathBuf>>,
#[arg()]
package_name: String,
}
impl New {
#[tracing::instrument(skip(self), target = "cargo_lambda")]
pub async fn run(&mut self) -> Result<()> {
tracing::trace!(options = ?self, "creating new project");
validate_name(&self.package_name)?;
if let Some(name) = &self.bin_name {
validate_name(name)?;
}
if self.extension {
self.extension_options.validate_options()?;
} else {
match self.function_options.validate_options(self.no_interactive) {
Err(CreateError::UnexpectedInput(err)) if is_user_cancellation_error(&err) => {
return Ok(())
}
Err(err) => return Err(err.into()),
Ok(()) => {}
}
}
self.create_package().await?;
self.open_code_editor().await
}
async fn create_package(&self) -> Result<()> {
let template_source = TemplateSource::try_from(self.template_option())?;
let template_path = template_source.expand().await?;
let parser = ParserBuilder::with_stdlib().build().into_diagnostic()?;
let template_vars = if self.extension {
self.extension_options.variables()?
} else {
self.function_options
.variables(&self.package_name, &self.bin_name)?
};
let mut globals = liquid::object!({
"project_name": self.package_name,
"binary_name": self.bin_name,
});
globals.extend(template_vars);
globals.extend(self.render_variables());
tracing::debug!(variables = ?globals, "rendering templates");
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(|| CreateError::InvalidTemplateEntry(entry_path.to_path_buf()))?;
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 == "LICENSE" || self.is_ignore_file(relative) {
continue;
}
if entry_name == "Cargo.toml"
|| entry_name == "README.md"
|| (entry_name == "main.rs" && parent_name == Some("src"))
|| (entry_name == "lib.rs" && parent_name == Some("src"))
|| parent_name == Some("bin")
|| self.is_render_file(relative)
{
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 open_code_editor(&self) -> Result<()> {
if !self.open {
return Ok(());
}
let editor = env::var("EDITOR").unwrap_or_default();
let editor = editor.trim();
if editor.is_empty() {
Err(CreateError::InvalidEditor(self.package_name.clone()).into())
} else {
silent_command(editor.trim(), &[&self.package_name]).await
}
}
fn template_option(&self) -> &str {
match self.template.as_deref() {
Some(t) => t,
None if self.extension => extensions::DEFAULT_TEMPLATE_URL,
None => functions::DEFAULT_TEMPLATE_URL,
}
}
fn is_render_file(&self, path: &Path) -> bool {
self.render_file
.as_ref()
.map(|v| v.contains(&path.to_path_buf()))
.unwrap_or(false)
}
fn render_variables(&self) -> Object {
let vars = self.render_var.clone().unwrap_or_default();
let mut map = HashMap::new();
for var in vars {
let mut split = var.splitn(2, '=');
if let (Some(k), Some(v)) = (split.next(), split.next()) {
map.insert(k.to_string(), v.to_string());
}
}
let mut object = Object::new();
for (k, v) in map {
object.insert(k.into(), Value::scalar(v));
}
object
}
fn is_ignore_file(&self, path: &Path) -> bool {
self.ignore_file
.as_ref()
.map(|v| v.contains(&path.to_path_buf()))
.unwrap_or(false)
}
}
pub(crate) 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(CreateError::InvalidPackageName(name.to_string()).into()),
}
}