-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
plugin.rs
271 lines (235 loc) · 8.26 KB
/
plugin.rs
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
use std::{
fs::{self, create_dir_all, File, OpenOptions},
io::{BufRead, BufReader, ErrorKind, Write},
path::{Path, PathBuf},
};
use anyhow::{Context, Result};
use clap::{ArgEnum, Parser, Subcommand};
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, ArgEnum)]
pub enum PluginTargetType {
/// wasm32-unknown-unknown target.
Wasm32UnknownUnknown,
/// wasm32-wasi target.
Wasm32Wasi,
}
#[derive(Parser, Debug)]
pub struct PluginScaffoldOptions {
/// Set the resulting plugin name, defaults to the directory name
#[clap(long)]
pub name: Option<String>,
/// Sets default build target type of the plugin.
///
/// "wasm32-wasi" enables wasi (https://github.com/WebAssembly/WASI) support for the generated
/// binary which allows to use macros like 'println!' or 'dbg!' and other
/// system-related calls.
///
/// "wasm32-unknown-unknown" will makes those calls as no-op, instead
/// generates slightly smaller binaries.
#[clap(long, arg_enum)]
pub target_type: PluginTargetType,
pub path: PathBuf,
}
/// Infer package name of the plugin if not specified via cli options.
fn get_name(option: &PluginScaffoldOptions) -> Result<&str> {
if let Some(ref name) = option.name {
return Ok(name);
}
let file_name = option.path.file_name().ok_or_else(|| {
anyhow::format_err!(
"cannot auto-detect package name from path {:?} ; use --name to override",
option.path.as_os_str()
)
})?;
file_name.to_str().ok_or_else(|| {
anyhow::format_err!(
"cannot create package with a non-unicode name: {:?}",
file_name
)
})
}
/// Generate ignore file for the project.
///
/// Note: this is slim implementation does not support different vcs other than
/// git at the moment.
fn write_ignore_file(base_path: &Path) -> Result<()> {
let ignore_list: Vec<String> = vec!["/target", "^target/", "target"]
.iter()
.map(|v| v.to_string())
.collect();
let ignore_file_path = base_path.join(".gitignore");
let ignore: String = match File::open(&ignore_file_path) {
Err(err) => match err {
io_err if io_err.kind() == ErrorKind::NotFound => ignore_list.join("\n") + "\n",
_ => return Err(err).context("failed to open .gitignore"),
},
Ok(file) => {
let existing = BufReader::new(file);
let existing_items = existing.lines().collect::<Result<Vec<_>, _>>().unwrap();
let mut out = String::new();
out.push_str("\n\n# Added by swc\n");
if ignore_list.iter().any(|item| existing_items.contains(item)) {
out.push_str("#\n# already existing elements were commented out\n");
}
out.push('\n');
for item in &ignore_list {
if existing_items.contains(item) {
out.push('#');
}
out.push_str(item);
out.push('\n');
}
out
}
};
let mut f = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(&ignore_file_path)?;
write!(f, "{}", ignore).context("failed to write to .gitignore file")?;
Ok(())
}
impl super::CommandRunner for PluginScaffoldOptions {
fn execute_inner(&self) -> Result<()> {
Ok(())
}
/// Create a rust project for the plugin from template.
/// This largely mimic https://github.com/rust-lang/cargo/blob/master/src/cargo/ops/cargo_new.rs,
/// but also thinner implementation based on some assumptions like skipping
/// to support non-git based vcs.
fn execute(&self) -> Result<()> {
let path = &self.path;
if path.exists() {
anyhow::bail!("destination `{}` already exists", path.display())
}
let name = get_name(self)?;
// Choose to rely on system's git binary instead of depends on git lib for now
// to avoid bring in large / heavy dependencies into cli binaries.
// Depends on our usecase grows, we can revisit this.
let mut base_git_cmd = if cfg!(target_os = "windows") {
let mut c = std::process::Command::new("cmd");
c.arg("/C").arg("git");
c
} else {
std::process::Command::new("git")
};
// init git repo
base_git_cmd
.args(["init", name])
.output()
.context("failed to create dir for the plugin")?;
// generate .gitignore
write_ignore_file(path)?;
// Create `Cargo.toml` file with necessary sections
fs::write(
&path.join("Cargo.toml"),
format!(
r#"[package]
name = "{}"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
serde = "1"
swc_plugin = "*""#,
name
)
.as_bytes(),
)
.context("failed to write Cargo.toml file")?;
let build_target = match self.target_type {
PluginTargetType::Wasm32UnknownUnknown => "wasm32-unknown-unknown",
PluginTargetType::Wasm32Wasi => "wasm32-wasi",
};
// Create cargo config for build target
let cargo_config_path = path.join(".cargo");
create_dir_all(&cargo_config_path).context("`create_dir_all` failed")?;
fs::write(
&cargo_config_path.join("config"),
format!(
r#"[build]
target = "{}""#,
build_target
)
.as_bytes(),
)
.context("failed to write config toml file")?;
// Create package.json for npm package publishing.
let dist_output_path = format!("target/{}/release/{}.wasm", build_target, name);
fs::write(
&path.join("package.json"),
format!(
r#"{{
"name": "{}",
"version": "0.1.0",
"description": "",
"author": "",
"license": "ISC",
"keywords": ["swc-plugin"],
"main": "{}",
"scripts": {{
"prepublishOnly": "cargo build --release"
}},
"files": []
}}
"#,
name, dist_output_path
)
.as_bytes(),
)
.context("failed to write Cargo.toml file")?;
// Create entrypoint src file
let src_path = path.join("src");
create_dir_all(&src_path)?;
fs::write(
&src_path.join("lib.rs"),
r#"use swc_plugin::{ast::*, plugin_transform};
pub struct TransformVisitor;
impl VisitMut for TransformVisitor {
// Implement necessary visit_mut_* methods for actual custom transform.
// A comprehensive list of possible visitor methods can be found here:
// https://rustdoc.swc.rs/swc_ecma_visit/trait.VisitMut.html
}
/// An example plugin function with macro support.
/// `plugin_transform` macro interop pointers into deserialized structs, as well
/// as returning ptr back to host.
///
/// It is possible to opt out from macro by writing transform fn manually via
/// `__plugin_process_impl(
/// ast_ptr: *const u8,
/// ast_ptr_len: i32,
/// config_str_ptr: *const u8,
/// config_str_ptr_len: i32,
/// context_str_ptr: *const u8,
/// context_str_ptr_len: i32) ->
/// i32 /* 0 for success, fail otherwise.
/// Note this is only for internal pointer interop result,
/// not actual transform result */
///
/// if plugin need to handle low-level ptr directly. However, there are
/// important steps manually need to be performed like sending transformed
/// results back to host. Refer swc_plugin_macro how does it work internally.
#[plugin_transform]
pub fn process_transform(program: Program, _plugin_config: String, _context: String) -> Program {
program.fold_with(&mut as_folder(TransformVisitor))
}
"#
.as_bytes(),
)
.context("failed to write the rust source file")?;
println!(
r#"✅ Successfully created {}.
If you haven't, please ensure to add target via "rustup target add {}" "#,
path.display(),
build_target
);
Ok(())
}
}
/// Set of subcommands for the plugin subcommand.
#[derive(Subcommand)]
pub enum PluginSubcommand {
/// Create a new plugin project with minimal scaffolding template.
New(PluginScaffoldOptions),
}