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;
const MAX_STDERR_BYTES: usize = 16 << 10;
#[derive(Debug, thiserror::Error)]
enum RunError {
#[error("failed to run: {0}")]
Io(#[from] std::io::Error),
#[error("exceeded its {} ms deadline and was killed", .0.as_millis())]
Deadline(Duration),
#[error("printed more than {MAX_OUTPUT_BYTES} bytes and was killed")]
TooLarge,
#[error("exited {status}; stderr: {stderr}")]
Failed {
status: std::process::ExitStatus,
stderr: String,
},
}
async fn spawn_plugin(command: &mut Command) -> std::io::Result<tokio::process::Child> {
let mut wait = Duration::from_millis(5);
for _ in 0..6 {
match command.spawn() {
Err(error) if error.kind() == std::io::ErrorKind::ExecutableFileBusy => {
tokio::time::sleep(wait).await;
wait *= 2;
}
result => return result,
}
}
command.spawn()
}
async fn run_query(
program: &Path,
directory: &Path,
text: &str,
deadline: Duration,
) -> Result<Vec<u8>, RunError> {
use tokio::io::AsyncReadExt;
let mut child = spawn_plugin(
Command::new(program)
.arg(text)
.current_dir(directory)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0)
.kill_on_drop(true),
)
.await?;
let mut group = GroupKill(child.id());
let stdout = child.stdout.take().expect("stdout is piped");
let stderr = child.stderr.take().expect("stderr is piped");
let stderr = tokio::spawn(async move {
let mut kept = Vec::new();
let mut limited = stderr.take(MAX_STDERR_BYTES as u64);
let read = limited.read_to_end(&mut kept).await;
let drained = tokio::io::copy(&mut limited.into_inner(), &mut tokio::io::sink()).await;
if let Err(error) = read.and(drained) {
tracing::debug!(%error, "plugin stderr read failed");
}
String::from_utf8_lossy(&kept).trim().to_owned()
});
let run = async {
let mut output = Vec::new();
stdout
.take(MAX_OUTPUT_BYTES as u64 + 1)
.read_to_end(&mut output)
.await?;
if output.len() > MAX_OUTPUT_BYTES {
return Err(RunError::TooLarge);
}
let status = child.wait().await?;
group.disarm();
Ok((status, output))
};
match tokio::time::timeout(deadline, run).await {
Ok(Ok((status, output))) if status.success() => Ok(output),
Ok(Ok((status, _))) => Err(RunError::Failed {
status,
stderr: stderr.await.unwrap_or_default(),
}),
Ok(Err(error)) => Err(error),
Err(_) => Err(RunError::Deadline(deadline)),
}
}
struct GroupKill(Option<u32>);
impl GroupKill {
fn disarm(&mut self) {
self.0 = None;
}
}
impl Drop for GroupKill {
fn drop(&mut self) {
let Some(group) = self.0 else {
return;
};
let spawned = Command::new("kill")
.args(["-KILL", "--", &format!("-{group}")])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
if let Err(error) = spawned {
tracing::warn!(group, %error, "could not kill plugin process group");
}
}
}
#[must_use]
pub fn is_keyword(text: &str) -> bool {
!text.is_empty() && !text.contains(char::is_whitespace)
}
#[derive(Debug, Clone, PartialEq, Eq, 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, keyword: Option<&str>) -> Duration {
let requested = self.timeout_ms.map_or(QUERY_TIMEOUT, |ms| {
Duration::from_millis(ms).clamp(Duration::from_millis(50), MAX_QUERY_TIMEOUT)
});
if keyword.is_some() {
requested
} else {
requested.min(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, PartialEq, Eq)]
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, deadline: Duration) -> (Vec<Item>, Option<Duration>) {
let program = self.resolve(&self.manifest.query);
let stdout = match run_query(&program, &self.directory, text, deadline).await {
Ok(stdout) => stdout,
Err(error) => {
tracing::warn!(plugin = %self.id, ?program, %error, "plugin query dropped");
return (Vec::new(), None);
}
};
let response: PluginResponse = match serde_json::from_slice(&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 mut command = Command::new(&program);
command
.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());
let id = self.id.clone();
tokio::spawn(async move {
match spawn_plugin(&mut command).await {
Ok(mut child) => {
let _ = child.wait().await;
}
Err(error) => {
tracing::error!(plugin = %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 {
Self::discover_in(&Self::roots())
}
#[must_use]
pub fn roots() -> Vec<PathBuf> {
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")),
);
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 replace_plugins(&mut self, discovered: Self) -> bool {
if self.plugins == discovered.plugins {
return false;
}
self.plugins = discovered.plugins;
true
}
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)| {
let deadline = plugin.manifest.timeout(self.effective_keyword(plugin));
plugin.query(query, deadline)
});
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 !is_keyword(keyword) {
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 applied = manifest.timeout(manifest.keyword.as_deref()).as_millis();
if u128::from(ms) != applied {
let why = if manifest.keyword.is_none() && applied == QUERY_TIMEOUT.as_millis() {
" — only a keyworded plugin may take longer than the interactive default"
} else {
""
};
report
.warnings
.push(format!("timeout_ms = {ms} is clamped to {applied} ms{why}"));
}
}
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 program = plugin.resolve(&plugin.manifest.query);
let stdout = match run_query(
&program,
&plugin.directory,
sample_query,
plugin.manifest.timeout(plugin.manifest.keyword.as_deref()),
)
.await
{
Ok(stdout) => stdout,
Err(error) => {
report.errors.push(format!("query command {error}"));
return report;
}
};
match serde_json::from_slice::<PluginResponse>(&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
}
#[must_use]
pub fn scaffold_keyword(name: &str) -> Option<String> {
let keyword = name
.to_lowercase()
.split_whitespace()
.collect::<Vec<_>>()
.join("-");
let usable =
!keyword.is_empty() && !keyword.starts_with('.') && !keyword.contains(['/', '\\', '\0']);
usable.then_some(keyword)
}
pub fn scaffold(root: &Path, name: &str) -> std::io::Result<(PathBuf, String)> {
let Some(keyword) = scaffold_keyword(name) else {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{name:?} does not make a plugin directory name"),
));
};
let directory = root.join(&keyword);
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 toml_string = |text: &str| toml::Value::String(text.to_owned()).to_string();
std::fs::write(
directory.join("manifest.toml"),
format!(
"name = {}\n\
description = \"Describe what this plugin searches\"\n\
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",
toml_string(name),
toml_string(&keyword),
),
)?;
let shell_name = name.replace('\'', r"'\''");
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\
name='{shell_name}'\n\
query=\"$1\"\n\
# Text going into a JSON string needs its backslashes and quotes\n\
# escaped.\n\
json() {{ printf '%s' \"$1\" | sed 's/[\\\\\"]/\\\\&/g'; }}\n\
printf '{{\"items\":[{{\"uid\":\"hello\",\"title\":\"Hello %s\",\
\"subtitle\":\"%s\",\"arg\":\"%s\"}}]}}' \
\"$(json \"${{query:-world}}\")\" \"$(json \"$name\")\" \"$(json \"$query\")\"\n"
),
)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))?;
}
Ok((directory, keyword))
}
#[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 a_keyword_is_one_non_empty_word() {
assert!(is_keyword("gh"));
assert!(is_keyword("=="));
for bad in ["", "gh x", " gh", "gh\t"] {
assert!(!is_keyword(bad), "{bad:?}");
}
}
#[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;
let keyword = Some("gh");
assert_eq!(manifest.timeout(keyword), Duration::from_millis(180));
manifest.timeout_ms = Some(60_000);
assert_eq!(manifest.timeout(keyword), Duration::from_millis(3000));
manifest.timeout_ms = Some(1);
assert_eq!(manifest.timeout(keyword), Duration::from_millis(50));
}
#[test]
fn only_a_keyworded_plugin_may_raise_its_deadline() {
let mut manifest = plugin(None).manifest;
manifest.timeout_ms = Some(3000);
assert_eq!(manifest.timeout(None), Duration::from_millis(180));
assert_eq!(manifest.timeout(Some("gh")), Duration::from_millis(3000));
manifest.timeout_ms = Some(100);
assert_eq!(manifest.timeout(None), Duration::from_millis(100));
}
#[tokio::test(flavor = "multi_thread")]
async fn the_host_holds_an_always_on_plugin_to_the_interactive_deadline() {
let root = tempfile::tempdir().expect("tempdir");
let mut slow = scripted(
root.path(),
"#!/bin/sh\nsleep 0.5\necho '{\"items\":[{\"title\":\"late\"}]}'\n",
Some(3000),
);
slow.id = "slow".to_owned();
let mut host = PluginHost {
plugins: vec![slow],
..PluginHost::default()
};
assert_eq!(host.query("t x").await.items.len(), 1);
host.set_keyword_overrides([("slow", "")]);
assert!(host.query("x").await.items.is_empty());
}
#[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, keyword) = scaffold(root.path(), "Demo").expect("scaffold succeeds");
assert_eq!(directory, root.path().join("demo"));
assert_eq!(keyword, "demo");
assert!(scaffold(root.path(), "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 a_scaffold_name_is_data_not_syntax() {
let root = tempfile::tempdir().expect("tempdir");
let name = r#"It's "100%" done"#;
let (directory, keyword) = scaffold(root.path(), name).expect("scaffold succeeds");
assert_eq!(keyword, r#"it's-"100%"-done"#);
let manifest: Manifest = toml::from_str(
&std::fs::read_to_string(directory.join("manifest.toml")).expect("manifest"),
)
.expect("the manifest parses");
assert_eq!(manifest.name, name);
let output = std::process::Command::new(directory.join("search.sh"))
.arg(r#"say "hi" \"#)
.output()
.expect("the script runs");
let response: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("the output is JSON");
let item = &response["items"][0];
assert_eq!(item["subtitle"], name);
assert_eq!(item["title"], r#"Hello say "hi" \"#);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_query_script_still_open_for_writing_runs_once_it_is_closed() {
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
let root = tempfile::tempdir().expect("tempdir");
let script = root.path().join("search.sh");
let mut held = std::fs::File::create(&script).expect("create");
held.write_all(b"#!/bin/sh\nprintf ok\n").expect("write");
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).expect("chmod");
let release = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(30));
drop(held);
});
let stdout = run_query(&script, root.path(), "", Duration::from_secs(3))
.await
.expect("the query runs once the writer has closed the script");
assert_eq!(stdout, b"ok");
release.join().expect("release thread");
}
#[test]
fn a_scaffold_cannot_name_a_directory_outside_the_root() {
for name in ["../x", "a/b", ".hidden", " ", ""] {
assert_eq!(scaffold_keyword(name), None, "{name:?}");
}
assert_eq!(scaffold_keyword("My Plugin").as_deref(), Some("my-plugin"));
let root = tempfile::tempdir().expect("tempdir");
let error = scaffold(&root.path().join("plugins"), "../x").expect_err("refused");
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
assert!(!root.path().join("x").exists());
}
#[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);
}
fn scripted(root: &Path, script: &str, timeout_ms: Option<u64>) -> Plugin {
use std::os::unix::fs::PermissionsExt;
let path = root.join("q");
std::fs::write(&path, script).expect("script");
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("chmod");
let mut plugin = plugin(Some("t"));
plugin.directory = root.to_path_buf();
plugin.manifest.timeout_ms = timeout_ms;
plugin
}
fn alive(pid: u32) -> bool {
std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| {
stat.rsplit(") ")
.next()
.is_some_and(|rest| !rest.starts_with('Z'))
})
}
#[tokio::test(flavor = "multi_thread")]
async fn oversized_output_is_refused_without_waiting_for_the_deadline() {
let root = tempfile::tempdir().expect("tempdir");
let plugin = scripted(
root.path(),
"#!/bin/sh\nhead -c 2000000 /dev/zero\nsleep 5\n",
Some(3000),
);
let started = std::time::Instant::now();
let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
assert!(items.is_empty());
assert!(
started.elapsed() < Duration::from_millis(1500),
"took {:?}: output was buffered until the deadline",
started.elapsed()
);
}
#[tokio::test(flavor = "multi_thread")]
async fn an_overrunning_plugin_is_killed_with_its_children() {
let root = tempfile::tempdir().expect("tempdir");
let plugin = scripted(
root.path(),
"#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
Some(1000),
);
let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
assert!(items.is_empty());
assert!(
!outlives(&root.path().join("child.pid")).await,
"the plugin's child outlived the deadline"
);
}
async fn outlives(pid_file: &Path) -> bool {
let pid: u32 = std::fs::read_to_string(pid_file)
.expect("the script recorded its child")
.trim()
.parse()
.expect("pid");
let deadline = std::time::Instant::now() + Duration::from_secs(2);
while alive(pid) && std::time::Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(20)).await;
}
let survived = alive(pid);
if survived {
let _ = std::process::Command::new("kill")
.args(["-KILL", &pid.to_string()])
.status();
}
survived
}
#[tokio::test(flavor = "multi_thread")]
async fn an_abandoned_query_is_killed_with_its_children() {
let root = tempfile::tempdir().expect("tempdir");
let plugin = scripted(
root.path(),
"#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
Some(3000),
);
let pid_file = root.path().join("child.pid");
let running = tokio::spawn(async move {
let deadline = plugin.manifest.timeout(Some("t"));
plugin.query("x", deadline).await
});
let started = std::time::Instant::now();
let recorded =
|path: &Path| std::fs::read_to_string(path).is_ok_and(|pid| pid.ends_with('\n'));
while !recorded(&pid_file) && started.elapsed() < Duration::from_secs(2) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
running.abort();
assert!(running.await.is_err_and(|error| error.is_cancelled()));
assert!(
!outlives(&pid_file).await,
"the abandoned query's child kept running"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn lint_applies_the_launchers_output_cap() {
let root = tempfile::tempdir().expect("tempdir");
let directory = root.path().join("big");
std::fs::create_dir_all(&directory).expect("dir");
std::fs::write(
directory.join("manifest.toml"),
"name = \"Big\"\nkeyword = \"big\"\nquery = \"./q\"\n",
)
.expect("manifest");
scripted(
&directory,
"#!/bin/sh\nprintf '{\"items\":[{\"uid\":\"a\",\"title\":\"'\n\
head -c 1100000 /dev/zero | tr '\\0' a\nprintf '\"}]}'\n",
None,
);
let report = lint(&directory, "x").await;
assert!(!report.is_clean(), "oversized output linted clean");
}
#[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 a_fresh_discovery_keeps_the_users_settings() {
let root = tempfile::tempdir().expect("tempdir");
let write = |id: &str| {
let dir = root.path().join(id);
std::fs::create_dir_all(&dir).expect("plugin dir");
std::fs::write(
dir.join("manifest.toml"),
"name = \"P\"\nkeyword = \"p\"\nquery = \"./q\"\n",
)
.expect("manifest");
};
write("old");
let roots = [root.path().to_path_buf()];
let mut host = PluginHost::discover_in(&roots);
host.set_disabled(["old"]);
host.set_keyword_overrides([("new", "n")]);
assert!(!host.replace_plugins(PluginHost::discover_in(&roots)));
write("new");
assert!(host.replace_plugins(PluginHost::discover_in(&roots)));
assert!(
host.get("old").is_none(),
"the disabled plugin came back on"
);
let new = host.get("new").expect("the new plugin was picked up");
assert_eq!(host.effective_keyword(new), Some("n"));
}
#[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]);
}
}