nu-command 0.114.0

Nushell's built-in commands
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
use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use nu_test_support::prelude::*;
use rstest::rstest;
use std::path::{Path, PathBuf};

#[test]
fn empty_glob_pattern_triggers_error() {
    Playground::setup("glob_test_1", |dirs, sandbox| {
        sandbox.with_files(&[
            EmptyFile("yehuda.txt"),
            EmptyFile("jttxt"),
            EmptyFile("andres.txt"),
        ]);

        let actual = nu!(
            cwd: dirs.test(),
            "glob ''",
        );

        assert!(actual.err.contains("must not be empty"));
    })
}

#[test]
fn nonempty_glob_lists_matching_paths() {
    Playground::setup("glob_sanity_star", |dirs, sandbox| {
        sandbox.with_files(&[
            EmptyFile("yehuda.txt"),
            EmptyFile("jttxt"),
            EmptyFile("andres.txt"),
        ]);

        let actual = nu!(
            cwd: dirs.test(),
            "glob '*' | length",
        );

        assert_eq!(actual.out, "3");
    })
}

#[test]
fn glob_subdirs() {
    Playground::setup("glob_subdirs", |dirs, sandbox| {
        sandbox.with_files(&[
            EmptyFile("yehuda.txt"),
            EmptyFile("jttxt"),
            EmptyFile("andres.txt"),
        ]);
        sandbox.mkdir("children");
        sandbox.within("children").with_files(&[
            EmptyFile("timothy.txt"),
            EmptyFile("tiffany.txt"),
            EmptyFile("trish.txt"),
        ]);

        let actual = nu!(
            cwd: dirs.test(),
            "glob '**/*' | length",
        );

        assert_eq!(
            actual.out, "8",
            "count must be 8 due to 6 files and 2 folders, including the cwd"
        );
    })
}

#[test]
fn glob_subdirs_ignore_dirs() {
    Playground::setup("glob_subdirs_ignore_directories", |dirs, sandbox| {
        sandbox.with_files(&[
            EmptyFile("yehuda.txt"),
            EmptyFile("jttxt"),
            EmptyFile("andres.txt"),
        ]);
        sandbox.mkdir("children");
        sandbox.within("children").with_files(&[
            EmptyFile("timothy.txt"),
            EmptyFile("tiffany.txt"),
            EmptyFile("trish.txt"),
        ]);

        let actual = nu!(
            cwd: dirs.test(),
            "glob '**/*' -D | length",
        );

        assert_eq!(
            actual.out, "6",
            "directory count must be 6, ignoring the cwd and the children folders"
        );
    })
}

#[test]
fn glob_ignore_files() {
    Playground::setup("glob_ignore_files", |dirs, sandbox| {
        sandbox.with_files(&[
            EmptyFile("yehuda.txt"),
            EmptyFile("jttxt"),
            EmptyFile("andres.txt"),
        ]);
        sandbox.mkdir("children");
        sandbox.within("children").with_files(&[
            EmptyFile("timothy.txt"),
            EmptyFile("tiffany.txt"),
            EmptyFile("trish.txt"),
        ]);

        let actual = nu!(
            cwd: dirs.test(),
            "glob '*' -F | length",
        );

        assert_eq!(
            actual.out, "1",
            "should only find one folder; ignoring cwd, files, subfolders"
        );
    })
}

// clone of fs::create_file_at removing the parent panic, whose purpose I do not grok.
pub fn create_file_at(full_path: impl AsRef<Path>) -> Result<(), std::io::Error> {
    let full_path = full_path.as_ref();
    std::fs::write(full_path, b"fake data")
}

// playground has root directory and subdirectories foo and foo/bar to play with
// specify all test files relative to root directory.
// OK to use fwd slash in paths, they're hacked to OS dir separator when needed (windows)
#[rstest]
#[case(".", "'*z'", &["ablez", "baker", "charliez"], &["ablez", "charliez"], "simple glob")]
#[case(".", "'qqq'", &["ablez", "baker", "charliez"], &[], "glob matches none")]
#[case("foo/bar", r"'*[\]}]*'", &["foo/bar/ab}le", "foo/bar/baker", "foo/bar/cha]rlie"], &["foo/bar/ab}le", "foo/bar/cha]rlie"], "glob has quoted metachars")]
#[case("foo/bar", "'../*'", &["foo/able", "foo/bar/baker", "foo/charlie"], &["foo/bar/../able", "foo/bar/../bar", "foo/bar/../charlie"], "glob matches files in parent")]
#[case("foo", "'./{a,b}*'", &["foo/able", "foo/bar/baker", "foo/charlie"], &["foo/able", "foo/bar"], "glob with leading ./ matches peer files")]
fn glob_files_in_parent(
    #[case] wd: &str,
    #[case] glob: &str,
    #[case] ini: &[&str],
    #[case] exp: &[&str],
    #[case] tag: &str,
) {
    Playground::setup("glob_test", |dirs, sandbox| {
        sandbox.within("foo").within("bar");
        let working_directory = &dirs.test().join(wd);

        for f in ini {
            create_file_at(dirs.test().join(f)).expect("couldn't create file");
        }

        let actual = nu!(
            cwd: working_directory,
            format!(r#"glob {glob} | sort | str join " ""#)
        );

        let mut expected: Vec<String> = vec![];
        for e in exp {
            // Normalize windows paths by converting / to \ and resolving .. components lexically.
            #[cfg(windows)]
            let e = {
                let mut path = PathBuf::new();
                for c in Path::new(e).components() {
                    if c == std::path::Component::ParentDir {
                        path.pop();
                    } else {
                        path.push(c)
                    }
                }
                path
            };
            #[cfg(not(windows))]
            let e = PathBuf::from(e);

            expected.push(dirs.test().join(e).to_string_lossy().to_string());
        }

        let expected = expected.join(" ");
        assert_eq!(actual.out, expected, "\n  test: {tag}");
    });
}

#[test]
fn glob_follow_symlinks() {
    Playground::setup("glob_follow_symlinks", |dirs, sandbox| {
        // Create a directory with some files
        sandbox.mkdir("target_dir");
        sandbox
            .within("target_dir")
            .with_files(&[EmptyFile("target_file.txt")]);

        let target_dir = dirs.test().join("target_dir");
        let symlink_path = dirs.test().join("symlink_dir");
        #[cfg(unix)]
        std::os::unix::fs::symlink(target_dir, &symlink_path).expect("Failed to create symlink");
        #[cfg(windows)]
        std::os::windows::fs::symlink_dir(target_dir, &symlink_path)
            .expect("Failed to create symlink");

        // on some systems/filesystems, symlinks are followed by default
        // on others (like Linux /sys), they aren't
        // Test that with the --follow-symlinks flag, files are found for sure
        let with_flag = nu!(
            cwd: dirs.test(),
            "glob 'symlink_dir/*.txt' --follow-symlinks | length",
        );

        assert_eq!(
            with_flag.out, "1",
            "Should find file with --follow-symlinks flag"
        );
    })
}

#[test]
#[exp(nu_experimental::DC_GLOB)]
fn glob_dc_glob_supports_depth_and_exclude() -> Result {
    Playground::setup("glob_dc_depth_exclude", |dirs, sandbox| {
        sandbox.with_files(&[EmptyFile("three.txt"), EmptyFile("four.txt")]);

        test()
            .cwd(dirs.test())
            .run("glob '*.txt' --depth 1 --exclude [four.txt] | length")
            .expect_value_eq(1)
            .expect("glob should support --depth and --exclude with dc-glob enabled");
    });

    Ok(())
}

#[test]
#[exp(nu_experimental::DC_GLOB)]
fn glob_dc_glob_supports_follow_symlinks() -> Result {
    Playground::setup("glob_dc_follow_symlink", |dirs, sandbox| {
        sandbox.mkdir("target_dir");
        sandbox
            .within("target_dir")
            .with_files(&[EmptyFile("target_file.txt")]);

        let target_dir = dirs.test().join("target_dir");
        let symlink_path = dirs.test().join("symlink_dir");
        #[cfg(unix)]
        std::os::unix::fs::symlink(target_dir, &symlink_path).expect("Failed to create symlink");
        #[cfg(windows)]
        std::os::windows::fs::symlink_dir(target_dir, &symlink_path)
            .expect("Failed to create symlink");

        test()
            .cwd(dirs.test())
            .run("glob 'symlink_dir/*.txt' --follow-symlinks | length")
            .expect_value_eq(1)
            .expect("glob should follow symlinked dirs when --follow-symlinks is set");
    });

    Ok(())
}

#[test]
#[exp(nu_experimental::DC_GLOB)]
fn glob_debug_subcommands_enabled() -> Result {
    Playground::setup("glob_dc_debug_subcommands", |dirs, sandbox| {
        sandbox.with_files(&[EmptyFile("file.txt")]);

        test()
            .cwd(dirs.test())
            .run("glob --dbg-parse '*' | str contains 'Wildcard'")
            .expect_value_eq(true)
            .expect("--dbg-parse should be available with dc-glob enabled");

        test()
            .cwd(dirs.test())
            .run("glob --dbg-compile '**/*' | str contains 'Complete'")
            .expect_value_eq(true)
            .expect("--dbg-compile should be available with dc-glob enabled");

        test()
            .cwd(dirs.test())
            .run("glob --dbg-matches '.'")
            .expect_value_eq(true)
            .expect("--dbg-matches should be available with dc-glob enabled");

        test()
            .cwd(dirs.test())
            .run("glob --dbg-glob '*.txt' | length")
            .expect_value_eq(1)
            .expect("--dbg-glob should be available with dc-glob enabled");
    });

    Ok(())
}

#[test]
#[exp(nu_experimental::DC_GLOB = false)]
fn glob_debug_subcommands_disabled() -> Result {
    Playground::setup("glob_dc_debug_subcommands_off", |dirs, _sandbox| {
        let err = test()
            .cwd(dirs.test())
            .run("glob --dbg-parse '*'")
            .expect_parse_error()
            .expect("glob should reject dbg flags when dc-glob is disabled");

        let err = err.to_string();
        assert!(
            err.contains("unknown_flag")
                || err.contains("unknown flag")
                || err.contains("doesn't have flag"),
            "expected unknown-flag parse error, got: {err}"
        );
    });

    Ok(())
}

#[test]
#[exp(nu_experimental::DC_GLOB)]
fn glob_debug_subcommands_require_pattern_argument() -> Result {
    Playground::setup("glob_dc_debug_missing_pattern", |dirs, _sandbox| {
        let parse = test()
            .cwd(dirs.test())
            .run("glob --dbg-parse")
            .expect_parse_error()
            .expect("--dbg-parse should require pattern argument");
        let parse = parse.to_string();
        assert!(
            parse.contains("missing")
                || parse.contains("required positional")
                || parse.contains("missing_positional"),
            "expected missing-argument parse error, got: {parse}"
        );

        let compile = test()
            .cwd(dirs.test())
            .run("glob --dbg-compile")
            .expect_parse_error()
            .expect("--dbg-compile should require pattern argument");
        let compile = compile.to_string();
        assert!(
            compile.contains("missing")
                || compile.contains("required positional")
                || compile.contains("missing_positional"),
            "expected missing-argument parse error, got: {compile}"
        );

        let matches = test()
            .cwd(dirs.test())
            .run("glob --dbg-matches")
            .expect_parse_error()
            .expect("--dbg-matches should require pattern argument");
        let matches = matches.to_string();
        assert!(
            matches.contains("missing")
                || matches.contains("required positional")
                || matches.contains("missing_positional"),
            "expected missing-argument parse error, got: {matches}"
        );

        let dbg_glob = test()
            .cwd(dirs.test())
            .run("glob --dbg-glob")
            .expect_parse_error()
            .expect("--dbg-glob should require pattern argument");
        let dbg_glob = dbg_glob.to_string();
        assert!(
            dbg_glob.contains("missing")
                || dbg_glob.contains("required positional")
                || dbg_glob.contains("missing_positional"),
            "expected missing-argument parse error, got: {dbg_glob}"
        );
    });

    Ok(())
}

#[test]
#[exp(nu_experimental::DC_GLOB)]
fn glob_dc_glob_literal_prefix_wildcard() -> Result {
    Playground::setup("glob_dc_literal_prefix_wildcard", |dirs, sandbox| {
        sandbox.mkdir("subdir");
        sandbox.within("subdir").with_files(&[
            EmptyFile("nu_test1"),
            EmptyFile("nu_test2"),
            EmptyFile("other"),
        ]);

        test()
            .cwd(dirs.test())
            .run("glob 'subdir/nu*' | length")
            .expect_value_eq(2)
            .expect("glob 'subdir/nu*' should match both nu_test files with dc-glob");
    });

    Ok(())
}

#[test]
#[exp(nu_experimental::DC_GLOB)]
fn glob_dc_glob_wildcard_then_literal() -> Result {
    Playground::setup("glob_dc_wildcard_literal", |dirs, sandbox| {
        sandbox.mkdir("subdir");
        sandbox.within("subdir").with_files(&[
            EmptyFile("nu_test1"),
            EmptyFile("nu_test2"),
            EmptyFile("other"),
        ]);

        test()
            .cwd(dirs.test())
            .run("glob 'subdir/*nu*' | length")
            .expect_value_eq(2)
            .expect("glob 'subdir/*nu*' should match both nu_test files with dc-glob");
    });

    Ok(())
}

#[test]
#[exp(nu_experimental::DC_GLOB)]
fn glob_dc_glob_literal_prefix_wildcard_absolute() -> Result {
    Playground::setup("glob_dc_literal_prefix_abs", |dirs, sandbox| {
        sandbox.mkdir("subdir");
        sandbox
            .within("subdir")
            .with_files(&[EmptyFile("nu_test.txt")]);

        let pattern = format!("{}/subdir/nu*", dirs.test().to_string_lossy());
        test()
            .cwd(dirs.test())
            .run(format!("glob '{pattern}' | length"))
            .expect_value_eq(1)
            .expect("absolute glob pattern with literal-then-wildcard should work with dc-glob");
    });

    Ok(())
}