use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use serde::Deserialize;
use tokio::process::Command;
use crate::model::{Icon, Item, ItemKey, Mod, Source};
const QUERY_TIMEOUT: Duration = Duration::from_millis(180);
const MAX_QUERY_TIMEOUT: Duration = Duration::from_millis(3000);
const MAX_OUTPUT_BYTES: usize = 1 << 20;
#[derive(Debug, Clone, Deserialize)]
pub struct Manifest {
pub name: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub keyword: Option<String>,
pub query: String,
#[serde(default)]
pub activate: Option<String>,
#[serde(default)]
pub icon: Option<String>,
#[serde(default)]
pub timeout_ms: Option<u64>,
}
impl Manifest {
#[must_use]
pub fn timeout(&self) -> Duration {
self.timeout_ms.map_or(QUERY_TIMEOUT, |ms| {
Duration::from_millis(ms).clamp(Duration::from_millis(50), MAX_QUERY_TIMEOUT)
})
}
}
#[derive(Debug, Clone, Deserialize)]
struct PluginItem {
title: String,
#[serde(default)]
subtitle: String,
#[serde(default)]
arg: Option<String>,
#[serde(default)]
icon: Option<PluginIcon>,
#[serde(default = "default_valid")]
valid: bool,
#[serde(default)]
uid: Option<String>,
#[serde(default)]
autocomplete: Option<String>,
#[serde(default)]
variables: std::collections::HashMap<String, String>,
#[serde(default)]
mods: std::collections::HashMap<String, PluginMod>,
}
#[derive(Debug, Clone, Deserialize)]
struct PluginMod {
#[serde(default)]
subtitle: String,
#[serde(default)]
arg: Option<String>,
#[serde(default = "default_valid")]
valid: bool,
#[serde(default)]
variables: std::collections::HashMap<String, String>,
}
fn normalise_modifier(name: &str) -> Option<&'static str> {
match name.trim().to_lowercase().as_str() {
"ctrl" | "control" => Some("ctrl"),
"alt" | "option" => Some("alt"),
"shift" => Some("shift"),
"cmd" | "command" | "super" | "meta" => Some("super"),
_ => None,
}
}
const fn default_valid() -> bool {
true
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
enum PluginIcon {
Named(String),
Path {
#[serde(alias = "name")]
path: String,
},
}
impl PluginIcon {
fn into_icon(self) -> Icon {
match self {
Self::Named(name) | Self::Path { path: name } => Icon::Name(name),
}
}
}
#[derive(Debug, Clone, Deserialize)]
struct PluginResponse {
items: Vec<PluginItem>,
#[serde(default)]
variables: std::collections::HashMap<String, String>,
#[serde(default)]
rerun: Option<f64>,
}
const RERUN_RANGE: std::ops::RangeInclusive<f64> = 0.5..=5.0;
#[derive(Debug, Clone, Default)]
pub struct QueryResults {
pub items: Vec<Item>,
pub rerun: Option<Duration>,
}
fn merge_variables(
response: &std::collections::HashMap<String, String>,
item: std::collections::HashMap<String, String>,
) -> Vec<(String, String)> {
let mut merged = response.clone();
merged.extend(item);
let mut variables: Vec<(String, String)> = merged.into_iter().collect();
variables.sort();
variables
}
#[derive(Debug, Clone)]
pub struct Plugin {
pub manifest: Manifest,
pub directory: PathBuf,
pub id: String,
}
impl Plugin {
fn resolve(&self, command: &str) -> PathBuf {
let path = Path::new(command);
if path.is_absolute() {
path.to_path_buf()
} else {
self.directory.join(path)
}
}
#[must_use]
pub fn match_query_as<'a>(&self, keyword: Option<&str>, query: &'a str) -> Option<&'a str> {
match keyword {
None => Some(query),
Some(keyword) => {
let rest = query.strip_prefix(keyword)?;
match rest.strip_prefix(' ') {
Some(rest) => Some(rest.trim_start()),
None if rest.is_empty() => Some(""),
None => None,
}
}
}
}
#[must_use]
pub fn match_query<'a>(&self, query: &'a str) -> Option<&'a str> {
self.match_query_as(self.manifest.keyword.as_deref(), query)
}
async fn query(&self, text: &str) -> (Vec<Item>, Option<Duration>) {
let program = self.resolve(&self.manifest.query);
let child = Command::new(&program)
.arg(text)
.current_dir(&self.directory)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.output();
let deadline = self.manifest.timeout();
let output = match tokio::time::timeout(deadline, child).await {
Ok(Ok(output)) => output,
Ok(Err(error)) => {
tracing::warn!(plugin = %self.id, ?program, %error, "plugin failed to run");
return (Vec::new(), None);
}
Err(_) => {
tracing::warn!(
plugin = %self.id,
timeout_ms = deadline.as_millis(),
"plugin exceeded its deadline; dropping results"
);
return (Vec::new(), None);
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::warn!(plugin = %self.id, status = ?output.status, %stderr, "plugin exited non-zero");
return (Vec::new(), None);
}
if output.stdout.len() > MAX_OUTPUT_BYTES {
tracing::warn!(plugin = %self.id, bytes = output.stdout.len(), "plugin output too large");
return (Vec::new(), None);
}
let response: PluginResponse = match serde_json::from_slice(&output.stdout) {
Ok(response) => response,
Err(error) => {
tracing::warn!(plugin = %self.id, %error, "plugin emitted invalid JSON");
return (Vec::new(), None);
}
};
let fallback_icon = self.manifest.icon.as_ref().map(|n| Icon::Name(n.clone()));
let PluginResponse {
items,
variables: response_variables,
rerun,
} = response;
let rerun = rerun.filter(|seconds| seconds.is_finite()).map(|seconds| {
Duration::from_secs_f64(seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end()))
});
let items = items
.into_iter()
.filter(|item| item.valid)
.map(|item| {
let arg = item.arg.unwrap_or_else(|| item.title.clone());
let variables = merge_variables(&response_variables, item.variables);
let mut mods: Vec<Mod> = item
.mods
.into_iter()
.filter(|(_, alternate)| alternate.valid)
.filter_map(|(modifier, alternate)| {
let modifier = normalise_modifier(&modifier)?;
let mut merged: std::collections::HashMap<String, String> =
variables.iter().cloned().collect();
merged.extend(alternate.variables);
let mut alternate_variables: Vec<(String, String)> =
merged.into_iter().collect();
alternate_variables.sort();
Some(Mod {
modifier: modifier.to_owned(),
subtitle: alternate.subtitle,
arg: alternate.arg.unwrap_or_else(|| arg.clone()),
variables: alternate_variables,
})
})
.collect();
mods.sort_by(|a, b| a.modifier.cmp(&b.modifier));
let identity = item.uid.as_deref().unwrap_or(&arg);
Item {
key: ItemKey(format!("plugin:{}:{identity}", self.id)),
id: 0,
title: item.title,
subtitle: if item.subtitle.is_empty() {
self.manifest.description.clone()
} else {
item.subtitle
},
icon: item
.icon
.map(PluginIcon::into_icon)
.or_else(|| fallback_icon.clone()),
category_icon: fallback_icon.clone(),
window: None,
source: Source::Plugin {
plugin: self.id.clone(),
arg,
variables,
mods,
},
autocomplete: item.autocomplete,
score: 0.0,
}
})
.collect();
(items, rerun)
}
pub fn activate(&self, arg: &str, variables: &[(String, String)]) {
let (program, extra) = match self.manifest.activate.as_deref() {
Some(activate) => (self.resolve(activate), Vec::new()),
None => (
self.resolve(&self.manifest.query),
vec!["--activate".to_owned()],
),
};
let result = Command::new(&program)
.envs(variables.iter().map(|(key, value)| (key, value)))
.args(extra)
.arg(arg)
.current_dir(&self.directory)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
match result {
Ok(mut child) => {
tokio::spawn(async move {
let _ = child.wait().await;
});
}
Err(error) => {
tracing::error!(plugin = %self.id, ?program, %error, "failed to activate plugin item");
}
}
}
}
#[derive(Debug, Default, Clone)]
pub struct PluginHost {
plugins: Vec<Plugin>,
disabled: std::collections::HashSet<String>,
keyword_overrides: std::collections::HashMap<String, String>,
}
impl PluginHost {
#[must_use]
pub fn discover() -> Self {
let mut roots: Vec<PathBuf> = dirs::data_dir()
.map(|dir| dir.join("jump").join("plugins"))
.into_iter()
.collect();
let system = std::env::var_os("XDG_DATA_DIRS")
.filter(|value| !value.is_empty())
.map_or_else(
|| {
vec![
PathBuf::from("/usr/local/share"),
PathBuf::from("/usr/share"),
]
},
|value| std::env::split_paths(&value).collect(),
);
roots.extend(
system
.into_iter()
.map(|dir| dir.join("jump").join("plugins")),
);
Self::discover_in(&roots)
}
#[must_use]
pub fn discover_in(roots: &[PathBuf]) -> Self {
let mut plugins: Vec<Plugin> = Vec::new();
for root in roots {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(error) => {
tracing::warn!(%error, ?root, "failed to read plugin directory");
continue;
}
};
for entry in entries.flatten() {
let directory = entry.path();
if !directory.is_dir() {
continue;
}
let Some(id) = directory
.file_name()
.and_then(|name| name.to_str())
.map(ToOwned::to_owned)
else {
continue;
};
if plugins.iter().any(|plugin| plugin.id == id) {
tracing::debug!(plugin = %id, ?directory, "shadowed by an earlier root");
continue;
}
let manifest_path = directory.join("manifest.toml");
let contents = match std::fs::read_to_string(&manifest_path) {
Ok(contents) => contents,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(error) => {
tracing::warn!(%error, ?manifest_path, "failed to read plugin manifest");
continue;
}
};
let manifest: Manifest = match toml::from_str(&contents) {
Ok(manifest) => manifest,
Err(error) => {
tracing::warn!(%error, ?manifest_path, "invalid plugin manifest");
continue;
}
};
tracing::info!(plugin = %id, keyword = ?manifest.keyword, "loaded plugin");
plugins.push(Plugin {
manifest,
directory,
id,
});
}
}
Self {
plugins,
disabled: std::collections::HashSet::new(),
keyword_overrides: std::collections::HashMap::new(),
}
}
pub fn set_disabled<I, S>(&mut self, ids: I)
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.disabled = ids.into_iter().map(Into::into).collect();
}
pub fn set_keyword_overrides<I, K, V>(&mut self, overrides: I)
where
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<String>,
{
self.keyword_overrides = overrides
.into_iter()
.map(|(id, keyword)| (id.into(), keyword.into()))
.collect();
}
#[must_use]
pub fn effective_keyword<'a>(&'a self, plugin: &'a Plugin) -> Option<&'a str> {
match self.keyword_overrides.get(&plugin.id) {
Some(keyword) if keyword.is_empty() => None,
Some(keyword) => Some(keyword.as_str()),
None => plugin.manifest.keyword.as_deref(),
}
}
pub fn all(&self) -> impl Iterator<Item = (&Plugin, bool)> {
self.plugins
.iter()
.map(|plugin| (plugin, !self.disabled.contains(&plugin.id)))
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.plugins.is_empty()
}
#[must_use]
pub fn get(&self, id: &str) -> Option<&Plugin> {
self.plugins
.iter()
.filter(|plugin| !self.disabled.contains(&plugin.id))
.find(|plugin| plugin.id == id)
}
pub async fn query(&self, text: &str) -> QueryResults {
let matching: Vec<_> = self
.plugins
.iter()
.filter(|plugin| !self.disabled.contains(&plugin.id))
.filter_map(|plugin| {
plugin
.match_query_as(self.effective_keyword(plugin), text)
.map(|query| (plugin, query))
})
.collect();
if matching.is_empty() {
return QueryResults::default();
}
let keyworded: Vec<_> = matching
.iter()
.filter(|(plugin, _)| self.effective_keyword(plugin).is_some())
.collect();
let selected: Vec<_> = if keyworded.is_empty() {
matching.iter().collect()
} else {
keyworded
};
let futures = selected
.into_iter()
.map(|(plugin, query)| plugin.query(query));
let mut results = QueryResults::default();
for (items, rerun) in futures::future::join_all(futures).await {
results.items.extend(items);
results.rerun = match (results.rerun, rerun) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
}
results
}
#[must_use]
pub fn is_claimed(&self, text: &str) -> bool {
self.plugins
.iter()
.filter(|plugin| !self.disabled.contains(&plugin.id))
.any(|plugin| {
let keyword = self.effective_keyword(plugin);
keyword.is_some() && plugin.match_query_as(keyword, text).is_some()
})
}
}
#[derive(Debug, Default)]
pub struct LintReport {
pub errors: Vec<String>,
pub warnings: Vec<String>,
pub items: usize,
}
impl LintReport {
#[must_use]
pub fn is_clean(&self) -> bool {
self.errors.is_empty()
}
}
pub async fn lint(directory: &Path, sample_query: &str) -> LintReport {
let mut report = LintReport::default();
let manifest_path = directory.join("manifest.toml");
let contents = match std::fs::read_to_string(&manifest_path) {
Ok(contents) => contents,
Err(error) => {
report
.errors
.push(format!("cannot read {}: {error}", manifest_path.display()));
return report;
}
};
let manifest: Manifest = match toml::from_str(&contents) {
Ok(manifest) => manifest,
Err(error) => {
report
.errors
.push(format!("manifest does not parse: {error}"));
return report;
}
};
if let Some(keyword) = manifest.keyword.as_deref() {
if keyword.is_empty() || keyword.contains(char::is_whitespace) {
report.errors.push(format!(
"keyword {keyword:?} must be one non-empty word — it is matched \
up to the first space of the query"
));
}
} else {
report.warnings.push(
"no keyword: the plugin runs on every keystroke and must answer \
well inside 180 ms"
.to_owned(),
);
}
if let Some(ms) = manifest.timeout_ms {
let clamped = manifest.timeout().as_millis();
if u128::from(ms) != clamped {
report
.warnings
.push(format!("timeout_ms = {ms} is clamped to {clamped} ms"));
}
}
let check_command = |report: &mut LintReport, label: &str, command: &str| {
let path = if Path::new(command).is_absolute() {
PathBuf::from(command)
} else {
directory.join(command)
};
if !path.is_file() {
report
.errors
.push(format!("{label} command {} does not exist", path.display()));
return;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let executable = path
.metadata()
.map(|meta| meta.permissions().mode() & 0o111 != 0)
.unwrap_or(false);
if !executable {
report.errors.push(format!(
"{label} command {} is not executable (chmod +x)",
path.display()
));
}
}
};
check_command(&mut report, "query", &manifest.query);
if let Some(activate) = manifest.activate.as_deref() {
check_command(&mut report, "activate", activate);
}
if !report.errors.is_empty() {
return report;
}
let plugin = Plugin {
manifest,
directory: directory.to_path_buf(),
id: directory
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("plugin")
.to_owned(),
};
let deadline = plugin.manifest.timeout();
let program = plugin.directory.join(&plugin.manifest.query);
let output = match tokio::time::timeout(
deadline,
Command::new(&program)
.arg(sample_query)
.current_dir(&plugin.directory)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.output(),
)
.await
{
Ok(Ok(output)) => output,
Ok(Err(error)) => {
report
.errors
.push(format!("query command failed to run: {error}"));
return report;
}
Err(_) => {
report.errors.push(format!(
"query command exceeded its {} ms deadline and was killed",
deadline.as_millis()
));
return report;
}
};
if !output.status.success() {
report.errors.push(format!(
"query command exited {:?}; stderr: {}",
output.status.code(),
String::from_utf8_lossy(&output.stderr).trim()
));
return report;
}
match serde_json::from_slice::<PluginResponse>(&output.stdout) {
Ok(response) => {
report.items = response.items.len();
if response.items.is_empty() {
report
.warnings
.push("sample query produced no items".to_owned());
}
for item in &response.items {
if item.uid.is_none() {
report.warnings.push(format!(
"item {:?} has no uid — without one, usage ranking \
cannot learn it",
item.title
));
}
}
}
Err(error) => {
report
.errors
.push(format!("output is not valid script-filter JSON: {error}"));
}
}
report
}
pub fn scaffold(directory: &Path, name: &str) -> std::io::Result<()> {
if directory.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
format!("{} already exists", directory.display()),
));
}
std::fs::create_dir_all(directory)?;
let keyword = name.to_lowercase().replace(char::is_whitespace, "-");
std::fs::write(
directory.join("manifest.toml"),
format!(
"name = \"{name}\"\n\
description = \"Describe what this plugin searches\"\n\
keyword = \"{keyword}\"\n\
query = \"./search.sh\"\n\
# activate = \"./open.sh\" # separate action command, optional\n\
icon = \"system-search-symbolic\"\n\
# timeout_ms = 1000 # up to 3000 for slow keyworded plugins\n"
),
)?;
let script = directory.join("search.sh");
std::fs::write(
&script,
format!(
"#!/bin/sh\n\
# jump runs this with the query as $1 and reads script-filter\n\
# JSON from stdout. Without an `activate` command in the\n\
# manifest, activation re-runs this script as: search.sh\n\
# --activate <arg>.\n\
if [ \"$1\" = \"--activate\" ]; then\n\
\t# \"$2\" is the chosen item's arg.\n\
\texit 0\n\
fi\n\
\n\
query=\"$1\"\n\
printf '{{\"items\":[{{\"uid\":\"hello\",\"title\":\"Hello %s\",\
\"subtitle\":\"{name}\",\"arg\":\"%s\"}}]}}' \
\"${{query:-world}}\" \"$query\"\n"
),
)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn plugin(keyword: Option<&str>) -> Plugin {
Plugin {
manifest: Manifest {
name: "Test".to_owned(),
description: String::new(),
keyword: keyword.map(ToOwned::to_owned),
query: "./q".to_owned(),
activate: None,
icon: None,
timeout_ms: None,
},
directory: PathBuf::from("/tmp"),
id: "test".to_owned(),
}
}
#[test]
fn keywordless_plugin_sees_whole_query() {
assert_eq!(plugin(None).match_query("hello there"), Some("hello there"));
}
#[test]
fn keyword_is_stripped() {
assert_eq!(plugin(Some("gh")).match_query("gh jump"), Some("jump"));
}
#[test]
fn bare_keyword_yields_empty_query() {
assert_eq!(plugin(Some("gh")).match_query("gh"), Some(""));
}
#[test]
fn keyword_requires_word_boundary() {
assert_eq!(plugin(Some("gh")).match_query("ghost"), None);
}
#[test]
fn non_matching_keyword_is_skipped() {
assert_eq!(plugin(Some("gh")).match_query("firefox"), None);
}
#[test]
fn timeout_is_clamped_to_the_ceiling() {
let mut manifest = plugin(None).manifest;
assert_eq!(manifest.timeout(), Duration::from_millis(180));
manifest.timeout_ms = Some(60_000);
assert_eq!(manifest.timeout(), Duration::from_millis(3000));
manifest.timeout_ms = Some(1);
assert_eq!(manifest.timeout(), Duration::from_millis(50));
}
#[test]
fn uid_and_autocomplete_parse_from_alfred_json() {
let response: PluginResponse = serde_json::from_str(
r#"{"items":[
{"uid":"repo","title":"jump","arg":"https://example.com/?q=jump",
"autocomplete":"gh jump ", "icon":{"path":"/tmp/icon.png"}},
{"title":"plain"}
]}"#,
)
.expect("alfred json parses");
assert_eq!(response.items[0].uid.as_deref(), Some("repo"));
assert_eq!(response.items[0].autocomplete.as_deref(), Some("gh jump "));
assert_eq!(response.items[1].uid, None);
}
#[test]
fn rerun_parses_and_is_clamped_sanely() {
let parse = |json: &str| -> Option<f64> {
serde_json::from_str::<PluginResponse>(json)
.expect("json parses")
.rerun
};
assert_eq!(parse(r#"{"items":[]}"#), None);
assert_eq!(parse(r#"{"items":[],"rerun":1.5}"#), Some(1.5));
let clamp = |seconds: f64| seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end());
assert_eq!(clamp(0.1), 0.5);
assert_eq!(clamp(60.0), 5.0);
assert_eq!(clamp(2.0), 2.0);
}
#[test]
fn mods_normalise_inherit_and_override() {
let response: PluginResponse = serde_json::from_str(
r#"{"variables":{"SESSION":"abc"},
"items":[{"title":"repo","arg":"main",
"mods":{
"cmd":{"subtitle":"Open on the web","arg":"https://example.com"},
"alt":{"subtitle":"Copy","variables":{"MODE":"copy"}},
"shift":{"subtitle":"Off","valid":false},
"hyper":{"subtitle":"Unbindable"}
}}]}"#,
)
.expect("alfred json parses");
let item = &response.items[0];
assert_eq!(normalise_modifier("cmd"), Some("super"));
assert_eq!(normalise_modifier("Control"), Some("ctrl"));
assert_eq!(normalise_modifier("hyper"), None);
let usable: Vec<&String> = item
.mods
.iter()
.filter(|(_, m)| m.valid)
.filter(|(name, _)| normalise_modifier(name).is_some())
.map(|(name, _)| name)
.collect();
assert_eq!(usable.len(), 2);
assert_eq!(item.mods["alt"].arg, None);
assert_eq!(item.mods["cmd"].arg.as_deref(), Some("https://example.com"));
}
#[test]
fn item_variables_win_over_response_variables() {
let response: PluginResponse = serde_json::from_str(
r#"{"variables":{"SESSION":"abc","MODE":"list"},
"items":[{"title":"one","variables":{"MODE":"open"}},
{"title":"two"}]}"#,
)
.expect("alfred json parses");
let merged = merge_variables(&response.variables, response.items[0].variables.clone());
assert_eq!(
merged,
vec![
("MODE".to_owned(), "open".to_owned()),
("SESSION".to_owned(), "abc".to_owned()),
]
);
let inherited = merge_variables(&response.variables, response.items[1].variables.clone());
assert_eq!(inherited.len(), 2);
assert!(inherited.contains(&("MODE".to_owned(), "list".to_owned())));
}
#[tokio::test(flavor = "multi_thread")]
async fn scaffold_produces_a_plugin_that_lints_clean() {
let root = tempfile::tempdir().expect("tempdir");
let directory = root.path().join("demo");
scaffold(&directory, "Demo").expect("scaffold succeeds");
assert!(scaffold(&directory, "Demo").is_err());
let report = lint(&directory, "hello").await;
assert!(report.is_clean(), "unexpected errors: {:?}", report.errors);
assert_eq!(report.items, 1);
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
}
#[tokio::test(flavor = "multi_thread")]
async fn lint_reports_missing_and_broken_pieces() {
let root = tempfile::tempdir().expect("tempdir");
let report = lint(root.path(), "x").await;
assert!(!report.is_clean());
let directory = root.path().join("broken");
std::fs::create_dir_all(&directory).expect("dir");
std::fs::write(
directory.join("manifest.toml"),
"name = \"Broken\"\nkeyword = \"two words\"\nquery = \"./missing.sh\"\n",
)
.expect("manifest");
let report = lint(&directory, "x").await;
assert_eq!(report.errors.len(), 2, "{:?}", report.errors);
}
#[test]
fn discovery_walks_roots_in_order_and_user_shadows_system() {
let user = tempfile::tempdir().expect("tempdir");
let system = tempfile::tempdir().expect("tempdir");
let write = |root: &std::path::Path, id: &str, name: &str| {
let dir = root.join(id);
std::fs::create_dir_all(&dir).expect("plugin dir");
std::fs::write(
dir.join("manifest.toml"),
format!("name = \"{name}\"\nquery = \"./q\"\n"),
)
.expect("manifest");
};
write(user.path(), "shared", "User copy");
write(user.path(), "mine", "User only");
write(system.path(), "shared", "System copy");
write(system.path(), "packaged", "System only");
std::fs::create_dir_all(system.path().join("junk")).expect("junk dir");
let host =
PluginHost::discover_in(&[user.path().to_path_buf(), system.path().to_path_buf()]);
let mut ids: Vec<&str> = host.all().map(|(plugin, _)| plugin.id.as_str()).collect();
ids.sort_unstable();
assert_eq!(ids, ["mine", "packaged", "shared"]);
let shared = host.get("shared").expect("shared plugin");
assert_eq!(shared.manifest.name, "User copy");
}
#[test]
fn keyword_overrides_replace_and_remove_the_manifest_keyword() {
let mut host = PluginHost {
plugins: vec![plugin(Some("gh"))],
disabled: std::collections::HashSet::new(),
keyword_overrides: std::collections::HashMap::new(),
};
assert!(host.is_claimed("gh jump"));
host.set_keyword_overrides([("test", "g")]);
assert!(host.is_claimed("g jump"));
assert!(!host.is_claimed("gh jump"));
host.set_keyword_overrides([("test", "")]);
assert!(!host.is_claimed("g jump"));
assert!(!host.is_claimed("gh jump"));
let plugin = &host.plugins[0];
assert_eq!(host.effective_keyword(plugin), None);
host.set_keyword_overrides([("other", "x")]);
assert!(host.is_claimed("gh jump"));
}
#[test]
fn disabled_plugins_neither_run_nor_activate() {
let mut host = PluginHost {
plugins: vec![plugin(Some("gh"))],
disabled: std::collections::HashSet::new(),
keyword_overrides: std::collections::HashMap::new(),
};
assert!(host.is_claimed("gh jump"));
assert!(host.get("test").is_some());
host.set_disabled(["test"]);
assert!(!host.is_claimed("gh jump"));
assert!(host.get("test").is_none());
assert_eq!(host.all().map(|(_, on)| on).collect::<Vec<_>>(), [false]);
}
}