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 run_query(
108 program: &Path,
109 directory: &Path,
110 text: &str,
111 deadline: Duration,
112) -> Result<Vec<u8>, RunError> {
113 use tokio::io::AsyncReadExt;
114
115 let mut child = Command::new(program)
116 .arg(text)
117 .current_dir(directory)
118 .stdin(Stdio::null())
119 .stdout(Stdio::piped())
120 .stderr(Stdio::piped())
121 .process_group(0)
122 .kill_on_drop(true)
123 .spawn()?;
124 let mut group = GroupKill(child.id());
127 let stdout = child.stdout.take().expect("stdout is piped");
128 let stderr = child.stderr.take().expect("stderr is piped");
129
130 let stderr = tokio::spawn(async move {
133 let mut kept = Vec::new();
134 let mut limited = stderr.take(MAX_STDERR_BYTES as u64);
135 let read = limited.read_to_end(&mut kept).await;
136 let drained = tokio::io::copy(&mut limited.into_inner(), &mut tokio::io::sink()).await;
137 if let Err(error) = read.and(drained) {
138 tracing::debug!(%error, "plugin stderr read failed");
139 }
140 String::from_utf8_lossy(&kept).trim().to_owned()
141 });
142
143 let run = async {
144 let mut output = Vec::new();
145 stdout
146 .take(MAX_OUTPUT_BYTES as u64 + 1)
147 .read_to_end(&mut output)
148 .await?;
149 if output.len() > MAX_OUTPUT_BYTES {
150 return Err(RunError::TooLarge);
151 }
152 let status = child.wait().await?;
153 group.disarm();
155 Ok((status, output))
156 };
157
158 match tokio::time::timeout(deadline, run).await {
159 Ok(Ok((status, output))) if status.success() => Ok(output),
160 Ok(Ok((status, _))) => Err(RunError::Failed {
161 status,
162 stderr: stderr.await.unwrap_or_default(),
163 }),
164 Ok(Err(error)) => Err(error),
166 Err(_) => Err(RunError::Deadline(deadline)),
167 }
168}
169
170struct GroupKill(Option<u32>);
183
184impl GroupKill {
185 fn disarm(&mut self) {
186 self.0 = None;
187 }
188}
189
190impl Drop for GroupKill {
191 fn drop(&mut self) {
192 let Some(group) = self.0 else {
193 return;
194 };
195 let spawned = Command::new("kill")
196 .args(["-KILL", "--", &format!("-{group}")])
197 .stdin(Stdio::null())
198 .stdout(Stdio::null())
199 .stderr(Stdio::null())
200 .spawn();
201 if let Err(error) = spawned {
202 tracing::warn!(group, %error, "could not kill plugin process group");
203 }
204 }
205}
206
207#[must_use]
212pub fn is_keyword(text: &str) -> bool {
213 !text.is_empty() && !text.contains(char::is_whitespace)
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
218pub struct Manifest {
219 pub name: String,
221 #[serde(default)]
223 pub description: String,
224 #[serde(default)]
227 pub keyword: Option<String>,
228 pub query: String,
230 #[serde(default)]
234 pub activate: Option<String>,
235 #[serde(default)]
237 pub icon: Option<String>,
238 #[serde(default)]
241 pub timeout_ms: Option<u64>,
242}
243
244impl Manifest {
245 #[must_use]
254 pub fn timeout(&self, keyword: Option<&str>) -> Duration {
255 let requested = self.timeout_ms.map_or(QUERY_TIMEOUT, |ms| {
256 Duration::from_millis(ms).clamp(Duration::from_millis(50), MAX_QUERY_TIMEOUT)
257 });
258 if keyword.is_some() {
259 requested
260 } else {
261 requested.min(QUERY_TIMEOUT)
262 }
263 }
264}
265
266#[derive(Debug, Clone, Deserialize)]
268struct PluginItem {
269 title: String,
270 #[serde(default)]
271 subtitle: String,
272 #[serde(default)]
274 arg: Option<String>,
275 #[serde(default)]
278 icon: Option<PluginIcon>,
279 #[serde(default = "default_valid")]
281 valid: bool,
282 #[serde(default)]
286 uid: Option<String>,
287 #[serde(default)]
289 autocomplete: Option<String>,
290 #[serde(default)]
294 variables: std::collections::HashMap<String, String>,
295 #[serde(default)]
299 mods: std::collections::HashMap<String, PluginMod>,
300}
301
302#[derive(Debug, Clone, Deserialize)]
304struct PluginMod {
305 #[serde(default)]
306 subtitle: String,
307 #[serde(default)]
308 arg: Option<String>,
309 #[serde(default = "default_valid")]
311 valid: bool,
312 #[serde(default)]
313 variables: std::collections::HashMap<String, String>,
314}
315
316fn normalise_modifier(name: &str) -> Option<&'static str> {
321 match name.trim().to_lowercase().as_str() {
322 "ctrl" | "control" => Some("ctrl"),
323 "alt" | "option" => Some("alt"),
324 "shift" => Some("shift"),
325 "cmd" | "command" | "super" | "meta" => Some("super"),
327 _ => None,
328 }
329}
330
331const fn default_valid() -> bool {
332 true
333}
334
335#[derive(Debug, Clone, Deserialize)]
336#[serde(untagged)]
337enum PluginIcon {
338 Named(String),
339 Path {
340 #[serde(alias = "name")]
341 path: String,
342 },
343}
344
345impl PluginIcon {
346 fn into_icon(self) -> Icon {
347 match self {
348 Self::Named(name) | Self::Path { path: name } => Icon::Name(name),
349 }
350 }
351}
352
353#[derive(Debug, Clone, Deserialize)]
354struct PluginResponse {
355 items: Vec<PluginItem>,
356 #[serde(default)]
358 variables: std::collections::HashMap<String, String>,
359 #[serde(default)]
362 rerun: Option<f64>,
363}
364
365const RERUN_RANGE: std::ops::RangeInclusive<f64> = 0.5..=5.0;
369
370#[derive(Debug, Clone, Default)]
373pub struct QueryResults {
374 pub items: Vec<Item>,
376 pub rerun: Option<Duration>,
378}
379
380fn merge_variables(
383 response: &std::collections::HashMap<String, String>,
384 item: std::collections::HashMap<String, String>,
385) -> Vec<(String, String)> {
386 let mut merged = response.clone();
387 merged.extend(item);
388 let mut variables: Vec<(String, String)> = merged.into_iter().collect();
389 variables.sort();
390 variables
391}
392
393#[derive(Debug, Clone, PartialEq, Eq)]
395pub struct Plugin {
396 pub manifest: Manifest,
398 pub directory: PathBuf,
400 pub id: String,
402}
403
404impl Plugin {
405 fn resolve(&self, command: &str) -> PathBuf {
408 let path = Path::new(command);
409 if path.is_absolute() {
410 path.to_path_buf()
411 } else {
412 self.directory.join(path)
413 }
414 }
415
416 #[must_use]
422 pub fn match_query_as<'a>(&self, keyword: Option<&str>, query: &'a str) -> Option<&'a str> {
423 match keyword {
424 None => Some(query),
425 Some(keyword) => {
426 let rest = query.strip_prefix(keyword)?;
427 match rest.strip_prefix(' ') {
428 Some(rest) => Some(rest.trim_start()),
429 None if rest.is_empty() => Some(""),
432 None => None,
433 }
434 }
435 }
436 }
437
438 #[must_use]
440 pub fn match_query<'a>(&self, query: &'a str) -> Option<&'a str> {
441 self.match_query_as(self.manifest.keyword.as_deref(), query)
442 }
443
444 async fn query(&self, text: &str, deadline: Duration) -> (Vec<Item>, Option<Duration>) {
447 let program = self.resolve(&self.manifest.query);
448
449 let stdout = match run_query(&program, &self.directory, text, deadline).await {
450 Ok(stdout) => stdout,
451 Err(error) => {
452 tracing::warn!(plugin = %self.id, ?program, %error, "plugin query dropped");
453 return (Vec::new(), None);
454 }
455 };
456
457 let response: PluginResponse = match serde_json::from_slice(&stdout) {
458 Ok(response) => response,
459 Err(error) => {
460 tracing::warn!(plugin = %self.id, %error, "plugin emitted invalid JSON");
461 return (Vec::new(), None);
462 }
463 };
464
465 let fallback_icon = self.manifest.icon.as_ref().map(|n| Icon::Name(n.clone()));
466 let PluginResponse {
467 items,
468 variables: response_variables,
469 rerun,
470 } = response;
471
472 let rerun = rerun.filter(|seconds| seconds.is_finite()).map(|seconds| {
474 Duration::from_secs_f64(seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end()))
475 });
476
477 let items = items
478 .into_iter()
479 .filter(|item| item.valid)
480 .map(|item| {
481 let arg = item.arg.unwrap_or_else(|| item.title.clone());
482 let variables = merge_variables(&response_variables, item.variables);
483
484 let mut mods: Vec<Mod> = item
488 .mods
489 .into_iter()
490 .filter(|(_, alternate)| alternate.valid)
491 .filter_map(|(modifier, alternate)| {
492 let modifier = normalise_modifier(&modifier)?;
493 let mut merged: std::collections::HashMap<String, String> =
494 variables.iter().cloned().collect();
495 merged.extend(alternate.variables);
496 let mut alternate_variables: Vec<(String, String)> =
497 merged.into_iter().collect();
498 alternate_variables.sort();
499
500 Some(Mod {
501 modifier: modifier.to_owned(),
502 subtitle: alternate.subtitle,
503 arg: alternate.arg.unwrap_or_else(|| arg.clone()),
504 variables: alternate_variables,
505 })
506 })
507 .collect();
508 mods.sort_by(|a, b| a.modifier.cmp(&b.modifier));
510 let identity = item.uid.as_deref().unwrap_or(&arg);
514 Item {
515 key: ItemKey(format!("plugin:{}:{identity}", self.id)),
518 id: 0,
520 title: item.title,
521 subtitle: if item.subtitle.is_empty() {
522 self.manifest.description.clone()
523 } else {
524 item.subtitle
525 },
526 icon: item
527 .icon
528 .map(PluginIcon::into_icon)
529 .or_else(|| fallback_icon.clone()),
530 category_icon: fallback_icon.clone(),
531 window: None,
532 source: Source::Plugin {
533 plugin: self.id.clone(),
534 arg,
535 variables,
536 mods,
537 },
538 autocomplete: item.autocomplete,
539 score: 0.0,
540 }
541 })
542 .collect();
543
544 (items, rerun)
545 }
546
547 pub fn activate(&self, arg: &str, variables: &[(String, String)]) {
556 let (program, extra) = match self.manifest.activate.as_deref() {
557 Some(activate) => (self.resolve(activate), Vec::new()),
558 None => (
559 self.resolve(&self.manifest.query),
560 vec!["--activate".to_owned()],
561 ),
562 };
563
564 let result = Command::new(&program)
565 .envs(variables.iter().map(|(key, value)| (key, value)))
566 .args(extra)
567 .arg(arg)
568 .current_dir(&self.directory)
569 .stdin(Stdio::null())
570 .stdout(Stdio::null())
571 .stderr(Stdio::null())
572 .spawn();
573
574 match result {
575 Ok(mut child) => {
576 tokio::spawn(async move {
578 let _ = child.wait().await;
579 });
580 }
581 Err(error) => {
582 tracing::error!(plugin = %self.id, ?program, %error, "failed to activate plugin item");
583 }
584 }
585 }
586}
587
588#[derive(Debug, Default, Clone)]
590pub struct PluginHost {
591 plugins: Vec<Plugin>,
592 disabled: std::collections::HashSet<String>,
595 keyword_overrides: std::collections::HashMap<String, String>,
599}
600
601impl PluginHost {
602 #[must_use]
604 pub fn discover() -> Self {
605 Self::discover_in(&Self::roots())
606 }
607
608 #[must_use]
617 pub fn roots() -> Vec<PathBuf> {
618 let mut roots: Vec<PathBuf> = dirs::data_dir()
619 .map(|dir| dir.join("jump").join("plugins"))
620 .into_iter()
621 .collect();
622
623 let system = std::env::var_os("XDG_DATA_DIRS")
624 .filter(|value| !value.is_empty())
625 .map_or_else(
626 || {
627 vec![
628 PathBuf::from("/usr/local/share"),
629 PathBuf::from("/usr/share"),
630 ]
631 },
632 |value| std::env::split_paths(&value).collect(),
633 );
634 roots.extend(
635 system
636 .into_iter()
637 .map(|dir| dir.join("jump").join("plugins")),
638 );
639 roots
640 }
641
642 #[must_use]
647 pub fn discover_in(roots: &[PathBuf]) -> Self {
648 let mut plugins: Vec<Plugin> = Vec::new();
649
650 for root in roots {
651 let entries = match std::fs::read_dir(root) {
652 Ok(entries) => entries,
653 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
654 Err(error) => {
655 tracing::warn!(%error, ?root, "failed to read plugin directory");
656 continue;
657 }
658 };
659
660 for entry in entries.flatten() {
661 let directory = entry.path();
662 if !directory.is_dir() {
663 continue;
664 }
665
666 let Some(id) = directory
667 .file_name()
668 .and_then(|name| name.to_str())
669 .map(ToOwned::to_owned)
670 else {
671 continue;
672 };
673
674 if plugins.iter().any(|plugin| plugin.id == id) {
675 tracing::debug!(plugin = %id, ?directory, "shadowed by an earlier root");
676 continue;
677 }
678
679 let manifest_path = directory.join("manifest.toml");
680 let contents = match std::fs::read_to_string(&manifest_path) {
681 Ok(contents) => contents,
682 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
683 Err(error) => {
684 tracing::warn!(%error, ?manifest_path, "failed to read plugin manifest");
685 continue;
686 }
687 };
688
689 let manifest: Manifest = match toml::from_str(&contents) {
690 Ok(manifest) => manifest,
691 Err(error) => {
692 tracing::warn!(%error, ?manifest_path, "invalid plugin manifest");
693 continue;
694 }
695 };
696
697 tracing::info!(plugin = %id, keyword = ?manifest.keyword, "loaded plugin");
698 plugins.push(Plugin {
699 manifest,
700 directory,
701 id,
702 });
703 }
704 }
705
706 Self {
707 plugins,
708 disabled: std::collections::HashSet::new(),
709 keyword_overrides: std::collections::HashMap::new(),
710 }
711 }
712
713 pub fn replace_plugins(&mut self, discovered: Self) -> bool {
717 if self.plugins == discovered.plugins {
718 return false;
719 }
720 self.plugins = discovered.plugins;
721 true
722 }
723
724 pub fn set_disabled<I, S>(&mut self, ids: I)
726 where
727 I: IntoIterator<Item = S>,
728 S: Into<String>,
729 {
730 self.disabled = ids.into_iter().map(Into::into).collect();
731 }
732
733 pub fn set_keyword_overrides<I, K, V>(&mut self, overrides: I)
735 where
736 I: IntoIterator<Item = (K, V)>,
737 K: Into<String>,
738 V: Into<String>,
739 {
740 self.keyword_overrides = overrides
741 .into_iter()
742 .map(|(id, keyword)| (id.into(), keyword.into()))
743 .collect();
744 }
745
746 #[must_use]
749 pub fn effective_keyword<'a>(&'a self, plugin: &'a Plugin) -> Option<&'a str> {
750 match self.keyword_overrides.get(&plugin.id) {
751 Some(keyword) if keyword.is_empty() => None,
752 Some(keyword) => Some(keyword.as_str()),
753 None => plugin.manifest.keyword.as_deref(),
754 }
755 }
756
757 pub fn all(&self) -> impl Iterator<Item = (&Plugin, bool)> {
760 self.plugins
761 .iter()
762 .map(|plugin| (plugin, !self.disabled.contains(&plugin.id)))
763 }
764
765 #[must_use]
767 pub fn is_empty(&self) -> bool {
768 self.plugins.is_empty()
769 }
770
771 #[must_use]
774 pub fn get(&self, id: &str) -> Option<&Plugin> {
775 self.plugins
776 .iter()
777 .filter(|plugin| !self.disabled.contains(&plugin.id))
778 .find(|plugin| plugin.id == id)
779 }
780
781 pub async fn query(&self, text: &str) -> QueryResults {
786 let matching: Vec<_> = self
787 .plugins
788 .iter()
789 .filter(|plugin| !self.disabled.contains(&plugin.id))
790 .filter_map(|plugin| {
791 plugin
792 .match_query_as(self.effective_keyword(plugin), text)
793 .map(|query| (plugin, query))
794 })
795 .collect();
796
797 if matching.is_empty() {
798 return QueryResults::default();
799 }
800
801 let keyworded: Vec<_> = matching
804 .iter()
805 .filter(|(plugin, _)| self.effective_keyword(plugin).is_some())
806 .collect();
807
808 let selected: Vec<_> = if keyworded.is_empty() {
809 matching.iter().collect()
810 } else {
811 keyworded
812 };
813
814 let futures = selected.into_iter().map(|(plugin, query)| {
815 let deadline = plugin.manifest.timeout(self.effective_keyword(plugin));
816 plugin.query(query, deadline)
817 });
818
819 let mut results = QueryResults::default();
820 for (items, rerun) in futures::future::join_all(futures).await {
821 results.items.extend(items);
822 results.rerun = match (results.rerun, rerun) {
825 (Some(a), Some(b)) => Some(a.min(b)),
826 (a, b) => a.or(b),
827 };
828 }
829 results
830 }
831
832 #[must_use]
835 pub fn is_claimed(&self, text: &str) -> bool {
836 self.plugins
837 .iter()
838 .filter(|plugin| !self.disabled.contains(&plugin.id))
839 .any(|plugin| {
840 let keyword = self.effective_keyword(plugin);
841 keyword.is_some() && plugin.match_query_as(keyword, text).is_some()
842 })
843 }
844}
845
846#[derive(Debug, Default)]
848pub struct LintReport {
849 pub errors: Vec<String>,
851 pub warnings: Vec<String>,
853 pub items: usize,
855}
856
857impl LintReport {
858 #[must_use]
860 pub fn is_clean(&self) -> bool {
861 self.errors.is_empty()
862 }
863}
864
865pub async fn lint(directory: &Path, sample_query: &str) -> LintReport {
871 let mut report = LintReport::default();
872
873 let manifest_path = directory.join("manifest.toml");
874 let contents = match std::fs::read_to_string(&manifest_path) {
875 Ok(contents) => contents,
876 Err(error) => {
877 report
878 .errors
879 .push(format!("cannot read {}: {error}", manifest_path.display()));
880 return report;
881 }
882 };
883
884 let manifest: Manifest = match toml::from_str(&contents) {
885 Ok(manifest) => manifest,
886 Err(error) => {
887 report
888 .errors
889 .push(format!("manifest does not parse: {error}"));
890 return report;
891 }
892 };
893
894 if let Some(keyword) = manifest.keyword.as_deref() {
895 if !is_keyword(keyword) {
896 report.errors.push(format!(
897 "keyword {keyword:?} must be one non-empty word — it is matched \
898 up to the first space of the query"
899 ));
900 }
901 } else {
902 report.warnings.push(
903 "no keyword: the plugin runs on every keystroke and must answer \
904 well inside 180 ms"
905 .to_owned(),
906 );
907 }
908
909 if let Some(ms) = manifest.timeout_ms {
910 let applied = manifest.timeout(manifest.keyword.as_deref()).as_millis();
911 if u128::from(ms) != applied {
912 let why = if manifest.keyword.is_none() && applied == QUERY_TIMEOUT.as_millis() {
913 " — only a keyworded plugin may take longer than the interactive default"
914 } else {
915 ""
916 };
917 report
918 .warnings
919 .push(format!("timeout_ms = {ms} is clamped to {applied} ms{why}"));
920 }
921 }
922
923 let check_command = |report: &mut LintReport, label: &str, command: &str| {
924 let path = if Path::new(command).is_absolute() {
925 PathBuf::from(command)
926 } else {
927 directory.join(command)
928 };
929 if !path.is_file() {
930 report
931 .errors
932 .push(format!("{label} command {} does not exist", path.display()));
933 return;
934 }
935 #[cfg(unix)]
936 {
937 use std::os::unix::fs::PermissionsExt;
938 let executable = path
939 .metadata()
940 .map(|meta| meta.permissions().mode() & 0o111 != 0)
941 .unwrap_or(false);
942 if !executable {
943 report.errors.push(format!(
944 "{label} command {} is not executable (chmod +x)",
945 path.display()
946 ));
947 }
948 }
949 };
950 check_command(&mut report, "query", &manifest.query);
951 if let Some(activate) = manifest.activate.as_deref() {
952 check_command(&mut report, "activate", activate);
953 }
954 if !report.errors.is_empty() {
955 return report;
956 }
957
958 let plugin = Plugin {
960 manifest,
961 directory: directory.to_path_buf(),
962 id: directory
963 .file_name()
964 .and_then(|name| name.to_str())
965 .unwrap_or("plugin")
966 .to_owned(),
967 };
968 let program = plugin.resolve(&plugin.manifest.query);
969 let stdout = match run_query(
970 &program,
971 &plugin.directory,
972 sample_query,
973 plugin.manifest.timeout(plugin.manifest.keyword.as_deref()),
974 )
975 .await
976 {
977 Ok(stdout) => stdout,
978 Err(error) => {
979 report.errors.push(format!("query command {error}"));
980 return report;
981 }
982 };
983
984 match serde_json::from_slice::<PluginResponse>(&stdout) {
985 Ok(response) => {
986 report.items = response.items.len();
987 if response.items.is_empty() {
988 report
989 .warnings
990 .push("sample query produced no items".to_owned());
991 }
992 for item in &response.items {
993 if item.uid.is_none() {
994 report.warnings.push(format!(
995 "item {:?} has no uid — without one, usage ranking \
996 cannot learn it",
997 item.title
998 ));
999 }
1000 }
1001 }
1002 Err(error) => {
1003 report
1004 .errors
1005 .push(format!("output is not valid script-filter JSON: {error}"));
1006 }
1007 }
1008
1009 report
1010}
1011
1012#[must_use]
1019pub fn scaffold_keyword(name: &str) -> Option<String> {
1020 let keyword = name
1021 .to_lowercase()
1022 .split_whitespace()
1023 .collect::<Vec<_>>()
1024 .join("-");
1025 let usable =
1026 !keyword.is_empty() && !keyword.starts_with('.') && !keyword.contains(['/', '\\', '\0']);
1027 usable.then_some(keyword)
1028}
1029
1030pub fn scaffold(root: &Path, name: &str) -> std::io::Result<(PathBuf, String)> {
1046 let Some(keyword) = scaffold_keyword(name) else {
1047 return Err(std::io::Error::new(
1048 std::io::ErrorKind::InvalidInput,
1049 format!("{name:?} does not make a plugin directory name"),
1050 ));
1051 };
1052 let directory = root.join(&keyword);
1053 if directory.exists() {
1054 return Err(std::io::Error::new(
1055 std::io::ErrorKind::AlreadyExists,
1056 format!("{} already exists", directory.display()),
1057 ));
1058 }
1059 std::fs::create_dir_all(&directory)?;
1060
1061 let toml_string = |text: &str| toml::Value::String(text.to_owned()).to_string();
1062 std::fs::write(
1063 directory.join("manifest.toml"),
1064 format!(
1065 "name = {}\n\
1066 description = \"Describe what this plugin searches\"\n\
1067 keyword = {}\n\
1068 query = \"./search.sh\"\n\
1069 # activate = \"./open.sh\" # separate action command, optional\n\
1070 icon = \"system-search-symbolic\"\n\
1071 # timeout_ms = 1000 # up to 3000 for slow keyworded plugins\n",
1072 toml_string(name),
1073 toml_string(&keyword),
1074 ),
1075 )?;
1076
1077 let shell_name = name.replace('\'', r"'\''");
1079 let script = directory.join("search.sh");
1080 std::fs::write(
1081 &script,
1082 format!(
1083 "#!/bin/sh\n\
1084 # jump runs this with the query as $1 and reads script-filter\n\
1085 # JSON from stdout. Without an `activate` command in the\n\
1086 # manifest, activation re-runs this script as: search.sh\n\
1087 # --activate <arg>.\n\
1088 if [ \"$1\" = \"--activate\" ]; then\n\
1089 \t# \"$2\" is the chosen item's arg.\n\
1090 \texit 0\n\
1091 fi\n\
1092 \n\
1093 name='{shell_name}'\n\
1094 query=\"$1\"\n\
1095 # Text going into a JSON string needs its backslashes and quotes\n\
1096 # escaped.\n\
1097 json() {{ printf '%s' \"$1\" | sed 's/[\\\\\"]/\\\\&/g'; }}\n\
1098 printf '{{\"items\":[{{\"uid\":\"hello\",\"title\":\"Hello %s\",\
1099 \"subtitle\":\"%s\",\"arg\":\"%s\"}}]}}' \
1100 \"$(json \"${{query:-world}}\")\" \"$(json \"$name\")\" \"$(json \"$query\")\"\n"
1101 ),
1102 )?;
1103 #[cfg(unix)]
1104 {
1105 use std::os::unix::fs::PermissionsExt;
1106 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))?;
1107 }
1108 Ok((directory, keyword))
1109}
1110
1111#[cfg(test)]
1112mod tests {
1113 use super::*;
1114
1115 fn plugin(keyword: Option<&str>) -> Plugin {
1116 Plugin {
1117 manifest: Manifest {
1118 name: "Test".to_owned(),
1119 description: String::new(),
1120 keyword: keyword.map(ToOwned::to_owned),
1121 query: "./q".to_owned(),
1122 activate: None,
1123 icon: None,
1124 timeout_ms: None,
1125 },
1126 directory: PathBuf::from("/tmp"),
1127 id: "test".to_owned(),
1128 }
1129 }
1130
1131 #[test]
1132 fn keywordless_plugin_sees_whole_query() {
1133 assert_eq!(plugin(None).match_query("hello there"), Some("hello there"));
1134 }
1135
1136 #[test]
1137 fn keyword_is_stripped() {
1138 assert_eq!(plugin(Some("gh")).match_query("gh jump"), Some("jump"));
1139 }
1140
1141 #[test]
1142 fn bare_keyword_yields_empty_query() {
1143 assert_eq!(plugin(Some("gh")).match_query("gh"), Some(""));
1144 }
1145
1146 #[test]
1147 fn a_keyword_is_one_non_empty_word() {
1148 assert!(is_keyword("gh"));
1149 assert!(is_keyword("=="));
1150 for bad in ["", "gh x", " gh", "gh\t"] {
1151 assert!(!is_keyword(bad), "{bad:?}");
1152 }
1153 }
1154
1155 #[test]
1156 fn keyword_requires_word_boundary() {
1157 assert_eq!(plugin(Some("gh")).match_query("ghost"), None);
1159 }
1160
1161 #[test]
1162 fn non_matching_keyword_is_skipped() {
1163 assert_eq!(plugin(Some("gh")).match_query("firefox"), None);
1164 }
1165
1166 #[test]
1167 fn timeout_is_clamped_to_the_ceiling() {
1168 let mut manifest = plugin(None).manifest;
1169 let keyword = Some("gh");
1170 assert_eq!(manifest.timeout(keyword), Duration::from_millis(180));
1171
1172 manifest.timeout_ms = Some(60_000);
1173 assert_eq!(manifest.timeout(keyword), Duration::from_millis(3000));
1174
1175 manifest.timeout_ms = Some(1);
1176 assert_eq!(manifest.timeout(keyword), Duration::from_millis(50));
1177 }
1178
1179 #[test]
1180 fn only_a_keyworded_plugin_may_raise_its_deadline() {
1181 let mut manifest = plugin(None).manifest;
1184 manifest.timeout_ms = Some(3000);
1185 assert_eq!(manifest.timeout(None), Duration::from_millis(180));
1186 assert_eq!(manifest.timeout(Some("gh")), Duration::from_millis(3000));
1187
1188 manifest.timeout_ms = Some(100);
1189 assert_eq!(manifest.timeout(None), Duration::from_millis(100));
1190 }
1191
1192 #[tokio::test(flavor = "multi_thread")]
1193 async fn the_host_holds_an_always_on_plugin_to_the_interactive_deadline() {
1194 let root = tempfile::tempdir().expect("tempdir");
1197 let mut slow = scripted(
1198 root.path(),
1199 "#!/bin/sh\nsleep 0.5\necho '{\"items\":[{\"title\":\"late\"}]}'\n",
1200 Some(3000),
1201 );
1202 slow.id = "slow".to_owned();
1203 let mut host = PluginHost {
1204 plugins: vec![slow],
1205 ..PluginHost::default()
1206 };
1207 assert_eq!(host.query("t x").await.items.len(), 1);
1208
1209 host.set_keyword_overrides([("slow", "")]);
1214 assert!(host.query("x").await.items.is_empty());
1215 }
1216
1217 #[test]
1218 fn uid_and_autocomplete_parse_from_alfred_json() {
1219 let response: PluginResponse = serde_json::from_str(
1220 r#"{"items":[
1221 {"uid":"repo","title":"jump","arg":"https://example.com/?q=jump",
1222 "autocomplete":"gh jump ", "icon":{"path":"/tmp/icon.png"}},
1223 {"title":"plain"}
1224 ]}"#,
1225 )
1226 .expect("alfred json parses");
1227
1228 assert_eq!(response.items[0].uid.as_deref(), Some("repo"));
1229 assert_eq!(response.items[0].autocomplete.as_deref(), Some("gh jump "));
1230 assert_eq!(response.items[1].uid, None);
1231 }
1232
1233 #[test]
1234 fn rerun_parses_and_is_clamped_sanely() {
1235 let parse = |json: &str| -> Option<f64> {
1236 serde_json::from_str::<PluginResponse>(json)
1237 .expect("json parses")
1238 .rerun
1239 };
1240 assert_eq!(parse(r#"{"items":[]}"#), None);
1241 assert_eq!(parse(r#"{"items":[],"rerun":1.5}"#), Some(1.5));
1242
1243 let clamp = |seconds: f64| seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end());
1245 assert_eq!(clamp(0.1), 0.5);
1246 assert_eq!(clamp(60.0), 5.0);
1247 assert_eq!(clamp(2.0), 2.0);
1248 }
1249
1250 #[test]
1251 fn mods_normalise_inherit_and_override() {
1252 let response: PluginResponse = serde_json::from_str(
1253 r#"{"variables":{"SESSION":"abc"},
1254 "items":[{"title":"repo","arg":"main",
1255 "mods":{
1256 "cmd":{"subtitle":"Open on the web","arg":"https://example.com"},
1257 "alt":{"subtitle":"Copy","variables":{"MODE":"copy"}},
1258 "shift":{"subtitle":"Off","valid":false},
1259 "hyper":{"subtitle":"Unbindable"}
1260 }}]}"#,
1261 )
1262 .expect("alfred json parses");
1263
1264 let item = &response.items[0];
1265 assert_eq!(normalise_modifier("cmd"), Some("super"));
1266 assert_eq!(normalise_modifier("Control"), Some("ctrl"));
1267 assert_eq!(normalise_modifier("hyper"), None);
1268
1269 let usable: Vec<&String> = item
1272 .mods
1273 .iter()
1274 .filter(|(_, m)| m.valid)
1275 .filter(|(name, _)| normalise_modifier(name).is_some())
1276 .map(|(name, _)| name)
1277 .collect();
1278 assert_eq!(usable.len(), 2);
1279
1280 assert_eq!(item.mods["alt"].arg, None);
1282 assert_eq!(item.mods["cmd"].arg.as_deref(), Some("https://example.com"));
1283 }
1284
1285 #[test]
1286 fn item_variables_win_over_response_variables() {
1287 let response: PluginResponse = serde_json::from_str(
1288 r#"{"variables":{"SESSION":"abc","MODE":"list"},
1289 "items":[{"title":"one","variables":{"MODE":"open"}},
1290 {"title":"two"}]}"#,
1291 )
1292 .expect("alfred json parses");
1293
1294 let merged = merge_variables(&response.variables, response.items[0].variables.clone());
1295 assert_eq!(
1296 merged,
1297 vec![
1298 ("MODE".to_owned(), "open".to_owned()),
1299 ("SESSION".to_owned(), "abc".to_owned()),
1300 ]
1301 );
1302
1303 let inherited = merge_variables(&response.variables, response.items[1].variables.clone());
1305 assert_eq!(inherited.len(), 2);
1306 assert!(inherited.contains(&("MODE".to_owned(), "list".to_owned())));
1307 }
1308
1309 #[tokio::test(flavor = "multi_thread")]
1310 async fn scaffold_produces_a_plugin_that_lints_clean() {
1311 let root = tempfile::tempdir().expect("tempdir");
1312
1313 let (directory, keyword) = scaffold(root.path(), "Demo").expect("scaffold succeeds");
1314 assert_eq!(directory, root.path().join("demo"));
1315 assert_eq!(keyword, "demo");
1316 assert!(scaffold(root.path(), "Demo").is_err());
1318
1319 let report = lint(&directory, "hello").await;
1320 assert!(report.is_clean(), "unexpected errors: {:?}", report.errors);
1321 assert_eq!(report.items, 1);
1322 assert!(report.warnings.is_empty(), "{:?}", report.warnings);
1323 }
1324
1325 #[tokio::test(flavor = "multi_thread")]
1326 async fn a_scaffold_name_is_data_not_syntax() {
1327 let root = tempfile::tempdir().expect("tempdir");
1330 let name = r#"It's "100%" done"#;
1331 let (directory, keyword) = scaffold(root.path(), name).expect("scaffold succeeds");
1332 assert_eq!(keyword, r#"it's-"100%"-done"#);
1333
1334 let manifest: Manifest = toml::from_str(
1335 &std::fs::read_to_string(directory.join("manifest.toml")).expect("manifest"),
1336 )
1337 .expect("the manifest parses");
1338 assert_eq!(manifest.name, name);
1339
1340 let output = std::process::Command::new(directory.join("search.sh"))
1341 .arg(r#"say "hi" \"#)
1342 .output()
1343 .expect("the script runs");
1344 let response: serde_json::Value =
1345 serde_json::from_slice(&output.stdout).expect("the output is JSON");
1346 let item = &response["items"][0];
1347 assert_eq!(item["subtitle"], name);
1348 assert_eq!(item["title"], r#"Hello say "hi" \"#);
1349 }
1350
1351 #[test]
1352 fn a_scaffold_cannot_name_a_directory_outside_the_root() {
1353 for name in ["../x", "a/b", ".hidden", " ", ""] {
1354 assert_eq!(scaffold_keyword(name), None, "{name:?}");
1355 }
1356 assert_eq!(scaffold_keyword("My Plugin").as_deref(), Some("my-plugin"));
1357 let root = tempfile::tempdir().expect("tempdir");
1358 let error = scaffold(&root.path().join("plugins"), "../x").expect_err("refused");
1359 assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
1360 assert!(!root.path().join("x").exists());
1361 }
1362
1363 #[tokio::test(flavor = "multi_thread")]
1364 async fn lint_reports_missing_and_broken_pieces() {
1365 let root = tempfile::tempdir().expect("tempdir");
1366
1367 let report = lint(root.path(), "x").await;
1369 assert!(!report.is_clean());
1370
1371 let directory = root.path().join("broken");
1373 std::fs::create_dir_all(&directory).expect("dir");
1374 std::fs::write(
1375 directory.join("manifest.toml"),
1376 "name = \"Broken\"\nkeyword = \"two words\"\nquery = \"./missing.sh\"\n",
1377 )
1378 .expect("manifest");
1379 let report = lint(&directory, "x").await;
1380 assert_eq!(report.errors.len(), 2, "{:?}", report.errors);
1381 }
1382
1383 fn scripted(root: &Path, script: &str, timeout_ms: Option<u64>) -> Plugin {
1385 use std::os::unix::fs::PermissionsExt;
1386
1387 let path = root.join("q");
1388 std::fs::write(&path, script).expect("script");
1389 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("chmod");
1390 let mut plugin = plugin(Some("t"));
1391 plugin.directory = root.to_path_buf();
1392 plugin.manifest.timeout_ms = timeout_ms;
1393 plugin
1394 }
1395
1396 fn alive(pid: u32) -> bool {
1398 std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| {
1399 stat.rsplit(") ")
1400 .next()
1401 .is_some_and(|rest| !rest.starts_with('Z'))
1402 })
1403 }
1404
1405 #[tokio::test(flavor = "multi_thread")]
1406 async fn oversized_output_is_refused_without_waiting_for_the_deadline() {
1407 let root = tempfile::tempdir().expect("tempdir");
1411 let plugin = scripted(
1412 root.path(),
1413 "#!/bin/sh\nhead -c 2000000 /dev/zero\nsleep 5\n",
1414 Some(3000),
1415 );
1416
1417 let started = std::time::Instant::now();
1418 let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
1419 assert!(items.is_empty());
1420 assert!(
1421 started.elapsed() < Duration::from_millis(1500),
1422 "took {:?}: output was buffered until the deadline",
1423 started.elapsed()
1424 );
1425 }
1426
1427 #[tokio::test(flavor = "multi_thread")]
1428 async fn an_overrunning_plugin_is_killed_with_its_children() {
1429 let root = tempfile::tempdir().expect("tempdir");
1437 let plugin = scripted(
1438 root.path(),
1439 "#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
1440 Some(1000),
1441 );
1442
1443 let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
1444 assert!(items.is_empty());
1445
1446 assert!(
1447 !outlives(&root.path().join("child.pid")).await,
1448 "the plugin's child outlived the deadline"
1449 );
1450 }
1451
1452 async fn outlives(pid_file: &Path) -> bool {
1456 let pid: u32 = std::fs::read_to_string(pid_file)
1457 .expect("the script recorded its child")
1458 .trim()
1459 .parse()
1460 .expect("pid");
1461 let deadline = std::time::Instant::now() + Duration::from_secs(2);
1462 while alive(pid) && std::time::Instant::now() < deadline {
1463 tokio::time::sleep(Duration::from_millis(20)).await;
1464 }
1465 let survived = alive(pid);
1466 if survived {
1467 let _ = std::process::Command::new("kill")
1468 .args(["-KILL", &pid.to_string()])
1469 .status();
1470 }
1471 survived
1472 }
1473
1474 #[tokio::test(flavor = "multi_thread")]
1475 async fn an_abandoned_query_is_killed_with_its_children() {
1476 let root = tempfile::tempdir().expect("tempdir");
1479 let plugin = scripted(
1480 root.path(),
1481 "#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
1482 Some(3000),
1483 );
1484 let pid_file = root.path().join("child.pid");
1485
1486 let running = tokio::spawn(async move {
1487 let deadline = plugin.manifest.timeout(Some("t"));
1488 plugin.query("x", deadline).await
1489 });
1490 let started = std::time::Instant::now();
1491 let recorded =
1492 |path: &Path| std::fs::read_to_string(path).is_ok_and(|pid| pid.ends_with('\n'));
1493 while !recorded(&pid_file) && started.elapsed() < Duration::from_secs(2) {
1494 tokio::time::sleep(Duration::from_millis(10)).await;
1495 }
1496 running.abort();
1497 assert!(running.await.is_err_and(|error| error.is_cancelled()));
1498
1499 assert!(
1500 !outlives(&pid_file).await,
1501 "the abandoned query's child kept running"
1502 );
1503 }
1504
1505 #[tokio::test(flavor = "multi_thread")]
1506 async fn lint_applies_the_launchers_output_cap() {
1507 let root = tempfile::tempdir().expect("tempdir");
1510 let directory = root.path().join("big");
1511 std::fs::create_dir_all(&directory).expect("dir");
1512 std::fs::write(
1513 directory.join("manifest.toml"),
1514 "name = \"Big\"\nkeyword = \"big\"\nquery = \"./q\"\n",
1515 )
1516 .expect("manifest");
1517 scripted(
1518 &directory,
1519 "#!/bin/sh\nprintf '{\"items\":[{\"uid\":\"a\",\"title\":\"'\n\
1520 head -c 1100000 /dev/zero | tr '\\0' a\nprintf '\"}]}'\n",
1521 None,
1522 );
1523
1524 let report = lint(&directory, "x").await;
1525 assert!(!report.is_clean(), "oversized output linted clean");
1526 }
1527
1528 #[test]
1529 fn discovery_walks_roots_in_order_and_user_shadows_system() {
1530 let user = tempfile::tempdir().expect("tempdir");
1531 let system = tempfile::tempdir().expect("tempdir");
1532
1533 let write = |root: &std::path::Path, id: &str, name: &str| {
1534 let dir = root.join(id);
1535 std::fs::create_dir_all(&dir).expect("plugin dir");
1536 std::fs::write(
1537 dir.join("manifest.toml"),
1538 format!("name = \"{name}\"\nquery = \"./q\"\n"),
1539 )
1540 .expect("manifest");
1541 };
1542
1543 write(user.path(), "shared", "User copy");
1544 write(user.path(), "mine", "User only");
1545 write(system.path(), "shared", "System copy");
1546 write(system.path(), "packaged", "System only");
1547 std::fs::create_dir_all(system.path().join("junk")).expect("junk dir");
1549
1550 let host =
1551 PluginHost::discover_in(&[user.path().to_path_buf(), system.path().to_path_buf()]);
1552
1553 let mut ids: Vec<&str> = host.all().map(|(plugin, _)| plugin.id.as_str()).collect();
1554 ids.sort_unstable();
1555 assert_eq!(ids, ["mine", "packaged", "shared"]);
1556
1557 let shared = host.get("shared").expect("shared plugin");
1559 assert_eq!(shared.manifest.name, "User copy");
1560 }
1561
1562 #[test]
1563 fn a_fresh_discovery_keeps_the_users_settings() {
1564 let root = tempfile::tempdir().expect("tempdir");
1567 let write = |id: &str| {
1568 let dir = root.path().join(id);
1569 std::fs::create_dir_all(&dir).expect("plugin dir");
1570 std::fs::write(
1571 dir.join("manifest.toml"),
1572 "name = \"P\"\nkeyword = \"p\"\nquery = \"./q\"\n",
1573 )
1574 .expect("manifest");
1575 };
1576 write("old");
1577 let roots = [root.path().to_path_buf()];
1578 let mut host = PluginHost::discover_in(&roots);
1579 host.set_disabled(["old"]);
1580 host.set_keyword_overrides([("new", "n")]);
1581
1582 assert!(!host.replace_plugins(PluginHost::discover_in(&roots)));
1583
1584 write("new");
1585 assert!(host.replace_plugins(PluginHost::discover_in(&roots)));
1586 assert!(
1587 host.get("old").is_none(),
1588 "the disabled plugin came back on"
1589 );
1590 let new = host.get("new").expect("the new plugin was picked up");
1591 assert_eq!(host.effective_keyword(new), Some("n"));
1592 }
1593
1594 #[test]
1595 fn keyword_overrides_replace_and_remove_the_manifest_keyword() {
1596 let mut host = PluginHost {
1597 plugins: vec![plugin(Some("gh"))],
1598 disabled: std::collections::HashSet::new(),
1599 keyword_overrides: std::collections::HashMap::new(),
1600 };
1601
1602 assert!(host.is_claimed("gh jump"));
1604
1605 host.set_keyword_overrides([("test", "g")]);
1607 assert!(host.is_claimed("g jump"));
1608 assert!(!host.is_claimed("gh jump"));
1609
1610 host.set_keyword_overrides([("test", "")]);
1613 assert!(!host.is_claimed("g jump"));
1614 assert!(!host.is_claimed("gh jump"));
1615 let plugin = &host.plugins[0];
1616 assert_eq!(host.effective_keyword(plugin), None);
1617
1618 host.set_keyword_overrides([("other", "x")]);
1620 assert!(host.is_claimed("gh jump"));
1621 }
1622
1623 #[test]
1624 fn disabled_plugins_neither_run_nor_activate() {
1625 let mut host = PluginHost {
1626 plugins: vec![plugin(Some("gh"))],
1627 disabled: std::collections::HashSet::new(),
1628 keyword_overrides: std::collections::HashMap::new(),
1629 };
1630
1631 assert!(host.is_claimed("gh jump"));
1632 assert!(host.get("test").is_some());
1633
1634 host.set_disabled(["test"]);
1635 assert!(!host.is_claimed("gh jump"));
1636 assert!(host.get("test").is_none());
1637 assert_eq!(host.all().map(|(_, on)| on).collect::<Vec<_>>(), [false]);
1639 }
1640}