-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_plugin.rs
More file actions
345 lines (318 loc) Β· 12 KB
/
Copy pathrun_plugin.rs
File metadata and controls
345 lines (318 loc) Β· 12 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use anyhow::{bail, Context, Result};
use console::style;
use std::path::{Path, PathBuf};
use std::process::Command;
use super::{load_registry, plugins_dir, PluginCapabilities, PluginManifest};
/// Build a [`Command`] for a plugin binary, handling script files on Windows.
///
/// On Windows, bash scripts (those starting with `#!`) cannot be executed
/// directly because the OS doesn't interpret shebangs. We detect script files
/// and wrap them through `sh` so that Git-for-Windows / MSYS2 / WSL can
/// execute them.
fn build_plugin_command(bin_path: &Path) -> Command {
#[cfg(windows)]
{
if is_script_file(bin_path) {
let mut cmd = Command::new("sh");
cmd.arg(bin_path);
return cmd;
}
}
Command::new(bin_path)
}
/// Returns `true` when the file at `path` starts with `#!` (a shebang),
/// indicating it is a script rather than a native binary.
#[cfg(windows)]
fn is_script_file(path: &Path) -> bool {
std::fs::read(path)
.map(|bytes| bytes.starts_with(b"#!"))
.unwrap_or(false)
}
type ProtocolInfo = (String, String, PathBuf, PluginCapabilities, Option<String>);
pub(super) fn run_plugin_cmd(name: &str, args: &[String]) -> Result<()> {
let bin_path = super::resolve_plugin_command(name)
.or_else(|| resolve_plugin_by_name(name))
.ok_or_else(|| {
let hint = match find_commands_for_plugin(name) {
Some(cmds) if !cmds.is_empty() => format!(
"\n Did you mean one of its commands? {}",
style(cmds.join(", ")).cyan()
),
_ => String::new(),
};
anyhow::anyhow!(
"Plugin command '{}' not found.{}\n Run {} to see installed plugins.",
name,
hint,
style("fledge plugin list").cyan()
)
})?;
if let Some((plugin_name, plugin_version, plugin_dir, capabilities, runtime)) =
resolve_protocol_info(name)?
{
if runtime.as_deref() == Some("wasm") {
#[cfg(feature = "wasm")]
{
let manifest_path = plugin_dir.join("plugin.toml");
let content = std::fs::read_to_string(&manifest_path)
.context("reading plugin.toml for WASM plugin")?;
let manifest: PluginManifest =
toml::from_str(&content).context("parsing plugin.toml for WASM plugin")?;
let wasm_binary = manifest
.commands
.iter()
.find(|c| c.name == name)
.or_else(|| manifest.commands.first())
.map(|c| plugin_dir.join(&c.binary))
.ok_or_else(|| anyhow::anyhow!("WASM plugin has no commands defined"))?;
return super::wasm::run_wasm_plugin(
&wasm_binary,
args,
&plugin_name,
&plugin_version,
&plugin_dir,
&capabilities,
);
}
#[cfg(not(feature = "wasm"))]
{
bail!(
"Plugin '{}' requires the WASM runtime, which was not compiled in \
(rebuild with --features wasm).",
name
);
}
}
return crate::protocol::run_protocol_plugin(
&bin_path,
args,
&plugin_name,
&plugin_version,
&plugin_dir,
&capabilities,
);
}
let mut cmd = build_plugin_command(&bin_path);
cmd.args(args);
if let Some(plugin_dir) = resolve_plugin_source_dir(&bin_path) {
cmd.env("FLEDGE_PLUGIN_DIR", &plugin_dir);
}
let status = cmd
.status()
.with_context(|| format!("running plugin '{name}'"))?;
if !status.success() {
let code = status.code().unwrap_or(1);
bail!("Plugin '{}' exited with code {}", name, code);
}
Ok(())
}
/// Compute the plugin's source directory from the resolved binary path.
///
/// `bin_path` is typically the symlink at `~/.config/fledge/plugins/bin/<cmd>`,
/// which resolves to `~/.config/fledge/plugins/<plugin>/bin/<cmd>` (or
/// similar). The plugin's source dir is two levels up from the resolved
/// binary β that's the location where multi-file shell plugins keep their
/// helpers, and what `FLEDGE_PLUGIN_DIR` should point to.
///
/// Returns `None` if the path can't be resolved (in which case we just don't
/// set the env var β plugins that don't rely on it work as before).
pub(super) fn resolve_plugin_source_dir(bin_path: &Path) -> Option<PathBuf> {
let resolved = std::fs::canonicalize(bin_path).ok()?;
// <plugin_dir>/<bin_subdir>/<binary> β take parent twice.
resolved.parent()?.parent().map(|p| p.to_path_buf())
}
pub(super) fn run_hook(plugin_dir: &Path, hook: &str, event: &str) -> Result<()> {
println!(
" {} Running {} hook...",
style("βΆοΈ").cyan().bold(),
style(event).dim()
);
let hook_path = plugin_dir.join(hook);
let status = if hook_path.exists() {
let canonical_hook = hook_path
.canonicalize()
.with_context(|| format!("canonicalizing hook path '{}'", hook))?;
let canonical_plugin_dir = plugin_dir
.canonicalize()
.unwrap_or_else(|_| plugin_dir.to_path_buf());
if !canonical_hook.starts_with(&canonical_plugin_dir) {
bail!("Hook path '{}' escapes plugin directory", hook);
}
super::make_executable(&hook_path)?;
run_hook_file(&hook_path, plugin_dir).with_context(|| format!("running {event} hook"))?
} else {
let parts = shell_words::split(hook)
.with_context(|| format!("parsing {event} hook command: {hook}"))?;
if parts.is_empty() {
bail!("Empty hook command for {event}");
}
Command::new(&parts[0])
.args(&parts[1..])
.current_dir(plugin_dir)
.env("FLEDGE_PLUGIN_DIR", plugin_dir)
.status()
.with_context(|| format!("running {event} hook"))?
};
if !status.success() {
let code = status.code().unwrap_or(1);
bail!("Hook '{}' exited with code {}", event, code);
}
Ok(())
}
/// Execute a hook file, handling platform differences. On Windows, shell
/// scripts (`.sh` or extensionless) are wrapped with `sh` / `bash` /
/// `git-bash` since `Command::new("script.sh")` produces OS error 193.
/// `.bat` and `.cmd` files are executed via `cmd /c`.
fn run_hook_file(hook_path: &Path, plugin_dir: &Path) -> Result<std::process::ExitStatus> {
if cfg!(windows) {
let ext = hook_path.extension().and_then(|e| e.to_str()).unwrap_or("");
match ext {
"bat" | "cmd" => {
return Command::new("cmd")
.args(["/c", &hook_path.to_string_lossy()])
.current_dir(plugin_dir)
.env("FLEDGE_PLUGIN_DIR", plugin_dir)
.status()
.context("running hook via cmd /c");
}
"exe" => {
return Command::new(hook_path)
.current_dir(plugin_dir)
.env("FLEDGE_PLUGIN_DIR", plugin_dir)
.status()
.context("running hook exe");
}
_ => {
// Shell script or extensionless β try sh, bash, git-bash
for shell in &["sh", "bash"] {
if let Ok(status) = Command::new(shell)
.arg(hook_path)
.current_dir(plugin_dir)
.env("FLEDGE_PLUGIN_DIR", plugin_dir)
.status()
{
return Ok(status);
}
}
// git-bash as last resort (common on Windows via Git for Windows)
let git_bash = Path::new("C:\\Program Files\\Git\\bin\\bash.exe");
if git_bash.exists() {
return Command::new(git_bash)
.arg(hook_path)
.current_dir(plugin_dir)
.env("FLEDGE_PLUGIN_DIR", plugin_dir)
.status()
.context("running hook via git-bash");
}
bail!(
"Cannot run hook '{}': no shell interpreter found.\n \
Install Git for Windows (which includes bash) or add sh/bash to PATH.",
hook_path.display()
);
}
}
}
Command::new(hook_path)
.current_dir(plugin_dir)
.env("FLEDGE_PLUGIN_DIR", plugin_dir)
.status()
.context("running hook")
}
fn resolve_plugin_by_name(plugin_name: &str) -> Option<PathBuf> {
let registry = load_registry().ok()?;
let entry = registry
.plugins
.iter()
.find(|p| p.name == plugin_name || p.name == format!("fledge-{plugin_name}"))?;
let first_cmd = entry.commands.first()?;
super::resolve_plugin_command(first_cmd)
}
fn find_commands_for_plugin(plugin_name: &str) -> Option<Vec<String>> {
let registry = load_registry().ok()?;
registry
.plugins
.iter()
.find(|p| p.name == plugin_name || p.name == format!("fledge-{plugin_name}"))
.map(|p| p.commands.clone())
}
/// Check whether `protocol` is a known/supported value and return the protocol
/// info tuple, `Ok(None)` for "no protocol declared" (legacy fallback), or
/// `Err` when the plugin explicitly targets an unsupported protocol version.
pub(super) fn apply_protocol(
protocol: Option<&str>,
plugin_name: String,
plugin_version: String,
plugin_dir: PathBuf,
caps: PluginCapabilities,
runtime: Option<&str>,
) -> Result<Option<ProtocolInfo>> {
match protocol {
Some("fledge-v1") => Ok(Some((
plugin_name,
plugin_version,
plugin_dir,
caps,
runtime.map(String::from),
))),
Some(unsupported) => bail!(
"Plugin '{}' requires protocol '{}' which is not supported by this version of fledge.\n \
Update fledge to use this plugin: cargo install fledge",
plugin_name,
unsupported
),
None => Ok(None),
}
}
fn resolve_protocol_info(name: &str) -> Result<Option<ProtocolInfo>> {
let registry = match load_registry() {
Ok(r) => r,
Err(_) => return Ok(None),
};
let entry = match registry.plugins.iter().find(|p| {
p.name == name || p.name == format!("fledge-{name}") || p.commands.iter().any(|c| c == name)
}) {
Some(e) => e,
None => return Ok(None),
};
let plugin_dir = plugins_dir().join(&entry.name);
let manifest_path = plugin_dir.join("plugin.toml");
let content = match std::fs::read_to_string(&manifest_path) {
Ok(c) => c,
Err(_) => return Ok(None),
};
let manifest: PluginManifest = match toml::from_str(&content) {
Ok(m) => m,
Err(_) => return Ok(None),
};
let caps = entry
.capabilities
.clone()
.unwrap_or_else(|| manifest.capabilities.clone());
apply_protocol(
manifest.plugin.protocol.as_deref(),
manifest.plugin.name.clone(),
manifest.plugin.version.clone(),
plugin_dir,
caps,
manifest.plugin.runtime.as_deref(),
)
}
pub(super) fn which_fledge_plugin(name: &str) -> Option<PathBuf> {
let target = format!("fledge-{name}");
let path_var = std::env::var("PATH").ok()?;
for dir in std::env::split_paths(&path_var) {
let candidate = dir.join(&target);
if candidate.exists() {
return Some(candidate);
}
if cfg!(windows) {
for ext in &[".exe", ".bat", ".cmd"] {
let with_ext = dir.join(format!("{target}{ext}"));
if with_ext.exists() {
return Some(with_ext);
}
}
}
}
None
}