pasta_lua 0.2.3

Pasta Lua - Lua integration for Pasta DSL
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
//! File discovery for Pasta Loader.
//!
//! This module provides file discovery functionality using glob patterns.

use glob::glob;
use std::fs;
use std::path::{Component, Path, PathBuf};

use super::LoaderError;

/// Check if a pattern contains directory traversal components.
///
/// Rejects patterns containing `..`, absolute paths, or Windows drive prefixes
/// to prevent file discovery outside the intended base directory.
fn contains_traversal(pattern: &str) -> bool {
    let path = Path::new(pattern);
    path.components().any(|c| {
        matches!(
            c,
            Component::ParentDir | Component::RootDir | Component::Prefix(_)
        )
    })
}

fn is_within_base_dir(base_dir: &Path, path: &Path) -> bool {
    path.strip_prefix(base_dir).is_ok()
}

fn has_symlink_component(base_dir: &Path, path: &Path) -> std::io::Result<bool> {
    let Ok(relative) = path.strip_prefix(base_dir) else {
        return Ok(false);
    };

    let mut current = base_dir.to_path_buf();
    for component in relative.components() {
        current.push(component.as_os_str());
        if fs::symlink_metadata(&current)?.file_type().is_symlink() {
            return Ok(true);
        }
    }

    Ok(false)
}

/// Discover pasta files matching the given patterns.
///
/// Files in `profile/` directory are excluded from discovery.
/// Patterns containing directory traversal (`..`, absolute paths) are rejected.
/// Matches outside `base_dir` and paths containing a symlinked component
/// (including Windows junctions) are skipped.
///
/// # Arguments
/// * `base_dir` - Base directory to search from
/// * `patterns` - Glob patterns (e.g., ["dic/*/*.pasta"])
///
/// # Returns
/// * `Ok(Vec<PathBuf>)` - List of discovered files (may be empty)
/// * `Err(LoaderError)` - Directory not found or pattern error
pub(crate) fn discover_files(
    base_dir: &Path,
    patterns: &[String],
) -> Result<Vec<PathBuf>, LoaderError> {
    // Verify base directory exists
    if !base_dir.exists() {
        return Err(LoaderError::directory_not_found(base_dir));
    }

    if !base_dir.is_dir() {
        return Err(LoaderError::directory_not_found(base_dir));
    }

    let mut files = Vec::new();

    for pattern in patterns {
        // Reject patterns with directory traversal components
        if contains_traversal(pattern) {
            tracing::warn!(
                pattern = %pattern,
                "Rejecting pattern with directory traversal"
            );
            continue;
        }

        let full_pattern = base_dir.join(pattern);
        let pattern_str = full_pattern.to_string_lossy();

        tracing::debug!(pattern = %pattern_str, "Searching for files");

        for entry in glob(&pattern_str)? {
            let path = entry?;

            if !is_within_base_dir(base_dir, &path) {
                tracing::warn!(
                    path = %path.display(),
                    base_dir = %base_dir.display(),
                    "Skipping match outside base directory"
                );
                continue;
            }

            match has_symlink_component(base_dir, &path) {
                Ok(true) => {
                    tracing::debug!(path = %path.display(), "Skipping symlinked path");
                    continue;
                }
                Err(error) => {
                    tracing::warn!(
                        path = %path.display(),
                        error = %error,
                        "Skipping path with unreadable metadata"
                    );
                    continue;
                }
                Ok(false) => {}
            }

            // Skip files in profile/ directory
            if is_in_profile_dir(base_dir, &path) {
                tracing::debug!(path = %path.display(), "Skipping profile file");
                continue;
            }

            files.push(path);
        }
    }

    if files.is_empty() {
        tracing::warn!(
            base_dir = %base_dir.display(),
            patterns = ?patterns,
            "No .pasta files found"
        );
    }

    Ok(files)
}

/// Check if a path is inside the profile/ directory.
fn is_in_profile_dir(base_dir: &Path, path: &Path) -> bool {
    let profile_dir = base_dir.join("profile");
    path.starts_with(&profile_dir)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_structure(temp: &TempDir) -> PathBuf {
        let base = temp.path();

        // Create dic structure
        fs::create_dir_all(base.join("dic/greeting")).unwrap();
        fs::create_dir_all(base.join("dic/conversation")).unwrap();
        fs::write(base.join("dic/greeting/hello.pasta"), "# hello").unwrap();
        fs::write(base.join("dic/greeting/goodbye.pasta"), "# goodbye").unwrap();
        fs::write(base.join("dic/conversation/chat.pasta"), "# chat").unwrap();

        // Create file directly in dic (should be ignored by dic/*/*.pasta)
        fs::write(base.join("dic/root.pasta"), "# root").unwrap();

        // Create profile structure (should be excluded)
        fs::create_dir_all(base.join("profile/pasta/cache/lua")).unwrap();
        fs::write(
            base.join("profile/pasta/cache/lua/cached.pasta"),
            "# cached",
        )
        .unwrap();

        base.to_path_buf()
    }

    #[test]
    fn test_discover_default_pattern() {
        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);

        let patterns = vec!["dic/*/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();

        assert_eq!(files.len(), 3);
        let file_names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        assert!(file_names.contains(&"hello.pasta".to_string()));
        assert!(file_names.contains(&"goodbye.pasta".to_string()));
        assert!(file_names.contains(&"chat.pasta".to_string()));
    }

    #[test]
    fn test_discover_excludes_root_dic() {
        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);

        let patterns = vec!["dic/*/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();

        // Should not include dic/root.pasta
        let file_names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        assert!(!file_names.contains(&"root.pasta".to_string()));
    }

    #[test]
    fn test_discover_excludes_profile() {
        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);

        // Even with a pattern that would match profile, it should be excluded
        let patterns = vec!["**/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();

        let file_names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        assert!(!file_names.contains(&"cached.pasta".to_string()));
    }

    #[test]
    fn test_discover_nonexistent_directory() {
        let temp = TempDir::new().unwrap();
        let nonexistent = temp.path().join("nonexistent");

        let patterns = vec!["dic/*/*.pasta".to_string()];
        let result = discover_files(&nonexistent, &patterns);

        assert!(result.is_err());
        match result {
            Err(LoaderError::DirectoryNotFound(_)) => {}
            _ => panic!("Expected DirectoryNotFound error"),
        }
    }

    #[test]
    fn test_discover_empty_directory() {
        let temp = TempDir::new().unwrap();
        let base_dir = temp.path();

        // Create empty dic structure
        fs::create_dir_all(base_dir.join("dic/empty")).unwrap();

        let patterns = vec!["dic/*/*.pasta".to_string()];
        let files = discover_files(base_dir, &patterns).unwrap();

        assert!(files.is_empty());
    }

    #[test]
    fn test_discover_multiple_patterns() {
        let temp = TempDir::new().unwrap();
        let base_dir = temp.path();

        // Create structures for multiple patterns
        fs::create_dir_all(base_dir.join("dic/sub")).unwrap();
        fs::create_dir_all(base_dir.join("extra")).unwrap();
        fs::write(base_dir.join("dic/sub/a.pasta"), "# a").unwrap();
        fs::write(base_dir.join("extra/b.pasta"), "# b").unwrap();

        let patterns = vec!["dic/*/*.pasta".to_string(), "extra/*.pasta".to_string()];
        let files = discover_files(base_dir, &patterns).unwrap();

        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_discover_rejects_parent_dir_traversal() {
        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);

        // Pattern with ".." should be silently skipped
        let patterns = vec!["../../../etc/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();
        assert!(files.is_empty());
    }

    #[test]
    fn test_discover_rejects_traversal_preserves_valid() {
        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);

        // Mix of valid and traversal patterns — valid should still work
        let patterns = vec!["../secret/*.pasta".to_string(), "dic/*/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();
        assert_eq!(files.len(), 3);
    }

    #[test]
    fn test_contains_traversal() {
        assert!(contains_traversal("../foo/*.pasta"));
        assert!(contains_traversal("foo/../../bar/*.pasta"));
        assert!(!contains_traversal("dic/*/*.pasta"));
        assert!(!contains_traversal("**/*.pasta"));
        assert!(!contains_traversal("extra/*.pasta"));
    }

    #[test]
    fn test_contains_traversal_absolute_paths() {
        // RootDir component (absolute path) must be rejected
        assert!(contains_traversal("/etc/*.pasta"));
        // Windows drive prefix must be rejected (Prefix component on Windows)
        #[cfg(windows)]
        assert!(contains_traversal(r"C:\secret\*.pasta"));
    }

    #[test]
    fn test_discover_base_dir_is_file() {
        // base_dir exists but is a regular file -> DirectoryNotFound
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("not_a_dir");
        fs::write(&file_path, "plain file").unwrap();

        let patterns = vec!["dic/*/*.pasta".to_string()];
        let result = discover_files(&file_path, &patterns);

        match result {
            Err(LoaderError::DirectoryNotFound(path)) => {
                assert_eq!(path, file_path);
            }
            other => panic!("Expected DirectoryNotFound, got: {:?}", other),
        }
    }

    #[test]
    fn test_discover_invalid_glob_pattern() {
        // Unclosed character class is an invalid glob pattern -> GlobPattern error
        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);

        let patterns = vec!["dic/[/*.pasta".to_string()];
        let result = discover_files(&base_dir, &patterns);

        assert!(matches!(result, Err(LoaderError::GlobPattern(_))));
    }

    #[test]
    fn test_discover_rejects_absolute_pattern() {
        // Absolute patterns are silently skipped (traversal guard), result is empty
        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);

        let patterns = vec!["/etc/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();
        assert!(files.is_empty());
    }

    #[test]
    fn test_discover_profile_prefix_dir_not_excluded() {
        // Only the exact "profile" directory is excluded. A sibling directory
        // whose name merely starts with "profile" (e.g. "profile2") must NOT
        // be excluded — exclusion works on path components, not string prefix.
        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);
        fs::create_dir_all(base_dir.join("profile2/inner")).unwrap();
        fs::write(base_dir.join("profile2/inner/kept.pasta"), "# kept").unwrap();

        let patterns = vec!["**/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();
        let file_names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        assert!(file_names.contains(&"kept.pasta".to_string()));
        // The real profile/ file stays excluded
        assert!(!file_names.contains(&"cached.pasta".to_string()));
    }

    #[test]
    fn test_is_within_base_dir() {
        let temp = TempDir::new().unwrap();
        let base_dir = temp.path().join("base");
        let child = base_dir.join("dic/test.pasta");
        let outside = temp.path().join("outside/test.pasta");

        assert!(is_within_base_dir(&base_dir, &child));
        assert!(!is_within_base_dir(&base_dir, &outside));
    }

    #[cfg(unix)]
    #[test]
    fn test_discover_skips_symlinked_file() {
        use std::os::unix::fs as unix_fs;

        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);
        let external = temp.path().join("external.pasta");
        fs::write(&external, "# external").unwrap();
        unix_fs::symlink(&external, base_dir.join("dic/greeting/link.pasta")).unwrap();

        let patterns = vec!["dic/*/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();
        let file_names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        assert_eq!(files.len(), 3);
        assert!(!file_names.contains(&"link.pasta".to_string()));
    }

    #[cfg(windows)]
    #[test]
    fn test_discover_skips_junction_directory() {
        // Windows junctions (mount-point reparse points) can redirect discovery
        // outside base_dir exactly like symlinks. Rust std reports them via
        // `FileType::is_symlink()` (name-surrogate reparse tag), so
        // `has_symlink_component` must skip them — this test pins that behavior.
        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);
        let external_dir = temp.path().join("external");
        fs::create_dir_all(&external_dir).unwrap();
        fs::write(external_dir.join("secret.pasta"), "# secret").unwrap();

        // Create junction without elevation: cmd /C mklink /J <link> <target>
        let junction = base_dir.join("dic").join("linked");
        let status = std::process::Command::new("cmd")
            .arg("/C")
            .arg("mklink")
            .arg("/J")
            .arg(&junction)
            .arg(&external_dir)
            .status()
            .expect("failed to spawn cmd for mklink");
        assert!(status.success(), "mklink /J failed");

        let patterns = vec!["dic/*/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();
        let file_names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        assert_eq!(files.len(), 3);
        assert!(!file_names.contains(&"secret.pasta".to_string()));
    }

    #[cfg(unix)]
    #[test]
    fn test_discover_skips_symlinked_directory() {
        use std::os::unix::fs as unix_fs;

        let temp = TempDir::new().unwrap();
        let base_dir = create_test_structure(&temp);
        let external_dir = temp.path().join("external");
        fs::create_dir_all(&external_dir).unwrap();
        fs::write(external_dir.join("secret.pasta"), "# secret").unwrap();
        unix_fs::symlink(&external_dir, base_dir.join("dic/linked")).unwrap();

        let patterns = vec!["dic/*/*.pasta".to_string()];
        let files = discover_files(&base_dir, &patterns).unwrap();
        let file_names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        assert_eq!(files.len(), 3);
        assert!(!file_names.contains(&"secret.pasta".to_string()));
    }
}