nu-engine 0.115.1

Nushell's evaluation engine
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
use nu_glob::MatchOptions;
use nu_path::{absolute_with, expand_path_with};
use nu_protocol::{
    NuGlob, ShellError, Signals, Span, Spanned, shell_error::generic::GenericError,
    shell_error::io::IoError,
};
use std::{
    fs, io,
    path::{Component, Path, PathBuf},
};

/// This function is like `nu_glob::glob` from the `glob` crate, except it is relative to a given cwd.
///
/// It returns a tuple of two values: the first is an optional prefix that the expanded filenames share.
/// This prefix can be removed from the front of each value to give an approximation of the relative path
/// to the user
///
/// The second of the two values is an iterator over the matching filepaths.
#[allow(clippy::type_complexity)]
pub fn glob_from(
    pattern: &Spanned<NuGlob>,
    cwd: &Path,
    span: Span,
    options: Option<MatchOptions>,
    signals: Signals,
) -> Result<
    (
        Option<PathBuf>,
        Box<dyn Iterator<Item = Result<PathBuf, ShellError>> + Send>,
    ),
    ShellError,
> {
    let no_glob_for_pattern = matches!(pattern.item, NuGlob::DoNotExpand(_));
    let pattern_span = pattern.span;
    let (prefix, pattern) = if nu_glob::is_glob_with_backend(pattern.item.as_ref()) {
        // Pattern contains glob, split it
        let mut p = PathBuf::new();
        let path = PathBuf::from(&pattern.item.as_ref());
        let components = path.components();
        let mut counter = 0;

        for c in components {
            if let Component::Normal(os) = c
                && nu_glob::is_glob_with_backend(os.to_string_lossy().as_ref())
            {
                break;
            }
            p.push(c);
            counter += 1;
        }

        let mut just_pattern = PathBuf::new();
        for c in counter..path.components().count() {
            if let Some(comp) = path.components().nth(c) {
                just_pattern.push(comp);
            }
        }
        if no_glob_for_pattern {
            just_pattern = PathBuf::from(nu_glob::escape_with_backend(
                &just_pattern.to_string_lossy(),
            ));
        }

        // Now expand `p` to get full prefix
        let path = expand_path_with(p, cwd, pattern.item.is_expand());
        let escaped_prefix = PathBuf::from(nu_glob::escape_with_backend(&path.to_string_lossy()));

        (Some(path), escaped_prefix.join(just_pattern))
    } else {
        let path = PathBuf::from(&pattern.item.as_ref());
        let path = expand_path_with(path, cwd, pattern.item.is_expand());
        let is_symlink = match fs::symlink_metadata(&path) {
            Ok(attr) => attr.file_type().is_symlink(),
            Err(_) => false,
        };

        if is_symlink {
            (path.parent().map(|parent| parent.to_path_buf()), path)
        } else {
            let path = match absolute_with(path.clone(), cwd) {
                Ok(p) if p.exists() => {
                    if nu_glob::is_glob_with_backend(p.to_string_lossy().as_ref()) {
                        // our path might contain glob metacharacters too.
                        // in such case, we need to escape our path to make
                        // glob work successfully
                        PathBuf::from(nu_glob::escape_with_backend(&p.to_string_lossy()))
                    } else {
                        p
                    }
                }
                Ok(_) => {
                    return Err(IoError::new(
                        io::Error::from(io::ErrorKind::NotFound),
                        pattern_span,
                        path,
                    )
                    .into());
                }
                Err(err) => {
                    return Err(IoError::new(err, pattern_span, path).into());
                }
            };
            (path.parent().map(|parent| parent.to_path_buf()), path)
        }
    };

    let pattern = pattern.to_string_lossy().to_string();

    if nu_experimental::DC_GLOB.get() {
        let pattern_path = PathBuf::from(&pattern);
        // If the resolved pattern is an existing *literal* path (no active glob
        // metacharacters), return it directly. Passing a plain path to
        // glob_from_interruptible makes the traversal engine call read_dir() on it,
        // which either fails with "Not a directory" (for files) or iterates the
        // directory's contents instead of matching the directory itself (for
        // directories), both of which produce incorrect empty results.
        //
        // Patterns that still contain glob metacharacters must go through the
        // walker even when a same-named path exists (e.g. a file named `*` must
        // not make bare `*` / `ls` return only that one entry). See #18631.
        if pattern_path.exists() && !nu_glob::is_glob_with_backend(&pattern) {
            return Ok((prefix, Box::new(std::iter::once(Ok(pattern_path)))));
        }

        let iter =
            nu_glob::dc_glob::glob_from_interruptible(cwd, &pattern, signals.interrupt_flag())
                .map_err(|e| {
                    ShellError::Generic(GenericError::new(
                        "Error extracting glob pattern",
                        e.to_string(),
                        span,
                    ))
                })?;

        // dc-glob returns paths relative to the traversal start directory.
        // Join them with `prefix` to produce absolute paths, matching the
        // legacy backend's behaviour.
        let prefix_for_map = prefix.clone();
        let mapped = iter.map(move |x| match x {
            Ok(v) => {
                let v = match &prefix_for_map {
                    Some(p) if v.is_relative() => p.join(&v),
                    _ => v,
                };
                Ok(v)
            }
            Err(e) => Err(ShellError::Generic(GenericError::new(
                "Error extracting glob pattern",
                e.to_string(),
                span,
            ))),
        });

        Ok((prefix, Box::new(mapped)))
    } else {
        let glob_options = options.unwrap_or_default();
        let glob = nu_glob::glob_with(&pattern, glob_options, signals).map_err(|e| {
            ShellError::Generic(GenericError::new(
                "Error extracting glob pattern",
                e.to_string(),
                span,
            ))
        })?;

        let mapped = glob.map(move |x| match x {
            Ok(v) => Ok(v),
            Err(e) => Err(ShellError::Generic(GenericError::new(
                "Error extracting glob pattern",
                e.error().to_string(),
                span,
            ))),
        });

        Ok((prefix, Box::new(mapped)))
    }
}

#[cfg(test)]
mod tests {
    use super::glob_from;
    use nu_protocol::{NuGlob, Signals, Span, Spanned};
    use std::fs;
    use std::path::{Path, PathBuf};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};

    static NEXT_ID: AtomicU64 = AtomicU64::new(0);

    fn unique_test_dir(prefix: &str) -> PathBuf {
        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);

        std::env::temp_dir().join(format!(
            "nu_engine_glob_from_{prefix}_{}_{}",
            std::process::id(),
            ts + u128::from(NEXT_ID.fetch_add(1, Ordering::Relaxed))
        ))
    }

    fn write_file(path: &PathBuf) {
        let create_result = fs::create_dir_all(path.parent().unwrap_or(path));
        assert!(
            create_result.is_ok(),
            "failed to create parent dir for {}: {:?}",
            path.display(),
            create_result
        );

        let write_result = fs::write(path, b"x");
        assert!(
            write_result.is_ok(),
            "failed to write test file {}: {:?}",
            path.display(),
            write_result
        );
    }

    #[test]
    #[exp(nu_experimental::DC_GLOB)]
    fn glob_from_dc_glob_remains_lazy_for_first_item() {
        let root = unique_test_dir("lazy_first_item");
        let root_create_result = fs::create_dir_all(&root);
        assert!(
            root_create_result.is_ok(),
            "failed to create root test directory {}: {:?}",
            root.display(),
            root_create_result
        );

        // A top-level match gives the iterator a fast first row.
        write_file(&root.join("top.rs"));

        // Create enough matches that eager collection would fully drain on construction.
        let nested_count = 9000usize;
        for idx in 0..nested_count {
            write_file(&root.join(format!("deep/dir_{idx}/file_{idx}.rs")));
        }

        let ctrlc = Arc::new(AtomicBool::new(false));
        let signals = Signals::new(ctrlc);
        let pattern = Spanned {
            item: NuGlob::Expand("**/*.rs".to_string()),
            span: Span::test_data(),
        };

        let result = glob_from(&pattern, &root, Span::test_data(), None, signals.clone());
        assert!(result.is_ok(), "glob_from failed");

        let (_, mut iter) = match result {
            Ok(v) => v,
            Err(err) => panic!("glob_from failed unexpectedly: {err}"),
        };

        let first = iter.next();
        assert!(
            matches!(first, Some(Ok(_))),
            "expected first iterator item to be a match, got: {first:?}"
        );

        // Interrupt after the first row. If glob_from eagerly materializes,
        // the returned iterator has already consumed all rows and this has no effect.
        signals.trigger();

        let remaining = iter.count();
        assert!(
            remaining < 6000,
            "expected interrupt to stop iteration before full drain; remaining={remaining}"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    #[exp(nu_experimental::DC_GLOB)]
    fn glob_from_dc_glob_matches_literal_file() {
        let root = unique_test_dir("literal_file");
        fs::create_dir_all(&root).expect("failed to create root");
        let file = root.join("test.txt");
        write_file(&file);

        let ctrlc = Arc::new(AtomicBool::new(false));
        let signals = Signals::new(ctrlc);
        let pattern = Spanned {
            item: NuGlob::Expand(file.to_string_lossy().to_string()),
            span: Span::test_data(),
        };

        let result = glob_from(&pattern, Path::new("/"), Span::test_data(), None, signals);
        assert!(result.is_ok(), "glob_from failed");

        let (_, mut iter) = result.unwrap();
        let first = iter.next();
        assert!(
            matches!(first, Some(Ok(ref p)) if *p == file),
            "expected file path itself, got: {first:?}"
        );
        assert!(iter.next().is_none(), "expected exactly one result");

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    #[exp(nu_experimental::DC_GLOB)]
    fn glob_from_dc_glob_matches_literal_directory() {
        let root = unique_test_dir("literal_dir");
        fs::create_dir_all(&root).expect("failed to create root");

        let ctrlc = Arc::new(AtomicBool::new(false));
        let signals = Signals::new(ctrlc);
        let pattern = Spanned {
            item: NuGlob::Expand(root.to_string_lossy().to_string()),
            span: Span::test_data(),
        };

        let result = glob_from(&pattern, Path::new("/"), Span::test_data(), None, signals);
        assert!(result.is_ok(), "glob_from failed");

        let (_, mut iter) = result.unwrap();
        let first = iter.next();
        assert!(
            matches!(first, Some(Ok(ref p)) if *p == root),
            "expected directory path itself, got: {first:?}"
        );
        assert!(iter.next().is_none(), "expected exactly one result");

        let _ = fs::remove_dir_all(&root);
    }

    // Windows does not allow `*` in filenames, so this regression only applies on Unix.
    #[cfg(not(windows))]
    #[test]
    #[exp(nu_experimental::DC_GLOB)]
    fn glob_from_dc_glob_star_with_literal_star_file() {
        // Regression for #18631: a file named `*` must not make pattern `*`
        // short-circuit to only that path.
        let root = unique_test_dir("star_file");
        fs::create_dir_all(&root).expect("failed to create root");
        write_file(&root.join("a"));
        write_file(&root.join("b"));
        write_file(&root.join("*"));

        let ctrlc = Arc::new(AtomicBool::new(false));
        let signals = Signals::new(ctrlc);
        let pattern = Spanned {
            item: NuGlob::Expand("*".to_string()),
            span: Span::test_data(),
        };

        let result = glob_from(&pattern, &root, Span::test_data(), None, signals);
        assert!(result.is_ok(), "glob_from failed");

        let (_, iter) = match result {
            Ok(v) => v,
            Err(err) => panic!("glob_from failed unexpectedly: {err}"),
        };
        let mut names: Vec<String> = iter
            .map(|r| {
                r.expect("glob path ok")
                    .file_name()
                    .expect("basename")
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        names.sort();

        assert_eq!(
            names,
            vec!["*".to_string(), "a".to_string(), "b".to_string()]
        );

        let _ = fs::remove_dir_all(&root);
    }

    // Windows does not allow `*` in filenames, so this regression only applies on Unix.
    #[cfg(not(windows))]
    #[test]
    #[exp(nu_experimental::DC_GLOB)]
    fn glob_from_dc_glob_prefix_wildcard_with_literal_match_name() {
        // Pattern `foo*` must still expand when a file literally named `foo*` exists.
        let root = unique_test_dir("foo_star");
        fs::create_dir_all(&root).expect("failed to create root");
        write_file(&root.join("foo1"));
        write_file(&root.join("foo2"));
        write_file(&root.join("foo*"));
        write_file(&root.join("other"));

        let ctrlc = Arc::new(AtomicBool::new(false));
        let signals = Signals::new(ctrlc);
        let pattern = Spanned {
            item: NuGlob::Expand("foo*".to_string()),
            span: Span::test_data(),
        };

        let result = glob_from(&pattern, &root, Span::test_data(), None, signals);
        assert!(result.is_ok(), "glob_from failed");

        let (_, iter) = match result {
            Ok(v) => v,
            Err(err) => panic!("glob_from failed unexpectedly: {err}"),
        };
        let mut names: Vec<String> = iter
            .map(|r| {
                r.expect("glob path ok")
                    .file_name()
                    .expect("basename")
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        names.sort();

        assert_eq!(
            names,
            vec!["foo*".to_string(), "foo1".to_string(), "foo2".to_string()]
        );

        let _ = fs::remove_dir_all(&root);
    }
}