1use std::process::Stdio;
18
19use serde::{Deserialize, Serialize};
20
21use tokio::process::Command;
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct Link {
26 pub name: String,
28 #[serde(default)]
31 pub keyword: String,
32 pub template: String,
34}
35
36impl Link {
37 #[must_use]
43 pub fn match_query<'a>(&self, query: &'a str) -> Option<&'a str> {
44 if self.keyword.is_empty() {
45 return None;
46 }
47 let rest = query.strip_prefix(self.keyword.as_str())?;
48 match rest.strip_prefix(' ') {
49 Some(rest) => Some(rest.trim_start()),
50 None if rest.is_empty() => Some(""),
51 None => None,
52 }
53 }
54
55 #[must_use]
57 pub fn url_for(&self, query: &str) -> String {
58 self.template.replace("{query}", &encode_component(query))
59 }
60}
61
62#[must_use]
68pub fn encode_component(text: &str) -> String {
69 let mut encoded = String::with_capacity(text.len());
70 for byte in text.bytes() {
71 match byte {
72 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
73 encoded.push(byte as char);
74 }
75 _ => {
76 encoded.push('%');
78 encoded.push(
79 char::from_digit(u32::from(byte >> 4), 16)
80 .unwrap_or('0')
81 .to_ascii_uppercase(),
82 );
83 encoded.push(
84 char::from_digit(u32::from(byte & 0xf), 16)
85 .unwrap_or('0')
86 .to_ascii_uppercase(),
87 );
88 }
89 }
90 }
91 encoded
92}
93
94pub fn open(url: &str) {
96 let result = Command::new("xdg-open")
97 .arg(url)
98 .stdin(Stdio::null())
99 .stdout(Stdio::null())
100 .stderr(Stdio::null())
101 .spawn();
102
103 match result {
104 Ok(mut child) => {
105 tokio::spawn(async move {
106 let _ = child.wait().await;
107 });
108 }
109 Err(error) => tracing::error!(%error, url, "could not open URL"),
110 }
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116
117 fn link(keyword: &str, template: &str) -> Link {
118 Link {
119 name: "Test".to_owned(),
120 keyword: keyword.to_owned(),
121 template: template.to_owned(),
122 }
123 }
124
125 #[test]
126 fn keyword_claims_with_word_boundary() {
127 let yt = link("yt", "https://youtube.com/results?search_query={query}");
128 assert_eq!(yt.match_query("yt cats"), Some("cats"));
129 assert_eq!(yt.match_query("yt"), Some(""));
130 assert_eq!(yt.match_query("youtube"), None);
131 assert_eq!(yt.match_query("firefox"), None);
132 }
133
134 #[test]
135 fn fallbacks_have_no_keyword_and_claim_nothing() {
136 let ddg = link("", "https://duckduckgo.com/?q={query}");
137 assert_eq!(ddg.match_query("anything"), None);
138 }
139
140 #[test]
141 fn query_is_encoded_into_the_template() {
142 let ddg = link("", "https://duckduckgo.com/?q={query}");
143 assert_eq!(
144 ddg.url_for("caffè & crème"),
145 "https://duckduckgo.com/?q=caff%C3%A8%20%26%20cr%C3%A8me"
146 );
147 }
148
149 #[test]
150 fn template_without_placeholder_is_left_alone() {
151 let home = link("home", "https://example.com/dashboard");
152 assert_eq!(home.url_for("ignored"), "https://example.com/dashboard");
153 }
154
155 #[test]
156 fn unreserved_characters_pass_through() {
157 assert_eq!(encode_component("abc-XYZ_0.9~"), "abc-XYZ_0.9~");
158 assert_eq!(encode_component("a/b?c=d"), "a%2Fb%3Fc%3Dd");
159 }
160}