nu-command 0.115.1

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
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use nu_engine::{command_prelude::*, env};
use nu_protocol::PipelineMetadata;
use nu_protocol::engine::CommandType;
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::path::{Path, PathBuf};
use which::WhichConfig;
use which::sys::{RealSys, Sys};

#[derive(Clone)]
pub struct Which;

impl Command for Which {
    fn name(&self) -> &str {
        "which"
    }

    fn signature(&self) -> Signature {
        Signature::build("which")
            .input_output_types(vec![(Type::Nothing, Type::table())])
            .allow_variants_without_examples(true)
            .param(Parameter::Rest(
                PositionalArg::new("applications", SyntaxShape::String)
                    .desc("Application(s).")
                    .completion(Completion::Builtin(BuiltinCompletion::Command {
                        internal_only: false,
                    })),
            ))
            .switch("all", "List all executables.", Some('a'))
            .category(Category::System)
    }

    fn description(&self) -> &str {
        "Finds a program file, alias or custom command. If `application` is not provided, all deduplicated commands will be returned."
    }

    fn search_terms(&self) -> Vec<&str> {
        vec![
            "find",
            "path",
            "location",
            "command",
            "whereis",     // linux binary to find binary locations in path
            "get-command", // powershell command to find commands and binaries in path
        ]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        _input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        which(engine_state, stack, call)
    }

    fn examples(&self) -> Vec<Example<'_>> {
        vec![
            Example {
                description: "Find if the 'myapp' application is available",
                example: "which myapp",
                result: None,
            },
            Example {
                description: "Find all executables across all paths without deduplication",
                example: "which -a",
                result: None,
            },
        ]
    }
}

/// Returns the source file path that covers `span`, if any.
fn file_for_span(engine_state: &EngineState, span: Span) -> Option<String> {
    engine_state
        .files()
        .find(|f| f.covered_span.contains_span(span))
        .map(|f| f.name.to_string())
}

/// Returns the source file path for a declaration, if it can be determined.
///
/// - Aliases: resolved via `decl_span()` (the alias expansion span)
/// - Custom commands: resolved from the block's span via `block_id()`
/// - Plugins: resolved from the plugin identity's filename
/// - Known externals (`extern` declarations): resolved via `decl_span()`
fn file_for_decl(
    engine_state: &EngineState,
    decl: &dyn nu_protocol::engine::Command,
) -> Option<String> {
    if let Some(block_id) = decl.block_id() {
        return engine_state
            .get_block(block_id)
            .span
            .and_then(|sp| file_for_span(engine_state, sp));
    }
    #[cfg(feature = "plugin")]
    if decl.is_plugin() {
        return decl
            .plugin_identity()
            .map(|id| id.filename().to_string_lossy().to_string());
    }
    if let Some(span) = decl.decl_span() {
        return file_for_span(engine_state, span);
    }
    None
}

// Shortcut for creating an entry to the output table.
fn entry(
    arg: impl Into<String>,
    path: impl Into<String>,
    cmd_type: CommandType,
    definition: Option<String>,
    file: Option<String>,
    span: Span,
) -> Value {
    let arg = arg.into();
    let path = path.into();
    let path_value = if path.is_empty() {
        file.unwrap_or_default()
    } else {
        path.clone()
    };

    let mut record = record! {
        "command" => Value::string(arg, span),
        "path" => Value::string(path_value, span),
        "type" => Value::string(cmd_type.to_string(), span),
    };

    if let Some(def) = definition {
        record.insert("definition", Value::string(def, span));
    }

    Value::record(record, span)
}

fn get_entry_in_commands(engine_state: &EngineState, name: &str, span: Span) -> Option<Value> {
    let decl_id = engine_state.find_decl(name.as_bytes(), &[])?;
    let decl = engine_state.get_decl(decl_id);
    let definition = if decl.command_type() == CommandType::Alias {
        decl.as_alias().map(|alias| {
            String::from_utf8_lossy(engine_state.get_span_contents(alias.wrapped_call.span))
                .to_string()
        })
    } else {
        None
    };
    let file = file_for_decl(engine_state, decl);
    Some(entry(name, "", decl.command_type(), definition, file, span))
}

/// Reads `$env.PATHEXT` from the shell environment as an `OsString`, mirroring
/// how `PATH` is read for lookups. The lookup is case-insensitive, matching the
/// usual `PATHEXT` casing on Windows.
///
/// When the shell environment has no visible `PATHEXT`, a value that was
/// explicitly hidden (e.g. `hide-env PATHEXT`) stays hidden: `None` is
/// returned rather than resurrecting the hidden value from the process
/// environment. Only when the shell has never seen `PATHEXT` do we fall back
/// to the process `PATHEXT`, so default behavior is unchanged. Returns `None`
/// when unset everywhere, which is the normal case on non-Windows systems.
fn env_path_ext(engine_state: &EngineState, stack: &Stack) -> Option<OsString> {
    if let Some(value) = stack.get_env_var(engine_state, "pathext") {
        return env::env_to_string("PATHEXT", value, engine_state, stack)
            .ok()
            .map(OsString::from);
    }
    if stack.is_env_var_hidden("PATHEXT") {
        None
    } else {
        std::env::var_os("PATHEXT")
    }
}

/// A [`which::sys::Sys`] that behaves like the real system in every respect
/// except that `PATHEXT` is sourced from nushell's environment (`$env.PATHEXT`)
/// instead of the process environment. This lets `which` honor in-shell changes
/// to `PATHEXT` (for example via `with-env`), the same way it already honors
/// in-shell changes to `PATH` (which is passed in explicitly).
#[derive(Clone)]
struct NuWhichSys {
    path_ext: Option<OsString>,
}

impl Sys for NuWhichSys {
    type ReadDirEntry = std::fs::DirEntry;
    type Metadata = std::fs::Metadata;

    fn is_windows(&self) -> bool {
        RealSys.is_windows()
    }

    fn current_dir(&self) -> std::io::Result<PathBuf> {
        RealSys.current_dir()
    }

    fn home_dir(&self) -> Option<PathBuf> {
        RealSys.home_dir()
    }

    fn env_split_paths(&self, paths: &OsStr) -> Vec<PathBuf> {
        RealSys.env_split_paths(paths)
    }

    fn env_path(&self) -> Option<OsString> {
        RealSys.env_path()
    }

    fn env_path_ext(&self) -> Option<OsString> {
        self.path_ext.clone()
    }

    // `env_windows_path_ext` is deliberately left as the trait default, which
    // re-parses `self.env_path_ext()` on every call. `RealSys` overrides it to
    // cache the process `PATHEXT` in a process-wide `OnceLock`, which would
    // ignore `$env.PATHEXT`; the default keeps our value authoritative.

    fn metadata(&self, path: &Path) -> std::io::Result<Self::Metadata> {
        RealSys.metadata(path)
    }

    fn symlink_metadata(&self, path: &Path) -> std::io::Result<Self::Metadata> {
        RealSys.symlink_metadata(path)
    }

    fn read_dir(
        &self,
        path: &Path,
    ) -> std::io::Result<Box<dyn Iterator<Item = std::io::Result<Self::ReadDirEntry>>>> {
        RealSys.read_dir(path)
    }

    fn is_valid_executable(&self, path: &Path) -> std::io::Result<bool> {
        RealSys.is_valid_executable(path)
    }
}

fn get_first_entry_in_path(
    item: &str,
    span: Span,
    cwd: impl AsRef<Path>,
    paths: impl AsRef<OsStr>,
    path_ext: &Option<OsString>,
) -> Option<Value> {
    WhichConfig::new_with_sys(NuWhichSys {
        path_ext: path_ext.clone(),
    })
    .binary_name(item.into())
    .custom_cwd(cwd.as_ref().to_path_buf())
    .custom_path_list(paths.as_ref().to_os_string())
    .first_result()
    .map(|path| {
        let full_path = path.to_string_lossy().to_string();
        entry(
            item,
            full_path.clone(),
            CommandType::External,
            None,
            Some(full_path),
            span,
        )
    })
    .ok()
}

fn get_all_entries_in_path(
    item: &str,
    span: Span,
    cwd: impl AsRef<Path>,
    paths: impl AsRef<OsStr>,
    path_ext: &Option<OsString>,
) -> Vec<Value> {
    // The results may contain the same canonical path more than once. On systems
    // where PATH contains both a real directory and a symlink pointing to the same
    // place (e.g. `/usr/bin` and `/bin -> /usr/bin` on WSL/Debian), the same path
    // would appear multiple times. The HashSet deduplicates those before we build
    // the output rows.
    let mut seen = HashSet::new();
    WhichConfig::new_with_sys(NuWhichSys {
        path_ext: path_ext.clone(),
    })
    .binary_name(item.into())
    .custom_cwd(cwd.as_ref().to_path_buf())
    .custom_path_list(paths.as_ref().to_os_string())
    .all_results()
    .map(|iter| {
        iter.filter(|path| seen.insert(path.clone()))
            .map(|path| {
                let full_path = path.to_string_lossy().to_string();
                entry(
                    item,
                    full_path.clone(),
                    CommandType::External,
                    None,
                    Some(full_path),
                    span,
                )
            })
            .collect()
    })
    .unwrap_or_default()
}

fn list_all_executables(
    engine_state: &EngineState,
    paths: impl AsRef<OsStr>,
    path_ext: &Option<OsString>,
    all: bool,
    span: Span,
) -> Vec<Value> {
    let decls = engine_state.get_decls_sorted(false);

    let mut results = Vec::with_capacity(decls.len());
    let mut seen_commands = HashSet::with_capacity(decls.len());

    for (name_bytes, decl_id) in decls {
        let name = String::from_utf8_lossy(&name_bytes).to_string();
        seen_commands.insert(name.clone());
        let decl = engine_state.get_decl(decl_id);
        let definition = if decl.command_type() == CommandType::Alias {
            decl.as_alias().map(|alias| {
                String::from_utf8_lossy(engine_state.get_span_contents(alias.wrapped_call.span))
                    .to_string()
            })
        } else {
            None
        };
        let file = file_for_decl(engine_state, decl);

        results.push(entry(
            name,
            String::new(),
            decl.command_type(),
            definition,
            file,
            span,
        ));
    }

    // Add PATH executables
    let path_iter = RealSys
        .env_split_paths(paths.as_ref())
        .into_iter()
        .filter_map(|dir| fs::read_dir(dir).ok())
        .flat_map(|entries| entries.flatten())
        .map(|entry| entry.path())
        .filter_map(|path| {
            if !path.is_executable(path_ext.as_deref()) {
                return None;
            }
            let filename = path.file_name()?.to_string_lossy().to_string();

            if !all && !seen_commands.insert(filename.clone()) {
                return None;
            }

            let full_path = path.to_string_lossy().to_string();
            Some(entry(
                filename,
                full_path.clone(),
                CommandType::External,
                None,
                Some(full_path),
                span,
            ))
        });

    results.extend(path_iter);
    results
}

#[derive(Debug)]
struct WhichArgs {
    applications: Vec<Spanned<String>>,
    all: bool,
}

fn which_single(
    application: Spanned<String>,
    all: bool,
    engine_state: &EngineState,
    cwd: impl AsRef<Path>,
    paths: impl AsRef<OsStr>,
    path_ext: &Option<OsString>,
) -> Vec<Value> {
    let cwd = cwd.as_ref();
    let paths = paths.as_ref();
    let (external, prog_name) = if application.item.starts_with('^') {
        (true, application.item[1..].to_string())
    } else {
        (false, application.item.clone())
    };

    // If prog_name is an external command, don't search for nu-specific programs.
    // If all is false, we can save some time by only searching for the first match.
    match (all, external) {
        (true, true) => get_all_entries_in_path(&prog_name, application.span, cwd, paths, path_ext),
        (true, false) => {
            let mut output: Vec<Value> = vec![];
            if let Some(entry) = get_entry_in_commands(engine_state, &prog_name, application.span) {
                output.push(entry);
            }
            output.extend(get_all_entries_in_path(
                &prog_name,
                application.span,
                cwd,
                paths,
                path_ext,
            ));
            output
        }
        (false, true) => {
            get_first_entry_in_path(&prog_name, application.span, cwd, paths, path_ext)
                .into_iter()
                .collect()
        }
        (false, false) => get_entry_in_commands(engine_state, &prog_name, application.span)
            .or_else(|| get_first_entry_in_path(&prog_name, application.span, cwd, paths, path_ext))
            .into_iter()
            .collect(),
    }
}

fn which(
    engine_state: &EngineState,
    stack: &mut Stack,
    call: &Call,
) -> Result<PipelineData, ShellError> {
    let head = call.head;
    let which_args = WhichArgs {
        applications: call.rest(engine_state, stack, 0)?,
        all: call.has_flag(engine_state, stack, "all")?,
    };

    let mut output = vec![];

    let cwd = engine_state.cwd_as_string(Some(stack))?;

    // PATH may not be set in minimal environments (e.g. plugin test harnesses).
    // In that case we can still resolve built-ins, aliases, custom commands and
    // known externals; we just won't find any PATH-based binaries.
    let paths = env::path_str(engine_state, stack, head).unwrap_or_default();

    // Source PATHEXT from the shell environment so `which` honors in-shell
    // changes to `$env.PATHEXT`, just like it already honors `$env.PATH`.
    let path_ext = env_path_ext(engine_state, stack);

    let metadata = PipelineMetadata::default().with_path_columns(vec!["path".into()]);

    if which_args.applications.is_empty() {
        return Ok(
            list_all_executables(engine_state, &paths, &path_ext, which_args.all, head)
                .into_iter()
                .into_pipeline_data(head, engine_state.signals().clone())
                .set_metadata(Some(metadata)),
        );
    }

    for app in which_args.applications {
        let values = which_single(app, which_args.all, engine_state, &cwd, &paths, &path_ext);
        output.extend(values);
    }

    Ok(output
        .into_iter()
        .into_pipeline_data(head, engine_state.signals().clone())
        .set_metadata(Some(metadata)))
}

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

    #[test]
    fn test_examples() -> nu_test_support::Result {
        nu_test_support::test().examples(Which)
    }
}

// --------------------
// Copied from https://docs.rs/is_executable/ v1.0.5
// Removed path.exists() check in `mod windows`.

/// An extension trait for `std::fs::Path` providing an `is_executable` method.
///
/// See the module documentation for examples.
pub trait IsExecutable {
    /// Returns `true` if there is a file at the given path and it is
    /// executable. Returns `false` otherwise.
    ///
    /// On Windows, `path_ext` is the shell's `PATHEXT` (`$env.PATHEXT`) used to
    /// decide whether a file extension counts as executable; passing `None`
    /// falls back to checking the binary type. On other platforms it is ignored.
    ///
    /// See the module documentation for details.
    fn is_executable(&self, path_ext: Option<&OsStr>) -> bool;
}

#[cfg(unix)]
mod unix {
    use std::os::unix::fs::PermissionsExt;
    use std::path::Path;

    use super::IsExecutable;

    impl IsExecutable for Path {
        fn is_executable(&self, _path_ext: Option<&std::ffi::OsStr>) -> bool {
            let metadata = match self.metadata() {
                Ok(metadata) => metadata,
                Err(_) => return false,
            };
            let permissions = metadata.permissions();
            metadata.is_file() && permissions.mode() & 0o111 != 0
        }
    }
}

#[cfg(target_os = "windows")]
mod windows {
    use std::os::windows::ffi::OsStrExt;
    use std::path::Path;

    use windows::Win32::Storage::FileSystem::GetBinaryTypeW;
    use windows::core::PCWSTR;

    use super::IsExecutable;

    impl IsExecutable for Path {
        fn is_executable(&self, path_ext: Option<&std::ffi::OsStr>) -> bool {
            // Check using file extension against the shell's `$env.PATHEXT`.
            if let Some(pathext) = path_ext
                && let Some(extension) = self.extension()
            {
                let extension = extension.to_string_lossy();

                // Originally taken from:
                // https://github.com/nushell/nushell/blob/93e8f6c05e1e1187d5b674d6b633deb839c84899/crates/nu-cli/src/completion/command.rs#L64-L74
                return pathext
                    .to_string_lossy()
                    .split(';')
                    // Filter out empty tokens and ';' at the end
                    .filter(|f| f.len() > 1)
                    .any(|ext| {
                        // Cut off the leading '.' character
                        let ext = &ext[1..];
                        extension.eq_ignore_ascii_case(ext)
                    });
            }

            // Check using file properties
            // This code is only reached if there is no file extension or retrieving PATHEXT fails
            let windows_string: Vec<u16> = self.as_os_str().encode_wide().chain(Some(0)).collect();
            let mut binary_type: u32 = 0;

            let result =
                unsafe { GetBinaryTypeW(PCWSTR(windows_string.as_ptr()), &mut binary_type) };
            if result.is_ok()
                && let 0..=6 = binary_type
            {
                return true;
            }

            false
        }
    }
}

// For WASI, we can't check if a file is executable
// Since wasm and wasi
//  is not supposed to add executables ideologically,
// specify them collectively
#[cfg(any(target_os = "wasi", target_family = "wasm"))]
mod wasm {
    use std::path::Path;

    use super::IsExecutable;

    impl IsExecutable for Path {
        fn is_executable(&self, _path_ext: Option<&std::ffi::OsStr>) -> bool {
            false
        }
    }
}