mdquery-rs 0.2.1

A Rust binding library for macOS Spotlight search using Metadata Query API
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use super::{MDItemKey, MDQuery, MDQueryScope};
use anyhow::Result;

/// Builder for constructing MDQuery instances with a fluent interface.
///
/// This builder allows for creating complex metadata queries on macOS using
/// the Spotlight search technology. It provides methods to build search expressions
/// that can be combined with logical AND operations.
///
/// # Examples
///
/// ```
/// use mdquery_rs::{MDQueryBuilder, MDQueryScope};
///
/// // Find files containing "document" in their name
/// let query = MDQueryBuilder::default()
///     .name_like("document")
///     .build(vec![MDQueryScope::Home], None)
///     .unwrap();
///     
/// let results = query.execute().unwrap();
/// for item in results {
///     println!("{:?}", item.path());
/// }
/// ```
#[derive(Default)]
pub struct MDQueryBuilder {
    condition: MDQueryCondition,
}

impl MDQueryBuilder {
    /// Builds the final MDQuery with the current expressions.
    ///
    /// # Parameters
    /// * `scopes` - List of search scopes to apply (e.g., Home, Computer)
    /// * `max_count` - Optional maximum number of results to return
    ///
    /// # Returns
    /// A Result containing the MDQuery if successful, or an error if no expressions were added.
    ///
    /// # Errors
    /// Returns an error if no expressions were added to the builder.
    pub fn build(self, scopes: Vec<MDQueryScope>, max_count: Option<usize>) -> Result<MDQuery> {
        if self.condition.is_empty() {
            anyhow::bail!("No expressions to build");
        }
        let query = self.condition.into_expression();
        MDQuery::new(&query, Some(scopes), max_count)
    }

    /// Creates a new builder from a condition.
    ///
    /// # Parameters
    /// * `condition` - The condition to add to the builder
    ///
    /// # Returns
    /// Self for method chaining
    pub fn from_condition(condition: MDQueryCondition) -> Self {
        Self { condition }
    }

    /// Creates a new builder from a raw query string.
    ///
    /// # Parameters
    /// * `query` - The raw query string
    ///
    /// # Returns
    /// Self for method chaining
    pub fn from_raw(query: &str) -> Self {
        let mut condition = MDQueryCondition::default();
        condition.add(MDQueryConditionExpression::Expression(query.to_string()));
        Self { condition }
    }
    
    /// Adds an expression to match items whose display name contains the specified string.
    ///
    /// This performs a case-insensitive substring search and supports Chinese Pinyin.
    ///
    /// # Parameters
    /// * `name` - The substring to match in display names
    ///
    /// # Returns
    /// Self for method chaining
    pub fn name_like(mut self, name: &str) -> Self {
        self.condition
            .add(MDQueryConditionExpression::Expression(format!(
                "{} == \"*{}*\"w",
                MDItemKey::DisplayName,
                name
            )));
        self
    }

    /// Adds an expression to match items whose display name exactly matches the specified string.
    ///
    /// This performs a case-insensitive exact match.
    ///
    /// # Parameters
    /// * `name` - The exact name to match
    ///
    /// # Returns
    /// Self for method chaining
    pub fn name_is(mut self, name: &str) -> Self {
        self.condition
            .add(MDQueryConditionExpression::Expression(format!(
                "{} == \"{}\"c",
                MDItemKey::DisplayName,
                name
            )));
        self
    }

    /// Adds a time-based comparison expression.
    ///
    /// # Parameters
    /// * `key` - The time-related metadata key to compare
    /// * `op` - The comparison operator to use
    /// * `timestamp` - Unix timestamp to compare against
    ///
    /// # Returns
    /// Self for method chaining
    ///
    /// # Panics
    /// Panics if the provided key is not a time-related key.
    pub fn time(mut self, key: MDItemKey, op: MDQueryCompareOp, timestamp: i64) -> Self {
        if !key.is_time() {
            panic!("Cannot use time on non-time key");
        }

        let time_str = chrono::DateTime::from_timestamp(timestamp, 0)
            .unwrap()
            .to_rfc3339();

        self.condition
            .add(MDQueryConditionExpression::Expression(format!(
                "{} {} $time.iso({})",
                key,
                op.into_query_string(),
                time_str
            )));
        self
    }

    /// Adds a file size comparison expression.
    ///
    /// # Parameters
    /// * `op` - The comparison operator to use
    /// * `size` - The file size in bytes to compare against
    ///
    /// # Returns
    /// Self for method chaining
    pub fn size(mut self, op: MDQueryCompareOp, size: u64) -> Self {
        self.condition
            .add(MDQueryConditionExpression::Expression(format!(
                "{} {} {}",
                MDItemKey::Size,
                op.into_query_string(),
                size
            )));
        self
    }

    /// Adds an expression to filter items based on whether they are directories.
    ///
    /// # Parameters
    /// * `value` - If true, matches only directories; if false, matches only non-directories
    ///
    /// # Returns
    /// Self for method chaining
    ///
    /// # Note
    /// Special directory types such as app bundles are not included in the directory scope.
    pub fn is_dir(mut self, value: bool) -> Self {
        self.condition
            .add(MDQueryConditionExpression::Expression(format!(
                "{} {} \"{}\"",
                MDItemKey::ContentType,
                if value { "==" } else { "!=" },
                "public.folder"
            )));
        self
    }

    /// Adds an expression to filter items based on whether they are application bundles.
    ///
    /// # Returns
    /// Self for method chaining
    pub fn is_app(self) -> Self {
        self.content_type("com.apple.application-bundle")
    }

    /// Adds an expression to match items with the specified file extension.
    ///
    /// # Parameters
    /// * `ext` - The file extension to match (without the leading dot)
    ///
    /// # Returns
    /// Self for method chaining
    pub fn extension(mut self, ext: &str) -> Self {
        self.condition
            .add(MDQueryConditionExpression::Expression(format!(
                "{} == \"*.{}\"c",
                MDItemKey::FSName,
                ext
            )));
        self
    }

    /// Adds an expression to match items with the specified content type.
    ///
    /// # Parameters
    /// * `content_type` - The content type UTI string to match
    ///
    /// # Returns
    /// Self for method chaining
    pub fn content_type(mut self, content_type: &str) -> Self {
        self.condition
            .add(MDQueryConditionExpression::Expression(format!(
                "{} == \"{}\"",
                MDItemKey::ContentType,
                content_type
            )));
        self
    }
}

/// A structure for building complex, nested query conditions with logical operators.
///
/// `MDQueryCondition` allows for creating sophisticated search expressions by combining
/// multiple conditions with either logical AND (All) or logical OR (Any) operators.
/// It can be used to build complex queries that are not easily expressible with the
/// simple chained methods of `MDQueryBuilder`.
pub struct MDQueryCondition {
    /// Specifies whether the expressions should be combined with logical AND (All) or OR (Any).
    condition_type: MDQueryConditionType,
    /// The list of expressions to be combined according to the condition_type.
    expressions: Vec<MDQueryConditionExpression>,
}

impl Default for MDQueryCondition {
    fn default() -> Self {
        Self {
            condition_type: MDQueryConditionType::All,
            expressions: Vec::new(),
        }
    }
}

impl MDQueryCondition {
    /// Converts the condition structure into a query expression string.
    ///
    /// This method recursively processes the condition structure, combining all expressions
    /// according to the condition_type (All = AND, Any = OR) and returning a properly
    /// formatted query string that can be used with MDQuery.
    ///
    /// # Returns
    /// A string representation of the combined query expression, properly parenthesized.
    pub fn into_expression(self) -> String {
        let expr = match self.condition_type {
            MDQueryConditionType::All => self
                .expressions
                .into_iter()
                .map(|e| e.into_expression())
                .collect::<Vec<_>>()
                .join(" && "),
            MDQueryConditionType::Any => self
                .expressions
                .into_iter()
                .map(|e| e.into_expression())
                .collect::<Vec<_>>()
                .join(" || "),
        };
        format!("({})", expr)
    }

    /// Add a new expression to the condition.
    ///
    /// # Parameters
    /// * `expr` - The expression to add to the condition
    pub fn add(&mut self, expr: MDQueryConditionExpression) {
        self.expressions.push(expr);
    }

    /// Checks if the condition is empty.
    ///
    /// # Returns
    /// True if the condition is empty, false otherwise.
    pub fn is_empty(&self) -> bool {
        self.expressions.is_empty()
    }
}

/// Defines the logical operation to apply when combining multiple expressions.
///
/// This enum determines how the expressions within an `MDQueryCondition` are combined:
/// - `All`: Combines expressions with logical AND (&&)
/// - `Any`: Combines expressions with logical OR (||)
pub enum MDQueryConditionType {
    /// Combines all expressions with logical AND (&&)
    All,
    /// Combines all expressions with logical OR (||)
    Any,
}

/// Represents either a nested condition or a raw query expression string.
///
/// This enum allows for building complex, nested query structures by combining
/// both raw expression strings and other condition structures.
pub enum MDQueryConditionExpression {
    /// A nested condition structure
    Condition(MDQueryCondition),
    /// A raw query expression string
    Expression(String),
}

impl MDQueryConditionExpression {
    /// Converts the expression into a query string.
    ///
    /// For nested conditions, this recursively processes the condition structure.
    /// For raw expressions, it wraps the expression in parentheses.
    ///
    /// # Returns
    /// A properly formatted query string representation of this expression.
    pub fn into_expression(self) -> String {
        match self {
            Self::Condition(c) => c.into_expression(),
            Self::Expression(e) => format!("({})", e),
        }
    }
}

/// Comparison operators for metadata query expressions.
pub enum MDQueryCompareOp {
    /// Greater than (>)
    GreaterThan,
    /// Less than (<)
    LessThan,
    /// Equal to (==)
    Equal,
    /// Greater than or equal to (>=)
    GreaterThanOrEqual,
    /// Less than or equal to (<=)
    LessThanOrEqual,
}

impl MDQueryCompareOp {
    /// Converts the operator to its string representation in a query.
    ///
    /// # Returns
    /// The string representation of the operator.
    fn into_query_string(self) -> &'static str {
        match self {
            Self::GreaterThan => ">",
            Self::LessThan => "<",
            Self::Equal => "==",
            Self::GreaterThanOrEqual => ">=",
            Self::LessThanOrEqual => "<=",
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;

    #[test]
    fn test_name_like() {
        let builder = MDQueryBuilder::default().name_like("Safari");
        let query = builder
            .build(vec![MDQueryScope::Computer], Some(1))
            .unwrap();
        let results = query.execute().unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(
            results[0].path(),
            Some(PathBuf::from("/Applications/Safari.app"))
        );
    }

    #[test]
    fn test_is_app() {
        let builder = MDQueryBuilder::default().name_like("Safari").is_app();
        let query = builder
            .build(vec![MDQueryScope::Computer], Some(1))
            .unwrap();
        let results = query.execute().unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(
            results[0].path(),
            Some(PathBuf::from("/Applications/Safari.app"))
        );
    }

    #[test]
    fn test_extension() {
        let builder = MDQueryBuilder::default().extension("txt");
        let query = builder
            .build(vec![MDQueryScope::Computer], Some(1))
            .unwrap();
        let results = query.execute().unwrap();
        assert!(!results.is_empty());
        assert!(results[0]
            .path()
            .unwrap()
            .to_str()
            .unwrap()
            .ends_with(".txt"));
    }

    #[test]
    fn test_time_search() {
        let now = chrono::Utc::now().timestamp();
        let builder = MDQueryBuilder::default().time(
            MDItemKey::ModificationDate,
            MDQueryCompareOp::LessThan,
            now,
        );
        let query = builder
            .build(vec![MDQueryScope::from_path("/Applications")], Some(1))
            .unwrap();
        let results = query.execute().unwrap();
        assert!(!results.is_empty());
    }

    #[test]
    fn test_size_filter() {
        let builder = MDQueryBuilder::default().size(MDQueryCompareOp::GreaterThan, 1024 * 1024); // > 1MB
        let query = builder
            .build(vec![MDQueryScope::Computer], Some(1))
            .unwrap();
        let results = query.execute().unwrap();
        assert!(!results.is_empty());
    }

    #[test]
    fn test_is_dir() {
        let builder = MDQueryBuilder::default().is_dir(true);
        let query = builder
            .build(vec![MDQueryScope::Computer], Some(1))
            .unwrap();
        let results = query.execute().unwrap();
        assert!(!results.is_empty());
    }

    #[test]
    fn test_condition_all() {
        let condition = MDQueryCondition {
            condition_type: MDQueryConditionType::All,
            expressions: vec![
                MDQueryConditionExpression::Expression("kMDItemFSName == \"test.txt\"".into()),
                MDQueryConditionExpression::Expression("kMDItemTextContent == \"hello\"".into()),
            ],
        };
        assert_eq!(
            condition.into_expression(),
            "((kMDItemFSName == \"test.txt\") && (kMDItemTextContent == \"hello\"))"
        );
    }

    #[test]
    fn test_condition_any() {
        let condition = MDQueryCondition {
            condition_type: MDQueryConditionType::Any,
            expressions: vec![
                MDQueryConditionExpression::Expression("kMDItemFSName == \"doc.pdf\"".into()),
                MDQueryConditionExpression::Expression("kMDItemFSName == \"doc.txt\"".into()),
            ],
        };
        assert_eq!(
            condition.into_expression(),
            "((kMDItemFSName == \"doc.pdf\") || (kMDItemFSName == \"doc.txt\"))"
        );
    }

    #[test]
    fn test_nested_condition() {
        let inner_condition = MDQueryCondition {
            condition_type: MDQueryConditionType::Any,
            expressions: vec![
                MDQueryConditionExpression::Expression("kMDItemFSName == \"*.txt\"".into()),
                MDQueryConditionExpression::Expression("kMDItemFSName == \"*.pdf\"".into()),
            ],
        };

        let outer_condition = MDQueryCondition {
            condition_type: MDQueryConditionType::All,
            expressions: vec![
                MDQueryConditionExpression::Condition(inner_condition),
                MDQueryConditionExpression::Expression("kMDItemTextContent == \"test\"".into()),
            ],
        };

        assert_eq!(
            outer_condition.into_expression(),
            "(((kMDItemFSName == \"*.txt\") || (kMDItemFSName == \"*.pdf\")) && (kMDItemTextContent == \"test\"))"
        );
    }

    #[test]
    fn test_empty_condition() {
        let condition = MDQueryCondition {
            condition_type: MDQueryConditionType::All,
            expressions: vec![],
        };
        assert_eq!(condition.into_expression(), "()");
    }
}