1use std::path::{Path, PathBuf};
48use std::process::Stdio;
49use std::time::Duration;
50
51use serde::Deserialize;
52use tokio::process::Command;
53
54use crate::model::{Icon, Item, ItemKey, Mod, Source};
55
56const QUERY_TIMEOUT: Duration = Duration::from_millis(180);
64
65const MAX_QUERY_TIMEOUT: Duration = Duration::from_millis(3000);
70
71const MAX_OUTPUT_BYTES: usize = 1 << 20;
76
77const MAX_STDERR_BYTES: usize = 16 << 10;
81
82#[derive(Debug, thiserror::Error)]
84enum RunError {
85 #[error("failed to run: {0}")]
86 Io(#[from] std::io::Error),
87 #[error("exceeded its {} ms deadline and was killed", .0.as_millis())]
88 Deadline(Duration),
89 #[error("printed more than {MAX_OUTPUT_BYTES} bytes and was killed")]
90 TooLarge,
91 #[error("exited {status}; stderr: {stderr}")]
92 Failed {
93 status: std::process::ExitStatus,
94 stderr: String,
95 },
96}
97
98async fn spawn_plugin(command: &mut Command) -> std::io::Result<tokio::process::Child> {
108 let mut wait = Duration::from_millis(5);
109 for _ in 0..6 {
110 match command.spawn() {
111 Err(error) if error.kind() == std::io::ErrorKind::ExecutableFileBusy => {
112 tokio::time::sleep(wait).await;
113 wait *= 2;
114 }
115 result => return result,
116 }
117 }
118 command.spawn()
119}
120
121async fn run_query(
131 program: &Path,
132 directory: &Path,
133 text: &str,
134 deadline: Duration,
135) -> Result<Vec<u8>, RunError> {
136 use tokio::io::AsyncReadExt;
137
138 let mut child = spawn_plugin(
139 Command::new(program)
140 .arg(text)
141 .current_dir(directory)
142 .stdin(Stdio::null())
143 .stdout(Stdio::piped())
144 .stderr(Stdio::piped())
145 .process_group(0)
146 .kill_on_drop(true),
147 )
148 .await?;
149 let mut group = GroupKill(child.id());
152 let stdout = child.stdout.take().expect("stdout is piped");
153 let stderr = child.stderr.take().expect("stderr is piped");
154
155 let stderr = tokio::spawn(async move {
158 let mut kept = Vec::new();
159 let mut limited = stderr.take(MAX_STDERR_BYTES as u64);
160 let read = limited.read_to_end(&mut kept).await;
161 let drained = tokio::io::copy(&mut limited.into_inner(), &mut tokio::io::sink()).await;
162 if let Err(error) = read.and(drained) {
163 tracing::debug!(%error, "plugin stderr read failed");
164 }
165 String::from_utf8_lossy(&kept).trim().to_owned()
166 });
167
168 let run = async {
169 let mut output = Vec::new();
170 stdout
171 .take(MAX_OUTPUT_BYTES as u64 + 1)
172 .read_to_end(&mut output)
173 .await?;
174 if output.len() > MAX_OUTPUT_BYTES {
175 return Err(RunError::TooLarge);
176 }
177 let status = child.wait().await?;
178 group.disarm();
180 Ok((status, output))
181 };
182
183 match tokio::time::timeout(deadline, run).await {
184 Ok(Ok((status, output))) if status.success() => Ok(output),
185 Ok(Ok((status, _))) => Err(RunError::Failed {
186 status,
187 stderr: stderr.await.unwrap_or_default(),
188 }),
189 Ok(Err(error)) => Err(error),
191 Err(_) => Err(RunError::Deadline(deadline)),
192 }
193}
194
195struct GroupKill(Option<u32>);
208
209impl GroupKill {
210 fn disarm(&mut self) {
211 self.0 = None;
212 }
213}
214
215impl Drop for GroupKill {
216 fn drop(&mut self) {
217 let Some(group) = self.0 else {
218 return;
219 };
220 let spawned = Command::new("kill")
221 .args(["-KILL", "--", &format!("-{group}")])
222 .stdin(Stdio::null())
223 .stdout(Stdio::null())
224 .stderr(Stdio::null())
225 .spawn();
226 if let Err(error) = spawned {
227 tracing::warn!(group, %error, "could not kill plugin process group");
228 }
229 }
230}
231
232#[must_use]
237pub fn is_keyword(text: &str) -> bool {
238 !text.is_empty() && !text.contains(char::is_whitespace)
239}
240
241#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
243pub struct Manifest {
244 pub name: String,
246 #[serde(default)]
248 pub description: String,
249 #[serde(default)]
252 pub keyword: Option<String>,
253 pub query: String,
255 #[serde(default)]
259 pub activate: Option<String>,
260 #[serde(default)]
262 pub icon: Option<String>,
263 #[serde(default)]
266 pub timeout_ms: Option<u64>,
267}
268
269impl Manifest {
270 #[must_use]
279 pub fn timeout(&self, keyword: Option<&str>) -> Duration {
280 let requested = self.timeout_ms.map_or(QUERY_TIMEOUT, |ms| {
281 Duration::from_millis(ms).clamp(Duration::from_millis(50), MAX_QUERY_TIMEOUT)
282 });
283 if keyword.is_some() {
284 requested
285 } else {
286 requested.min(QUERY_TIMEOUT)
287 }
288 }
289}
290
291#[derive(Debug, Clone, Deserialize)]
293struct PluginItem {
294 title: String,
295 #[serde(default)]
296 subtitle: String,
297 #[serde(default)]
299 arg: Option<String>,
300 #[serde(default)]
303 icon: Option<PluginIcon>,
304 #[serde(default = "default_valid")]
306 valid: bool,
307 #[serde(default)]
311 uid: Option<String>,
312 #[serde(default)]
314 autocomplete: Option<String>,
315 #[serde(default)]
319 variables: std::collections::HashMap<String, String>,
320 #[serde(default)]
324 mods: std::collections::HashMap<String, PluginMod>,
325}
326
327#[derive(Debug, Clone, Deserialize)]
329struct PluginMod {
330 #[serde(default)]
331 subtitle: String,
332 #[serde(default)]
333 arg: Option<String>,
334 #[serde(default = "default_valid")]
336 valid: bool,
337 #[serde(default)]
338 variables: std::collections::HashMap<String, String>,
339}
340
341fn normalise_modifier(name: &str) -> Option<&'static str> {
346 match name.trim().to_lowercase().as_str() {
347 "ctrl" | "control" => Some("ctrl"),
348 "alt" | "option" => Some("alt"),
349 "shift" => Some("shift"),
350 "cmd" | "command" | "super" | "meta" => Some("super"),
352 _ => None,
353 }
354}
355
356const fn default_valid() -> bool {
357 true
358}
359
360#[derive(Debug, Clone, Deserialize)]
361#[serde(untagged)]
362enum PluginIcon {
363 Named(String),
364 Path {
365 #[serde(alias = "name")]
366 path: String,
367 },
368}
369
370impl PluginIcon {
371 fn into_icon(self) -> Icon {
372 match self {
373 Self::Named(name) | Self::Path { path: name } => Icon::Name(name),
374 }
375 }
376}
377
378#[derive(Debug, Clone, Deserialize)]
379struct PluginResponse {
380 items: Vec<PluginItem>,
381 #[serde(default)]
383 variables: std::collections::HashMap<String, String>,
384 #[serde(default)]
387 rerun: Option<f64>,
388}
389
390const RERUN_RANGE: std::ops::RangeInclusive<f64> = 0.5..=5.0;
394
395#[derive(Debug, Clone, Default)]
398pub struct QueryResults {
399 pub items: Vec<Item>,
401 pub rerun: Option<Duration>,
403}
404
405fn merge_variables(
408 response: &std::collections::HashMap<String, String>,
409 item: std::collections::HashMap<String, String>,
410) -> Vec<(String, String)> {
411 let mut merged = response.clone();
412 merged.extend(item);
413 let mut variables: Vec<(String, String)> = merged.into_iter().collect();
414 variables.sort();
415 variables
416}
417
418#[derive(Debug, Clone, PartialEq, Eq)]
420pub struct Plugin {
421 pub manifest: Manifest,
423 pub directory: PathBuf,
425 pub id: String,
427}
428
429impl Plugin {
430 fn resolve(&self, command: &str) -> PathBuf {
433 let path = Path::new(command);
434 if path.is_absolute() {
435 path.to_path_buf()
436 } else {
437 self.directory.join(path)
438 }
439 }
440
441 #[must_use]
447 pub fn match_query_as<'a>(&self, keyword: Option<&str>, query: &'a str) -> Option<&'a str> {
448 match keyword {
449 None => Some(query),
450 Some(keyword) => {
451 let rest = query.strip_prefix(keyword)?;
452 match rest.strip_prefix(' ') {
453 Some(rest) => Some(rest.trim_start()),
454 None if rest.is_empty() => Some(""),
457 None => None,
458 }
459 }
460 }
461 }
462
463 #[must_use]
465 pub fn match_query<'a>(&self, query: &'a str) -> Option<&'a str> {
466 self.match_query_as(self.manifest.keyword.as_deref(), query)
467 }
468
469 async fn query(&self, text: &str, deadline: Duration) -> (Vec<Item>, Option<Duration>) {
472 let program = self.resolve(&self.manifest.query);
473
474 let stdout = match run_query(&program, &self.directory, text, deadline).await {
475 Ok(stdout) => stdout,
476 Err(error) => {
477 tracing::warn!(plugin = %self.id, ?program, %error, "plugin query dropped");
478 return (Vec::new(), None);
479 }
480 };
481
482 let response: PluginResponse = match serde_json::from_slice(&stdout) {
483 Ok(response) => response,
484 Err(error) => {
485 tracing::warn!(plugin = %self.id, %error, "plugin emitted invalid JSON");
486 return (Vec::new(), None);
487 }
488 };
489
490 let fallback_icon = self.manifest.icon.as_ref().map(|n| Icon::Name(n.clone()));
491 let PluginResponse {
492 items,
493 variables: response_variables,
494 rerun,
495 } = response;
496
497 let rerun = rerun.filter(|seconds| seconds.is_finite()).map(|seconds| {
499 Duration::from_secs_f64(seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end()))
500 });
501
502 let items = items
503 .into_iter()
504 .filter(|item| item.valid)
505 .map(|item| {
506 let arg = item.arg.unwrap_or_else(|| item.title.clone());
507 let variables = merge_variables(&response_variables, item.variables);
508
509 let mut mods: Vec<Mod> = item
513 .mods
514 .into_iter()
515 .filter(|(_, alternate)| alternate.valid)
516 .filter_map(|(modifier, alternate)| {
517 let modifier = normalise_modifier(&modifier)?;
518 let mut merged: std::collections::HashMap<String, String> =
519 variables.iter().cloned().collect();
520 merged.extend(alternate.variables);
521 let mut alternate_variables: Vec<(String, String)> =
522 merged.into_iter().collect();
523 alternate_variables.sort();
524
525 Some(Mod {
526 modifier: modifier.to_owned(),
527 subtitle: alternate.subtitle,
528 arg: alternate.arg.unwrap_or_else(|| arg.clone()),
529 variables: alternate_variables,
530 })
531 })
532 .collect();
533 mods.sort_by(|a, b| a.modifier.cmp(&b.modifier));
535 let identity = item.uid.as_deref().unwrap_or(&arg);
539 Item {
540 key: ItemKey(format!("plugin:{}:{identity}", self.id)),
543 id: 0,
545 title: item.title,
546 subtitle: if item.subtitle.is_empty() {
547 self.manifest.description.clone()
548 } else {
549 item.subtitle
550 },
551 icon: item
552 .icon
553 .map(PluginIcon::into_icon)
554 .or_else(|| fallback_icon.clone()),
555 category_icon: fallback_icon.clone(),
556 window: None,
557 source: Source::Plugin {
558 plugin: self.id.clone(),
559 arg,
560 variables,
561 mods,
562 },
563 autocomplete: item.autocomplete,
564 score: 0.0,
565 }
566 })
567 .collect();
568
569 (items, rerun)
570 }
571
572 pub fn activate(&self, arg: &str, variables: &[(String, String)]) {
581 let (program, extra) = match self.manifest.activate.as_deref() {
582 Some(activate) => (self.resolve(activate), Vec::new()),
583 None => (
584 self.resolve(&self.manifest.query),
585 vec!["--activate".to_owned()],
586 ),
587 };
588
589 let mut command = Command::new(&program);
590 command
591 .envs(variables.iter().map(|(key, value)| (key, value)))
592 .args(extra)
593 .arg(arg)
594 .current_dir(&self.directory)
595 .stdin(Stdio::null())
596 .stdout(Stdio::null())
597 .stderr(Stdio::null());
598
599 let id = self.id.clone();
600 tokio::spawn(async move {
601 match spawn_plugin(&mut command).await {
602 Ok(mut child) => {
604 let _ = child.wait().await;
605 }
606 Err(error) => {
607 tracing::error!(plugin = %id, ?program, %error, "failed to activate plugin item");
608 }
609 }
610 });
611 }
612}
613
614#[derive(Debug, Default, Clone)]
616pub struct PluginHost {
617 plugins: Vec<Plugin>,
618 disabled: std::collections::HashSet<String>,
621 keyword_overrides: std::collections::HashMap<String, String>,
625}
626
627impl PluginHost {
628 #[must_use]
630 pub fn discover() -> Self {
631 Self::discover_in(&Self::roots())
632 }
633
634 #[must_use]
643 pub fn roots() -> Vec<PathBuf> {
644 let mut roots: Vec<PathBuf> = dirs::data_dir()
645 .map(|dir| dir.join("jump").join("plugins"))
646 .into_iter()
647 .collect();
648
649 let system = std::env::var_os("XDG_DATA_DIRS")
650 .filter(|value| !value.is_empty())
651 .map_or_else(
652 || {
653 vec![
654 PathBuf::from("/usr/local/share"),
655 PathBuf::from("/usr/share"),
656 ]
657 },
658 |value| std::env::split_paths(&value).collect(),
659 );
660 roots.extend(
661 system
662 .into_iter()
663 .map(|dir| dir.join("jump").join("plugins")),
664 );
665 roots
666 }
667
668 #[must_use]
673 pub fn discover_in(roots: &[PathBuf]) -> Self {
674 let mut plugins: Vec<Plugin> = Vec::new();
675
676 for root in roots {
677 let entries = match std::fs::read_dir(root) {
678 Ok(entries) => entries,
679 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
680 Err(error) => {
681 tracing::warn!(%error, ?root, "failed to read plugin directory");
682 continue;
683 }
684 };
685
686 for entry in entries.flatten() {
687 let directory = entry.path();
688 if !directory.is_dir() {
689 continue;
690 }
691
692 let Some(id) = directory
693 .file_name()
694 .and_then(|name| name.to_str())
695 .map(ToOwned::to_owned)
696 else {
697 continue;
698 };
699
700 if plugins.iter().any(|plugin| plugin.id == id) {
701 tracing::debug!(plugin = %id, ?directory, "shadowed by an earlier root");
702 continue;
703 }
704
705 let manifest_path = directory.join("manifest.toml");
706 let contents = match std::fs::read_to_string(&manifest_path) {
707 Ok(contents) => contents,
708 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
709 Err(error) => {
710 tracing::warn!(%error, ?manifest_path, "failed to read plugin manifest");
711 continue;
712 }
713 };
714
715 let manifest: Manifest = match toml::from_str(&contents) {
716 Ok(manifest) => manifest,
717 Err(error) => {
718 tracing::warn!(%error, ?manifest_path, "invalid plugin manifest");
719 continue;
720 }
721 };
722
723 tracing::info!(plugin = %id, keyword = ?manifest.keyword, "loaded plugin");
724 plugins.push(Plugin {
725 manifest,
726 directory,
727 id,
728 });
729 }
730 }
731
732 Self {
733 plugins,
734 disabled: std::collections::HashSet::new(),
735 keyword_overrides: std::collections::HashMap::new(),
736 }
737 }
738
739 pub fn replace_plugins(&mut self, discovered: Self) -> bool {
743 if self.plugins == discovered.plugins {
744 return false;
745 }
746 self.plugins = discovered.plugins;
747 true
748 }
749
750 pub fn set_disabled<I, S>(&mut self, ids: I)
752 where
753 I: IntoIterator<Item = S>,
754 S: Into<String>,
755 {
756 self.disabled = ids.into_iter().map(Into::into).collect();
757 }
758
759 pub fn set_keyword_overrides<I, K, V>(&mut self, overrides: I)
761 where
762 I: IntoIterator<Item = (K, V)>,
763 K: Into<String>,
764 V: Into<String>,
765 {
766 self.keyword_overrides = overrides
767 .into_iter()
768 .map(|(id, keyword)| (id.into(), keyword.into()))
769 .collect();
770 }
771
772 #[must_use]
775 pub fn effective_keyword<'a>(&'a self, plugin: &'a Plugin) -> Option<&'a str> {
776 match self.keyword_overrides.get(&plugin.id) {
777 Some(keyword) if keyword.is_empty() => None,
778 Some(keyword) => Some(keyword.as_str()),
779 None => plugin.manifest.keyword.as_deref(),
780 }
781 }
782
783 pub fn all(&self) -> impl Iterator<Item = (&Plugin, bool)> {
786 self.plugins
787 .iter()
788 .map(|plugin| (plugin, !self.disabled.contains(&plugin.id)))
789 }
790
791 #[must_use]
793 pub fn is_empty(&self) -> bool {
794 self.plugins.is_empty()
795 }
796
797 #[must_use]
800 pub fn get(&self, id: &str) -> Option<&Plugin> {
801 self.plugins
802 .iter()
803 .filter(|plugin| !self.disabled.contains(&plugin.id))
804 .find(|plugin| plugin.id == id)
805 }
806
807 pub async fn query(&self, text: &str) -> QueryResults {
812 let matching: Vec<_> = self
813 .plugins
814 .iter()
815 .filter(|plugin| !self.disabled.contains(&plugin.id))
816 .filter_map(|plugin| {
817 plugin
818 .match_query_as(self.effective_keyword(plugin), text)
819 .map(|query| (plugin, query))
820 })
821 .collect();
822
823 if matching.is_empty() {
824 return QueryResults::default();
825 }
826
827 let keyworded: Vec<_> = matching
830 .iter()
831 .filter(|(plugin, _)| self.effective_keyword(plugin).is_some())
832 .collect();
833
834 let selected: Vec<_> = if keyworded.is_empty() {
835 matching.iter().collect()
836 } else {
837 keyworded
838 };
839
840 let futures = selected.into_iter().map(|(plugin, query)| {
841 let deadline = plugin.manifest.timeout(self.effective_keyword(plugin));
842 plugin.query(query, deadline)
843 });
844
845 let mut results = QueryResults::default();
846 for (items, rerun) in futures::future::join_all(futures).await {
847 results.items.extend(items);
848 results.rerun = match (results.rerun, rerun) {
851 (Some(a), Some(b)) => Some(a.min(b)),
852 (a, b) => a.or(b),
853 };
854 }
855 results
856 }
857
858 #[must_use]
861 pub fn is_claimed(&self, text: &str) -> bool {
862 self.plugins
863 .iter()
864 .filter(|plugin| !self.disabled.contains(&plugin.id))
865 .any(|plugin| {
866 let keyword = self.effective_keyword(plugin);
867 keyword.is_some() && plugin.match_query_as(keyword, text).is_some()
868 })
869 }
870}
871
872#[derive(Debug, Default)]
874pub struct LintReport {
875 pub errors: Vec<String>,
877 pub warnings: Vec<String>,
879 pub items: usize,
881}
882
883impl LintReport {
884 #[must_use]
886 pub fn is_clean(&self) -> bool {
887 self.errors.is_empty()
888 }
889}
890
891pub async fn lint(directory: &Path, sample_query: &str) -> LintReport {
897 let mut report = LintReport::default();
898
899 let manifest_path = directory.join("manifest.toml");
900 let contents = match std::fs::read_to_string(&manifest_path) {
901 Ok(contents) => contents,
902 Err(error) => {
903 report
904 .errors
905 .push(format!("cannot read {}: {error}", manifest_path.display()));
906 return report;
907 }
908 };
909
910 let manifest: Manifest = match toml::from_str(&contents) {
911 Ok(manifest) => manifest,
912 Err(error) => {
913 report
914 .errors
915 .push(format!("manifest does not parse: {error}"));
916 return report;
917 }
918 };
919
920 if let Some(keyword) = manifest.keyword.as_deref() {
921 if !is_keyword(keyword) {
922 report.errors.push(format!(
923 "keyword {keyword:?} must be one non-empty word — it is matched \
924 up to the first space of the query"
925 ));
926 }
927 } else {
928 report.warnings.push(
929 "no keyword: the plugin runs on every keystroke and must answer \
930 well inside 180 ms"
931 .to_owned(),
932 );
933 }
934
935 if let Some(ms) = manifest.timeout_ms {
936 let applied = manifest.timeout(manifest.keyword.as_deref()).as_millis();
937 if u128::from(ms) != applied {
938 let why = if manifest.keyword.is_none() && applied == QUERY_TIMEOUT.as_millis() {
939 " — only a keyworded plugin may take longer than the interactive default"
940 } else {
941 ""
942 };
943 report
944 .warnings
945 .push(format!("timeout_ms = {ms} is clamped to {applied} ms{why}"));
946 }
947 }
948
949 let check_command = |report: &mut LintReport, label: &str, command: &str| {
950 let path = if Path::new(command).is_absolute() {
951 PathBuf::from(command)
952 } else {
953 directory.join(command)
954 };
955 if !path.is_file() {
956 report
957 .errors
958 .push(format!("{label} command {} does not exist", path.display()));
959 return;
960 }
961 #[cfg(unix)]
962 {
963 use std::os::unix::fs::PermissionsExt;
964 let executable = path
965 .metadata()
966 .map(|meta| meta.permissions().mode() & 0o111 != 0)
967 .unwrap_or(false);
968 if !executable {
969 report.errors.push(format!(
970 "{label} command {} is not executable (chmod +x)",
971 path.display()
972 ));
973 }
974 }
975 };
976 check_command(&mut report, "query", &manifest.query);
977 if let Some(activate) = manifest.activate.as_deref() {
978 check_command(&mut report, "activate", activate);
979 }
980 if !report.errors.is_empty() {
981 return report;
982 }
983
984 let plugin = Plugin {
986 manifest,
987 directory: directory.to_path_buf(),
988 id: directory
989 .file_name()
990 .and_then(|name| name.to_str())
991 .unwrap_or("plugin")
992 .to_owned(),
993 };
994 let program = plugin.resolve(&plugin.manifest.query);
995 let stdout = match run_query(
996 &program,
997 &plugin.directory,
998 sample_query,
999 plugin.manifest.timeout(plugin.manifest.keyword.as_deref()),
1000 )
1001 .await
1002 {
1003 Ok(stdout) => stdout,
1004 Err(error) => {
1005 report.errors.push(format!("query command {error}"));
1006 return report;
1007 }
1008 };
1009
1010 match serde_json::from_slice::<PluginResponse>(&stdout) {
1011 Ok(response) => {
1012 report.items = response.items.len();
1013 if response.items.is_empty() {
1014 report
1015 .warnings
1016 .push("sample query produced no items".to_owned());
1017 }
1018 for item in &response.items {
1019 if item.uid.is_none() {
1020 report.warnings.push(format!(
1021 "item {:?} has no uid — without one, usage ranking \
1022 cannot learn it",
1023 item.title
1024 ));
1025 }
1026 }
1027 }
1028 Err(error) => {
1029 report
1030 .errors
1031 .push(format!("output is not valid script-filter JSON: {error}"));
1032 }
1033 }
1034
1035 report
1036}
1037
1038#[must_use]
1045pub fn scaffold_keyword(name: &str) -> Option<String> {
1046 let keyword = name
1047 .to_lowercase()
1048 .split_whitespace()
1049 .collect::<Vec<_>>()
1050 .join("-");
1051 let usable =
1052 !keyword.is_empty() && !keyword.starts_with('.') && !keyword.contains(['/', '\\', '\0']);
1053 usable.then_some(keyword)
1054}
1055
1056pub fn scaffold(root: &Path, name: &str) -> std::io::Result<(PathBuf, String)> {
1072 let Some(keyword) = scaffold_keyword(name) else {
1073 return Err(std::io::Error::new(
1074 std::io::ErrorKind::InvalidInput,
1075 format!("{name:?} does not make a plugin directory name"),
1076 ));
1077 };
1078 let directory = root.join(&keyword);
1079 if directory.exists() {
1080 return Err(std::io::Error::new(
1081 std::io::ErrorKind::AlreadyExists,
1082 format!("{} already exists", directory.display()),
1083 ));
1084 }
1085 std::fs::create_dir_all(&directory)?;
1086
1087 let toml_string = |text: &str| toml::Value::String(text.to_owned()).to_string();
1088 std::fs::write(
1089 directory.join("manifest.toml"),
1090 format!(
1091 "name = {}\n\
1092 description = \"Describe what this plugin searches\"\n\
1093 keyword = {}\n\
1094 query = \"./search.sh\"\n\
1095 # activate = \"./open.sh\" # separate action command, optional\n\
1096 icon = \"system-search-symbolic\"\n\
1097 # timeout_ms = 1000 # up to 3000 for slow keyworded plugins\n",
1098 toml_string(name),
1099 toml_string(&keyword),
1100 ),
1101 )?;
1102
1103 let shell_name = name.replace('\'', r"'\''");
1105 let script = directory.join("search.sh");
1106 std::fs::write(
1107 &script,
1108 format!(
1109 "#!/bin/sh\n\
1110 # jump runs this with the query as $1 and reads script-filter\n\
1111 # JSON from stdout. Without an `activate` command in the\n\
1112 # manifest, activation re-runs this script as: search.sh\n\
1113 # --activate <arg>.\n\
1114 if [ \"$1\" = \"--activate\" ]; then\n\
1115 \t# \"$2\" is the chosen item's arg.\n\
1116 \texit 0\n\
1117 fi\n\
1118 \n\
1119 name='{shell_name}'\n\
1120 query=\"$1\"\n\
1121 # Text going into a JSON string needs its backslashes and quotes\n\
1122 # escaped.\n\
1123 json() {{ printf '%s' \"$1\" | sed 's/[\\\\\"]/\\\\&/g'; }}\n\
1124 printf '{{\"items\":[{{\"uid\":\"hello\",\"title\":\"Hello %s\",\
1125 \"subtitle\":\"%s\",\"arg\":\"%s\"}}]}}' \
1126 \"$(json \"${{query:-world}}\")\" \"$(json \"$name\")\" \"$(json \"$query\")\"\n"
1127 ),
1128 )?;
1129 #[cfg(unix)]
1130 {
1131 use std::os::unix::fs::PermissionsExt;
1132 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))?;
1133 }
1134 Ok((directory, keyword))
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139 use super::*;
1140
1141 fn plugin(keyword: Option<&str>) -> Plugin {
1142 Plugin {
1143 manifest: Manifest {
1144 name: "Test".to_owned(),
1145 description: String::new(),
1146 keyword: keyword.map(ToOwned::to_owned),
1147 query: "./q".to_owned(),
1148 activate: None,
1149 icon: None,
1150 timeout_ms: None,
1151 },
1152 directory: PathBuf::from("/tmp"),
1153 id: "test".to_owned(),
1154 }
1155 }
1156
1157 #[test]
1158 fn keywordless_plugin_sees_whole_query() {
1159 assert_eq!(plugin(None).match_query("hello there"), Some("hello there"));
1160 }
1161
1162 #[test]
1163 fn keyword_is_stripped() {
1164 assert_eq!(plugin(Some("gh")).match_query("gh jump"), Some("jump"));
1165 }
1166
1167 #[test]
1168 fn bare_keyword_yields_empty_query() {
1169 assert_eq!(plugin(Some("gh")).match_query("gh"), Some(""));
1170 }
1171
1172 #[test]
1173 fn a_keyword_is_one_non_empty_word() {
1174 assert!(is_keyword("gh"));
1175 assert!(is_keyword("=="));
1176 for bad in ["", "gh x", " gh", "gh\t"] {
1177 assert!(!is_keyword(bad), "{bad:?}");
1178 }
1179 }
1180
1181 #[test]
1182 fn keyword_requires_word_boundary() {
1183 assert_eq!(plugin(Some("gh")).match_query("ghost"), None);
1185 }
1186
1187 #[test]
1188 fn non_matching_keyword_is_skipped() {
1189 assert_eq!(plugin(Some("gh")).match_query("firefox"), None);
1190 }
1191
1192 #[test]
1193 fn timeout_is_clamped_to_the_ceiling() {
1194 let mut manifest = plugin(None).manifest;
1195 let keyword = Some("gh");
1196 assert_eq!(manifest.timeout(keyword), Duration::from_millis(180));
1197
1198 manifest.timeout_ms = Some(60_000);
1199 assert_eq!(manifest.timeout(keyword), Duration::from_millis(3000));
1200
1201 manifest.timeout_ms = Some(1);
1202 assert_eq!(manifest.timeout(keyword), Duration::from_millis(50));
1203 }
1204
1205 #[test]
1206 fn only_a_keyworded_plugin_may_raise_its_deadline() {
1207 let mut manifest = plugin(None).manifest;
1210 manifest.timeout_ms = Some(3000);
1211 assert_eq!(manifest.timeout(None), Duration::from_millis(180));
1212 assert_eq!(manifest.timeout(Some("gh")), Duration::from_millis(3000));
1213
1214 manifest.timeout_ms = Some(100);
1215 assert_eq!(manifest.timeout(None), Duration::from_millis(100));
1216 }
1217
1218 #[tokio::test(flavor = "multi_thread")]
1219 async fn the_host_holds_an_always_on_plugin_to_the_interactive_deadline() {
1220 let root = tempfile::tempdir().expect("tempdir");
1223 let mut slow = scripted(
1224 root.path(),
1225 "#!/bin/sh\nsleep 0.5\necho '{\"items\":[{\"title\":\"late\"}]}'\n",
1226 Some(3000),
1227 );
1228 slow.id = "slow".to_owned();
1229 let mut host = PluginHost {
1230 plugins: vec![slow],
1231 ..PluginHost::default()
1232 };
1233 assert_eq!(host.query("t x").await.items.len(), 1);
1234
1235 host.set_keyword_overrides([("slow", "")]);
1240 assert!(host.query("x").await.items.is_empty());
1241 }
1242
1243 #[test]
1244 fn uid_and_autocomplete_parse_from_alfred_json() {
1245 let response: PluginResponse = serde_json::from_str(
1246 r#"{"items":[
1247 {"uid":"repo","title":"jump","arg":"https://example.com/?q=jump",
1248 "autocomplete":"gh jump ", "icon":{"path":"/tmp/icon.png"}},
1249 {"title":"plain"}
1250 ]}"#,
1251 )
1252 .expect("alfred json parses");
1253
1254 assert_eq!(response.items[0].uid.as_deref(), Some("repo"));
1255 assert_eq!(response.items[0].autocomplete.as_deref(), Some("gh jump "));
1256 assert_eq!(response.items[1].uid, None);
1257 }
1258
1259 #[test]
1260 fn rerun_parses_and_is_clamped_sanely() {
1261 let parse = |json: &str| -> Option<f64> {
1262 serde_json::from_str::<PluginResponse>(json)
1263 .expect("json parses")
1264 .rerun
1265 };
1266 assert_eq!(parse(r#"{"items":[]}"#), None);
1267 assert_eq!(parse(r#"{"items":[],"rerun":1.5}"#), Some(1.5));
1268
1269 let clamp = |seconds: f64| seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end());
1271 assert_eq!(clamp(0.1), 0.5);
1272 assert_eq!(clamp(60.0), 5.0);
1273 assert_eq!(clamp(2.0), 2.0);
1274 }
1275
1276 #[test]
1277 fn mods_normalise_inherit_and_override() {
1278 let response: PluginResponse = serde_json::from_str(
1279 r#"{"variables":{"SESSION":"abc"},
1280 "items":[{"title":"repo","arg":"main",
1281 "mods":{
1282 "cmd":{"subtitle":"Open on the web","arg":"https://example.com"},
1283 "alt":{"subtitle":"Copy","variables":{"MODE":"copy"}},
1284 "shift":{"subtitle":"Off","valid":false},
1285 "hyper":{"subtitle":"Unbindable"}
1286 }}]}"#,
1287 )
1288 .expect("alfred json parses");
1289
1290 let item = &response.items[0];
1291 assert_eq!(normalise_modifier("cmd"), Some("super"));
1292 assert_eq!(normalise_modifier("Control"), Some("ctrl"));
1293 assert_eq!(normalise_modifier("hyper"), None);
1294
1295 let usable: Vec<&String> = item
1298 .mods
1299 .iter()
1300 .filter(|(_, m)| m.valid)
1301 .filter(|(name, _)| normalise_modifier(name).is_some())
1302 .map(|(name, _)| name)
1303 .collect();
1304 assert_eq!(usable.len(), 2);
1305
1306 assert_eq!(item.mods["alt"].arg, None);
1308 assert_eq!(item.mods["cmd"].arg.as_deref(), Some("https://example.com"));
1309 }
1310
1311 #[test]
1312 fn item_variables_win_over_response_variables() {
1313 let response: PluginResponse = serde_json::from_str(
1314 r#"{"variables":{"SESSION":"abc","MODE":"list"},
1315 "items":[{"title":"one","variables":{"MODE":"open"}},
1316 {"title":"two"}]}"#,
1317 )
1318 .expect("alfred json parses");
1319
1320 let merged = merge_variables(&response.variables, response.items[0].variables.clone());
1321 assert_eq!(
1322 merged,
1323 vec![
1324 ("MODE".to_owned(), "open".to_owned()),
1325 ("SESSION".to_owned(), "abc".to_owned()),
1326 ]
1327 );
1328
1329 let inherited = merge_variables(&response.variables, response.items[1].variables.clone());
1331 assert_eq!(inherited.len(), 2);
1332 assert!(inherited.contains(&("MODE".to_owned(), "list".to_owned())));
1333 }
1334
1335 #[tokio::test(flavor = "multi_thread")]
1336 async fn scaffold_produces_a_plugin_that_lints_clean() {
1337 let root = tempfile::tempdir().expect("tempdir");
1338
1339 let (directory, keyword) = scaffold(root.path(), "Demo").expect("scaffold succeeds");
1340 assert_eq!(directory, root.path().join("demo"));
1341 assert_eq!(keyword, "demo");
1342 assert!(scaffold(root.path(), "Demo").is_err());
1344
1345 let report = lint(&directory, "hello").await;
1346 assert!(report.is_clean(), "unexpected errors: {:?}", report.errors);
1347 assert_eq!(report.items, 1);
1348 assert!(report.warnings.is_empty(), "{:?}", report.warnings);
1349 }
1350
1351 #[tokio::test(flavor = "multi_thread")]
1352 async fn a_scaffold_name_is_data_not_syntax() {
1353 let root = tempfile::tempdir().expect("tempdir");
1356 let name = r#"It's "100%" done"#;
1357 let (directory, keyword) = scaffold(root.path(), name).expect("scaffold succeeds");
1358 assert_eq!(keyword, r#"it's-"100%"-done"#);
1359
1360 let manifest: Manifest = toml::from_str(
1361 &std::fs::read_to_string(directory.join("manifest.toml")).expect("manifest"),
1362 )
1363 .expect("the manifest parses");
1364 assert_eq!(manifest.name, name);
1365
1366 let output = std::process::Command::new(directory.join("search.sh"))
1367 .arg(r#"say "hi" \"#)
1368 .output()
1369 .expect("the script runs");
1370 let response: serde_json::Value =
1371 serde_json::from_slice(&output.stdout).expect("the output is JSON");
1372 let item = &response["items"][0];
1373 assert_eq!(item["subtitle"], name);
1374 assert_eq!(item["title"], r#"Hello say "hi" \"#);
1375 }
1376
1377 #[tokio::test(flavor = "multi_thread")]
1378 async fn a_query_script_still_open_for_writing_runs_once_it_is_closed() {
1379 use std::io::Write;
1385 use std::os::unix::fs::PermissionsExt;
1386
1387 let root = tempfile::tempdir().expect("tempdir");
1388 let script = root.path().join("search.sh");
1389 let mut held = std::fs::File::create(&script).expect("create");
1390 held.write_all(b"#!/bin/sh\nprintf ok\n").expect("write");
1391 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).expect("chmod");
1392 let release = std::thread::spawn(move || {
1393 std::thread::sleep(Duration::from_millis(30));
1394 drop(held);
1395 });
1396
1397 let stdout = run_query(&script, root.path(), "", Duration::from_secs(3))
1398 .await
1399 .expect("the query runs once the writer has closed the script");
1400 assert_eq!(stdout, b"ok");
1401 release.join().expect("release thread");
1402 }
1403
1404 #[test]
1405 fn a_scaffold_cannot_name_a_directory_outside_the_root() {
1406 for name in ["../x", "a/b", ".hidden", " ", ""] {
1407 assert_eq!(scaffold_keyword(name), None, "{name:?}");
1408 }
1409 assert_eq!(scaffold_keyword("My Plugin").as_deref(), Some("my-plugin"));
1410 let root = tempfile::tempdir().expect("tempdir");
1411 let error = scaffold(&root.path().join("plugins"), "../x").expect_err("refused");
1412 assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
1413 assert!(!root.path().join("x").exists());
1414 }
1415
1416 #[tokio::test(flavor = "multi_thread")]
1417 async fn lint_reports_missing_and_broken_pieces() {
1418 let root = tempfile::tempdir().expect("tempdir");
1419
1420 let report = lint(root.path(), "x").await;
1422 assert!(!report.is_clean());
1423
1424 let directory = root.path().join("broken");
1426 std::fs::create_dir_all(&directory).expect("dir");
1427 std::fs::write(
1428 directory.join("manifest.toml"),
1429 "name = \"Broken\"\nkeyword = \"two words\"\nquery = \"./missing.sh\"\n",
1430 )
1431 .expect("manifest");
1432 let report = lint(&directory, "x").await;
1433 assert_eq!(report.errors.len(), 2, "{:?}", report.errors);
1434 }
1435
1436 fn scripted(root: &Path, script: &str, timeout_ms: Option<u64>) -> Plugin {
1438 use std::os::unix::fs::PermissionsExt;
1439
1440 let path = root.join("q");
1441 std::fs::write(&path, script).expect("script");
1442 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("chmod");
1443 let mut plugin = plugin(Some("t"));
1444 plugin.directory = root.to_path_buf();
1445 plugin.manifest.timeout_ms = timeout_ms;
1446 plugin
1447 }
1448
1449 fn alive(pid: u32) -> bool {
1451 std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| {
1452 stat.rsplit(") ")
1453 .next()
1454 .is_some_and(|rest| !rest.starts_with('Z'))
1455 })
1456 }
1457
1458 #[tokio::test(flavor = "multi_thread")]
1459 async fn oversized_output_is_refused_without_waiting_for_the_deadline() {
1460 let root = tempfile::tempdir().expect("tempdir");
1464 let plugin = scripted(
1465 root.path(),
1466 "#!/bin/sh\nhead -c 2000000 /dev/zero\nsleep 5\n",
1467 Some(3000),
1468 );
1469
1470 let started = std::time::Instant::now();
1471 let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
1472 assert!(items.is_empty());
1473 assert!(
1474 started.elapsed() < Duration::from_millis(1500),
1475 "took {:?}: output was buffered until the deadline",
1476 started.elapsed()
1477 );
1478 }
1479
1480 #[tokio::test(flavor = "multi_thread")]
1481 async fn an_overrunning_plugin_is_killed_with_its_children() {
1482 let root = tempfile::tempdir().expect("tempdir");
1490 let plugin = scripted(
1491 root.path(),
1492 "#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
1493 Some(1000),
1494 );
1495
1496 let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
1497 assert!(items.is_empty());
1498
1499 assert!(
1500 !outlives(&root.path().join("child.pid")).await,
1501 "the plugin's child outlived the deadline"
1502 );
1503 }
1504
1505 async fn outlives(pid_file: &Path) -> bool {
1509 let pid: u32 = std::fs::read_to_string(pid_file)
1510 .expect("the script recorded its child")
1511 .trim()
1512 .parse()
1513 .expect("pid");
1514 let deadline = std::time::Instant::now() + Duration::from_secs(2);
1515 while alive(pid) && std::time::Instant::now() < deadline {
1516 tokio::time::sleep(Duration::from_millis(20)).await;
1517 }
1518 let survived = alive(pid);
1519 if survived {
1520 let _ = std::process::Command::new("kill")
1521 .args(["-KILL", &pid.to_string()])
1522 .status();
1523 }
1524 survived
1525 }
1526
1527 #[tokio::test(flavor = "multi_thread")]
1528 async fn an_abandoned_query_is_killed_with_its_children() {
1529 let root = tempfile::tempdir().expect("tempdir");
1532 let plugin = scripted(
1533 root.path(),
1534 "#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
1535 Some(3000),
1536 );
1537 let pid_file = root.path().join("child.pid");
1538
1539 let running = tokio::spawn(async move {
1540 let deadline = plugin.manifest.timeout(Some("t"));
1541 plugin.query("x", deadline).await
1542 });
1543 let started = std::time::Instant::now();
1544 let recorded =
1545 |path: &Path| std::fs::read_to_string(path).is_ok_and(|pid| pid.ends_with('\n'));
1546 while !recorded(&pid_file) && started.elapsed() < Duration::from_secs(2) {
1547 tokio::time::sleep(Duration::from_millis(10)).await;
1548 }
1549 running.abort();
1550 assert!(running.await.is_err_and(|error| error.is_cancelled()));
1551
1552 assert!(
1553 !outlives(&pid_file).await,
1554 "the abandoned query's child kept running"
1555 );
1556 }
1557
1558 #[tokio::test(flavor = "multi_thread")]
1559 async fn lint_applies_the_launchers_output_cap() {
1560 let root = tempfile::tempdir().expect("tempdir");
1563 let directory = root.path().join("big");
1564 std::fs::create_dir_all(&directory).expect("dir");
1565 std::fs::write(
1566 directory.join("manifest.toml"),
1567 "name = \"Big\"\nkeyword = \"big\"\nquery = \"./q\"\n",
1568 )
1569 .expect("manifest");
1570 scripted(
1571 &directory,
1572 "#!/bin/sh\nprintf '{\"items\":[{\"uid\":\"a\",\"title\":\"'\n\
1573 head -c 1100000 /dev/zero | tr '\\0' a\nprintf '\"}]}'\n",
1574 None,
1575 );
1576
1577 let report = lint(&directory, "x").await;
1578 assert!(!report.is_clean(), "oversized output linted clean");
1579 }
1580
1581 #[test]
1582 fn discovery_walks_roots_in_order_and_user_shadows_system() {
1583 let user = tempfile::tempdir().expect("tempdir");
1584 let system = tempfile::tempdir().expect("tempdir");
1585
1586 let write = |root: &std::path::Path, id: &str, name: &str| {
1587 let dir = root.join(id);
1588 std::fs::create_dir_all(&dir).expect("plugin dir");
1589 std::fs::write(
1590 dir.join("manifest.toml"),
1591 format!("name = \"{name}\"\nquery = \"./q\"\n"),
1592 )
1593 .expect("manifest");
1594 };
1595
1596 write(user.path(), "shared", "User copy");
1597 write(user.path(), "mine", "User only");
1598 write(system.path(), "shared", "System copy");
1599 write(system.path(), "packaged", "System only");
1600 std::fs::create_dir_all(system.path().join("junk")).expect("junk dir");
1602
1603 let host =
1604 PluginHost::discover_in(&[user.path().to_path_buf(), system.path().to_path_buf()]);
1605
1606 let mut ids: Vec<&str> = host.all().map(|(plugin, _)| plugin.id.as_str()).collect();
1607 ids.sort_unstable();
1608 assert_eq!(ids, ["mine", "packaged", "shared"]);
1609
1610 let shared = host.get("shared").expect("shared plugin");
1612 assert_eq!(shared.manifest.name, "User copy");
1613 }
1614
1615 #[test]
1616 fn a_fresh_discovery_keeps_the_users_settings() {
1617 let root = tempfile::tempdir().expect("tempdir");
1620 let write = |id: &str| {
1621 let dir = root.path().join(id);
1622 std::fs::create_dir_all(&dir).expect("plugin dir");
1623 std::fs::write(
1624 dir.join("manifest.toml"),
1625 "name = \"P\"\nkeyword = \"p\"\nquery = \"./q\"\n",
1626 )
1627 .expect("manifest");
1628 };
1629 write("old");
1630 let roots = [root.path().to_path_buf()];
1631 let mut host = PluginHost::discover_in(&roots);
1632 host.set_disabled(["old"]);
1633 host.set_keyword_overrides([("new", "n")]);
1634
1635 assert!(!host.replace_plugins(PluginHost::discover_in(&roots)));
1636
1637 write("new");
1638 assert!(host.replace_plugins(PluginHost::discover_in(&roots)));
1639 assert!(
1640 host.get("old").is_none(),
1641 "the disabled plugin came back on"
1642 );
1643 let new = host.get("new").expect("the new plugin was picked up");
1644 assert_eq!(host.effective_keyword(new), Some("n"));
1645 }
1646
1647 #[test]
1648 fn keyword_overrides_replace_and_remove_the_manifest_keyword() {
1649 let mut host = PluginHost {
1650 plugins: vec![plugin(Some("gh"))],
1651 disabled: std::collections::HashSet::new(),
1652 keyword_overrides: std::collections::HashMap::new(),
1653 };
1654
1655 assert!(host.is_claimed("gh jump"));
1657
1658 host.set_keyword_overrides([("test", "g")]);
1660 assert!(host.is_claimed("g jump"));
1661 assert!(!host.is_claimed("gh jump"));
1662
1663 host.set_keyword_overrides([("test", "")]);
1666 assert!(!host.is_claimed("g jump"));
1667 assert!(!host.is_claimed("gh jump"));
1668 let plugin = &host.plugins[0];
1669 assert_eq!(host.effective_keyword(plugin), None);
1670
1671 host.set_keyword_overrides([("other", "x")]);
1673 assert!(host.is_claimed("gh jump"));
1674 }
1675
1676 #[test]
1677 fn disabled_plugins_neither_run_nor_activate() {
1678 let mut host = PluginHost {
1679 plugins: vec![plugin(Some("gh"))],
1680 disabled: std::collections::HashSet::new(),
1681 keyword_overrides: std::collections::HashMap::new(),
1682 };
1683
1684 assert!(host.is_claimed("gh jump"));
1685 assert!(host.get("test").is_some());
1686
1687 host.set_disabled(["test"]);
1688 assert!(!host.is_claimed("gh jump"));
1689 assert!(host.get("test").is_none());
1690 assert_eq!(host.all().map(|(_, on)| on).collect::<Vec<_>>(), [false]);
1692 }
1693}