-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhandler.rs
414 lines (371 loc) · 10.9 KB
/
handler.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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use std::borrow::Cow;
use std::io::Write;
use std::ops::Deref;
use std::ops::DerefMut;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::ExitStatus;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use anyhow::anyhow;
use anyhow::bail;
use anyhow::Error;
use anyhow::Result;
use dprint_core::async_runtime::async_trait;
use dprint_core::async_runtime::LocalBoxFuture;
use dprint_core::configuration::ConfigKeyMap;
use dprint_core::configuration::GlobalConfiguration;
use dprint_core::plugins::AsyncPluginHandler;
use dprint_core::plugins::CancellationToken;
use dprint_core::plugins::FileMatchingInfo;
use dprint_core::plugins::FormatRequest;
use dprint_core::plugins::FormatResult;
use dprint_core::plugins::HostFormatRequest;
use dprint_core::plugins::PluginInfo;
use dprint_core::plugins::PluginResolveConfigurationResult;
use handlebars::Handlebars;
use serde::Deserialize;
use serde::Serialize;
use tokio::sync::oneshot;
use tokio::sync::oneshot::Receiver;
use tokio::sync::oneshot::Sender;
use crate::configuration::CommandConfiguration;
use crate::configuration::Configuration;
struct ChildKillOnDrop(std::process::Child);
impl Drop for ChildKillOnDrop {
fn drop(&mut self) {
let _ignore = self.0.kill();
}
}
impl Deref for ChildKillOnDrop {
type Target = std::process::Child;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ChildKillOnDrop {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub struct ExecHandler;
#[async_trait(?Send)]
impl AsyncPluginHandler for ExecHandler {
type Configuration = Configuration;
fn plugin_info(&self) -> PluginInfo {
let name = env!("CARGO_PKG_NAME").to_string();
let version = env!("CARGO_PKG_VERSION").to_string();
PluginInfo {
name: name.clone(),
version: version.clone(),
config_key: "exec".to_string(),
help_url: env!("CARGO_PKG_HOMEPAGE").to_string(),
config_schema_url: format!(
"https://plugins.dprint.dev/dprint/{}/{}/schema.json",
name, version
),
update_url: Some(format!(
"https://plugins.dprint.dev/dprint/{}/latest.json",
name
)),
}
}
fn license_text(&self) -> String {
include_str!("../LICENSE").to_string()
}
async fn resolve_config(
&self,
config: ConfigKeyMap,
global_config: GlobalConfiguration,
) -> PluginResolveConfigurationResult<Configuration> {
let result = Configuration::resolve(config, &global_config);
let config = result.config;
PluginResolveConfigurationResult {
file_matching: FileMatchingInfo {
file_extensions: config
.commands
.iter()
.flat_map(|c| c.file_extensions.iter())
.map(|s| s.trim_start_matches('.').to_string())
.collect(),
file_names: config
.commands
.iter()
.flat_map(|c| c.file_names.iter())
.map(|s| s.to_string())
.collect(),
},
config,
diagnostics: result.diagnostics,
}
}
async fn format(
&self,
request: FormatRequest<Self::Configuration>,
_format_with_host: impl FnMut(HostFormatRequest) -> LocalBoxFuture<'static, FormatResult> + 'static,
) -> FormatResult {
if request.range.is_some() {
// we don't support range formatting for this plugin
return Ok(None);
}
format_bytes(
request.file_path,
request.file_bytes,
request.config,
request.token.clone(),
)
.await
}
}
pub async fn format_bytes(
file_path: PathBuf,
original_file_bytes: Vec<u8>,
config: Arc<Configuration>,
token: Arc<dyn CancellationToken>,
) -> FormatResult {
fn trim_bytes_len(bytes: &[u8]) -> usize {
let mut start = 0;
let mut end = bytes.len();
while start < end && bytes[start].is_ascii_whitespace() {
start += 1;
}
if start == end {
return 0;
}
while end > start && bytes[end - 1].is_ascii_whitespace() {
end -= 1;
}
if end < start {
0
} else {
end - start
}
}
let mut file_bytes: Cow<Vec<u8>> = Cow::Borrowed(&original_file_bytes);
for command in select_commands(&config, &file_path)? {
// format here
let args = maybe_substitute_variables(&file_path, &config, command);
let mut child = ChildKillOnDrop(
Command::new(&command.executable)
.current_dir(&command.cwd)
.stdout(Stdio::piped())
.stdin(if command.stdin {
Stdio::piped()
} else {
Stdio::null()
})
.stderr(Stdio::piped())
.args(args)
.spawn()
.map_err(|e| anyhow!("Cannot start formatter process: {}", e))?,
);
// capturing stdout
let (out_tx, out_rx) = oneshot::channel();
let mut handles = Vec::with_capacity(2);
if let Some(stdout) = child.stdout.take() {
handles.push(dprint_core::async_runtime::spawn_blocking(|| {
read_stream_lines(stdout, out_tx)
}));
} else {
let _ = child.kill();
return Err(anyhow!("Formatter did not have a handle for stdout"));
}
// capturing stderr
let (err_tx, err_rx) = oneshot::channel();
if let Some(stderr) = child.stderr.take() {
handles.push(dprint_core::async_runtime::spawn_blocking(|| {
read_stream_lines(stderr, err_tx)
}));
}
// write file text into child's stdin
if command.stdin {
let mut stdin = child
.stdin
.take()
.ok_or_else(|| {
anyhow!(
"Cannot open the command's stdin. Perhaps you meant to set the command's \"stdin\" configuration to false?",
)
})?;
let file_bytes = file_bytes.into_owned();
dprint_core::async_runtime::spawn_blocking(move || {
stdin
.write_all(&file_bytes)
.map_err(|err| anyhow!("Cannot write into the command's stdin. {}", err))
})
.await??;
}
let child_completed = dprint_core::async_runtime::spawn_blocking(move || match child.wait() {
Ok(status) => Ok(status),
Err(e) => Err(anyhow!(
"Error while waiting for formatter to complete: {}",
e
)),
});
let result_future = async {
let handles_future = dprint_core::async_runtime::future::join_all(handles);
let (output_result, child_rs, handle_results) =
tokio::join!(out_rx, child_completed, handles_future);
let exit_status = child_rs??;
let output = output_result?;
for handle_result in handle_results {
handle_result??; // surface any errors capturing
}
Ok::<_, Error>((output, exit_status))
};
tokio::select! {
_ = token.wait_cancellation() => {
// return back the original text when cancelled
return Ok(None);
}
_ = tokio::time::sleep(Duration::from_secs(config.timeout as u64)) => {
return Err(timeout_err(&config));
}
result = result_future => {
let (ok_text, exit_status) = result?;
file_bytes = Cow::Owned(handle_child_exit_status(ok_text, err_rx, exit_status).await?)
}
}
}
const MIN_CHARS_TO_EMPTY: usize = 100;
Ok(if *file_bytes == original_file_bytes {
None
} else if trim_bytes_len(&original_file_bytes) > MIN_CHARS_TO_EMPTY
&& trim_bytes_len(&file_bytes) == 0
{
// prevent someone formatting all their files to empty files
bail!(
concat!(
"The original file text was greater than {} characters, but the formatted text was empty. ",
"Perhaps dprint-plugin-exec has been misconfigured?",
),
MIN_CHARS_TO_EMPTY
)
} else {
Some(file_bytes.into_owned())
})
}
fn select_commands<'a>(
config: &'a Configuration,
file_path: &Path,
) -> Result<Vec<&'a CommandConfiguration>> {
if !config.is_valid {
bail!("Cannot format because the configuration was not valid.");
}
let mut binaries = Vec::new();
for command in &config.commands {
if let Some(associations) = &command.associations {
if associations.is_match(file_path) {
binaries.push(command);
}
} else if binaries.is_empty() && command.matches_exts_or_filenames(file_path) {
binaries.push(command);
break;
}
}
Ok(binaries)
}
async fn handle_child_exit_status(
ok_text: Vec<u8>,
err_rx: Receiver<Vec<u8>>,
exit_status: ExitStatus,
) -> Result<Vec<u8>, Error> {
if exit_status.success() {
return Ok(ok_text);
}
Err(anyhow!(
"Child process exited with code {}: {}",
exit_status.code().unwrap(),
String::from_utf8_lossy(
&err_rx
.await
.expect("Could not propagate error message from child process")
)
))
}
fn timeout_err(config: &Configuration) -> Error {
anyhow!(
"Child process has not returned a result within {} seconds.",
config.timeout,
)
}
fn read_stream_lines<R>(mut readable: R, sender: Sender<Vec<u8>>) -> Result<(), Error>
where
R: std::io::Read + Unpin,
{
let mut bytes = Vec::new();
readable.read_to_end(&mut bytes)?;
let _ignore = sender.send(bytes); // ignore error as that means the other end is closed
Ok(())
}
fn maybe_substitute_variables(
file_path: &Path,
config: &Configuration,
command: &CommandConfiguration,
) -> Vec<String> {
let mut handlebars = Handlebars::new();
handlebars.set_strict_mode(true);
#[derive(Clone, Serialize, Deserialize)]
struct TemplateVariables {
file_path: String,
line_width: u32,
use_tabs: bool,
indent_width: u8,
cwd: String,
timeout: u32,
}
let vars = TemplateVariables {
file_path: file_path.to_string_lossy().to_string(),
line_width: config.line_width,
use_tabs: config.use_tabs,
indent_width: config.indent_width,
cwd: command.cwd.to_string_lossy().to_string(),
timeout: config.timeout,
};
let mut c_args = vec![];
for arg in &command.args {
let formatted = handlebars
.render_template(arg, &vars)
.unwrap_or_else(|err| panic!("Cannot format: {}\n\n{}", arg, err));
c_args.push(formatted);
}
c_args
}
#[cfg(test)]
mod test {
use std::path::PathBuf;
use std::sync::Arc;
use dprint_core::plugins::NullCancellationToken;
use crate::configuration::Configuration;
use crate::format_bytes;
#[tokio::test]
async fn should_error_output_empty_file() {
let token = Arc::new(NullCancellationToken);
let unresolved_config = r#"{
"commands": [{
"command": "deno eval 'Deno.exit(0)'",
"exts": ["txt"]
}]
}"#;
let unresolved_config = serde_json::from_str(unresolved_config).unwrap();
let config = Configuration::resolve(unresolved_config, &Default::default()).config;
let result = format_bytes(
PathBuf::from("path.txt"),
"1".repeat(101).into_bytes(),
Arc::new(config),
token,
)
.await;
let err_text = result.err().unwrap().to_string();
assert_eq!(
err_text,
concat!(
"The original file text was greater than 100 characters, ",
"but the formatted text was empty. ",
"Perhaps dprint-plugin-exec has been misconfigured?"
)
)
}
}