luff 0.2.1

Print files with formatting
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
510
//! In-memory file representation for the WASM processing pipeline.
//!
//! [`VirtualFile`] is the primary data carrier — an owned pair of
//! `(path, content)` strings. It is `serde`-enabled for seamless
//! JS interop via `serde-wasm-bindgen`.
//!
//! Fields are private so that the path validation invariant established
//! by [`VirtualFile::new`] cannot be silently bypassed. Deserialization
//! goes through the same validation gate.

use super::error::WasmError;

/// Maximum allowed path length in bytes.
///
/// Generous for real use, but prevents a malicious JS caller from
/// shipping a multi-megabyte path string into the WASM heap.
const MAX_PATH_LEN: usize = 4096;

/// An in-memory file: owned path + owned content.
///
/// Paths are treated as display labels and are never resolved against
/// a real filesystem. They use `/` as the separator regardless of
/// host platform.
///
/// # Invariants
///
/// Fields are private. Construction via [`VirtualFile::new`] (or
/// deserialization) enforces that the path:
/// - Is not empty.
/// - Contains no null bytes.
/// - Does not exceed [`MAX_PATH_LEN`] bytes.
/// - Contains no ASCII control characters (0x00–0x1F) except `\t`.
/// - Contains no backslash (`\`) characters (use `/` as separator).
/// - Contains no `..` path-traversal components.
/// - Contains no empty path components (no consecutive or trailing `/`).
/// - Is relative (does not start with `/`).
///
/// # Ordering
///
/// Derived lexicographically on `(path, content)` for deterministic
/// output. This ordering is consistent with `PartialEq` and `Hash`.
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
pub struct VirtualFile {
    /// Forward-slash-separated relative path (e.g. `src/main.rs`).
    path: String,
    /// File content as a UTF-8 string.
    content: String,
}

/// Custom `Deserialize` that validates the path on the way in, so
/// untrusted input (e.g. from JS via `serde-wasm-bindgen`) cannot
/// produce a `VirtualFile` that violates the path invariant.
impl<'de> serde::Deserialize<'de> for VirtualFile {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(serde::Deserialize)]
        struct Raw {
            path: String,
            content: String,
        }

        let raw = Raw::deserialize(deserializer)?;
        validate_path(&raw.path).map_err(serde::de::Error::custom)?;
        Ok(Self {
            path: raw.path,
            content: raw.content,
        })
    }
}

impl VirtualFile {
    /// Creates a new `VirtualFile` after validating the path.
    ///
    /// Content is accepted as-is (arbitrary UTF-8).
    ///
    /// # Errors
    ///
    /// Returns [`WasmError::InvalidPath`] if the path is empty,
    /// contains null bytes, exceeds [`MAX_PATH_LEN`], contains
    /// disallowed control characters, includes backslashes,
    /// includes `..` traversal components, contains empty path
    /// components (consecutive or trailing slashes), or is absolute
    /// (starts with `/`).
    pub fn new(path: impl Into<String>, content: impl Into<String>) -> super::Result<Self> {
        let path = path.into();
        validate_path(&path)?;
        Ok(Self {
            path,
            content: content.into(),
        })
    }

    /// Creates a `VirtualFile` without path validation.
    ///
    /// Intended for internal use, tests, and benchmarks where the
    /// caller controls the input and validation overhead is
    /// undesirable. Production code receiving untrusted input must
    /// go through [`new`](Self::new) or deserialization, both of
    /// which enforce the path invariant.
    ///
    /// # Correctness
    ///
    /// The caller must ensure the path is a reasonable forward-slash-
    /// separated relative path. Violating this is not memory-unsafe,
    /// but may produce unexpected output if the path contains control
    /// characters, backslashes, or null bytes.
    //
    // Not `#[cfg(test)]`: kept available for benchmarks and future
    // crate-internal callers (e.g. CLI→WASM bridge with pre-validated
    // paths). Dead-code lint is suppressed in non-test builds only.
    #[cfg_attr(
        not(test),
        expect(dead_code, reason = "reserved for benchmarks and future internal use")
    )]
    #[must_use]
    pub(crate) fn new_unchecked(path: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            content: content.into(),
        }
    }

    /// The file path.
    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The file content.
    #[must_use]
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Returns the file name (last path component).
    #[must_use]
    pub fn file_name(&self) -> &str {
        self.path
            .rsplit_once('/')
            .map_or(self.path.as_str(), |(_, name)| name)
    }

    /// Returns the file extension (without the leading dot), if any.
    ///
    /// Extracts from the filename component only, so
    /// `src/my.module/Makefile` correctly returns `None`.
    ///
    /// Based on [`std::path::Path::extension`] with one intentional
    /// divergence: trailing-dot filenames like `Makefile.` return
    /// `None` here (std returns `Some("")`). This avoids matching an
    /// empty string against extension-ignore lists.
    ///
    /// - `.gitignore` → `None` (no stem before the dot)
    /// - `Makefile.` → `None` (empty extension — diverges from std)
    /// - `archive.tar.gz` → `Some("gz")`
    #[must_use]
    pub fn extension(&self) -> Option<&str> {
        let (stem, ext) = self.file_name().rsplit_once('.')?;
        // No extension when stem is empty (`.gitignore`) or extension
        // is empty (`Makefile.`).
        if stem.is_empty() || ext.is_empty() {
            None
        } else {
            Some(ext)
        }
    }

    /// Returns `true` if any path component starts with `.`.
    ///
    /// Uses [`normalized_path`](Self::normalized_path) so that the
    /// conventional `./` prefix does not cause false positives
    /// (the `.` in `./src/main.rs` is a current-directory marker,
    /// not a hidden-file indicator).
    #[must_use]
    pub fn is_dotfile(&self) -> bool {
        self.normalized_path()
            .split('/')
            .any(|component| component.starts_with('.'))
    }

    /// Normalized path with leading `./` stripped.
    #[must_use]
    pub fn normalized_path(&self) -> &str {
        self.path.strip_prefix("./").unwrap_or(&self.path)
    }
}

/// Validates a virtual file path.
fn validate_path(path: &str) -> super::Result<()> {
    if path.is_empty() {
        return Err(WasmError::InvalidPath("path is empty".into()));
    }

    if path.len() > MAX_PATH_LEN {
        return Err(WasmError::InvalidPath(format!(
            "path exceeds {MAX_PATH_LEN} bytes: {}",
            path.len()
        )));
    }

    // Reject absolute paths. The struct documents this field as a
    // relative path, and downstream consumers (tree renderer, glob
    // matching, potential filesystem writers) all assume relative
    // semantics. Enforce at the gate rather than hoping every
    // consumer checks independently.
    if path.starts_with('/') {
        return Err(WasmError::InvalidPath(
            "path must be relative (no leading '/')".into(),
        ));
    }

    // Disallow all ASCII control chars except \t (0x09).
    // Notably, \n (0x0A) is rejected — newlines in file paths are
    // almost certainly bugs, not intentional.
    if path.bytes().any(|b| b.is_ascii_control() && b != b'\t') {
        return Err(WasmError::InvalidPath(
            "path contains null byte or control character".into(),
        ));
    }

    // Reject backslashes. All path decomposition methods (`file_name`,
    // `extension`, `is_dotfile`, `normalized_path`) and the tree renderer
    // split on `/` only. A backslash would be treated as part of a path
    // component name, silently producing wrong results for every
    // downstream consumer. Fail loudly at the validation gate instead.
    if path.contains('\\') {
        return Err(WasmError::InvalidPath(
            "path contains backslash — use '/' as separator".into(),
        ));
    }

    // Defense-in-depth: reject path-traversal components (OWASP A01:2021).
    //
    // VirtualFile paths are display labels in the WASM module and are
    // never resolved against a filesystem here. However, downstream
    // consumers may pass them to filesystem APIs. Rejecting `..` at
    // the validation gate prevents an entire class of path-traversal
    // vulnerabilities regardless of how the path is used later.
    //
    // Also reject empty components (from consecutive slashes like
    // `src//main.rs` or trailing slashes like `src/`). Empty
    // components cause inconsistent behavior: the markdown renderer
    // shows them verbatim while the tree renderer silently collapses
    // them. Rejecting early ensures consistent output across formats.
    for component in path.split('/') {
        if component == ".." {
            return Err(WasmError::InvalidPath(
                "path contains '..' traversal component".into(),
            ));
        }
        if component.is_empty() {
            return Err(WasmError::InvalidPath(
                "path contains empty component (consecutive or trailing '/')".into(),
            ));
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn valid_path() {
        let f = VirtualFile::new("src/main.rs", "fn main() {}").unwrap();
        assert_eq!(f.path(), "src/main.rs");
        assert_eq!(f.content(), "fn main() {}");
        assert_eq!(f.file_name(), "main.rs");
        assert_eq!(f.extension(), Some("rs"));
        assert!(!f.is_dotfile());
    }

    #[test]
    fn rejects_empty_path() {
        assert!(VirtualFile::new("", "content").is_err());
    }

    #[test]
    fn rejects_null_byte() {
        assert!(VirtualFile::new("src/\0bad.rs", "").is_err());
    }

    #[test]
    fn rejects_control_chars() {
        assert!(VirtualFile::new("src/\x01bad.rs", "").is_err());
    }

    #[test]
    fn rejects_newline_in_path() {
        assert!(VirtualFile::new("src/\nbad.rs", "").is_err());
    }

    #[test]
    fn allows_tab_in_path() {
        assert!(VirtualFile::new("src/\tok.rs", "").is_ok());
    }

    #[test]
    fn rejects_overly_long_path() {
        let long = "a/".repeat(MAX_PATH_LEN);
        assert!(VirtualFile::new(long, "").is_err());
    }

    #[test]
    fn rejects_path_traversal() {
        assert!(VirtualFile::new("../etc/passwd", "").is_err());
        assert!(VirtualFile::new("src/../../etc/passwd", "").is_err());
        assert!(VirtualFile::new("src/..", "").is_err());
    }

    #[test]
    fn allows_double_dot_in_filename() {
        // `..foo` is not a traversal component — only exact `..` is.
        assert!(VirtualFile::new("src/..foo", "").is_ok());
        assert!(VirtualFile::new("src/foo..bar", "").is_ok());
    }

    #[test]
    fn rejects_backslash_path() {
        // Backslashes would silently break file_name(), extension(),
        // is_dotfile(), and tree rendering — all split on `/` only.
        assert!(VirtualFile::new("src\\main.rs", "").is_err());
        assert!(VirtualFile::new("src\\lib\\main.rs", "").is_err());
    }

    #[test]
    fn rejects_absolute_path() {
        assert!(VirtualFile::new("/etc/passwd", "").is_err());
        assert!(VirtualFile::new("/", "").is_err());
        assert!(VirtualFile::new("/src/main.rs", "").is_err());
    }

    #[test]
    fn rejects_consecutive_slashes() {
        assert!(VirtualFile::new("src//main.rs", "").is_err());
        assert!(VirtualFile::new("a///b", "").is_err());
    }

    #[test]
    fn rejects_trailing_slash() {
        assert!(VirtualFile::new("src/", "").is_err());
        assert!(VirtualFile::new("src/lib/", "").is_err());
    }

    #[test]
    fn extension_basic() {
        assert_eq!(
            VirtualFile::new_unchecked("main.rs", "").extension(),
            Some("rs")
        );
    }

    #[test]
    fn extension_multiple_dots() {
        assert_eq!(
            VirtualFile::new_unchecked("archive.tar.gz", "").extension(),
            Some("gz")
        );
    }

    #[test]
    fn extension_dotfile_returns_none() {
        // Matches std::path::Path::extension — no stem ⇒ no extension.
        assert_eq!(
            VirtualFile::new_unchecked(".gitignore", "").extension(),
            None
        );
    }

    #[test]
    fn extension_trailing_dot_returns_none() {
        // Intentional divergence from std (which returns Some("")).
        // Returning None here avoids matching empty strings against
        // extension-ignore lists.
        assert_eq!(
            VirtualFile::new_unchecked("Makefile.", "").extension(),
            None
        );
    }

    #[test]
    fn extension_no_dot() {
        assert_eq!(VirtualFile::new_unchecked("Makefile", "").extension(), None);
    }

    #[test]
    fn extension_ignores_dots_in_directory_components() {
        assert_eq!(
            VirtualFile::new_unchecked("src/my.module/Makefile", "").extension(),
            None
        );
        assert_eq!(
            VirtualFile::new_unchecked("src/my.module/lib.rs", "").extension(),
            Some("rs")
        );
    }

    #[test]
    fn dotfile_root() {
        assert!(VirtualFile::new_unchecked(".gitignore", "").is_dotfile());
    }

    #[test]
    fn dotfile_nested() {
        assert!(VirtualFile::new_unchecked("src/.hidden/file.rs", "").is_dotfile());
    }

    #[test]
    fn dotfile_dot_slash_prefix_is_not_dotfile() {
        // The `./` prefix is a current-directory marker, not a dotfile.
        assert!(!VirtualFile::new_unchecked("./src/main.rs", "").is_dotfile());
    }

    #[test]
    fn dotfile_dot_slash_with_actual_dotfile() {
        assert!(VirtualFile::new_unchecked("./.gitignore", "").is_dotfile());
    }

    #[test]
    fn not_dotfile() {
        assert!(!VirtualFile::new_unchecked("src/main.rs", "").is_dotfile());
    }

    #[test]
    fn normalized_path_strips_dot_slash() {
        let f = VirtualFile::new_unchecked("./src/main.rs", "");
        assert_eq!(f.normalized_path(), "src/main.rs");
    }

    #[test]
    fn normalized_path_noop_without_prefix() {
        let f = VirtualFile::new_unchecked("src/main.rs", "");
        assert_eq!(f.normalized_path(), "src/main.rs");
    }

    #[test]
    fn ordering_is_lexicographic_by_path() {
        let a = VirtualFile::new_unchecked("a.rs", "");
        let b = VirtualFile::new_unchecked("b.rs", "");
        let c = VirtualFile::new_unchecked("src/c.rs", "");
        let mut files = vec![c.clone(), a.clone(), b.clone()];
        files.sort();
        assert_eq!(files, vec![a, b, c]);
    }

    #[test]
    fn ord_consistent_with_eq() {
        let a = VirtualFile::new_unchecked("same.rs", "content a");
        let b = VirtualFile::new_unchecked("same.rs", "content b");
        // Same path, different content — tiebreak on content.
        if a.cmp(&b) == std::cmp::Ordering::Equal {
            assert_eq!(a, b);
        } else {
            assert_ne!(a, b);
        }
    }

    #[test]
    fn hash_consistent_with_eq() {
        use std::hash::{DefaultHasher, Hash, Hasher};

        let a = VirtualFile::new_unchecked("src/main.rs", "fn main() {}");
        let b = VirtualFile::new_unchecked("src/main.rs", "fn main() {}");
        assert_eq!(a, b);

        let hash = |v: &VirtualFile| {
            let mut h = DefaultHasher::new();
            v.hash(&mut h);
            h.finish()
        };
        assert_eq!(hash(&a), hash(&b));
    }

    #[test]
    fn serde_round_trip() {
        let original = VirtualFile::new("src/main.rs", "fn main() {}").unwrap();
        let json = serde_json::to_string(&original).unwrap();
        let recovered: VirtualFile = serde_json::from_str(&json).unwrap();
        assert_eq!(original, recovered);
    }

    #[test]
    fn deserialize_validates_empty_path() {
        let json = r#"{"path": "", "content": "bad"}"#;
        let result: Result<VirtualFile, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[test]
    fn deserialize_rejects_null_byte() {
        let json = r#"{"path": "src/\u0000bad.rs", "content": ""}"#;
        let result: Result<VirtualFile, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[test]
    fn deserialize_rejects_path_traversal() {
        let json = r#"{"path": "../etc/passwd", "content": "root:x:0:0"}"#;
        let result: Result<VirtualFile, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[test]
    fn deserialize_rejects_backslash() {
        let json = r#"{"path": "src\\main.rs", "content": ""}"#;
        let result: Result<VirtualFile, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }
}