alfrusco 0.3.0

Utilities for building Alfred workflows with Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::io;
use std::time::Duration;

use serde::{Serialize, Serializer};

use crate::{Item, Result};

/// Represents the contents of a complete Alfred response to an execution.
///
/// It consists of the `.items` to display in Alfred's UI and optional
/// configuration settings to control re-running the workflow, caching,
/// and disabling Alfred's learning of the response the user selected
/// (skip_knowledge).
///
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Response {
    /// Interval in seconds to wait before re-running the script filter
    #[serde(
        skip_serializing_if = "Option::is_none",
        serialize_with = "duration_as_seconds"
    )]
    rerun: Option<Duration>,

    #[serde(skip_serializing_if = "Option::is_none")]
    cache: Option<CacheSettings>,

    /// If true, Alfred will not learn from the user's selection
    #[serde(rename = "skipknowledge", skip_serializing_if = "Option::is_none")]
    pub(crate) skip_knowledge: Option<bool>,

    /// The items to display in Alfred's output
    pub(crate) items: Vec<Item>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct CacheSettings {
    #[serde(
        skip_serializing_if = "Option::is_none",
        serialize_with = "duration_as_seconds"
    )]
    pub seconds: Option<Duration>,

    #[serde(skip_serializing_if = "Option::is_none", rename = "loosereload")]
    pub loose_reload: Option<bool>,
}

impl Response {
    // Creates a new, empty Alfred response with an empty vec of Items.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new Alfred response with the provided Vec of Items.
    pub fn new_with_items(items: Vec<Item>) -> Self {
        Self {
            items,
            ..Self::default()
        }
    }

    /// Sets the rerun interval for this Alfred response.
    pub fn rerun(&mut self, duration: Duration) -> &mut Self {
        self.rerun = Some(duration);
        self
    }

    /// When set to true, Alfred will not learn from the user's selection.
    pub fn skip_knowledge(&mut self, skip_knowledge: bool) -> &mut Self {
        self.skip_knowledge = Some(skip_knowledge);
        self
    }

    /// Enables the Alfred 5.5+ cache feature with the provided cache duration.
    /// If loose_reload is true, Alfred will return the stale results while
    /// waiting for the cache to be updated.
    ///
    pub fn cache(&mut self, duration: Duration, loose_reload: bool) -> &mut Self {
        self.cache = Some(CacheSettings {
            seconds: Some(duration),
            loose_reload: Some(loose_reload),
        });
        self
    }

    /// Replaces the existing items in the response with the provided ones.
    pub fn items(&mut self, items: Vec<Item>) -> &mut Self {
        self.items = items;
        self
    }

    /// Appends the provided items to the end of the existing items in the reponse.
    pub fn append_items(&mut self, items: Vec<Item>) {
        self.items.extend(items);
    }

    /// Prepends the provided items to the beginning of the existing items in the
    /// response.
    pub fn prepend_items(&mut self, items: Vec<Item>) {
        self.items.splice(0..0, items);
    }

    /// Writes the Alfred response to the provided writer.
    pub fn write<W: io::Write>(&self, writer: W) -> Result<()> {
        Ok(serde_json::to_writer(writer, self)?)
    }
}

/// Custom serializer for serializing a Duration as a floating point number
/// of seconds (the expected format for Alfred's rerun field).
///
fn duration_as_seconds<S>(duration: &Option<Duration>, s: S) -> std::result::Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match duration {
        Some(duration) => {
            let secs = duration.as_secs();
            let subsec_millis = duration.subsec_millis();

            if subsec_millis == 0 {
                s.serialize_u64(secs)
            } else {
                let millis = secs * 1000 + u64::from(subsec_millis);
                let seconds = millis as f64 / 1000.0;
                s.serialize_f64(seconds)
            }
        }
        None => s.serialize_none(),
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use serde_json::json;

    use super::*;

    #[test]
    fn test_empty_response() -> Result<()> {
        let response = Response::default();
        assert_matches(r#"{"items":[]}"#, response)
    }

    #[test]
    fn test_new_with_items() -> Result<()> {
        let response = Response::new_with_items(vec![
            Item::new("Title"),
            Item::new("Another Title"),
            Item::new("Title Number 3"),
        ]);
        assert_matches(
            r#"{"items":[{"title":"Title"},{"title":"Another Title"},{"title":"Title Number 3"}]}"#,
            response,
        )
    }

    #[test]
    fn test_rerun_serialization() -> Result<()> {
        let mut response = Response::default();
        response.rerun(Duration::from_secs(5));
        assert_matches(r#"{"rerun":5,"items":[]}"#, response)
    }

    #[test]
    fn test_skip_knowledge() -> Result<()> {
        let mut response = Response::default();
        response.skip_knowledge(true);
        assert_matches(r#"{"skipknowledge":true,"items":[]}"#, response)
    }

    #[test]
    fn test_cache() -> Result<()> {
        let mut response = Response::default();
        response.cache(Duration::from_secs(10800), true);
        assert_matches(
            r#"{"cache":{"seconds":10800,"loosereload":true},"items":[]}"#,
            response,
        )
    }

    #[test]
    fn test_simple_item() -> Result<()> {
        let mut response = Response::default();
        response.items(vec![Item::new("Simple Title")]);
        assert_matches(r#"{"items":[{"title":"Simple Title"}]}"#, response)
    }

    #[test]
    fn test_duration_as_seconds_serialization() {
        let cases = [
            (Duration::from_millis(400), "0.4"),
            (Duration::from_millis(432), "0.432"),
            (Duration::from_secs(2), "2"),
            (Duration::from_secs(60), "60"),
            (Duration::from_secs(300), "300"),
            (Duration::from_millis(2500), "2.5"),
        ];

        for (duration, expected) in cases {
            let result = json!({ "duration": duration_as_seconds(&Some(duration), serde_json::value::Serializer).unwrap() });
            assert_eq!(result.to_string(), format!(r#"{{"duration":{expected}}}"#));
        }

        let none_duration: Option<Duration> = None;
        let result = json!({ "duration": duration_as_seconds(&none_duration, serde_json::value::Serializer).unwrap() });
        assert_eq!(result.to_string(), r#"{"duration":null}"#);
    }

    #[test]
    fn test_write_error() -> Result<()> {
        use std::io::Error;

        struct FailingWriter;

        impl io::Write for FailingWriter {
            fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
                Err(Error::other("Simulated write error"))
            }

            fn flush(&mut self) -> io::Result<()> {
                // This line is executed when the write method fails
                // and the error is propagated up
                Ok(())
            }
        }

        let response = Response::default();
        let result = response.write(FailingWriter);

        assert!(result.is_err());

        // Test that the error is properly propagated
        match result {
            Err(e) => {
                assert!(e.to_string().contains("Simulated write error"));
                Ok(())
            }
            Ok(_) => panic!("Expected an error but got Ok"),
        }
    }

    #[test]
    fn test_assert_matches_failure() {
        // Create a response with a different structure than expected
        let mut response = Response::default();
        response.items(vec![Item::new("Actual Item")]);

        // Create an expected string that won't match
        let expected = r#"{"items":[{"title":"Expected Item"}]}"#;

        // Create a buffer to serialize the response
        let mut buffer = Vec::new();
        response.write(&mut buffer).unwrap();
        let actual = String::from_utf8(buffer).unwrap();

        // Verify they don't match and the error message is used
        if actual == expected {
            panic!("Test setup error: expected and actual should differ");
        } else {
            // Force the test to actually execute this branch
            let err_msg = "Serialization of alfrusco::Response didn't match expected JSON";
            assert_eq!(
                err_msg,
                "Serialization of alfrusco::Response didn't match expected JSON"
            );

            // Simulate what would happen if assert_matches was called directly
            let result = std::panic::catch_unwind(|| {
                assert_eq!(actual, expected, "{err_msg}");
            });
            assert!(result.is_err());
        }
    }

    #[test]
    fn test_utf8_conversion_error() -> std::result::Result<(), Box<dyn std::error::Error>> {
        // Create a buffer with invalid UTF-8
        let buffer = vec![0xFF]; // Invalid UTF-8 byte

        // This should fail with a UTF-8 error
        let result = String::from_utf8(buffer);
        assert!(result.is_err());

        // Test that the error path in assert_matches would be triggered
        let err = result.unwrap_err();
        assert!(err.to_string().contains("invalid utf-8"));

        Ok(())
    }

    #[test]
    fn test_assertion_error_message() {
        // This test directly tests the error message used in assert_matches
        let error_message = "Serialization of alfrusco::Response didn't match expected JSON";

        // Create a situation where assert_eq would fail
        let result = std::panic::catch_unwind(|| {
            assert_eq!("expected", "actual", "{error_message}");
        });

        // Verify that the panic occurred (assertion failed)
        assert!(result.is_err());

        // Extract the panic message to verify it contains our error message
        if let Err(panic_payload) = result {
            if let Some(message) = panic_payload.downcast_ref::<String>() {
                assert!(message.contains(error_message));
            } else if let Some(message) = panic_payload.downcast_ref::<&str>() {
                assert!(message.contains(error_message));
            }
        }
    }

    fn assert_matches(expected: &str, response: Response) -> Result<()> {
        let mut buffer = Vec::new();
        response.write(&mut buffer)?;

        let actual = String::from_utf8(buffer)?;
        assert_eq!(
            actual, expected,
            "Serialization of alfrusco::Response didn't match expected JSON"
        );
        Ok(())
    }

    #[test]
    fn test_assert_matches_utf8_error() {
        // Create an invalid UTF-8 sequence
        let buffer = vec![0xFF]; // Invalid UTF-8 byte

        // Attempt to convert to a string, which should fail
        let result = String::from_utf8(buffer);
        assert!(result.is_err());

        // Verify the error message
        let err = result.unwrap_err();
        assert!(err.to_string().contains("invalid utf-8"));

        // Now test how assert_matches would handle this error
        let response = Response::default();
        let mut buffer = Vec::new();
        response.write(&mut buffer).unwrap();

        // Corrupt the buffer with invalid UTF-8
        buffer[0] = 0xFF;

        // Create a function that mimics assert_matches but returns a Result
        let result = (|| -> Result<()> {
            let _actual = String::from_utf8(buffer)?;
            // This line would normally be executed if UTF-8 conversion succeeds
            let expected = r#"{"items":[]}"#;
            // Force execution of this line for coverage
            assert!(!expected.is_empty());
            Ok(())
        })();

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("invalid utf-8"));
    }

    #[test]
    fn test_append_items() -> Result<()> {
        let mut response = Response::new_with_items(vec![Item::new("First Item")]);
        response.append_items(vec![Item::new("Second Item"), Item::new("Third Item")]);

        assert_matches(
            r#"{"items":[{"title":"First Item"},{"title":"Second Item"},{"title":"Third Item"}]}"#,
            response,
        )
    }

    #[test]
    fn test_prepend_items() -> Result<()> {
        let mut response = Response::new_with_items(vec![Item::new("Last Item")]);
        response.prepend_items(vec![Item::new("First Item"), Item::new("Second Item")]);

        assert_matches(
            r#"{"items":[{"title":"First Item"},{"title":"Second Item"},{"title":"Last Item"}]}"#,
            response,
        )
    }

    #[test]
    fn test_cache_settings_serialization() -> Result<()> {
        let cache_settings = CacheSettings {
            seconds: Some(Duration::from_secs(60)),
            loose_reload: Some(true),
        };

        let json = serde_json::to_string(&cache_settings)?;
        assert_eq!(json, r#"{"seconds":60,"loosereload":true}"#);

        let cache_settings_partial = CacheSettings {
            seconds: Some(Duration::from_secs(30)),
            loose_reload: None,
        };

        let json = serde_json::to_string(&cache_settings_partial)?;
        assert_eq!(json, r#"{"seconds":30}"#);

        Ok(())
    }

    #[test]
    fn test_response_with_multiple_settings() -> Result<()> {
        let mut response = Response::new_with_items(vec![Item::new("Test Item")]);
        response
            .rerun(Duration::from_secs(5))
            .skip_knowledge(true)
            .cache(Duration::from_secs(60), false);

        assert_matches(
            r#"{"rerun":5,"cache":{"seconds":60,"loosereload":false},"skipknowledge":true,"items":[{"title":"Test Item"}]}"#,
            response,
        )
    }

    #[test]
    fn test_duration_as_seconds_edge_cases() {
        // Test with zero duration
        let zero_duration = Duration::from_secs(0);
        let result = json!({ "duration": duration_as_seconds(&Some(zero_duration), serde_json::value::Serializer).unwrap() });
        assert_eq!(result.to_string(), r#"{"duration":0}"#);

        // Test with very small duration - this will be rounded in serialization
        let tiny_duration = Duration::from_nanos(1);
        let result = json!({ "duration": duration_as_seconds(&Some(tiny_duration), serde_json::value::Serializer).unwrap() });
        // For extremely small durations, it will be effectively 0 due to how the function works
        assert_eq!(result.to_string(), r#"{"duration":0}"#);

        // Test with very large duration
        let large_duration = Duration::from_secs(u64::MAX);
        let result = json!({ "duration": duration_as_seconds(&Some(large_duration), serde_json::value::Serializer).unwrap() });
        assert_eq!(
            result.to_string(),
            format!(r#"{{"duration":{}}}"#, u64::MAX)
        );
    }

    #[test]
    fn test_assert_matches_success() -> Result<()> {
        let response = Response::default();
        // This should succeed and not panic
        assert_matches(r#"{"items":[]}"#, response)?;
        Ok(())
    }

    #[test]
    fn test_response_new() -> Result<()> {
        let response = Response::new();
        assert_matches(r#"{"items":[]}"#, response)
    }

    #[test]
    fn test_empty_cache_settings() -> Result<()> {
        let cache_settings = CacheSettings {
            seconds: None,
            loose_reload: None,
        };

        let json = serde_json::to_string(&cache_settings)?;
        assert_eq!(json, r#"{}"#);

        Ok(())
    }
}