repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/move_/column.rs | crates/nu-command/tests/commands/move_/column.rs | use nu_test_support::nu;
#[test]
fn moves_a_column_before() {
let sample = r#"[
[column1 column2 column3 ... column98 column99 column100];
[------- ------- ------- --- -------- " A " ---------],
[------- ------- ------- --- -------- " N " ---------],
[------- ------- ------- --- -------- " D " ---------],
[------- ------- ------- --- -------- " R " ---------],
[------- ------- ------- --- -------- " E " ---------],
[------- ------- ------- --- -------- " S " ---------]
]"#;
let actual = nu!(format!(
r#"
{sample}
| move column99 --before column1
| rename chars
| get chars
| str trim
| str join
"#
));
assert!(actual.out.contains("ANDRES"));
}
#[test]
fn moves_columns_before() {
let sample = r#"[
[column1 column2 column3 ... column98 column99 column100];
[------- ------- " A " --- -------- " N " ---------]
[------- ------- " D " --- -------- " R " ---------]
[------- ------- " E " --- -------- " S " ---------]
[------- ------- " : " --- -------- " : " ---------]
[------- ------- " J " --- -------- " T " ---------]
]"#;
let actual = nu!(format!(
r#"
{sample}
| move column99 column3 --before column2
| rename _ chars_1 chars_2
| select chars_2 chars_1
| upsert new_col {{|f| $f | transpose | get column1 | str trim | str join}}
| get new_col
| str join
"#
));
assert!(actual.out.contains("ANDRES::JT"));
}
#[test]
fn moves_a_column_after() {
let sample = r#"[
[column1 column2 letters ... column98 and_more column100];
[------- ------- " A " --- -------- " N " ---------]
[------- ------- " D " --- -------- " R " ---------]
[------- ------- " E " --- -------- " S " ---------]
[------- ------- " : " --- -------- " : " ---------]
[------- ------- " J " --- -------- " T " ---------]
]"#;
let actual = nu!(format!(
r#"
{sample}
| move letters --after and_more
| move letters and_more --before column2
| rename _ chars_1 chars_2
| select chars_1 chars_2
| upsert new_col {{|f| $f | transpose | get column1 | str trim | str join}}
| get new_col
| str join
"#
));
assert!(actual.out.contains("ANDRES::JT"));
}
#[test]
fn moves_columns_after() {
let content = r#"[
[column1 column2 letters ... column98 and_more column100];
[------- ------- " A " --- -------- " N " ---------]
[------- ------- " D " --- -------- " R " ---------]
[------- ------- " E " --- -------- " S " ---------]
[------- ------- " : " --- -------- " : " ---------]
[------- ------- " J " --- -------- " T " ---------]
]"#;
let actual = nu!(format!(
r#"
{content}
| move letters and_more --after column1
| columns
| select 1 2
| str join
"#
));
assert!(actual.out.contains("lettersand_more"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/move_/umv.rs | crates/nu-command/tests/commands/move_/umv.rs | use nu_test_support::fs::{Stub::EmptyFile, Stub::FileWithContent, files_exist_at};
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use rstest::rstest;
#[test]
fn moves_a_file() {
Playground::setup("umv_test_1", |dirs, sandbox| {
sandbox
.with_files(&[EmptyFile("andres.txt")])
.mkdir("expected");
let original = dirs.test().join("andres.txt");
let expected = dirs.test().join("expected/yehuda.txt");
nu!(
cwd: dirs.test(),
"mv andres.txt expected/yehuda.txt"
);
assert!(!original.exists());
assert!(expected.exists());
})
}
#[test]
fn overwrites_if_moving_to_existing_file_and_force_provided() {
Playground::setup("umv_test_2", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("andres.txt"), EmptyFile("jttxt")]);
let original = dirs.test().join("andres.txt");
let expected = dirs.test().join("jttxt");
nu!(
cwd: dirs.test(),
"mv andres.txt -f jttxt"
);
assert!(!original.exists());
assert!(expected.exists());
})
}
#[test]
fn moves_a_directory() {
Playground::setup("umv_test_3", |dirs, sandbox| {
sandbox.mkdir("empty_dir");
let original_dir = dirs.test().join("empty_dir");
let expected = dirs.test().join("renamed_dir");
nu!(
cwd: dirs.test(),
"mv empty_dir renamed_dir"
);
assert!(!original_dir.exists());
assert!(expected.exists());
})
}
#[test]
fn moves_the_file_inside_directory_if_path_to_move_is_existing_directory() {
Playground::setup("umv_test_4", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("jttxt")]).mkdir("expected");
let original_dir = dirs.test().join("jttxt");
let expected = dirs.test().join("expected/jttxt");
nu!(
cwd: dirs.test(),
"mv jttxt expected"
);
assert!(!original_dir.exists());
assert!(expected.exists());
})
}
#[test]
fn moves_the_directory_inside_directory_if_path_to_move_is_existing_directory() {
Playground::setup("umv_test_5", |dirs, sandbox| {
sandbox
.within("contributors")
.with_files(&[EmptyFile("jttxt")])
.mkdir("expected");
let original_dir = dirs.test().join("contributors");
let expected = dirs.test().join("expected/contributors");
nu!(
cwd: dirs.test(),
"mv contributors expected"
);
assert!(!original_dir.exists());
assert!(expected.exists());
assert!(files_exist_at(&["jttxt"], expected))
})
}
#[test]
fn moves_using_path_with_wildcard() {
Playground::setup("umv_test_7", |dirs, sandbox| {
sandbox
.within("originals")
.with_files(&[
EmptyFile("andres.ini"),
EmptyFile("caco3_plastics.csv"),
EmptyFile("cargo_sample.toml"),
EmptyFile("jt.ini"),
EmptyFile("jt.xml"),
EmptyFile("sgml_description.json"),
EmptyFile("sample.ini"),
EmptyFile("utf16.ini"),
EmptyFile("yehuda.ini"),
])
.mkdir("work_dir")
.mkdir("expected");
let work_dir = dirs.test().join("work_dir");
let expected = dirs.test().join("expected");
nu!(cwd: work_dir, "mv ../originals/*.ini ../expected");
assert!(files_exist_at(
&["yehuda.ini", "jt.ini", "sample.ini", "andres.ini",],
expected
));
})
}
#[test]
fn moves_using_a_glob() {
Playground::setup("umv_test_8", |dirs, sandbox| {
sandbox
.within("meals")
.with_files(&[
EmptyFile("arepa.txt"),
EmptyFile("empanada.txt"),
EmptyFile("taquiza.txt"),
])
.mkdir("work_dir")
.mkdir("expected");
let meal_dir = dirs.test().join("meals");
let work_dir = dirs.test().join("work_dir");
let expected = dirs.test().join("expected");
nu!(cwd: work_dir, "mv ../meals/* ../expected");
assert!(meal_dir.exists());
assert!(files_exist_at(
&["arepa.txt", "empanada.txt", "taquiza.txt",],
expected
));
})
}
#[test]
fn moves_a_directory_with_files() {
Playground::setup("umv_test_9", |dirs, sandbox| {
sandbox
.mkdir("vehicles/car")
.mkdir("vehicles/bicycle")
.with_files(&[
EmptyFile("vehicles/car/car1.txt"),
EmptyFile("vehicles/car/car2.txt"),
])
.with_files(&[
EmptyFile("vehicles/bicycle/bicycle1.txt"),
EmptyFile("vehicles/bicycle/bicycle2.txt"),
]);
let original_dir = dirs.test().join("vehicles");
let expected_dir = dirs.test().join("expected");
nu!(
cwd: dirs.test(),
"mv vehicles expected"
);
assert!(!original_dir.exists());
assert!(expected_dir.exists());
assert!(files_exist_at(
&[
"car/car1.txt",
"car/car2.txt",
"bicycle/bicycle1.txt",
"bicycle/bicycle2.txt"
],
expected_dir
));
})
}
#[test]
fn errors_if_source_doesnt_exist() {
Playground::setup("umv_test_10", |dirs, sandbox| {
sandbox.mkdir("test_folder");
let actual = nu!(
cwd: dirs.test(),
"mv non-existing-file test_folder/"
);
assert!(actual.err.contains("nu::shell::io::not_found"));
})
}
#[test]
#[ignore = "GNU/uutils overwrites rather than error out"]
fn error_if_moving_to_existing_file_without_force() {
Playground::setup("umv_test_10_0", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("andres.txt"), EmptyFile("jttxt")]);
let actual = nu!(
cwd: dirs.test(),
"mv andres.txt jttxt"
);
assert!(actual.err.contains("file already exists"))
})
}
#[test]
fn errors_if_destination_doesnt_exist() {
Playground::setup("umv_test_10_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("empty.txt")]);
let actual = nu!(
cwd: dirs.test(),
"mv empty.txt does/not/exist/"
);
assert!(actual.err.contains("failed to access"));
assert!(actual.err.contains("Not a directory"));
})
}
#[test]
#[ignore = "GNU/uutils doesnt expand, rather cannot stat 'file?.txt'"]
fn errors_if_multiple_sources_but_destination_not_a_directory() {
Playground::setup("umv_test_10_2", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("file1.txt"),
EmptyFile("file2.txt"),
EmptyFile("file3.txt"),
]);
let actual = nu!(
cwd: dirs.test(),
"mv file?.txt not_a_dir"
);
assert!(
actual
.err
.contains("Can only move multiple sources if destination is a directory")
);
})
}
#[test]
fn errors_if_renaming_directory_to_an_existing_file() {
Playground::setup("umv_test_10_3", |dirs, sandbox| {
sandbox.mkdir("mydir").with_files(&[EmptyFile("empty.txt")]);
let actual = nu!(
cwd: dirs.test(),
"mv mydir empty.txt"
);
assert!(actual.err.contains("cannot overwrite non-directory"),);
assert!(actual.err.contains("with directory"),);
})
}
#[test]
fn errors_if_moving_to_itself() {
Playground::setup("umv_test_10_4", |dirs, sandbox| {
sandbox.mkdir("mydir").mkdir("mydir/mydir_2");
let actual = nu!(
cwd: dirs.test(),
"mv mydir mydir/mydir_2/"
);
assert!(actual.err.contains("cannot move"));
assert!(actual.err.contains("to a subdirectory"));
});
}
#[test]
fn does_not_error_on_relative_parent_path() {
Playground::setup("umv_test_11", |dirs, sandbox| {
sandbox
.mkdir("first")
.with_files(&[EmptyFile("first/william_hartnell.txt")]);
let original = dirs.test().join("first/william_hartnell.txt");
let expected = dirs.test().join("william_hartnell.txt");
nu!(
cwd: dirs.test().join("first"),
"mv william_hartnell.txt ./.."
);
assert!(!original.exists());
assert!(expected.exists());
})
}
#[test]
fn move_files_using_glob_two_parents_up_using_multiple_dots() {
Playground::setup("umv_test_12", |dirs, sandbox| {
sandbox.within("foo").within("bar").with_files(&[
EmptyFile("jtjson"),
EmptyFile("andres.xml"),
EmptyFile("yehuda.yaml"),
EmptyFile("kevin.txt"),
EmptyFile("many_more.ppl"),
]);
nu!(
cwd: dirs.test().join("foo/bar"),
r#"
mv * ...
"#
);
let files = &[
"yehuda.yaml",
"jtjson",
"andres.xml",
"kevin.txt",
"many_more.ppl",
];
let original_dir = dirs.test().join("foo/bar");
let destination_dir = dirs.test();
assert!(files_exist_at(files, destination_dir));
assert!(!files_exist_at(files, original_dir))
})
}
#[test]
fn move_file_from_two_parents_up_using_multiple_dots_to_current_dir() {
Playground::setup("cp_test_10", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("hello_there")]);
sandbox.within("foo").mkdir("bar");
nu!(
cwd: dirs.test().join("foo/bar"),
r#"
mv .../hello_there .
"#
);
let expected = dirs.test().join("foo/bar/hello_there");
let original = dirs.test().join("hello_there");
assert!(expected.exists());
assert!(!original.exists());
})
}
#[test]
fn does_not_error_when_some_file_is_moving_into_itself() {
Playground::setup("umv_test_13", |dirs, sandbox| {
sandbox.mkdir("11").mkdir("12");
let original_dir = dirs.test().join("11");
let expected = dirs.test().join("12/11");
nu!(cwd: dirs.test(), "mv 1* 12");
assert!(!original_dir.exists());
assert!(expected.exists());
})
}
#[test]
fn mv_ignores_ansi() {
Playground::setup("umv_test_ansi", |_dirs, sandbox| {
sandbox.with_files(&[EmptyFile("test.txt")]);
let actual = nu!(
cwd: sandbox.cwd(),
r#"
ls | find test | mv $in.0.name success.txt; ls | $in.0.name
"#
);
assert_eq!(actual.out, "success.txt");
})
}
#[test]
fn mv_directory_with_same_name() {
Playground::setup("umv_test_directory_with_same_name", |_dirs, sandbox| {
sandbox.mkdir("testdir");
sandbox.mkdir("testdir/testdir");
let cwd = sandbox.cwd().join("testdir");
let actual = nu!(
cwd: cwd,
r#"
mv testdir ..
"#
);
assert!(actual.err.contains("Directory not empty"));
})
}
#[test]
// Test that changing the case of a file/directory name works;
// this is an important edge case on Windows (and any other case-insensitive file systems).
// We were bitten badly by this once: https://github.com/nushell/nushell/issues/6583
// Currently as we are using `uutils` and have no say in the behavior, this should succeed on Linux,
// but fail on both macOS and Windows.
fn mv_change_case_of_directory() {
Playground::setup("mv_change_case_of_directory", |dirs, sandbox| {
sandbox
.mkdir("somedir")
.with_files(&[EmptyFile("somedir/somefile.txt")]);
let original_dir = String::from("somedir");
let new_dir = String::from("SomeDir");
#[allow(unused)]
let actual = nu!(
cwd: dirs.test(),
format!("mv {original_dir} {new_dir}")
);
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
{
// Doing this instead of `Path::exists()` because we need to check file existence in
// a case-sensitive way. `Path::exists()` is understandably case-insensitive on NTFS
let files_in_test_directory: Vec<String> = std::fs::read_dir(dirs.test())
.unwrap()
.map(|de| de.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert!(
!files_in_test_directory.contains(&original_dir)
&& files_in_test_directory.contains(&new_dir)
);
assert!(files_exist_at(&["somefile.txt"], dirs.test().join(new_dir)));
}
#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
actual.err.contains("to a subdirectory of itself");
})
}
#[test]
// Currently as we are using `uutils` and have no say in the behavior, this should succeed on Linux,
// but fail on both macOS and Windows.
fn mv_change_case_of_file() {
Playground::setup("mv_change_case_of_file", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("somefile.txt")]);
let original_file_name = String::from("somefile.txt");
let new_file_name = String::from("SomeFile.txt");
#[allow(unused)]
let actual = nu!(
cwd: dirs.test(),
format!("mv {original_file_name} -f {new_file_name}")
);
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
{
// Doing this instead of `Path::exists()` because we need to check file existence in
// a case-sensitive way. `Path::exists()` is understandably case-insensitive on NTFS
let files_in_test_directory: Vec<String> = std::fs::read_dir(dirs.test())
.unwrap()
.map(|de| de.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert!(
!files_in_test_directory.contains(&original_file_name)
&& files_in_test_directory.contains(&new_file_name)
);
}
#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
actual.err.contains("are the same file");
})
}
#[test]
#[ignore = "Update not supported..remove later"]
fn mv_with_update_flag() {
Playground::setup("umv_with_update_flag", |_dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("valid.txt"),
FileWithContent("newer_valid.txt", "body"),
]);
let actual = nu!(
cwd: sandbox.cwd(),
"mv -uf valid.txt newer_valid.txt; open newer_valid.txt",
);
assert_eq!(actual.out, "body");
// create a file after assert to make sure that newest_valid.txt is newest
std::thread::sleep(std::time::Duration::from_secs(1));
sandbox.with_files(&[FileWithContent("newest_valid.txt", "newest_body")]);
let actual = nu!(cwd: sandbox.cwd(), "mv -uf newest_valid.txt valid.txt; open valid.txt");
assert_eq!(actual.out, "newest_body");
// when destination doesn't exist
sandbox.with_files(&[FileWithContent("newest_valid.txt", "newest_body")]);
let actual = nu!(cwd: sandbox.cwd(), "mv -uf newest_valid.txt des_missing.txt; open des_missing.txt");
assert_eq!(actual.out, "newest_body");
});
}
#[test]
fn test_mv_no_clobber() {
Playground::setup("umv_test_13", |dirs, sandbox| {
let file_a = "test_mv_no_clobber_file_a";
let file_b = "test_mv_no_clobber_file_b";
sandbox.with_files(&[EmptyFile(file_a)]);
sandbox.with_files(&[EmptyFile(file_b)]);
let _ = nu!(cwd: dirs.test(), format!("mv -n {file_a} {file_b}"));
let file_count = nu!(
cwd: dirs.test(),
"ls test_mv* | length | to nuon"
);
assert_eq!(file_count.out, "2");
})
}
#[test]
fn mv_with_no_arguments() {
Playground::setup("umv_test_14", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"mv",
);
assert!(actual.err.contains("Missing file operand"));
})
}
#[test]
fn mv_with_no_target() {
Playground::setup("umv_test_15", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"mv a",
);
assert!(
actual.err.contains(
format!(
"Missing destination path operand after {}",
dirs.test().join("a").display()
)
.as_str()
)
);
})
}
#[rstest]
#[case("a]c")]
#[case("a[c")]
#[case("a[bc]d")]
#[case("a][c")]
fn mv_files_with_glob_metachars(#[case] src_name: &str) {
Playground::setup("umv_test_16", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
src_name,
"What is the sound of one hand clapping?",
)]);
let src = dirs.test().join(src_name);
let actual = nu!(
cwd: dirs.test(),
format!(
"mv '{}' {}",
src.display(),
"hello_world_dest"
)
);
assert!(actual.err.is_empty());
assert!(dirs.test().join("hello_world_dest").exists());
});
}
#[rstest]
#[case("a]c")]
#[case("a[c")]
#[case("a[bc]d")]
#[case("a][c")]
fn mv_files_with_glob_metachars_when_input_are_variables(#[case] src_name: &str) {
Playground::setup("umv_test_18", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
src_name,
"What is the sound of one hand clapping?",
)]);
let src = dirs.test().join(src_name);
let actual = nu!(
cwd: dirs.test(),
format!(
"let f = '{}'; mv $f {}",
src.display(),
"hello_world_dest"
)
);
assert!(actual.err.is_empty());
assert!(dirs.test().join("hello_world_dest").exists());
});
}
#[cfg(not(windows))]
#[rstest]
#[case("a]?c")]
#[case("a*.?c")]
// windows doesn't allow filename with `*`.
fn mv_files_with_glob_metachars_nw(#[case] src_name: &str) {
mv_files_with_glob_metachars(src_name);
mv_files_with_glob_metachars_when_input_are_variables(src_name);
}
#[test]
fn mv_with_cd() {
Playground::setup("umv_test_17", |_dirs, sandbox| {
sandbox
.mkdir("tmp_dir")
.with_files(&[FileWithContent("tmp_dir/file.txt", "body")]);
let actual = nu!(
cwd: sandbox.cwd(),
r#"do { cd tmp_dir; let f = 'file.txt'; mv $f .. }; open file.txt"#,
);
assert!(actual.out.contains("body"));
});
}
#[test]
fn test_mv_inside_glob_metachars_dir() {
Playground::setup("uv_files_inside_glob_metachars_dir", |dirs, sandbox| {
let sub_dir = "test[]";
sandbox
.within(sub_dir)
.with_files(&[FileWithContent("test_file.txt", "hello")]);
let actual = nu!(
cwd: dirs.test().join(sub_dir),
"mv test_file.txt ../",
);
assert!(actual.err.is_empty());
assert!(!files_exist_at(
&["test_file.txt"],
dirs.test().join(sub_dir)
));
assert!(files_exist_at(&["test_file.txt"], dirs.test()));
});
}
#[test]
fn test_mv_wildcards() {
Playground::setup("uv_with_wildcards", |dirs, sandbox| {
let sub_dir = "test[]";
sandbox
.within(sub_dir)
.with_files(&[FileWithContent(".a", "hello")]);
let actual = nu!(
cwd: dirs.test().join(sub_dir),
"mv * ../",
);
// by default, wildcard don't match dot files.
assert!(actual.err.contains("File not found"));
assert!(files_exist_at(&[".a"], dirs.test().join(sub_dir)));
assert!(!files_exist_at(&[".a"], dirs.test()));
// unless `-a` flag is provided.
let actual = nu!(
cwd: dirs.test().join(sub_dir),
"mv -a * ../",
);
// by default, wildcard don't match dot files.
assert!(actual.err.is_empty());
assert!(!files_exist_at(&[".a"], dirs.test().join(sub_dir)));
assert!(files_exist_at(&[".a"], dirs.test()));
});
}
#[test]
fn mv_with_tilde() {
Playground::setup("mv_tilde", |dirs, sandbox| {
sandbox.within("~tilde").with_files(&[
EmptyFile("f1.txt"),
EmptyFile("f2.txt"),
EmptyFile("f3.txt"),
]);
sandbox.within("~tilde2");
// mv file
let actual = nu!(cwd: dirs.test(), "mv '~tilde/f1.txt' ./");
assert!(actual.err.is_empty());
assert!(!files_exist_at(&["f1.txt"], dirs.test().join("~tilde")));
assert!(files_exist_at(&["f1.txt"], dirs.test()));
// pass variable
let actual = nu!(cwd: dirs.test(), "let f = '~tilde/f2.txt'; mv $f ./");
assert!(actual.err.is_empty());
assert!(!files_exist_at(&["f2.txt"], dirs.test().join("~tilde")));
assert!(files_exist_at(&["f1.txt"], dirs.test()));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/move_/mod.rs | crates/nu-command/tests/commands/move_/mod.rs | mod column;
mod umv;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/expand.rs | crates/nu-command/tests/commands/path/expand.rs | use nu_path::Path;
use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn expands_path_with_dot() {
Playground::setup("path_expand_1", |dirs, sandbox| {
sandbox.within("menu").with_files(&[EmptyFile("spam.txt")]);
let actual = nu!(cwd: dirs.test(), r#"
echo "menu/./spam.txt"
| path expand
"#);
let expected = dirs.test.join("menu").join("spam.txt");
assert_eq!(Path::new(&actual.out), expected);
})
}
#[cfg(unix)]
#[test]
fn expands_path_without_follow_symlink() {
Playground::setup("path_expand_3", |dirs, sandbox| {
sandbox.within("menu").with_files(&[EmptyFile("spam.txt")]);
let actual = nu!(cwd: dirs.test(), r#"
ln -s spam.txt menu/spam_link.ln;
echo "menu/./spam_link.ln"
| path expand -n
"#);
let expected = dirs.test.join("menu").join("spam_link.ln");
assert_eq!(Path::new(&actual.out), expected);
})
}
#[test]
fn expands_path_with_double_dot() {
Playground::setup("path_expand_2", |dirs, sandbox| {
sandbox.within("menu").with_files(&[EmptyFile("spam.txt")]);
let actual = nu!(cwd: dirs.test(), r#"
echo "menu/../menu/spam.txt"
| path expand
"#);
let expected = dirs.test.join("menu").join("spam.txt");
assert_eq!(Path::new(&actual.out), expected);
})
}
#[test]
fn const_path_expand() {
Playground::setup("const_path_expand", |dirs, sandbox| {
sandbox.within("menu").with_files(&[EmptyFile("spam.txt")]);
let actual = nu!(cwd: dirs.test(), r#"
const result = ("menu/./spam.txt" | path expand);
$result
"#);
let expected = dirs.test.join("menu").join("spam.txt");
assert_eq!(Path::new(&actual.out), expected);
})
}
#[cfg(windows)]
mod windows {
use super::*;
#[test]
fn expands_path_with_tilde_backward_slash() {
Playground::setup("path_expand_2", |dirs, _| {
let actual = nu!(cwd: dirs.test(), r#"
echo "~\tmp.txt" | path expand
"#);
assert!(!Path::new(&actual.out).starts_with("~"));
})
}
#[test]
fn win_expands_path_with_tilde_forward_slash() {
Playground::setup("path_expand_2", |dirs, _| {
let actual = nu!(cwd: dirs.test(), r#"
echo "~/tmp.txt" | path expand
"#);
assert!(!Path::new(&actual.out).starts_with("~"));
})
}
#[test]
fn expands_path_without_follow_symlink() {
Playground::setup("path_expand_3", |dirs, sandbox| {
sandbox.within("menu").with_files(&[EmptyFile("spam.txt")]);
let cwd = dirs.test();
std::os::windows::fs::symlink_file(
cwd.join("menu").join("spam.txt"),
cwd.join("menu").join("spam_link.ln"),
)
.unwrap();
let actual = nu!(cwd: dirs.test(), r#"
echo "menu/./spam_link.ln"
| path expand -n
"#);
let expected = dirs.test.join("menu").join("spam_link.ln");
assert_eq!(Path::new(&actual.out), expected);
})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/type_.rs | crates/nu-command/tests/commands/path/type_.rs | use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn returns_type_of_missing_file() {
let actual = nu!(cwd: "tests", r#"
echo "spam.txt"
| path type
"#);
assert_eq!(actual.out, "");
}
#[test]
fn returns_type_of_existing_file() {
Playground::setup("path_expand_1", |dirs, sandbox| {
sandbox.within("menu").with_files(&[EmptyFile("spam.txt")]);
let actual = nu!(cwd: dirs.test(), r#"
echo "menu"
| path type
"#);
assert_eq!(actual.out, "dir");
})
}
#[test]
fn returns_type_of_existing_directory() {
Playground::setup("path_expand_1", |dirs, sandbox| {
sandbox.within("menu").with_files(&[EmptyFile("spam.txt")]);
let actual = nu!(cwd: dirs.test(), r#"
echo "menu/spam.txt"
| path type
"#);
assert_eq!(actual.out, "file");
let actual = nu!(r#"
echo "~"
| path type
"#);
assert_eq!(actual.out, "dir");
})
}
#[test]
fn returns_type_of_existing_file_const() {
Playground::setup("path_type_const", |dirs, sandbox| {
sandbox.within("menu").with_files(&[EmptyFile("spam.txt")]);
let actual = nu!(cwd: dirs.test(), r#"
const ty = ("menu" | path type);
$ty
"#);
assert_eq!(actual.out, "dir");
})
}
#[test]
fn respects_cwd() {
Playground::setup("path_type_respects_cwd", |dirs, sandbox| {
sandbox.within("foo").with_files(&[EmptyFile("bar.txt")]);
let actual = nu!(cwd: dirs.test(), "cd foo; 'bar.txt' | path type");
assert_eq!(actual.out, "file");
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/parse.rs | crates/nu-command/tests/commands/path/parse.rs | use nu_test_support::nu;
#[cfg(windows)]
#[test]
fn parses_single_path_prefix() {
let actual = nu!(cwd: "tests", r"
echo 'C:\users\viking\spam.txt'
| path parse
| get prefix
");
assert_eq!(actual.out, "C:");
}
#[test]
fn parses_single_path_parent() {
let actual = nu!(cwd: "tests", r#"
echo 'home/viking/spam.txt'
| path parse
| get parent
"#);
assert_eq!(actual.out, "home/viking");
}
#[test]
fn parses_single_path_stem() {
let actual = nu!(cwd: "tests", r#"
echo 'home/viking/spam.txt'
| path parse
| get stem
"#);
assert_eq!(actual.out, "spam");
}
#[test]
fn parses_custom_extension_gets_extension() {
let actual = nu!(cwd: "tests", r#"
echo 'home/viking/spam.tar.gz'
| path parse --extension tar.gz
| get extension
"#);
assert_eq!(actual.out, "tar.gz");
}
#[test]
fn parses_custom_extension_gets_stem() {
let actual = nu!(cwd: "tests", r#"
echo 'home/viking/spam.tar.gz'
| path parse --extension tar.gz
| get stem
"#);
assert_eq!(actual.out, "spam");
}
#[test]
fn parses_ignoring_extension_gets_extension() {
let actual = nu!(cwd: "tests", r#"
echo 'home/viking/spam.tar.gz'
| path parse --extension ''
| get extension
"#);
assert_eq!(actual.out, "");
}
#[test]
fn parses_ignoring_extension_gets_stem() {
let actual = nu!(cwd: "tests", r#"
echo 'home/viking/spam.tar.gz'
| path parse --extension ""
| get stem
"#);
assert_eq!(actual.out, "spam.tar.gz");
}
#[test]
fn parses_into_correct_number_of_columns() {
let actual = nu!(cwd: "tests", r#"
echo 'home/viking/spam.txt'
| path parse
| transpose
| get column0
| length
"#);
#[cfg(windows)]
let expected = "4";
#[cfg(not(windows))]
let expected = "3";
assert_eq!(actual.out, expected);
}
#[test]
fn const_path_parse() {
let actual = nu!("const name = ('spam/eggs.txt' | path parse); $name.parent");
assert_eq!(actual.out, "spam");
let actual = nu!("const name = ('spam/eggs.txt' | path parse); $name.stem");
assert_eq!(actual.out, "eggs");
let actual = nu!("const name = ('spam/eggs.txt' | path parse); $name.extension");
assert_eq!(actual.out, "txt");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/exists.rs | crates/nu-command/tests/commands/path/exists.rs | use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn checks_if_existing_file_exists() {
Playground::setup("path_exists_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual = nu!(
cwd: dirs.test(),
"echo spam.txt | path exists"
);
assert_eq!(actual.out, "true");
})
}
#[test]
fn checks_if_missing_file_exists() {
Playground::setup("path_exists_2", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"echo spam.txt | path exists"
);
assert_eq!(actual.out, "false");
})
}
#[test]
fn checks_if_dot_exists() {
Playground::setup("path_exists_3", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"echo '.' | path exists"
);
assert_eq!(actual.out, "true");
})
}
#[test]
fn checks_if_double_dot_exists() {
Playground::setup("path_exists_4", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"echo '..' | path exists"
);
assert_eq!(actual.out, "true");
})
}
#[test]
fn checks_tilde_relative_path_exists() {
let actual = nu!("'~' | path exists");
assert_eq!(actual.out, "true");
}
#[test]
fn const_path_exists() {
let actual = nu!("const exists = ('~' | path exists); $exists");
assert_eq!(actual.out, "true");
}
#[test]
fn path_exists_under_a_non_directory() {
Playground::setup("path_exists_6", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"touch test_file; 'test_file/aaa' | path exists"
);
assert_eq!(actual.out, "false");
assert!(actual.err.is_empty());
})
}
#[test]
fn test_check_symlink_exists() {
use nu_test_support::{nu, playground::Playground};
let symlink_target = "symlink_target";
let symlink = "symlink";
Playground::setup("path_exists_5", |dirs, sandbox| {
#[cfg(not(windows))]
std::os::unix::fs::symlink(dirs.test().join(symlink_target), dirs.test().join(symlink))
.unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_file(
dirs.test().join(symlink_target),
dirs.test().join(symlink),
)
.unwrap();
let false_out = "false".to_string();
let shell_res = nu!(cwd: sandbox.cwd(), "'symlink_target' | path exists");
assert_eq!(false_out, shell_res.out);
let shell_res = nu!(cwd: sandbox.cwd(), "'symlink' | path exists");
assert_eq!(false_out, shell_res.out);
let shell_res = nu!(cwd: sandbox.cwd(), "'symlink' | path exists -n");
assert_eq!("true".to_string(), shell_res.out);
});
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/mod.rs | crates/nu-command/tests/commands/path/mod.rs | mod basename;
mod dirname;
mod exists;
mod expand;
mod join;
mod parse;
mod self_;
mod split;
mod type_;
use nu_test_support::nu;
use std::path::MAIN_SEPARATOR;
/// Helper function that joins string literals with '/' or '\', based on host OS
fn join_path_sep(pieces: &[&str]) -> String {
let sep_string = String::from(MAIN_SEPARATOR);
pieces.join(&sep_string)
}
#[cfg(windows)]
#[test]
fn joins_path_on_windows() {
let pieces = ["sausage", "bacon", "spam"];
let actual = join_path_sep(&pieces);
assert_eq!(&actual, "sausage\\bacon\\spam");
}
#[cfg(not(windows))]
#[test]
fn joins_path_on_other_than_windows() {
let pieces = ["sausage", "bacon", "spam"];
let actual = join_path_sep(&pieces);
assert_eq!(&actual, "sausage/bacon/spam");
}
#[test]
fn const_path_relative_to() {
let actual = nu!("'/home/viking' | path relative-to '/home'");
assert_eq!(actual.out, "viking");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/dirname.rs | crates/nu-command/tests/commands/path/dirname.rs | use nu_test_support::nu;
use super::join_path_sep;
#[test]
fn returns_dirname_of_empty_input() {
let actual = nu!(cwd: "tests", r#"
echo ""
| path dirname
"#);
assert_eq!(actual.out, "");
}
#[test]
fn replaces_dirname_of_empty_input() {
let actual = nu!(cwd: "tests", r#"
echo ""
| path dirname --replace newdir
"#);
assert_eq!(actual.out, "newdir");
}
#[test]
fn returns_dirname_of_path_ending_with_dot() {
let actual = nu!(cwd: "tests", r#"
echo "some/dir/."
| path dirname
"#);
assert_eq!(actual.out, "some");
}
#[test]
fn replaces_dirname_of_path_ending_with_dot() {
let actual = nu!(cwd: "tests", r#"
echo "some/dir/."
| path dirname --replace eggs
"#);
let expected = join_path_sep(&["eggs", "dir"]);
assert_eq!(actual.out, expected);
}
#[test]
fn returns_dirname_of_path_ending_with_double_dot() {
let actual = nu!(cwd: "tests", r#"
echo "some/dir/.."
| path dirname
"#);
assert_eq!(actual.out, "some/dir");
}
#[test]
fn replaces_dirname_of_path_with_double_dot() {
let actual = nu!(cwd: "tests", r#"
echo "some/dir/.."
| path dirname --replace eggs
"#);
let expected = join_path_sep(&["eggs", ".."]);
assert_eq!(actual.out, expected);
}
#[test]
fn returns_dirname_of_zero_levels() {
let actual = nu!(cwd: "tests", r#"
echo "some/dir/with/spam.txt"
| path dirname --num-levels 0
"#);
assert_eq!(actual.out, "some/dir/with/spam.txt");
}
#[test]
fn replaces_dirname_of_zero_levels_with_empty_string() {
let actual = nu!(cwd: "tests", r#"
echo "some/dir/with/spam.txt"
| path dirname --num-levels 0 --replace ""
"#);
assert_eq!(actual.out, "");
}
#[test]
fn replaces_dirname_of_more_levels() {
let actual = nu!(cwd: "tests", r#"
echo "some/dir/with/spam.txt"
| path dirname --replace eggs -n 2
"#);
let expected = join_path_sep(&["eggs", "with/spam.txt"]);
assert_eq!(actual.out, expected);
}
#[test]
fn replaces_dirname_of_way_too_many_levels() {
let actual = nu!(cwd: "tests", r#"
echo "some/dir/with/spam.txt"
| path dirname --replace eggs -n 999
"#);
let expected = join_path_sep(&["eggs", "some/dir/with/spam.txt"]);
assert_eq!(actual.out, expected);
}
#[test]
fn const_path_dirname() {
let actual = nu!("const name = ('spam/eggs.txt' | path dirname); $name");
assert_eq!(actual.out, "spam");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/join.rs | crates/nu-command/tests/commands/path/join.rs | use nu_test_support::nu;
use super::join_path_sep;
#[test]
fn returns_path_joined_from_list() {
let actual = nu!(cwd: "tests", r#"
echo [ home viking spam.txt ]
| path join
"#);
let expected = join_path_sep(&["home", "viking", "spam.txt"]);
assert_eq!(actual.out, expected);
}
#[test]
fn drop_one_path_join() {
let actual = nu!(cwd: "tests", r#"[a, b, c] | drop 1 | path join
"#);
let expected = join_path_sep(&["a", "b"]);
assert_eq!(actual.out, expected);
}
#[test]
fn appends_slash_when_joined_with_empty_path() {
let actual = nu!(cwd: "tests", r#"
echo "/some/dir"
| path join ''
"#);
let expected = join_path_sep(&["/some/dir", ""]);
assert_eq!(actual.out, expected);
}
#[test]
fn returns_joined_path_when_joining_empty_path() {
let actual = nu!(cwd: "tests", r#"
echo ""
| path join foo.txt
"#);
assert_eq!(actual.out, "foo.txt");
}
#[test]
fn const_path_join() {
let actual = nu!("const name = ('spam' | path join 'eggs.txt'); $name");
let expected = join_path_sep(&["spam", "eggs.txt"]);
assert_eq!(actual.out, expected);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/basename.rs | crates/nu-command/tests/commands/path/basename.rs | use nu_test_support::nu;
use super::join_path_sep;
#[test]
fn returns_basename_of_empty_input() {
let actual = nu!(cwd: "tests", r#"
echo ""
| path basename
"#);
assert_eq!(actual.out, "");
}
#[test]
fn replaces_basename_of_empty_input() {
let actual = nu!(cwd: "tests", r#"
echo ""
| path basename --replace newname.txt
"#);
assert_eq!(actual.out, "newname.txt");
}
#[test]
fn returns_basename_of_path_ending_with_dot() {
let actual = nu!(cwd: "tests", r#"
echo "some/file.txt/."
| path basename
"#);
assert_eq!(actual.out, "file.txt");
}
#[test]
fn replaces_basename_of_path_ending_with_dot() {
let actual = nu!(cwd: "tests", r#"
echo "some/file.txt/."
| path basename --replace viking.txt
"#);
let expected = join_path_sep(&["some", "viking.txt"]);
assert_eq!(actual.out, expected);
}
#[test]
fn returns_basename_of_path_ending_with_double_dot() {
let actual = nu!(cwd: "tests", r#"
echo "some/file.txt/.."
| path basename
"#);
assert_eq!(actual.out, "");
}
#[test]
fn replaces_basename_of_path_ending_with_double_dot() {
let actual = nu!(cwd: "tests", r#"
echo "some/file.txt/.."
| path basename --replace eggs
"#);
let expected = join_path_sep(&["some/file.txt/..", "eggs"]);
assert_eq!(actual.out, expected);
}
#[test]
fn const_path_basename() {
let actual = nu!("const name = ('spam/eggs.txt' | path basename); $name");
assert_eq!(actual.out, "eggs.txt");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/self_.rs | crates/nu-command/tests/commands/path/self_.rs | use std::path::Path;
use itertools::Itertools;
use nu_test_support::{fs::Stub, nu, playground::Playground};
#[test]
fn self_path_const() {
Playground::setup("path_self_const", |dirs, sandbox| {
sandbox
.within("scripts")
.with_files(&[Stub::FileWithContentToBeTrimmed(
"foo.nu",
r#"
export const paths = {
self: (path self),
dir: (path self .),
sibling: (path self sibling),
parent_dir: (path self ..),
cousin: (path self ../cousin),
}
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"use scripts/foo.nu; $foo.paths | values | str join (char nul)"#);
let (self_, dir, sibling, parent_dir, cousin) = actual
.out
.split("\0")
.collect_tuple()
.expect("should have 5 NUL separated paths");
let mut pathbuf = dirs.test().to_path_buf();
pathbuf.push("scripts");
assert_eq!(pathbuf, Path::new(dir));
pathbuf.push("foo.nu");
assert_eq!(pathbuf, Path::new(self_));
pathbuf.pop();
pathbuf.push("sibling");
assert_eq!(pathbuf, Path::new(sibling));
pathbuf.pop();
pathbuf.pop();
assert_eq!(pathbuf, Path::new(parent_dir));
pathbuf.push("cousin");
assert_eq!(pathbuf, Path::new(cousin));
})
}
#[test]
fn self_path_runtime() {
let actual = nu!("path self");
assert!(!actual.status.success());
assert!(actual.err.contains("can only run during parse-time"));
}
#[test]
fn self_path_repl() {
let actual = nu!("const foo = path self; $foo");
assert!(!actual.status.success());
assert!(actual.err.contains("nu::shell::io::file_not_found"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/path/split.rs | crates/nu-command/tests/commands/path/split.rs | use nu_test_support::nu;
#[test]
fn splits_empty_path() {
let actual = nu!(cwd: "tests", r#"
echo '' | path split | is-empty
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn splits_correctly_single_path() {
let actual = nu!(cwd: "tests", r#"
'home/viking/spam.txt'
| path split
| last
"#);
assert_eq!(actual.out, "spam.txt");
}
#[test]
fn splits_correctly_single_path_const() {
let actual = nu!(r#"
const result = ('home/viking/spam.txt' | path split);
$result | last
"#);
assert_eq!(actual.out, "spam.txt");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/random/dice.rs | crates/nu-command/tests/commands/random/dice.rs | use nu_test_support::nu;
#[test]
fn rolls_4_roll() {
let actual = nu!(r#"
random dice --dice 4 --sides 10 | length
"#);
assert_eq!(actual.out, "4");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/random/chars.rs | crates/nu-command/tests/commands/random/chars.rs | use nu_test_support::nu;
#[test]
fn generates_chars_of_specified_length() {
let actual = nu!(r#"
random chars --length 15 | str stats | get chars
"#);
let result = actual.out;
assert_eq!(result, "15");
}
#[test]
fn generates_chars_of_specified_filesize() {
let actual = nu!(r#"
random chars --length 1kb | str stats | get bytes
"#);
let result = actual.out;
assert_eq!(result, "1000");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/random/bool.rs | crates/nu-command/tests/commands/random/bool.rs | use nu_test_support::nu;
#[test]
fn generates_a_bool() {
let actual = nu!("random bool");
let output = actual.out;
let is_boolean_output = output == "true" || output == "false";
assert!(is_boolean_output);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/random/mod.rs | crates/nu-command/tests/commands/random/mod.rs | mod binary;
mod bool;
mod chars;
mod dice;
mod float;
mod int;
mod uuid;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/random/binary.rs | crates/nu-command/tests/commands/random/binary.rs | use nu_test_support::nu;
#[test]
fn generates_bytes_of_specified_length() {
let actual = nu!(r#"
random binary 16 | bytes length
"#);
let result = actual.out;
assert_eq!(result, "16");
}
#[test]
fn generates_bytes_of_specified_filesize() {
let actual = nu!(r#"
random binary 1kb | bytes length
"#);
let result = actual.out;
assert_eq!(result, "1000");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/random/float.rs | crates/nu-command/tests/commands/random/float.rs | use nu_test_support::nu;
#[test]
fn generates_a_float() {
let actual = nu!("random float 42..43");
// Attention: this relies on the string output
assert!(actual.out.starts_with("42") || actual.out.starts_with("43"));
let actual = nu!("random float 42..43 | describe");
assert_eq!(actual.out, "float")
}
#[test]
fn generates_55() {
let actual = nu!("random float 55..55");
assert!(actual.out.contains("55"));
}
#[test]
fn generates_0() {
let actual = nu!("random float ..<1");
assert!(actual.out.contains('0'));
}
#[test]
fn generate_inf() {
let actual = nu!("random float 1.. | describe");
assert_eq!(actual.out, "float");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/random/int.rs | crates/nu-command/tests/commands/random/int.rs | use nu_test_support::nu;
#[test]
fn generates_an_integer() {
let actual = nu!("random int 42..43");
assert!(actual.out.contains("42") || actual.out.contains("43"));
}
#[test]
fn generates_55() {
let actual = nu!("random int 55..55");
assert!(actual.out.contains("55"));
}
#[test]
fn generates_0() {
let actual = nu!("random int ..<1");
assert!(actual.out.contains('0'));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/random/uuid.rs | crates/nu-command/tests/commands/random/uuid.rs | use nu_test_support::nu;
use uuid::Uuid;
#[test]
fn generates_valid_uuid4_by_default() {
let actual = nu!("random uuid");
let result = Uuid::parse_str(actual.out.as_str());
assert!(result.is_ok());
if let Ok(uuid) = result {
assert_eq!(uuid.get_version_num(), 4);
}
}
#[test]
fn generates_valid_uuid1() {
let actual = nu!("random uuid -v 1 -m 00:11:22:33:44:55");
let result = Uuid::parse_str(actual.out.as_str());
assert!(result.is_ok());
if let Ok(uuid) = result {
assert_eq!(uuid.get_version_num(), 1);
}
}
#[test]
fn generates_valid_uuid3_with_namespace_and_name() {
let actual = nu!("random uuid -v 3 -n dns -s example.com");
let result = Uuid::parse_str(actual.out.as_str());
assert!(result.is_ok());
if let Ok(uuid) = result {
assert_eq!(uuid.get_version_num(), 3);
let namespace = Uuid::NAMESPACE_DNS;
let expected = Uuid::new_v3(&namespace, "example.com".as_bytes());
assert_eq!(uuid, expected);
}
}
#[test]
fn generates_valid_uuid4() {
let actual = nu!("random uuid -v 4");
let result = Uuid::parse_str(actual.out.as_str());
assert!(result.is_ok());
if let Ok(uuid) = result {
assert_eq!(uuid.get_version_num(), 4);
}
}
#[test]
fn generates_valid_uuid5_with_namespace_and_name() {
let actual = nu!("random uuid -v 5 -n dns -s example.com");
let result = Uuid::parse_str(actual.out.as_str());
assert!(result.is_ok());
if let Ok(uuid) = result {
assert_eq!(uuid.get_version_num(), 5);
let namespace = Uuid::NAMESPACE_DNS;
let expected = Uuid::new_v5(&namespace, "example.com".as_bytes());
assert_eq!(uuid, expected);
}
}
#[test]
fn generates_valid_uuid7() {
let actual = nu!("random uuid -v 7");
let result = Uuid::parse_str(actual.out.as_str());
assert!(result.is_ok());
if let Ok(uuid) = result {
assert_eq!(uuid.get_version_num(), 7);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/platform/ansi_.rs | crates/nu-command/tests/commands/platform/ansi_.rs | use nu_test_support::nu;
#[test]
fn test_ansi_shows_error_on_escape() {
let actual = nu!(r"ansi --escape \");
assert!(actual.err.contains("no need for escape characters"))
}
#[test]
fn test_ansi_list_outputs_table() {
let actual = nu!("ansi --list | length");
assert_eq!(actual.out, "440");
}
#[test]
fn test_ansi_codes() {
let actual = nu!("$'(ansi clear_scrollback_buffer)'");
assert_eq!(actual.out, "\x1b[3J");
// Currently, bg is placed before fg in the results
// It's okay if something internally changes this, but
// if so, the test case will need to be updated to:
// assert_eq!(actual.out, "\x1b[31;48;2;0;255;0mHello\x1b[0m");
let actual = nu!("$'(ansi { fg: red, bg: \"#00ff00\" })Hello(ansi reset)'");
assert_eq!(actual.out, "\x1b[48;2;0;255;0;31mHello\x1b[0m");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/platform/kill.rs | crates/nu-command/tests/commands/platform/kill.rs | use nu_test_support::nu;
#[test]
fn test_kill_invalid_pid() {
let pid = i32::MAX;
let actual = nu!(format!("kill {pid}"));
assert!(actual.err.contains("process didn't terminate successfully"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/platform/mod.rs | crates/nu-command/tests/commands/platform/mod.rs | mod ansi_;
mod char_;
mod kill;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/platform/char_.rs | crates/nu-command/tests/commands/platform/char_.rs | use nu_test_support::nu;
#[test]
fn test_char_list_outputs_table() {
let actual = nu!(r#"
char --list | length
"#);
assert_eq!(actual.out, "113");
}
#[test]
fn test_char_eol() {
let actual = nu!(r#"
let expected = if ($nu.os-info.name == 'windows') { "\r\n" } else { "\n" }
((char lsep) == $expected) and ((char line_sep) == $expected) and ((char eol) == $expected)
"#);
assert_eq!(actual.out, "true");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/debug/timeit.rs | crates/nu-command/tests/commands/debug/timeit.rs | use nu_test_support::nu;
#[test]
fn timeit_show_stdout() {
let actual = nu!("let t = timeit { nu --testbin cococo abcdefg }");
assert_eq!(actual.out, "abcdefg");
}
#[test]
fn timeit_show_stderr() {
let actual = nu!(
" with-env {FOO: bar, FOO2: baz} { let t = timeit { nu --testbin echo_env_mixed out-err FOO FOO2 } }"
);
assert!(actual.out.contains("bar"));
assert!(actual.err.contains("baz"));
}
#[test]
fn timeit_show_output() {
let actual = nu!("timeit --output { 'this is a test' } | get output");
assert_eq!(actual.out, "this is a test");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/debug/mod.rs | crates/nu-command/tests/commands/debug/mod.rs | mod metadata_set;
mod timeit;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/debug/metadata_set.rs | crates/nu-command/tests/commands/debug/metadata_set.rs | use nu_test_support::nu;
#[test]
fn errors_on_conflicting_metadata_flags() {
let actual = nu!(r#"
echo "foo" | metadata set --datasource-filepath foo.txt --datasource-ls
"#);
assert!(actual.err.contains("cannot use `--datasource-filepath`"));
assert!(actual.err.contains("with `--datasource-ls`"));
}
#[test]
fn works_with_datasource_filepath() {
let actual = nu!(r#"
echo "foo"
| metadata set --datasource-filepath foo.txt
| metadata
"#);
assert!(actual.out.contains("foo.txt"));
}
#[test]
fn works_with_datasource_ls() {
let actual = nu!(r#"
echo "foo"
| metadata set --datasource-ls
| metadata
"#);
assert!(actual.out.contains("ls"));
}
#[test]
fn works_with_merge_arbitrary_metadata() {
let actual = nu!(
cwd: ".",
r#"
echo "foo"
| metadata set --merge {custom_key: "custom_value", foo: 42}
| metadata
| get custom_key
"#
);
assert_eq!(actual.out, "custom_value");
}
#[test]
fn merge_preserves_existing_metadata() {
let actual = nu!(
cwd: ".",
r#"
echo "foo"
| metadata set --content-type "text/plain"
| metadata set --merge {custom: "value"}
| metadata
| get content_type
"#
);
assert_eq!(actual.out, "text/plain");
}
#[test]
fn custom_metadata_preserved_through_collect() {
let actual = nu!(
cwd: ".",
r#"
echo "foo"
| metadata set --merge {custom_key: "custom_value"}
| collect
| metadata
| get custom_key
"#
);
assert_eq!(actual.out, "custom_value");
}
#[test]
fn closure_adds_custom_without_clobbering_existing() {
let actual = nu!(r#"
"data" | metadata set --content-type "text/csv" | metadata set {|m| $m | upsert custom_key "value"} | metadata
"#);
assert!(actual.out.contains("text/csv"));
assert!(actual.out.contains("custom_key"));
}
#[test]
fn errors_when_closure_with_flags() {
let actual = nu!(r#"
echo "foo" | metadata set {|| {content_type: "text/plain"}} --content-type "ignored"
"#);
assert!(actual.err.contains("cannot use closure with other flags"));
}
#[test]
fn errors_when_closure_returns_non_record() {
let actual = nu!(r#"
echo "foo" | metadata set {|meta| "not a record"}
"#);
assert!(actual.err.contains("Closure must return a record"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/xlsx.rs | crates/nu-command/tests/format_conversions/xlsx.rs | use nu_test_support::nu;
#[test]
fn from_excel_file_to_table() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample_data.xlsx
| get SalesOrders
| get 4
| get column2
"#);
assert_eq!(actual.out, "Gill");
}
#[test]
fn from_excel_file_to_table_select_sheet() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample_data.xlsx --raw
| from xlsx --sheets ["SalesOrders"]
| columns
| get 0
"#);
assert_eq!(actual.out, "SalesOrders");
}
#[test]
fn from_excel_file_to_date() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample_data.xlsx
| get SalesOrders.4.column0
| format date "%Y-%m-%d"
"#);
assert_eq!(actual.out, "2018-02-26");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/nuon.rs | crates/nu-command/tests/format_conversions/nuon.rs | use nu_test_support::nu;
#[test]
fn to_nuon_correct_compaction() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open appveyor.yml
| to nuon
| str length
| $in > 500
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn to_nuon_list_of_numbers() {
let actual = nu!(r#"
[1, 2, 3, 4]
| to nuon
| from nuon
| $in == [1, 2, 3, 4]
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn to_nuon_list_of_strings() {
let actual = nu!(r#"
[abc, xyz, def]
| to nuon
| from nuon
| $in == [abc, xyz, def]
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn to_nuon_table() {
let actual = nu!(r#"
[[my, columns]; [abc, xyz], [def, ijk]]
| to nuon
| from nuon
| $in == [[my, columns]; [abc, xyz], [def, ijk]]
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn from_nuon_illegal_table() {
let actual = nu!(r#"
"[[repeated repeated]; [abc, xyz], [def, ijk]]"
| from nuon
"#);
assert!(actual.err.contains("column_defined_twice"));
}
#[test]
fn to_nuon_bool() {
let actual = nu!(r#"
false
| to nuon
| from nuon
"#);
assert_eq!(actual.out, "false");
}
#[test]
fn to_nuon_escaping() {
let actual = nu!(r#"
"hello\"world"
| to nuon
| from nuon
"#);
assert_eq!(actual.out, "hello\"world");
}
#[test]
fn to_nuon_escaping2() {
let actual = nu!(r#"
"hello\\world"
| to nuon
| from nuon
"#);
assert_eq!(actual.out, "hello\\world");
}
#[test]
fn to_nuon_escaping3() {
let actual = nu!(r#"
["hello\\world"]
| to nuon
| from nuon
| $in == [hello\world]
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn to_nuon_escaping4() {
let actual = nu!(r#"
["hello\"world"]
| to nuon
| from nuon
| $in == ["hello\"world"]
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn to_nuon_escaping5() {
let actual = nu!(r#"
{s: "hello\"world"}
| to nuon
| from nuon
| $in == {s: "hello\"world"}
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn to_nuon_negative_int() {
let actual = nu!(r#"
-1
| to nuon
| from nuon
"#);
assert_eq!(actual.out, "-1");
}
#[test]
fn to_nuon_records() {
let actual = nu!(r#"
{name: "foo bar", age: 100, height: 10}
| to nuon
| from nuon
| $in == {name: "foo bar", age: 100, height: 10}
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn to_nuon_range() {
let actual = nu!(r#"1..42 | to nuon"#);
assert_eq!(actual.out, "1..42");
let actual = nu!(r#"1..<42 | to nuon"#);
assert_eq!(actual.out, "1..<42");
let actual = nu!(r#"1..4..42 | to nuon"#);
assert_eq!(actual.out, "1..4..42");
let actual = nu!(r#"1..4..<42 | to nuon"#);
assert_eq!(actual.out, "1..4..<42");
let actual = nu!(r#"1.0..42.0 | to nuon"#);
assert_eq!(actual.out, "1.0..42.0");
let actual = nu!(r#"1.0..<42.0 | to nuon"#);
assert_eq!(actual.out, "1.0..<42.0");
let actual = nu!(r#"1.0..4.0..42.0 | to nuon"#);
assert_eq!(actual.out, "1.0..4.0..42.0");
let actual = nu!(r#"1.0..4.0..<42.0 | to nuon"#);
assert_eq!(actual.out, "1.0..4.0..<42.0");
}
#[test]
fn from_nuon_range() {
let actual = nu!(r#"'1..42' | from nuon | to nuon"#);
assert_eq!(actual.out, "1..42");
let actual = nu!(r#"'1..<42' | from nuon | to nuon"#);
assert_eq!(actual.out, "1..<42");
let actual = nu!(r#"'1..4..42' | from nuon | to nuon"#);
assert_eq!(actual.out, "1..4..42");
let actual = nu!(r#"'1..4..<42' | from nuon | to nuon"#);
assert_eq!(actual.out, "1..4..<42");
let actual = nu!(r#"'1.0..42.0' | from nuon | to nuon"#);
assert_eq!(actual.out, "1.0..42.0");
let actual = nu!(r#"'1.0..<42.0' | from nuon | to nuon"#);
assert_eq!(actual.out, "1.0..<42.0");
let actual = nu!(r#"'1.0..4.0..42.0' | from nuon | to nuon"#);
assert_eq!(actual.out, "1.0..4.0..42.0");
let actual = nu!(r#"'1.0..4.0..<42.0' | from nuon | to nuon"#);
assert_eq!(actual.out, "1.0..4.0..<42.0");
}
#[test]
fn to_nuon_filesize() {
let actual = nu!(r#"
1kib
| to nuon
"#);
assert_eq!(actual.out, "1024b");
}
#[test]
fn from_nuon_filesize() {
let actual = nu!(r#"
"1024b"
| from nuon
| describe
"#);
assert_eq!(actual.out, "filesize");
}
#[test]
fn to_nuon_duration() {
let actual = nu!(r#"
1min
| to nuon
"#);
assert_eq!(actual.out, "60000000000ns");
}
#[test]
fn from_nuon_duration() {
let actual = nu!(r#"
"60000000000ns"
| from nuon
| describe
"#);
assert_eq!(actual.out, "duration");
}
#[test]
fn to_nuon_datetime() {
let actual = nu!(r#"
2019-05-10
| to nuon
"#);
assert_eq!(actual.out, "2019-05-10T00:00:00+00:00");
}
#[test]
fn from_nuon_datetime() {
let actual = nu!(r#"
"2019-05-10T00:00:00+00:00"
| from nuon
| describe
"#);
assert_eq!(actual.out, "datetime");
}
#[test]
fn to_nuon_errs_on_closure() {
let actual = nu!(r#"
{|| to nuon}
| to nuon
"#);
assert!(actual.err.contains("not deserializable"));
}
#[test]
fn to_nuon_closure_coerced_to_quoted_string() {
let actual = nu!(r#"
{|| to nuon}
| to nuon --serialize
"#);
assert_eq!(actual.out, "\"{|| to nuon}\"");
}
#[test]
fn binary_to() {
let actual = nu!(r#"
0x[ab cd ef] | to nuon
"#);
assert_eq!(actual.out, "0x[ABCDEF]");
}
#[test]
fn binary_roundtrip() {
let actual = nu!(r#"
"0x[1f ff]" | from nuon | to nuon
"#);
assert_eq!(actual.out, "0x[1FFF]");
}
#[test]
fn read_binary_data() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample.nuon | get 5.3
"#);
assert_eq!(actual.out, "31")
}
#[test]
fn read_record() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample.nuon | get 4.name
"#);
assert_eq!(actual.out, "Bobby")
}
#[test]
fn read_bool() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample.nuon | get 3 | $in == true
"#);
assert_eq!(actual.out, "true")
}
#[test]
fn float_doesnt_become_int() {
let actual = nu!(r#"
1.0 | to nuon
"#);
assert_eq!(actual.out, "1.0")
}
#[test]
fn float_inf_parsed_properly() {
let actual = nu!(r#"
inf | to nuon
"#);
assert_eq!(actual.out, "inf")
}
#[test]
fn float_neg_inf_parsed_properly() {
let actual = nu!(r#"
-inf | to nuon
"#);
assert_eq!(actual.out, "-inf")
}
#[test]
fn float_nan_parsed_properly() {
let actual = nu!(r#"
NaN | to nuon
"#);
assert_eq!(actual.out, "NaN")
}
#[test]
fn to_nuon_converts_columns_with_spaces() {
let actual = nu!(r#"
let test = [[a, b, "c d"]; [1 2 3] [4 5 6]]; $test | to nuon | from nuon
"#);
assert!(actual.err.is_empty());
}
#[test]
fn to_nuon_quotes_empty_string() {
let actual = nu!(r#"
let test = ""; $test | to nuon
"#);
assert!(actual.err.is_empty());
assert_eq!(actual.out, r#""""#)
}
#[test]
fn to_nuon_quotes_empty_string_in_list() {
let actual = nu!(r#"
let test = [""]; $test | to nuon | from nuon | $in == [""]
"#);
assert!(actual.err.is_empty());
assert_eq!(actual.out, "true")
}
#[test]
fn to_nuon_quotes_empty_string_in_table() {
let actual = nu!(r#"
let test = [[a, b]; ['', la] [le lu]]; $test | to nuon | from nuon
"#);
assert!(actual.err.is_empty());
}
#[test]
fn does_not_quote_strings_unnecessarily() {
let actual = nu!(r#"
let test = [["a", "b", "c d"]; [1 2 3] [4 5 6]]; $test | to nuon
"#);
assert_eq!(actual.out, "[[a, b, \"c d\"]; [1, 2, 3], [4, 5, 6]]");
let actual = nu!(r#"
let a = {"ro name": "sam" rank: 10}; $a | to nuon
"#);
assert_eq!(actual.out, "{\"ro name\": sam, rank: 10}");
}
#[test]
fn quotes_some_strings_necessarily() {
let actual = nu!(r#"
['true','false','null',
'NaN','NAN','nan','+nan','-nan',
'inf','+inf','-inf','INF',
'Infinity','+Infinity','-Infinity','INFINITY',
'+19.99','-19.99', '19.99b',
'19.99kb','19.99mb','19.99gb','19.99tb','19.99pb','19.99eb','19.99zb',
'19.99kib','19.99mib','19.99gib','19.99tib','19.99pib','19.99eib','19.99zib',
'19ns', '19us', '19ms', '19sec', '19min', '19hr', '19day', '19wk',
'-11.0..-15.0', '11.0..-15.0', '-11.0..15.0',
'-11.0..<-15.0', '11.0..<-15.0', '-11.0..<15.0',
'-11.0..', '11.0..', '..15.0', '..-15.0', '..<15.0', '..<-15.0',
'2000-01-01', '2022-02-02T14:30:00', '2022-02-02T14:30:00+05:00',
',',''
'&&'
] | to nuon | from nuon | describe
"#);
assert_eq!(actual.out, "list<string>");
}
#[test]
fn quotes_some_strings_necessarily_in_record_keys() {
let actual = nu!(r#"
['=', 'a=', '=a'] | each {
{$in : 42}
} | reduce {|elt, acc| $acc | merge $elt} | to nuon | from nuon | columns | describe
"#);
assert_eq!(actual.out, "list<string>");
}
#[test]
fn read_code_should_fail_rather_than_panic() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"open code.nu | from nuon"#);
assert!(actual.err.contains("Error when loading"))
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/msgpack.rs | crates/nu-command/tests/format_conversions/msgpack.rs | use nu_test_support::{nu, playground::Playground};
use pretty_assertions::assert_eq;
fn msgpack_test(fixture_name: &str, commands: Option<&str>) -> nu_test_support::Outcome {
let path_to_generate_nu = nu_test_support::fs::fixtures()
.join("formats")
.join("msgpack")
.join("generate.nu");
let mut outcome = None;
Playground::setup(&format!("msgpack test {fixture_name}"), |dirs, _| {
assert!(
nu!(
cwd: dirs.test(),
format!(
"nu -n '{}' '{}'",
path_to_generate_nu.display(),
fixture_name
),
)
.status
.success()
);
outcome = Some(nu!(
cwd: dirs.test(),
collapse_output: false,
commands.map(|c| c.to_owned()).unwrap_or_else(|| format!("open {fixture_name}.msgpack"))
));
});
outcome.expect("failed to get outcome")
}
fn msgpack_nuon_test(fixture_name: &str, opts: &str) {
let path_to_nuon = nu_test_support::fs::fixtures()
.join("formats")
.join("msgpack")
.join(format!("{fixture_name}.nuon"));
let sample_nuon = std::fs::read_to_string(path_to_nuon).expect("failed to open nuon file");
let outcome = msgpack_test(
fixture_name,
Some(&format!(
"open --raw {fixture_name}.msgpack | from msgpack {opts} | to nuon --indent 4"
)),
);
assert!(outcome.status.success());
assert!(outcome.err.is_empty());
assert_eq!(
sample_nuon.replace("\r\n", "\n"),
outcome.out.replace("\r\n", "\n")
);
}
#[test]
fn sample() {
msgpack_nuon_test("sample", "");
}
#[test]
fn sample_roundtrip() {
let path_to_sample_nuon = nu_test_support::fs::fixtures()
.join("formats")
.join("msgpack")
.join("sample.nuon");
let sample_nuon =
std::fs::read_to_string(&path_to_sample_nuon).expect("failed to open sample.nuon");
let outcome = nu!(
collapse_output: false,
format!(
"open '{}' | to msgpack | from msgpack | to nuon --indent 4",
path_to_sample_nuon.display()
)
);
assert!(outcome.status.success());
assert!(outcome.err.is_empty());
assert_eq!(
sample_nuon.replace("\r\n", "\n"),
outcome.out.replace("\r\n", "\n")
);
}
#[test]
fn objects() {
msgpack_nuon_test("objects", "--objects");
}
#[test]
fn max_depth() {
let outcome = msgpack_test("max-depth", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("exceeded depth limit"));
}
#[test]
fn non_utf8() {
let outcome = msgpack_test("non-utf8", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("utf-8"));
}
#[test]
fn empty() {
let outcome = msgpack_test("empty", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("fill whole buffer"));
}
#[test]
fn eof() {
let outcome = msgpack_test("eof", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("fill whole buffer"));
}
#[test]
fn after_eof() {
let outcome = msgpack_test("after-eof", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("after end of"));
}
#[test]
fn reserved() {
let outcome = msgpack_test("reserved", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("Reserved"));
}
#[test]
fn u64_too_large() {
let outcome = msgpack_test("u64-too-large", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("integer too big"));
}
#[test]
fn non_string_map_key() {
let outcome = msgpack_test("non-string-map-key", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("string key"));
}
#[test]
fn timestamp_wrong_length() {
let outcome = msgpack_test("timestamp-wrong-length", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("Unknown MessagePack extension"));
}
#[test]
fn other_extension_type() {
let outcome = msgpack_test("other-extension-type", None);
assert!(!outcome.status.success());
assert!(outcome.err.contains("Unknown MessagePack extension"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/html.rs | crates/nu-command/tests/format_conversions/html.rs | use nu_test_support::nu;
#[test]
fn out_html_simple() {
let actual = nu!(r#"
echo 3 | to html
"#);
assert_eq!(
actual.out,
r"<html><style>body { background-color:white;color:black; }</style><body>3</body></html>"
);
}
#[test]
fn out_html_metadata() {
let actual = nu!(r#"
echo 3 | to html | metadata | get content_type
"#);
assert_eq!(actual.out, r#"text/html; charset=utf-8"#);
}
#[test]
fn out_html_partial() {
let actual = nu!(r#"
echo 3 | to html -p
"#);
assert_eq!(
actual.out,
"<div style=\"background-color:white;color:black;\">3</div>"
);
}
#[test]
fn out_html_table() {
let actual = nu!(r#"
echo '{"name": "darren"}' | from json | to html
"#);
assert_eq!(
actual.out,
r"<html><style>body { background-color:white;color:black; }</style><body><table><thead><tr><th>name</th></tr></thead><tbody><tr><td>darren</td></tr></tbody></table></body></html>"
);
}
#[test]
#[ignore]
fn test_cd_html_color_flag_dark_false() {
let actual = nu!(r#"
cd --help | to html --html-color
"#);
assert_eq!(
actual.out,
r"<html><style>body { background-color:white;color:black; }</style><body>Change directory.<br><br><span style='color:green;'>Usage<span style='color:black;font-weight:normal;'>:<br> > cd (path) <br><br></span></span><span style='color:green;'>Flags<span style='color:black;font-weight:normal;'>:<br> </span></span><span style='color:#037979;'>-h</span>,<span style='color:black;font-weight:normal;'> </span><span style='color:#037979;'>--help<span style='color:black;font-weight:normal;'> - Display the help message for this command<br><br></span><span style='color:green;'>Signatures<span style='color:black;font-weight:normal;'>:<br> <nothing> | cd <string?> -> <nothing><br> <string> | cd <string?> -> <nothing><br><br></span></span><span style='color:green;'>Parameters<span style='color:black;font-weight:normal;'>:<br> (optional) </span></span></span><span style='color:#037979;'>path<span style='color:black;font-weight:normal;'> <</span><span style='color:blue;font-weight:bold;'>directory<span style='color:black;font-weight:normal;'>>: the path to change to<br><br></span></span><span style='color:green;'>Examples<span style='color:black;font-weight:normal;'>:<br> Change to your home directory<br> > </span><span style='color:#037979;font-weight:bold;'>cd<span style='color:black;font-weight:normal;'> </span></span></span></span><span style='color:#037979;'>~<span style='color:black;font-weight:normal;'><br><br> Change to a directory via abbreviations<br> > </span><span style='color:#037979;font-weight:bold;'>cd<span style='color:black;font-weight:normal;'> </span></span></span><span style='color:#037979;'>d/s/9<span style='color:black;font-weight:normal;'><br><br> Change to the previous working directory ($OLDPWD)<br> > </span><span style='color:#037979;font-weight:bold;'>cd<span style='color:black;font-weight:normal;'> </span></span></span><span style='color:#037979;'>-<span style='color:black;font-weight:normal;'><br><br></body></html></span></span>"
);
}
#[test]
#[ignore]
fn test_no_color_flag() {
// TODO replace with something potentially more stable, otherwise this test needs to be
// manually updated when ever the help output changes
let actual = nu!(r#"
cd --help | to html --no-color
"#);
assert_eq!(
actual.out,
r"<html><style>body { background-color:white;color:black; }</style><body>Change directory.<br><br>Usage:<br> > cd (path) <br><br>Flags:<br> -h, --help - Display the help message for this command<br><br>Parameters:<br> path <directory>: The path to change to. (optional)<br><br>Input/output types:<br> ╭─#─┬──input──┬─output──╮<br> │ 0 │ nothing │ nothing │<br> │ 1 │ string │ nothing │<br> ╰───┴─────────┴─────────╯<br><br>Examples:<br> Change to your home directory<br> > cd ~<br><br> Change to the previous working directory ($OLDPWD)<br> > cd -<br><br></body></html>"
)
}
#[test]
fn test_list() {
let actual = nu!(r#"to html --list | where name == C64 | get 0 | to nuon"#);
assert_eq!(
actual.out,
r##"{name: "C64", black: "#090300", red: "#883932", green: "#55a049", yellow: "#bfce72", blue: "#40318d", purple: "#8b3f96", cyan: "#67b6bd", white: "#ffffff", brightBlack: "#000000", brightRed: "#883932", brightGreen: "#55a049", brightYellow: "#bfce72", brightBlue: "#40318d", brightPurple: "#8b3f96", brightCyan: "#67b6bd", brightWhite: "#f7f7f7", background: "#40318d", foreground: "#7869c4"}"##
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/ods.rs | crates/nu-command/tests/format_conversions/ods.rs | use nu_test_support::nu;
#[test]
fn from_ods_file_to_table() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample_data.ods
| get SalesOrders
| get 4
| get column2
"#);
assert_eq!(actual.out, "Gill");
}
#[test]
fn from_ods_file_to_table_select_sheet() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample_data.ods --raw
| from ods --sheets ["SalesOrders"]
| columns
| get 0
"#);
assert_eq!(actual.out, "SalesOrders");
}
#[test]
fn from_ods_file_to_table_select_sheet_with_annotations() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample_data_with_annotation.ods --raw
| from ods --sheets ["SalesOrders"]
| get SalesOrders
| get column4
| get 0
"#);
// The Units column in the sheet SalesOrders has an annotation and should be ignored.
assert_eq!(actual.out, "Units");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/json.rs | crates/nu-command/tests/format_conversions/json.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn table_to_json_text_and_from_json_text_back_into_table() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sgml_description.json
| to json
| from json
| get glossary.GlossDiv.GlossList.GlossEntry.GlossSee
"#);
assert_eq!(actual.out, "markup");
}
#[test]
fn table_to_json_float_doesnt_become_int() {
let actual = nu!(r#"
[[a]; [1.0]] | to json | from json | get 0.a | describe
"#);
assert_eq!(actual.out, "float")
}
#[test]
fn from_json_text_to_table() {
Playground::setup("filter_from_json_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"katz.txt",
r#"
{
"katz": [
{"name": "Yehuda", "rusty_luck": 1},
{"name": "JT", "rusty_luck": 1},
{"name": "Andres", "rusty_luck": 1},
{"name":"GorbyPuff", "rusty_luck": 1}
]
}
"#,
)]);
let actual = nu!(
cwd: dirs.test(),
"open katz.txt | from json | get katz | get rusty_luck | length "
);
assert_eq!(actual.out, "4");
})
}
#[test]
fn from_json_text_to_table_strict() {
Playground::setup("filter_from_json_test_1_strict", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"katz.txt",
r#"
{
"katz": [
{"name": "Yehuda", "rusty_luck": 1},
{"name": "JT", "rusty_luck": 1},
{"name": "Andres", "rusty_luck": 1},
{"name":"GorbyPuff", "rusty_luck": 1}
]
}
"#,
)]);
let actual = nu!(
cwd: dirs.test(),
"open katz.txt | from json -s | get katz | get rusty_luck | length "
);
assert_eq!(actual.out, "4");
})
}
#[test]
fn from_json_text_recognizing_objects_independently_to_table() {
Playground::setup("filter_from_json_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"katz.txt",
r#"
{"name": "Yehuda", "rusty_luck": 1}
{"name": "JT", "rusty_luck": 1}
{"name": "Andres", "rusty_luck": 1}
{"name":"GorbyPuff", "rusty_luck": 3}
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open katz.txt
| from json -o
| where name == "GorbyPuff"
| get rusty_luck.0
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
fn from_json_text_objects_is_stream() {
Playground::setup("filter_from_json_test_2_is_stream", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"katz.txt",
r#"
{"name": "Yehuda", "rusty_luck": 1}
{"name": "JT", "rusty_luck": 1}
{"name": "Andres", "rusty_luck": 1}
{"name":"GorbyPuff", "rusty_luck": 3}
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open katz.txt
| from json -o
| describe -n
"#);
assert_eq!(actual.out, "stream");
})
}
#[test]
fn from_json_text_recognizing_objects_independently_to_table_strict() {
Playground::setup("filter_from_json_test_2_strict", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"katz.txt",
r#"
{"name": "Yehuda", "rusty_luck": 1}
{"name": "JT", "rusty_luck": 1}
{"name": "Andres", "rusty_luck": 1}
{"name":"GorbyPuff", "rusty_luck": 3}
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open katz.txt
| from json -o -s
| where name == "GorbyPuff"
| get rusty_luck.0
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
fn table_to_json_text() {
Playground::setup("filter_to_json_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"sample.txt",
r#"
JonAndrehudaTZ,3
GorbyPuff,100
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open sample.txt
| lines
| split column "," name luck
| select name
| to json
| from json
| get 0
| get name
"#);
assert_eq!(actual.out, "JonAndrehudaTZ");
})
}
#[test]
fn table_to_json_text_strict() {
Playground::setup("filter_to_json_test_strict", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"sample.txt",
r#"
JonAndrehudaTZ,3
GorbyPuff,100
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open sample.txt
| lines
| split column "," name luck
| select name
| to json
| from json -s
| get 0
| get name
"#);
assert_eq!(actual.out, "JonAndrehudaTZ");
})
}
#[test]
fn top_level_values_from_json() {
for (value, type_name) in [("null", "nothing"), ("true", "bool"), ("false", "bool")] {
let actual = nu!(format!(r#""{value}" | from json | to json"#));
assert_eq!(actual.out, value);
let actual = nu!(format!(r#""{value}" | from json | describe"#));
assert_eq!(actual.out, type_name);
}
}
#[test]
fn top_level_values_from_json_strict() {
for (value, type_name) in [("null", "nothing"), ("true", "bool"), ("false", "bool")] {
let actual = nu!(format!(r#""{value}" | from json -s | to json"#));
assert_eq!(actual.out, value);
let actual = nu!(format!(r#""{value}" | from json -s | describe"#));
assert_eq!(actual.out, type_name);
}
}
#[test]
fn strict_parsing_fails_on_comment() {
let actual = nu!(r#"'{ "a": 1, /* comment */ "b": 2 }' | from json -s"#);
assert!(actual.err.contains("error parsing JSON text"));
}
#[test]
fn strict_parsing_fails_on_trailing_comma() {
let actual = nu!(r#"'{ "a": 1, "b": 2, }' | from json -s"#);
assert!(actual.err.contains("error parsing JSON text"));
}
#[test]
fn ranges_to_json_as_array() {
let value = r#"[ 1, 2, 3]"#;
let actual = nu!(r#"1..3 | to json"#);
assert_eq!(actual.out, value);
}
#[test]
fn unbounded_from_in_range_fails() {
let actual = nu!(r#"1.. | to json"#);
assert!(actual.err.contains("Cannot create range"));
}
#[test]
fn inf_in_range_fails() {
let actual = nu!(r#"inf..5 | to json"#);
assert!(actual.err.contains("can't convert to countable values"));
let actual = nu!(r#"5..inf | to json"#);
assert!(
actual
.err
.contains("Unbounded ranges are not allowed when converting to this format")
);
let actual = nu!(r#"-inf..inf | to json"#);
assert!(actual.err.contains("can't convert to countable values"));
}
#[test]
fn test_indent_flag() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
echo '{ "a": 1, "b": 2, "c": 3 }'
| from json
| to json --indent 3
"#);
let expected_output = "{ \"a\": 1, \"b\": 2, \"c\": 3}";
assert_eq!(actual.out, expected_output);
}
#[test]
fn test_tabs_indent_flag() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
echo '{ "a": 1, "b": 2, "c": 3 }'
| from json
| to json --tabs 2
"#);
let expected_output = "{\t\t\"a\": 1,\t\t\"b\": 2,\t\t\"c\": 3}";
assert_eq!(actual.out, expected_output);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/url.rs | crates/nu-command/tests/format_conversions/url.rs | use nu_test_support::nu;
#[test]
fn can_encode_and_decode_urlencoding() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open sample.url
| url build-query
| from url
| get cheese
"#);
assert_eq!(actual.out, "comté");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/xml.rs | crates/nu-command/tests/format_conversions/xml.rs | use nu_test_support::nu;
#[test]
fn table_to_xml_text_and_from_xml_text_back_into_table() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open jt.xml
| to xml
| from xml
| get content
| where tag == channel
| get content
| flatten
| where tag == item
| get content
| flatten
| where tag == guid
| get 0.attributes.isPermaLink
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn to_xml_error_unknown_column() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{tag: a bad_column: b} | to xml
"#);
assert!(actual.err.contains("Invalid column \"bad_column\""));
}
#[test]
fn to_xml_error_no_tag() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{attributes: {a: b c: d}} | to xml
"#);
assert!(actual.err.contains("Tag missing"));
}
#[test]
fn to_xml_error_tag_not_string() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{tag: 1 attributes: {a: b c: d}} | to xml
"#);
assert!(actual.err.contains("not a string"));
}
#[test]
fn to_xml_partial_escape() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{
tag: a
attributes: { a: "'a'\\" }
content: [ `'"qwe\` ]
} | to xml --partial-escape
"#);
assert_eq!(actual.out, r#"<a a="'a'\">'"qwe\</a>"#);
}
#[test]
fn to_xml_pi_comment_not_escaped() {
// PI and comment content should not be escaped
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{
tag: a
content: [
{tag: ?qwe content: `"'<>&`}
{tag: ! content: `"'<>&`}
]
} | to xml
"#);
assert_eq!(actual.out, r#"<a><?qwe "'<>&?><!--"'<>&--></a>"#);
}
#[test]
fn to_xml_self_closed() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{
tag: root
content: [
[tag attributes content];
[a null null]
[b {e: r} null]
[c {t: y} []]
]
} | to xml --self-closed
"#);
assert_eq!(actual.out, r#"<root><a/><b e="r"/><c t="y"/></root>"#);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/msgpackz.rs | crates/nu-command/tests/format_conversions/msgpackz.rs | use nu_test_support::nu;
use pretty_assertions::assert_eq;
#[test]
fn sample_roundtrip() {
let path_to_sample_nuon = nu_test_support::fs::fixtures()
.join("formats")
.join("msgpack")
.join("sample.nuon");
let sample_nuon =
std::fs::read_to_string(&path_to_sample_nuon).expect("failed to open sample.nuon");
let outcome = nu!(
collapse_output: false,
format!(
"open '{}' | to msgpackz | from msgpackz | to nuon --indent 4",
path_to_sample_nuon.display()
)
);
assert!(outcome.status.success());
assert!(outcome.err.is_empty());
assert_eq!(
sample_nuon.replace("\r\n", "\n"),
outcome.out.replace("\r\n", "\n")
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/tsv.rs | crates/nu-command/tests/format_conversions/tsv.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn table_to_tsv_text_and_from_tsv_text_back_into_table() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"open caco3_plastics.tsv | to tsv | from tsv | first | get origin"
);
assert_eq!(actual.out, "SPAIN");
}
#[test]
fn table_to_tsv_text_and_from_tsv_text_back_into_table_using_csv_separator() {
let actual = nu!(
cwd: "tests/fixtures/formats",
r#"open caco3_plastics.tsv | to tsv | from csv --separator "\t" | first | get origin"#
);
assert_eq!(actual.out, "SPAIN");
}
#[test]
fn table_to_tsv_text() {
Playground::setup("filter_to_tsv_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"tsv_text_sample.txt",
r#"
importer shipper tariff_item name origin
Plasticos Rival Reverte 2509000000 Calcium carbonate Spain
Tigre Ecuador OMYA Andina 3824909999 Calcium carbonate Colombia
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open tsv_text_sample.txt
| lines
| split column "\t" a b c d origin
| last 1
| to tsv
| lines
| select 1
"#);
assert!(actual.out.contains("Colombia"));
})
}
#[test]
fn table_to_tsv_text_skipping_headers_after_conversion() {
Playground::setup("filter_to_tsv_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"tsv_text_sample.txt",
r#"
importer shipper tariff_item name origin
Plasticos Rival Reverte 2509000000 Calcium carbonate Spain
Tigre Ecuador OMYA Andina 3824909999 Calcium carbonate Colombia
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open tsv_text_sample.txt
| lines
| split column "\t" a b c d origin
| last 1
| to tsv --noheaders
"#);
assert!(actual.out.contains("Colombia"));
})
}
#[test]
fn table_to_tsv_float_doesnt_become_int() {
let actual = nu!(r#"
[[a]; [1.0]] | to tsv | from tsv | get 0.a | describe
"#);
assert_eq!(actual.out, "float")
}
#[test]
fn from_tsv_text_to_table() {
Playground::setup("filter_from_tsv_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_amigos.txt",
r#"
first Name Last Name rusty_luck
Andrés Robalino 1
JT Turner 1
Yehuda Katz 1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_amigos.txt
| from tsv
| get rusty_luck
| length
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
#[ignore = "csv crate has a bug when the last line is a comment: https://github.com/BurntSushi/rust-csv/issues/363"]
fn from_tsv_text_with_comments_to_table() {
Playground::setup("filter_from_tsv_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
# This is a comment
first_name last_name rusty_luck
# This one too
Andrés Robalino 1
Jonathan Turner 1
Yehuda Katz 1
# This one also
"#,
)]);
let actual = nu!(cwd: dirs.test(), r##"
open los_tres_caballeros.txt
| from tsv --comment "#"
| get rusty_luck
| length
"##);
assert_eq!(actual.out, "3");
})
}
#[test]
fn from_tsv_text_with_custom_quotes_to_table() {
Playground::setup("filter_from_tsv_test_3", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name last_name rusty_luck
'And''rés' Robalino 1
Jonathan Turner 1
Yehuda Katz 1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from tsv --quote "'"
| first
| get first_name
"#);
assert_eq!(actual.out, "And'rés");
})
}
#[test]
fn from_tsv_text_with_custom_escapes_to_table() {
Playground::setup("filter_from_tsv_test_4", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name last_name rusty_luck
"And\"rés" Robalino 1
Jonathan Turner 1
Yehuda Katz 1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r"
open los_tres_caballeros.txt
| from tsv --escape '\'
| first
| get first_name
");
assert_eq!(actual.out, "And\"rés");
})
}
#[test]
fn from_tsv_text_skipping_headers_to_table() {
Playground::setup("filter_from_tsv_test_5", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_amigos.txt",
r#"
Andrés Robalino 1
JT Turner 1
Yehuda Katz 1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_amigos.txt
| from tsv --noheaders
| get column2
| length
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
fn from_tsv_text_with_missing_columns_to_table() {
Playground::setup("filter_from_tsv_test_6", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name last_name rusty_luck
Andrés Robalino
Jonathan Turner 1
Yehuda Katz 1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from tsv --flexible
| get -o rusty_luck
| compact
| length
"#);
assert_eq!(actual.out, "2");
})
}
#[test]
fn from_tsv_text_with_multiple_char_comment() {
Playground::setup("filter_from_tsv_test_7", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name last_name rusty_luck
Andrés Robalino 1
Jonathan Turner 1
Yehuda Katz 1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --comment "li"
"#);
assert!(actual.err.contains("single character separator"));
})
}
#[test]
fn from_tsv_text_with_wrong_type_comment() {
Playground::setup("filter_from_csv_test_8", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name last_name rusty_luck
Andrés Robalino 1
Jonathan Turner 1
Yehuda Katz 1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --comment ('123' | into int)
"#);
assert!(actual.err.contains("can't convert int to char"));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/markdown.rs | crates/nu-command/tests/format_conversions/markdown.rs | use nu_test_support::nu;
#[test]
fn md_empty() {
let actual = nu!(r#"
echo [[]; []] | from json | to md
"#);
assert_eq!(actual.out, "");
}
#[test]
fn md_empty_pretty() {
let actual = nu!(r#"
echo "{}" | from json | to md -p
"#);
assert_eq!(actual.out, "");
}
#[test]
fn md_simple() {
let actual = nu!(r#"
echo 3 | to md
"#);
assert_eq!(actual.out, "* 3");
}
#[test]
fn md_simple_pretty() {
let actual = nu!(r#"
echo 3 | to md -p
"#);
assert_eq!(actual.out, "* 3");
}
#[test]
fn md_table() {
let actual = nu!(r#"
echo [[name]; [jason]] | to md
"#);
assert_eq!(actual.out, "| name || --- || jason |");
}
#[test]
fn md_table_pretty() {
let actual = nu!(r#"
echo [[name]; [joseph]] | to md -p
"#);
assert_eq!(actual.out, "| name || ------ || joseph |");
}
#[test]
fn md_combined() {
let actual = nu!(r#"
def title [] {
echo [[H1]; ["Nu top meals"]]
};
def meals [] {
echo [[dish]; [Arepa] [Taco] [Pizza]]
};
title
| append (meals)
| to md --per-element --pretty
"#);
assert_eq!(
actual.out,
"# Nu top meals| dish || ----- || Arepa || Taco || Pizza |"
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/mod.rs | crates/nu-command/tests/format_conversions/mod.rs | mod csv;
mod html;
mod json;
mod markdown;
mod msgpack;
mod msgpackz;
mod nuon;
mod ods;
mod ssv;
mod toml;
mod tsv;
mod url;
mod xlsx;
mod xml;
mod yaml;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/yaml.rs | crates/nu-command/tests/format_conversions/yaml.rs | use nu_test_support::nu;
#[test]
fn table_to_yaml_text_and_from_yaml_text_back_into_table() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open appveyor.yml
| to yaml
| from yaml
| get environment.global.PROJECT_NAME
"#);
assert_eq!(actual.out, "nushell");
}
#[test]
fn table_to_yml_text_and_from_yml_text_back_into_table() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open appveyor.yml
| to yml
| from yml
| get environment.global.PROJECT_NAME
"#);
assert_eq!(actual.out, "nushell");
}
#[test]
fn convert_dict_to_yaml_with_boolean_key() {
let actual = nu!(r#"
"true: BooleanKey " | from yaml
"#);
assert!(actual.out.contains("BooleanKey"));
assert!(actual.err.is_empty());
}
#[test]
fn convert_dict_to_yaml_with_integer_key() {
let actual = nu!(r#"
"200: [] " | from yaml
"#);
assert!(actual.out.contains("200"));
assert!(actual.err.is_empty());
}
#[test]
fn convert_dict_to_yaml_with_integer_floats_key() {
let actual = nu!(r#"
"2.11: "1" " | from yaml
"#);
assert!(actual.out.contains("2.11"));
assert!(actual.err.is_empty());
}
#[test]
#[ignore]
fn convert_bool_to_yaml_in_yaml_spec_1_2() {
let actual = nu!(r#"
[y n no On OFF True true false] | to yaml
"#);
assert_eq!(
actual.out,
"- 'y'- 'n'- 'no'- 'On'- 'OFF'- 'True'- true- false"
);
assert!(actual.err.is_empty());
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/csv.rs | crates/nu-command/tests/format_conversions/csv.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn table_to_csv_text_and_from_csv_text_back_into_table() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"open caco3_plastics.csv | to csv | from csv | first | get origin "
);
assert_eq!(actual.out, "SPAIN");
}
#[test]
fn table_to_csv_text() {
Playground::setup("filter_to_csv_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"csv_text_sample.txt",
r#"
importer,shipper,tariff_item,name,origin
Plasticos Rival,Reverte,2509000000,Calcium carbonate,Spain
Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open csv_text_sample.txt
| lines
| str trim
| split column "," a b c d origin
| last 1
| to csv
| lines
| get 1
"#);
assert!(
actual
.out
.contains("Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia")
);
})
}
#[test]
fn table_to_csv_text_skipping_headers_after_conversion() {
Playground::setup("filter_to_csv_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"csv_text_sample.txt",
r#"
importer,shipper,tariff_item,name,origin
Plasticos Rival,Reverte,2509000000,Calcium carbonate,Spain
Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open csv_text_sample.txt
| lines
| str trim
| split column "," a b c d origin
| last 1
| to csv --noheaders
"#);
assert!(
actual
.out
.contains("Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia")
);
})
}
#[test]
fn table_to_csv_float_doesnt_become_int() {
let actual = nu!(r#"
[[a]; [1.0]] | to csv | from csv | get 0.a | describe
"#);
assert_eq!(actual.out, "float")
}
#[test]
fn infers_types() {
Playground::setup("filter_from_csv_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_cuatro_mosqueteros.csv",
r#"
first_name,last_name,rusty_luck,d
Andrés,Robalino,1,d
JT,Turner,1,d
Yehuda,Katz,1,d
Jason,Gedge,1,d
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_cuatro_mosqueteros.csv
| where rusty_luck > 0
| length
"#);
assert_eq!(actual.out, "4");
})
}
#[test]
fn from_csv_text_to_table() {
Playground::setup("filter_from_csv_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name,last_name,rusty_luck
Andrés,Robalino,1
JT,Turner,1
Yehuda,Katz,1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv
| get rusty_luck
| length
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
fn from_csv_text_with_separator_to_table() {
Playground::setup("filter_from_csv_test_3", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name;last_name;rusty_luck
Andrés;Robalino;1
JT;Turner;1
Yehuda;Katz;1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --separator ";"
| get rusty_luck
| length
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
fn from_csv_text_with_tab_separator_to_table() {
Playground::setup("filter_from_csv_test_4", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name last_name rusty_luck
Andrés Robalino 1
JT Turner 1
Yehuda Katz 1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --separator (char tab)
| get rusty_luck
| length
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
#[ignore = "csv crate has a bug when the last line is a comment: https://github.com/BurntSushi/rust-csv/issues/363"]
fn from_csv_text_with_comments_to_table() {
Playground::setup("filter_from_csv_test_5", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
# This is a comment
first_name,last_name,rusty_luck
# This one too
Andrés,Robalino,1
Jonathan,Turner,1
Yehuda,Katz,1
# This one also
"#,
)]);
let actual = nu!(cwd: dirs.test(), r##"
open los_tres_caballeros.txt
| from csv --comment "#"
| get rusty_luck
| length
"##);
assert_eq!(actual.out, "3");
})
}
#[test]
fn from_csv_text_with_custom_quotes_to_table() {
Playground::setup("filter_from_csv_test_6", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name,last_name,rusty_luck
'And''rés',Robalino,1
Jonathan,Turner,1
Yehuda,Katz,1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --quote "'"
| first
| get first_name
"#);
assert_eq!(actual.out, "And'rés");
})
}
#[test]
fn from_csv_text_with_custom_escapes_to_table() {
Playground::setup("filter_from_csv_test_7", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name,last_name,rusty_luck
"And\"rés",Robalino,1
Jonathan,Turner,1
Yehuda,Katz,1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r"
open los_tres_caballeros.txt
| from csv --escape '\'
| first
| get first_name
");
assert_eq!(actual.out, "And\"rés");
})
}
#[test]
fn from_csv_text_skipping_headers_to_table() {
Playground::setup("filter_from_csv_test_8", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_amigos.txt",
r#"
Andrés,Robalino,1
JT,Turner,1
Yehuda,Katz,1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_amigos.txt
| from csv --noheaders
| get column2
| length
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
fn from_csv_text_with_missing_columns_to_table() {
Playground::setup("filter_from_csv_test_9", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name,last_name,rusty_luck
Andrés,Robalino
Jonathan,Turner,1
Yehuda,Katz,1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --flexible
| get -o rusty_luck
| compact
| length
"#);
assert_eq!(actual.out, "2");
})
}
#[test]
fn from_csv_text_with_multiple_char_separator() {
Playground::setup("filter_from_csv_test_10", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name,last_name,rusty_luck
Andrés,Robalino,1
Jonathan,Turner,1
Yehuda,Katz,1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --separator "li"
"#);
assert!(
actual
.err
.contains("separator should be a single char or a 4-byte unicode")
);
})
}
#[test]
fn from_csv_text_with_wrong_type_separator() {
Playground::setup("filter_from_csv_test_11", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name,last_name,rusty_luck
Andrés,Robalino,1
Jonathan,Turner,1
Yehuda,Katz,1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --separator ('123' | into int)
"#);
assert!(actual.err.contains("can't convert int to string"));
})
}
#[test]
fn table_with_record_error() {
let actual = nu!(r#"
[[a b]; [1 2] [3 {a: 1 b: 2}]]
| to csv
"#);
assert!(actual.err.contains("can't convert"))
}
#[test]
fn list_not_table_parse_time_error() {
let actual = nu!(r#"
[{a: 1 b: 2} {a: 3 b: 4} 1]
| to csv
"#);
assert!(actual.err.contains("parser::input_type_mismatch"))
}
#[test]
fn list_not_table_runtime_error() {
let actual = nu!(r#"
echo [{a: 1 b: 2} {a: 3 b: 4} 1]
| to csv
"#);
assert!(actual.err.contains("Input type not supported"))
}
#[test]
fn string_to_csv_error() {
let actual = nu!(r#"
'qwe' | to csv
"#);
assert!(actual.err.contains("command doesn't support"))
}
#[test]
fn parses_csv_with_unicode_sep() {
Playground::setup("filter_from_csv_unicode_sep_test_3", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name;last_name;rusty_luck
Andrés;Robalino;1
JT;Turner;1
Yehuda;Katz;1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --separator "003B"
| get rusty_luck
| length
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
fn parses_csv_with_unicode_x1f_sep() {
Playground::setup("filter_from_csv_unicode_sep_x1f_test_3", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_namelast_namerusty_luck
AndrésRobalino1
JTTurner1
YehudaKatz1
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| from csv --separator "001F"
| get rusty_luck
| length
"#);
assert_eq!(actual.out, "3");
})
}
#[test]
fn from_csv_test_flexible_extra_vals() {
let actual = nu!(r#"
echo "a,b\n1,2,3" | from csv --flexible | first | values | to nuon
"#);
assert_eq!(actual.out, "[1, 2, 3]");
}
#[test]
fn from_csv_test_flexible_missing_vals() {
let actual = nu!(r#"
echo "a,b\n1" | from csv --flexible | first | values | to nuon
"#);
assert_eq!(actual.out, "[1]");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/ssv.rs | crates/nu-command/tests/format_conversions/ssv.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn from_ssv_text_to_table() {
Playground::setup("filter_from_ssv_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"oc_get_svc.txt",
r#"
NAME LABELS SELECTOR IP PORT(S)
docker-registry docker-registry=default docker-registry=default 172.30.78.158 5000/TCP
kubernetes component=apiserver,provider=kubernetes <none> 172.30.0.2 443/TCP
kubernetes-ro component=apiserver,provider=kubernetes <none> 172.30.0.1 80/TCP
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open oc_get_svc.txt
| from ssv
| get 0
| get IP
"#);
assert_eq!(actual.out, "172.30.78.158");
})
}
#[test]
fn from_ssv_text_to_table_with_separator_specified() {
Playground::setup("filter_from_ssv_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"oc_get_svc.txt",
r#"
NAME LABELS SELECTOR IP PORT(S)
docker-registry docker-registry=default docker-registry=default 172.30.78.158 5000/TCP
kubernetes component=apiserver,provider=kubernetes <none> 172.30.0.2 443/TCP
kubernetes-ro component=apiserver,provider=kubernetes <none> 172.30.0.1 80/TCP
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open oc_get_svc.txt
| from ssv --minimum-spaces 3
| get 0
| get IP
"#);
assert_eq!(actual.out, "172.30.78.158");
})
}
#[test]
fn from_ssv_text_treating_first_line_as_data_with_flag() {
Playground::setup("filter_from_ssv_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"oc_get_svc.txt",
r#"
docker-registry docker-registry=default docker-registry=default 172.30.78.158 5000/TCP
kubernetes component=apiserver,provider=kubernetes <none> 172.30.0.2 443/TCP
kubernetes-ro component=apiserver,provider=kubernetes <none> 172.30.0.1 80/TCP
"#,
)]);
let aligned_columns = nu!(cwd: dirs.test(), r#"
open oc_get_svc.txt
| from ssv --noheaders -a
| first
| get column0
"#);
let separator_based = nu!(cwd: dirs.test(), r#"
open oc_get_svc.txt
| from ssv --noheaders
| first
| get column0
"#);
assert_eq!(aligned_columns.out, separator_based.out);
assert_eq!(separator_based.out, "docker-registry");
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/format_conversions/toml.rs | crates/nu-command/tests/format_conversions/toml.rs | use nu_test_support::nu;
#[test]
fn record_map_to_toml() {
let actual = nu!(r#"
{a: 1 b: 2 c: 'qwe'}
| to toml
| from toml
| $in == {a: 1 b: 2 c: 'qwe'}
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn nested_records_to_toml() {
let actual = nu!(r#"
{a: {a: a b: b} c: 1}
| to toml
| from toml
| $in == {a: {a: a b: b} c: 1}
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn records_with_tables_to_toml() {
let actual = nu!(r#"
{a: [[a b]; [1 2] [3 4]] b: [[c d e]; [1 2 3]]}
| to toml
| from toml
| $in == {a: [[a b]; [1 2] [3 4]] b: [[c d e]; [1 2 3]]}
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn nested_tables_to_toml() {
let actual = nu!(r#"
{c: [[f g]; [[[h k]; [1 2] [3 4]] 1]]}
| to toml
| from toml
| $in == {c: [[f g]; [[[h k]; [1 2] [3 4]] 1]]}
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn table_to_toml_fails() {
// Tables can't be represented in toml
let actual = nu!(r#"
try { [[a b]; [1 2] [5 6]] | to toml | false } catch { true }
"#);
assert!(actual.err.contains("command doesn't support"));
}
#[test]
fn string_to_toml_fails() {
// Strings are not a top-level toml structure
let actual = nu!(r#"
try { 'not a valid toml' | to toml | false } catch { true }
"#);
assert!(actual.err.contains("command doesn't support"));
}
#[test]
fn big_record_to_toml_text_and_from_toml_text_back_into_record() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| to toml
| from toml
| get package.name
"#);
assert_eq!(actual.out, "nu");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/lib.rs | crates/nu-plugin-core/src/lib.rs | //! Functionality and types shared between the plugin and the engine, other than protocol types.
//!
//! If you are writing a plugin, you probably don't need this crate. We will make fewer guarantees
//! for the stability of the interface of this crate than for `nu_plugin`.
pub mod util;
mod communication_mode;
mod interface;
mod serializers;
pub use communication_mode::{
ClientCommunicationIo, CommunicationMode, PreparedServerCommunication, ServerCommunicationIo,
};
pub use interface::{
Interface, InterfaceManager, PipelineDataWriter, PluginRead, PluginWrite,
stream::{FromShellError, StreamManager, StreamManagerHandle, StreamReader, StreamWriter},
};
pub use serializers::{
Encoder, EncodingType, PluginEncoder, json::JsonSerializer, msgpack::MsgPackSerializer,
};
#[doc(hidden)]
pub use interface::test_util as interface_test_util;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/util/with_custom_values_in.rs | crates/nu-plugin-core/src/util/with_custom_values_in.rs | use nu_protocol::{CustomValue, IntoSpanned, ShellError, Spanned, Value};
#[allow(unused_imports)] // both are definitely used
use nu_protocol::{BlockId, VarId};
/// Do something with all [`CustomValue`]s recursively within a `Value`. This is not limited to
/// plugin custom values.
pub fn with_custom_values_in<E>(
value: &mut Value,
mut f: impl FnMut(Spanned<&mut Box<dyn CustomValue>>) -> Result<(), E>,
) -> Result<(), E>
where
E: From<ShellError>,
{
value.recurse_mut(&mut |value| {
let span = value.span();
match value {
Value::Custom { val, .. } => {
// Operate on a CustomValue.
f(val.into_spanned(span))
}
_ => Ok(()),
}
})
}
#[test]
fn find_custom_values() {
use nu_plugin_protocol::test_util::test_plugin_custom_value;
use nu_protocol::{engine::Closure, record};
let mut cv = Value::test_custom_value(Box::new(test_plugin_custom_value()));
let mut value = Value::test_record(record! {
"bare" => cv.clone(),
"list" => Value::test_list(vec![
cv.clone(),
Value::test_int(4),
]),
"closure" => Value::test_closure(
Closure {
block_id: BlockId::new(0),
captures: vec![(VarId::new(0), cv.clone()), (VarId::new(1), Value::test_string("foo"))]
}
),
});
// Do with_custom_values_in, and count the number of custom values found
let mut found = 0;
with_custom_values_in::<ShellError>(&mut value, |_| {
found += 1;
Ok(())
})
.expect("error");
assert_eq!(3, found, "found in value");
// Try it on bare custom value too
found = 0;
with_custom_values_in::<ShellError>(&mut cv, |_| {
found += 1;
Ok(())
})
.expect("error");
assert_eq!(1, found, "bare custom value didn't work");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/util/waitable.rs | crates/nu-plugin-core/src/util/waitable.rs | use std::sync::{
Arc, Condvar, Mutex, MutexGuard, PoisonError,
atomic::{AtomicBool, Ordering},
};
use nu_protocol::ShellError;
/// A shared container that may be empty, and allows threads to block until it has a value.
///
/// This side is read-only - use [`WaitableMut`] on threads that might write a value.
#[derive(Debug, Clone)]
pub struct Waitable<T: Clone + Send> {
shared: Arc<WaitableShared<T>>,
}
#[derive(Debug)]
pub struct WaitableMut<T: Clone + Send> {
shared: Arc<WaitableShared<T>>,
}
#[derive(Debug)]
struct WaitableShared<T: Clone + Send> {
is_set: AtomicBool,
mutex: Mutex<SyncState<T>>,
condvar: Condvar,
}
#[derive(Debug)]
struct SyncState<T: Clone + Send> {
writers: usize,
value: Option<T>,
}
#[track_caller]
fn fail_if_poisoned<'a, T>(
result: Result<MutexGuard<'a, T>, PoisonError<MutexGuard<'a, T>>>,
) -> Result<MutexGuard<'a, T>, ShellError> {
match result {
Ok(guard) => Ok(guard),
Err(_) => Err(ShellError::NushellFailedHelp {
msg: "Waitable mutex poisoned".into(),
help: std::panic::Location::caller().to_string(),
}),
}
}
impl<T: Clone + Send> WaitableMut<T> {
/// Create a new empty `WaitableMut`. Call [`.reader()`](Self::reader) to get [`Waitable`].
pub fn new() -> WaitableMut<T> {
WaitableMut {
shared: Arc::new(WaitableShared {
is_set: AtomicBool::new(false),
mutex: Mutex::new(SyncState {
writers: 1,
value: None,
}),
condvar: Condvar::new(),
}),
}
}
pub fn reader(&self) -> Waitable<T> {
Waitable {
shared: self.shared.clone(),
}
}
/// Set the value and let waiting threads know.
#[track_caller]
pub fn set(&self, value: T) -> Result<(), ShellError> {
let mut sync_state = fail_if_poisoned(self.shared.mutex.lock())?;
self.shared.is_set.store(true, Ordering::SeqCst);
sync_state.value = Some(value);
self.shared.condvar.notify_all();
Ok(())
}
}
impl<T: Clone + Send> Default for WaitableMut<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Clone + Send> Clone for WaitableMut<T> {
fn clone(&self) -> Self {
let shared = self.shared.clone();
shared
.mutex
.lock()
.expect("failed to lock mutex to increment writers")
.writers += 1;
WaitableMut { shared }
}
}
impl<T: Clone + Send> Drop for WaitableMut<T> {
fn drop(&mut self) {
// Decrement writers...
if let Ok(mut sync_state) = self.shared.mutex.lock() {
sync_state.writers = sync_state
.writers
.checked_sub(1)
.expect("would decrement writers below zero");
}
// and notify waiting threads so they have a chance to see it.
self.shared.condvar.notify_all();
}
}
impl<T: Clone + Send> Waitable<T> {
/// Wait for a value to be available and then clone it.
///
/// Returns `Ok(None)` if there are no writers left that could possibly place a value.
#[track_caller]
pub fn get(&self) -> Result<Option<T>, ShellError> {
let sync_state = fail_if_poisoned(self.shared.mutex.lock())?;
if let Some(value) = sync_state.value.clone() {
Ok(Some(value))
} else if sync_state.writers == 0 {
// There can't possibly be a value written, so no point in waiting.
Ok(None)
} else {
let sync_state = fail_if_poisoned(
self.shared
.condvar
.wait_while(sync_state, |g| g.writers > 0 && g.value.is_none()),
)?;
Ok(sync_state.value.clone())
}
}
/// Clone the value if one is available, but don't wait if not.
#[track_caller]
pub fn try_get(&self) -> Result<Option<T>, ShellError> {
let sync_state = fail_if_poisoned(self.shared.mutex.lock())?;
Ok(sync_state.value.clone())
}
/// Returns true if value is available.
#[track_caller]
pub fn is_set(&self) -> bool {
self.shared.is_set.load(Ordering::SeqCst)
}
}
#[test]
fn set_from_other_thread() -> Result<(), ShellError> {
let waitable_mut = WaitableMut::new();
let waitable = waitable_mut.reader();
assert!(!waitable.is_set());
std::thread::spawn(move || {
waitable_mut.set(42).expect("error on set");
});
assert_eq!(Some(42), waitable.get()?);
assert_eq!(Some(42), waitable.try_get()?);
assert!(waitable.is_set());
Ok(())
}
#[test]
fn dont_deadlock_if_waiting_without_writer() {
use std::time::Duration;
let (tx, rx) = std::sync::mpsc::channel();
let writer = WaitableMut::<()>::new();
let waitable = writer.reader();
// Ensure there are no writers
drop(writer);
std::thread::spawn(move || {
let _ = tx.send(waitable.get());
});
let result = rx
.recv_timeout(Duration::from_secs(10))
.expect("timed out")
.expect("error");
assert!(result.is_none());
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/util/mod.rs | crates/nu-plugin-core/src/util/mod.rs | mod waitable;
mod with_custom_values_in;
pub use waitable::*;
pub use with_custom_values_in::with_custom_values_in;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/serializers/msgpack.rs | crates/nu-plugin-core/src/serializers/msgpack.rs | use std::io::ErrorKind;
use nu_plugin_protocol::{PluginInput, PluginOutput};
use nu_protocol::{
ShellError,
shell_error::{self, io::IoError},
};
use serde::Deserialize;
use crate::{Encoder, PluginEncoder};
/// A `PluginEncoder` that enables the plugin to communicate with Nushell with MsgPack
/// serialized data.
///
/// Each message is written as a MessagePack object. There is no message envelope or separator.
#[derive(Clone, Copy, Debug)]
pub struct MsgPackSerializer;
impl PluginEncoder for MsgPackSerializer {
fn name(&self) -> &str {
"msgpack"
}
}
impl Encoder<PluginInput> for MsgPackSerializer {
fn encode(
&self,
plugin_input: &PluginInput,
writer: &mut impl std::io::Write,
) -> Result<(), nu_protocol::ShellError> {
rmp_serde::encode::write_named(writer, plugin_input).map_err(rmp_encode_err)
}
fn decode(
&self,
reader: &mut impl std::io::BufRead,
) -> Result<Option<PluginInput>, ShellError> {
let mut de = rmp_serde::Deserializer::new(reader);
PluginInput::deserialize(&mut de)
.map(Some)
.or_else(rmp_decode_err)
}
}
impl Encoder<PluginOutput> for MsgPackSerializer {
fn encode(
&self,
plugin_output: &PluginOutput,
writer: &mut impl std::io::Write,
) -> Result<(), ShellError> {
rmp_serde::encode::write_named(writer, plugin_output).map_err(rmp_encode_err)
}
fn decode(
&self,
reader: &mut impl std::io::BufRead,
) -> Result<Option<PluginOutput>, ShellError> {
let mut de = rmp_serde::Deserializer::new(reader);
PluginOutput::deserialize(&mut de)
.map(Some)
.or_else(rmp_decode_err)
}
}
/// Handle a msgpack encode error
fn rmp_encode_err(err: rmp_serde::encode::Error) -> ShellError {
match err {
rmp_serde::encode::Error::InvalidValueWrite(_) => {
// I/O error
ShellError::Io(IoError::new_internal(
// TODO: get a better kind here
shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other),
"Could not encode with rmp",
nu_protocol::location!(),
))
}
_ => {
// Something else
ShellError::PluginFailedToEncode {
msg: err.to_string(),
}
}
}
}
/// Handle a msgpack decode error. Returns `Ok(None)` on eof
fn rmp_decode_err<T>(err: rmp_serde::decode::Error) -> Result<Option<T>, ShellError> {
match err {
rmp_serde::decode::Error::InvalidMarkerRead(err)
| rmp_serde::decode::Error::InvalidDataRead(err) => match err.kind() {
ErrorKind::UnexpectedEof => Ok(None),
_ => {
// I/O error
Err(ShellError::Io(IoError::new_internal(
// TODO: get a better kind here
shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other),
"Could not decode with rmp",
nu_protocol::location!(),
)))
}
},
_ => {
// Something else
Err(ShellError::PluginFailedToDecode {
msg: err.to_string(),
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
crate::serializers::tests::generate_tests!(MsgPackSerializer {});
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/serializers/tests.rs | crates/nu-plugin-core/src/serializers/tests.rs | macro_rules! generate_tests {
($encoder:expr) => {
use nu_plugin_protocol::{
CallInfo, CustomValueOp, EvaluatedCall, PipelineDataHeader, PluginCall,
PluginCallResponse, PluginCustomValue, PluginInput, PluginOption, PluginOutput,
StreamData,
};
use nu_protocol::{
LabeledError, PipelineMetadata, PluginSignature, Signature, Span, Spanned, SyntaxShape,
Value,
};
#[test]
fn decode_eof() {
let mut buffer: &[u8] = &[];
let encoder = $encoder;
let result: Option<PluginInput> = encoder
.decode(&mut buffer)
.expect("eof should not result in an error");
assert!(result.is_none(), "decode result: {result:?}");
let result: Option<PluginOutput> = encoder
.decode(&mut buffer)
.expect("eof should not result in an error");
assert!(result.is_none(), "decode result: {result:?}");
}
#[test]
fn decode_io_error() {
struct ErrorProducer;
impl std::io::Read for ErrorProducer {
fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::Error::from(std::io::ErrorKind::ConnectionReset))
}
}
let encoder = $encoder;
let mut buffered = std::io::BufReader::new(ErrorProducer);
match Encoder::<PluginInput>::decode(&encoder, &mut buffered) {
Ok(_) => panic!("decode: i/o error was not passed through"),
Err(ShellError::Io(_)) => (), // okay
Err(other) => panic!(
"decode: got other error, should have been a \
ShellError::Io: {other:?}"
),
}
match Encoder::<PluginOutput>::decode(&encoder, &mut buffered) {
Ok(_) => panic!("decode: i/o error was not passed through"),
Err(ShellError::Io(_)) => (), // okay
Err(other) => panic!(
"decode: got other error, should have been a \
ShellError::Io: {other:?}"
),
}
}
#[test]
fn decode_gibberish() {
// just a sequence of bytes that shouldn't be valid in anything we use
let gibberish: &[u8] = &[
0, 80, 74, 85, 117, 122, 86, 100, 74, 115, 20, 104, 55, 98, 67, 203, 83, 85, 77,
112, 74, 79, 254, 71, 80,
];
let encoder = $encoder;
let mut buffered = std::io::BufReader::new(&gibberish[..]);
match Encoder::<PluginInput>::decode(&encoder, &mut buffered) {
Ok(value) => panic!("decode: parsed successfully => {value:?}"),
Err(ShellError::PluginFailedToDecode { .. }) => (), // okay
Err(other) => panic!(
"decode: got other error, should have been a \
ShellError::PluginFailedToDecode: {other:?}"
),
}
let mut buffered = std::io::BufReader::new(&gibberish[..]);
match Encoder::<PluginOutput>::decode(&encoder, &mut buffered) {
Ok(value) => panic!("decode: parsed successfully => {value:?}"),
Err(ShellError::PluginFailedToDecode { .. }) => (), // okay
Err(other) => panic!(
"decode: got other error, should have been a \
ShellError::PluginFailedToDecode: {other:?}"
),
}
}
#[test]
fn call_round_trip_signature() {
let plugin_call = PluginCall::Signature;
let plugin_input = PluginInput::Call(0, plugin_call);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&plugin_input, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginInput::Call(0, PluginCall::Signature) => {}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn call_round_trip_run() {
let name = "test".to_string();
let input = Value::bool(false, Span::new(1, 20));
let call = EvaluatedCall {
head: Span::new(0, 10),
positional: vec![
Value::float(1.0, Span::new(0, 10)),
Value::string("something", Span::new(0, 10)),
],
named: vec![(
Spanned {
item: "name".to_string(),
span: Span::new(0, 10),
},
Some(Value::float(1.0, Span::new(0, 10))),
)],
};
let metadata = Some(PipelineMetadata {
content_type: Some("foobar".into()),
..Default::default()
});
let plugin_call = PluginCall::Run(CallInfo {
name: name.clone(),
call: call.clone(),
input: PipelineDataHeader::Value(input.clone(), metadata.clone()),
});
let plugin_input = PluginInput::Call(1, plugin_call);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&plugin_input, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginInput::Call(1, PluginCall::Run(call_info)) => {
assert_eq!(name, call_info.name);
assert_eq!(PipelineDataHeader::Value(input, metadata), call_info.input);
assert_eq!(call.head, call_info.call.head);
assert_eq!(call.positional.len(), call_info.call.positional.len());
call.positional
.iter()
.zip(call_info.call.positional.iter())
.for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));
call.named
.iter()
.zip(call_info.call.named.iter())
.for_each(|(lhs, rhs)| {
// Comparing the keys
assert_eq!(lhs.0.item, rhs.0.item);
match (&lhs.1, &rhs.1) {
(None, None) => {}
(Some(a), Some(b)) => assert_eq!(a, b),
_ => panic!("not matching values"),
}
});
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn call_round_trip_customvalueop() {
let data = vec![1, 2, 3, 4, 5, 6, 7];
let span = Span::new(0, 20);
let custom_value_op = PluginCall::CustomValueOp(
Spanned {
item: PluginCustomValue::new("Foo".into(), data.clone(), false),
span,
},
CustomValueOp::ToBaseValue,
);
let plugin_input = PluginInput::Call(2, custom_value_op);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&plugin_input, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginInput::Call(2, PluginCall::CustomValueOp(val, op)) => {
assert_eq!("Foo", val.item.name());
assert_eq!(data, val.item.data());
assert_eq!(span, val.span);
#[allow(unreachable_patterns)]
match op {
CustomValueOp::ToBaseValue => (),
_ => panic!("wrong op: {op:?}"),
}
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn response_round_trip_signature() {
let signature = PluginSignature::new(
Signature::build("nu-plugin")
.required("first", SyntaxShape::String, "first required")
.required("second", SyntaxShape::Int, "second required")
.required_named("first-named", SyntaxShape::String, "first named", Some('f'))
.required_named(
"second-named",
SyntaxShape::String,
"second named",
Some('s'),
)
.rest("remaining", SyntaxShape::Int, "remaining"),
vec![],
);
let response = PluginCallResponse::Signature(vec![signature.clone()]);
let output = PluginOutput::CallResponse(3, response);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&output, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginOutput::CallResponse(
3,
PluginCallResponse::Signature(returned_signature),
) => {
assert_eq!(returned_signature.len(), 1);
assert_eq!(signature.sig.name, returned_signature[0].sig.name);
assert_eq!(
signature.sig.description,
returned_signature[0].sig.description
);
assert_eq!(
signature.sig.extra_description,
returned_signature[0].sig.extra_description
);
assert_eq!(signature.sig.is_filter, returned_signature[0].sig.is_filter);
signature
.sig
.required_positional
.iter()
.zip(returned_signature[0].sig.required_positional.iter())
.for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));
signature
.sig
.optional_positional
.iter()
.zip(returned_signature[0].sig.optional_positional.iter())
.for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));
signature
.sig
.named
.iter()
.zip(returned_signature[0].sig.named.iter())
.for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));
assert_eq!(
signature.sig.rest_positional,
returned_signature[0].sig.rest_positional,
);
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn response_round_trip_value() {
let value = Value::int(10, Span::new(2, 30));
let response = PluginCallResponse::value(value.clone());
let output = PluginOutput::CallResponse(4, response);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&output, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginOutput::CallResponse(
4,
PluginCallResponse::PipelineData(PipelineDataHeader::Value(returned_value, _)),
) => {
assert_eq!(value, returned_value)
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn response_round_trip_plugin_custom_value() {
let name = "test";
let data = vec![1, 2, 3, 4, 5];
let span = Span::new(2, 30);
let value = Value::custom(
Box::new(PluginCustomValue::new(name.into(), data.clone(), true)),
span,
);
let response = PluginCallResponse::PipelineData(PipelineDataHeader::value(value));
let output = PluginOutput::CallResponse(5, response);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&output, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginOutput::CallResponse(
5,
PluginCallResponse::PipelineData(PipelineDataHeader::Value(returned_value, _)),
) => {
assert_eq!(span, returned_value.span());
if let Some(plugin_val) = returned_value
.as_custom_value()
.unwrap()
.as_any()
.downcast_ref::<PluginCustomValue>()
{
assert_eq!(name, plugin_val.name());
assert_eq!(data, plugin_val.data());
assert!(plugin_val.notify_on_drop());
} else {
panic!("returned CustomValue is not a PluginCustomValue");
}
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn response_round_trip_error() {
let inner: LabeledError = ShellError::Io(IoError::new(
shell_error::io::ErrorKind::from_std(std::io::ErrorKind::NotFound),
Span::test_data(),
None,
))
.into();
let error: ShellError = LabeledError::new("label")
.with_code("test::error")
.with_url("https://example.org/test/error")
.with_help("some help")
.with_label("msg", Span::new(2, 30))
.with_inner(inner)
.into();
let response = PluginCallResponse::Error(error.clone());
let output = PluginOutput::CallResponse(6, response);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&output, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginOutput::CallResponse(6, PluginCallResponse::Error(msg)) => {
assert_eq!(error, msg)
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn response_round_trip_error_none() {
let error: ShellError = LabeledError::new("error").into();
let response = PluginCallResponse::Error(error.clone());
let output = PluginOutput::CallResponse(7, response);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&output, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginOutput::CallResponse(7, PluginCallResponse::Error(msg)) => {
assert_eq!(error, msg)
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn input_round_trip_stream_data_list() {
let span = Span::new(12, 30);
let item = Value::int(1, span);
let stream_data = StreamData::List(item.clone());
let plugin_input = PluginInput::Data(0, stream_data);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&plugin_input, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginInput::Data(id, StreamData::List(list_data)) => {
assert_eq!(0, id);
assert_eq!(item, list_data);
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn input_round_trip_stream_data_raw() {
let data = b"Hello world";
let stream_data = StreamData::Raw(Ok(data.to_vec()));
let plugin_input = PluginInput::Data(1, stream_data);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&plugin_input, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginInput::Data(id, StreamData::Raw(bytes)) => {
assert_eq!(1, id);
match bytes {
Ok(bytes) => assert_eq!(data, &bytes[..]),
Err(err) => panic!("decoded into error variant: {err:?}"),
}
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn output_round_trip_stream_data_list() {
let span = Span::new(12, 30);
let item = Value::int(1, span);
let stream_data = StreamData::List(item.clone());
let plugin_output = PluginOutput::Data(4, stream_data);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&plugin_output, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginOutput::Data(id, StreamData::List(list_data)) => {
assert_eq!(4, id);
assert_eq!(item, list_data);
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn output_round_trip_stream_data_raw() {
let data = b"Hello world";
let stream_data = StreamData::Raw(Ok(data.to_vec()));
let plugin_output = PluginOutput::Data(5, stream_data);
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&plugin_output, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginOutput::Data(id, StreamData::Raw(bytes)) => {
assert_eq!(5, id);
match bytes {
Ok(bytes) => assert_eq!(data, &bytes[..]),
Err(err) => panic!("decoded into error variant: {err:?}"),
}
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
#[test]
fn output_round_trip_option() {
let plugin_output = PluginOutput::Option(PluginOption::GcDisabled(true));
let encoder = $encoder;
let mut buffer: Vec<u8> = Vec::new();
encoder
.encode(&plugin_output, &mut buffer)
.expect("unable to serialize message");
let returned = encoder
.decode(&mut buffer.as_slice())
.expect("unable to deserialize message")
.expect("eof");
match returned {
PluginOutput::Option(PluginOption::GcDisabled(disabled)) => {
assert!(disabled);
}
_ => panic!("decoded into wrong value: {returned:?}"),
}
}
};
}
pub(crate) use generate_tests;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/serializers/json.rs | crates/nu-plugin-core/src/serializers/json.rs | use nu_plugin_protocol::{PluginInput, PluginOutput};
use nu_protocol::{
ShellError, location,
shell_error::{self, io::IoError},
};
use serde::Deserialize;
use crate::{Encoder, PluginEncoder};
/// A `PluginEncoder` that enables the plugin to communicate with Nushell with JSON
/// serialized data.
///
/// Each message in the stream is followed by a newline when serializing, but is not required for
/// deserialization. The output is not pretty printed and each object does not contain newlines.
/// If it is more convenient, a plugin may choose to separate messages by newline.
#[derive(Clone, Copy, Debug)]
pub struct JsonSerializer;
impl PluginEncoder for JsonSerializer {
fn name(&self) -> &str {
"json"
}
}
impl Encoder<PluginInput> for JsonSerializer {
fn encode(
&self,
plugin_input: &PluginInput,
writer: &mut impl std::io::Write,
) -> Result<(), nu_protocol::ShellError> {
serde_json::to_writer(&mut *writer, plugin_input).map_err(json_encode_err)?;
writer.write_all(b"\n").map_err(|err| {
ShellError::Io(IoError::new_internal(
err,
"Failed to write final line break",
location!(),
))
})
}
fn decode(
&self,
reader: &mut impl std::io::BufRead,
) -> Result<Option<PluginInput>, nu_protocol::ShellError> {
let mut de = serde_json::Deserializer::from_reader(reader);
PluginInput::deserialize(&mut de)
.map(Some)
.or_else(json_decode_err)
}
}
impl Encoder<PluginOutput> for JsonSerializer {
fn encode(
&self,
plugin_output: &PluginOutput,
writer: &mut impl std::io::Write,
) -> Result<(), ShellError> {
serde_json::to_writer(&mut *writer, plugin_output).map_err(json_encode_err)?;
writer.write_all(b"\n").map_err(|err| {
ShellError::Io(IoError::new_internal(
err,
"JsonSerializer could not encode linebreak",
nu_protocol::location!(),
))
})
}
fn decode(
&self,
reader: &mut impl std::io::BufRead,
) -> Result<Option<PluginOutput>, ShellError> {
let mut de = serde_json::Deserializer::from_reader(reader);
PluginOutput::deserialize(&mut de)
.map(Some)
.or_else(json_decode_err)
}
}
/// Handle a `serde_json` encode error.
fn json_encode_err(err: serde_json::Error) -> ShellError {
if err.is_io() {
ShellError::Io(IoError::new_internal(
shell_error::io::ErrorKind::from_std(err.io_error_kind().expect("is io")),
"Could not encode with json",
nu_protocol::location!(),
))
} else {
ShellError::PluginFailedToEncode {
msg: err.to_string(),
}
}
}
/// Handle a `serde_json` decode error. Returns `Ok(None)` on eof.
fn json_decode_err<T>(err: serde_json::Error) -> Result<Option<T>, ShellError> {
if err.is_eof() {
Ok(None)
} else if err.is_io() {
Err(ShellError::Io(IoError::new_internal(
shell_error::io::ErrorKind::from_std(err.io_error_kind().expect("is io")),
"Could not decode with json",
nu_protocol::location!(),
)))
} else {
Err(ShellError::PluginFailedToDecode {
msg: err.to_string(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
crate::serializers::tests::generate_tests!(JsonSerializer {});
#[test]
fn json_ends_in_newline() {
let mut out = vec![];
JsonSerializer {}
.encode(&PluginInput::Call(0, PluginCall::Signature), &mut out)
.expect("serialization error");
let string = std::str::from_utf8(&out).expect("utf-8 error");
assert!(
string.ends_with('\n'),
"doesn't end with newline: {string:?}"
);
}
#[test]
fn json_has_no_other_newlines() {
let mut out = vec![];
// use something deeply nested, to try to trigger any pretty printing
let output = PluginOutput::Data(
0,
StreamData::List(Value::test_list(vec![
Value::test_int(4),
// in case escaping failed
Value::test_string("newline\ncontaining\nstring"),
])),
);
JsonSerializer {}
.encode(&output, &mut out)
.expect("serialization error");
let string = std::str::from_utf8(&out).expect("utf-8 error");
assert_eq!(1, string.chars().filter(|ch| *ch == '\n').count());
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/serializers/mod.rs | crates/nu-plugin-core/src/serializers/mod.rs | use nu_plugin_protocol::{PluginInput, PluginOutput};
use nu_protocol::ShellError;
pub mod json;
pub mod msgpack;
#[cfg(test)]
mod tests;
/// Encoder for a specific message type. Usually implemented on [`PluginInput`]
/// and [`PluginOutput`].
pub trait Encoder<T>: Clone + Send + Sync {
/// Serialize a value in the [`PluginEncoder`]s format
///
/// Returns [`ShellError::Io`] if there was a problem writing, or
/// [`ShellError::PluginFailedToEncode`] for a serialization error.
fn encode(&self, data: &T, writer: &mut impl std::io::Write) -> Result<(), ShellError>;
/// Deserialize a value from the [`PluginEncoder`]'s format
///
/// Returns `None` if there is no more output to receive.
///
/// Returns [`ShellError::Io`] if there was a problem reading, or
/// [`ShellError::PluginFailedToDecode`] for a deserialization error.
fn decode(&self, reader: &mut impl std::io::BufRead) -> Result<Option<T>, ShellError>;
}
/// Encoding scheme that defines a plugin's communication protocol with Nu
pub trait PluginEncoder: Encoder<PluginInput> + Encoder<PluginOutput> {
/// The name of the encoder (e.g., `json`)
fn name(&self) -> &str;
}
/// Enum that supports all of the plugin serialization formats.
#[derive(Clone, Copy, Debug)]
pub enum EncodingType {
Json(json::JsonSerializer),
MsgPack(msgpack::MsgPackSerializer),
}
impl EncodingType {
/// Determine the plugin encoding type from the provided byte string (either `b"json"` or
/// `b"msgpack"`).
pub fn try_from_bytes(bytes: &[u8]) -> Option<Self> {
match bytes {
b"json" => Some(Self::Json(json::JsonSerializer {})),
b"msgpack" => Some(Self::MsgPack(msgpack::MsgPackSerializer {})),
_ => None,
}
}
}
impl<T> Encoder<T> for EncodingType
where
json::JsonSerializer: Encoder<T>,
msgpack::MsgPackSerializer: Encoder<T>,
{
fn encode(&self, data: &T, writer: &mut impl std::io::Write) -> Result<(), ShellError> {
match self {
EncodingType::Json(encoder) => encoder.encode(data, writer),
EncodingType::MsgPack(encoder) => encoder.encode(data, writer),
}
}
fn decode(&self, reader: &mut impl std::io::BufRead) -> Result<Option<T>, ShellError> {
match self {
EncodingType::Json(encoder) => encoder.decode(reader),
EncodingType::MsgPack(encoder) => encoder.decode(reader),
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/interface/tests.rs | crates/nu-plugin-core/src/interface/tests.rs | use super::{
Interface, InterfaceManager, PluginRead, PluginWrite,
stream::{StreamManager, StreamManagerHandle},
test_util::TestCase,
};
use nu_plugin_protocol::{
ByteStreamInfo, ListStreamInfo, PipelineDataHeader, PluginInput, PluginOutput, StreamData,
StreamMessage,
};
use nu_protocol::{
ByteStream, ByteStreamSource, ByteStreamType, DataSource, ListStream, PipelineData,
PipelineMetadata, ShellError, Signals, Span, Value, engine::Sequence, shell_error::io::IoError,
};
use std::{path::Path, sync::Arc};
fn test_metadata() -> PipelineMetadata {
PipelineMetadata {
data_source: DataSource::FilePath("/test/path".into()),
..Default::default()
}
}
#[derive(Debug)]
struct TestInterfaceManager {
stream_manager: StreamManager,
test: TestCase<PluginInput, PluginOutput>,
seq: Arc<Sequence>,
}
#[derive(Debug, Clone)]
struct TestInterface {
stream_manager_handle: StreamManagerHandle,
test: TestCase<PluginInput, PluginOutput>,
seq: Arc<Sequence>,
}
impl TestInterfaceManager {
fn new(test: &TestCase<PluginInput, PluginOutput>) -> TestInterfaceManager {
TestInterfaceManager {
stream_manager: StreamManager::new(),
test: test.clone(),
seq: Arc::new(Sequence::default()),
}
}
fn consume_all(&mut self) -> Result<(), ShellError> {
while let Some(msg) = self.test.read()? {
self.consume(msg)?;
}
Ok(())
}
}
impl InterfaceManager for TestInterfaceManager {
type Interface = TestInterface;
type Input = PluginInput;
fn get_interface(&self) -> Self::Interface {
TestInterface {
stream_manager_handle: self.stream_manager.get_handle(),
test: self.test.clone(),
seq: self.seq.clone(),
}
}
fn consume(&mut self, input: Self::Input) -> Result<(), ShellError> {
match input {
PluginInput::Data(..)
| PluginInput::End(..)
| PluginInput::Drop(..)
| PluginInput::Ack(..) => self.consume_stream_message(
input
.try_into()
.expect("failed to convert message to StreamMessage"),
),
_ => unimplemented!(),
}
}
fn stream_manager(&self) -> &StreamManager {
&self.stream_manager
}
fn prepare_pipeline_data(&self, data: PipelineData) -> Result<PipelineData, ShellError> {
Ok(data.set_metadata(Some(test_metadata())))
}
}
impl Interface for TestInterface {
type Output = PluginOutput;
type DataContext = ();
fn write(&self, output: Self::Output) -> Result<(), ShellError> {
self.test.write(&output)
}
fn flush(&self) -> Result<(), ShellError> {
Ok(())
}
fn stream_id_sequence(&self) -> &Sequence {
&self.seq
}
fn stream_manager_handle(&self) -> &StreamManagerHandle {
&self.stream_manager_handle
}
fn prepare_pipeline_data(
&self,
data: PipelineData,
_context: &(),
) -> Result<PipelineData, ShellError> {
// Add an arbitrary check to the data to verify this is being called
match data {
PipelineData::Value(Value::Binary { .. }, None) => Err(ShellError::NushellFailed {
msg: "TEST can't send binary".into(),
}),
_ => Ok(data),
}
}
}
#[test]
fn read_pipeline_data_empty() -> Result<(), ShellError> {
let manager = TestInterfaceManager::new(&TestCase::new());
let header = PipelineDataHeader::Empty;
assert!(matches!(
manager.read_pipeline_data(header, &Signals::empty())?,
PipelineData::Empty
));
Ok(())
}
#[test]
fn read_pipeline_data_value() -> Result<(), ShellError> {
let manager = TestInterfaceManager::new(&TestCase::new());
let value = Value::test_int(4);
let metadata = Some(PipelineMetadata {
data_source: DataSource::FilePath("/test/path".into()),
..Default::default()
});
let header = PipelineDataHeader::Value(value.clone(), metadata.clone());
match manager.read_pipeline_data(header, &Signals::empty())? {
PipelineData::Value(read_value, read_metadata) => {
assert_eq!(value, read_value);
assert_eq!(metadata, read_metadata);
}
PipelineData::ListStream(..) => panic!("unexpected ListStream"),
PipelineData::ByteStream(..) => panic!("unexpected ByteStream"),
PipelineData::Empty => panic!("unexpected Empty"),
}
Ok(())
}
#[test]
fn read_pipeline_data_list_stream() -> Result<(), ShellError> {
let test = TestCase::new();
let mut manager = TestInterfaceManager::new(&test);
let data = (0..100).map(Value::test_int).collect::<Vec<_>>();
for value in &data {
test.add(StreamMessage::Data(7, value.clone().into()));
}
test.add(StreamMessage::End(7));
let metadata = Some(PipelineMetadata {
content_type: Some("foobar".into()),
..Default::default()
});
let header = PipelineDataHeader::ListStream(ListStreamInfo {
id: 7,
span: Span::test_data(),
metadata,
});
let pipe = manager.read_pipeline_data(header, &Signals::empty())?;
assert!(
matches!(pipe, PipelineData::ListStream(..)),
"unexpected PipelineData: {pipe:?}"
);
// need to consume input
manager.consume_all()?;
let mut count = 0;
for (expected, read) in data.into_iter().zip(pipe) {
assert_eq!(expected, read);
count += 1;
}
assert_eq!(100, count);
assert!(test.has_unconsumed_write());
Ok(())
}
#[test]
fn read_pipeline_data_byte_stream() -> Result<(), ShellError> {
let test = TestCase::new();
let mut manager = TestInterfaceManager::new(&test);
let iterations = 100;
let out_pattern = b"hello".to_vec();
for _ in 0..iterations {
test.add(StreamMessage::Data(
12,
StreamData::Raw(Ok(out_pattern.clone())),
));
}
test.add(StreamMessage::End(12));
let test_span = Span::new(10, 13);
let metadata = Some(PipelineMetadata {
content_type: Some("foobar".into()),
..Default::default()
});
let header = PipelineDataHeader::ByteStream(ByteStreamInfo {
id: 12,
span: test_span,
type_: ByteStreamType::Unknown,
metadata,
});
let pipe = manager.read_pipeline_data(header, &Signals::empty())?;
// need to consume input
manager.consume_all()?;
match pipe {
PipelineData::ByteStream(stream, metadata) => {
assert_eq!(test_span, stream.span());
assert!(
metadata.is_some(),
"expected metadata to be Some due to prepare_pipeline_data()"
);
match stream.into_source() {
ByteStreamSource::Read(mut read) => {
let mut buf = Vec::new();
read.read_to_end(&mut buf)
.map_err(|err| IoError::new(err, test_span, None))?;
let iter = buf.chunks_exact(out_pattern.len());
assert_eq!(iter.len(), iterations);
for chunk in iter {
assert_eq!(out_pattern, chunk)
}
}
ByteStreamSource::File(..) => panic!("unexpected byte stream source: file"),
ByteStreamSource::Child(..) => {
panic!("unexpected byte stream source: child")
}
}
}
_ => panic!("unexpected PipelineData: {pipe:?}"),
}
// Don't need to check exactly what was written, just be sure that there is some output
assert!(test.has_unconsumed_write());
Ok(())
}
#[test]
fn read_pipeline_data_prepared_properly() -> Result<(), ShellError> {
let manager = TestInterfaceManager::new(&TestCase::new());
let metadata = Some(PipelineMetadata {
content_type: Some("foobar".into()),
..Default::default()
});
let header = PipelineDataHeader::ListStream(ListStreamInfo {
id: 0,
span: Span::test_data(),
metadata,
});
match manager.read_pipeline_data(header, &Signals::empty())? {
PipelineData::ListStream(_, meta) => match meta {
Some(PipelineMetadata { data_source, .. }) => match data_source {
DataSource::FilePath(path) => {
assert_eq!(Path::new("/test/path"), path);
Ok(())
}
_ => panic!("wrong metadata: {data_source:?}"),
},
None => panic!("metadata not set"),
},
_ => panic!("Unexpected PipelineData, should have been ListStream"),
}
}
#[test]
fn write_pipeline_data_empty() -> Result<(), ShellError> {
let test = TestCase::new();
let manager = TestInterfaceManager::new(&test);
let interface = manager.get_interface();
let (header, writer) = interface.init_write_pipeline_data(PipelineData::empty(), &())?;
assert!(matches!(header, PipelineDataHeader::Empty));
writer.write()?;
assert!(
!test.has_unconsumed_write(),
"Empty shouldn't write any stream messages, test: {test:#?}"
);
Ok(())
}
#[test]
fn write_pipeline_data_value() -> Result<(), ShellError> {
let test = TestCase::new();
let manager = TestInterfaceManager::new(&test);
let interface = manager.get_interface();
let value = Value::test_int(7);
let (header, writer) =
interface.init_write_pipeline_data(PipelineData::value(value.clone(), None), &())?;
match header {
PipelineDataHeader::Value(read_value, _) => assert_eq!(value, read_value),
_ => panic!("unexpected header: {header:?}"),
}
writer.write()?;
assert!(
!test.has_unconsumed_write(),
"Value shouldn't write any stream messages, test: {test:#?}"
);
Ok(())
}
#[test]
fn write_pipeline_data_prepared_properly() {
let manager = TestInterfaceManager::new(&TestCase::new());
let interface = manager.get_interface();
// Sending a binary should be an error in our test scenario
let value = Value::test_binary(vec![7, 8]);
match interface.init_write_pipeline_data(PipelineData::value(value, None), &()) {
Ok(_) => panic!("prepare_pipeline_data was not called"),
Err(err) => {
assert_eq!(
ShellError::NushellFailed {
msg: "TEST can't send binary".into()
}
.to_string(),
err.to_string()
);
}
}
}
#[test]
fn write_pipeline_data_list_stream() -> Result<(), ShellError> {
let test = TestCase::new();
let manager = TestInterfaceManager::new(&test);
let interface = manager.get_interface();
let values = vec![
Value::test_int(40),
Value::test_bool(false),
Value::test_string("this is a test"),
];
// Set up pipeline data for a list stream
let pipe = PipelineData::list_stream(
ListStream::new(
values.clone().into_iter(),
Span::test_data(),
Signals::empty(),
),
None,
);
let (header, writer) = interface.init_write_pipeline_data(pipe, &())?;
let info = match header {
PipelineDataHeader::ListStream(info) => info,
_ => panic!("unexpected header: {header:?}"),
};
writer.write()?;
// Now make sure the stream messages have been written
for value in values {
match test.next_written().expect("unexpected end of stream") {
PluginOutput::Data(id, data) => {
assert_eq!(info.id, id, "Data id");
match data {
StreamData::List(read_value) => assert_eq!(value, read_value, "Data value"),
_ => panic!("unexpected Data: {data:?}"),
}
}
other => panic!("unexpected output: {other:?}"),
}
}
match test.next_written().expect("unexpected end of stream") {
PluginOutput::End(id) => {
assert_eq!(info.id, id, "End id");
}
other => panic!("unexpected output: {other:?}"),
}
assert!(!test.has_unconsumed_write());
Ok(())
}
#[test]
fn write_pipeline_data_byte_stream() -> Result<(), ShellError> {
let test = TestCase::new();
let manager = TestInterfaceManager::new(&test);
let interface = manager.get_interface();
let expected = "hello\nworld\nthese are tests";
let span = Span::new(400, 500);
// Set up pipeline data for a byte stream
let data = PipelineData::byte_stream(
ByteStream::read(
std::io::Cursor::new(expected),
span,
Signals::empty(),
ByteStreamType::Unknown,
),
None,
);
let (header, writer) = interface.init_write_pipeline_data(data, &())?;
let info = match header {
PipelineDataHeader::ByteStream(info) => info,
_ => panic!("unexpected header: {header:?}"),
};
writer.write()?;
assert_eq!(span, info.span);
// Now make sure the stream messages have been written
let mut actual = Vec::new();
let mut ended = false;
for msg in test.written() {
match msg {
PluginOutput::Data(id, data) => {
if id == info.id {
let data: Result<Vec<u8>, ShellError> =
data.try_into().expect("wrong data in stream");
let data = data.expect("unexpected error in stream");
actual.extend(data);
} else {
panic!("unrecognized stream id: {id}");
}
}
PluginOutput::End(id) => {
if id == info.id {
ended = true;
} else {
panic!("unrecognized stream id: {id}");
}
}
other => panic!("unexpected output: {other:?}"),
}
}
assert_eq!(expected.as_bytes(), actual);
assert!(ended, "stream did not End");
Ok(())
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/interface/test_util.rs | crates/nu-plugin-core/src/interface/test_util.rs | use nu_protocol::ShellError;
use std::{
collections::VecDeque,
sync::{Arc, Mutex},
};
use crate::{PluginRead, PluginWrite};
const FAILED: &str = "failed to lock TestCase";
/// Mock read/write helper for the engine and plugin interfaces.
#[derive(Debug, Clone)]
pub struct TestCase<I, O> {
r#in: Arc<Mutex<TestData<I>>>,
out: Arc<Mutex<TestData<O>>>,
}
#[derive(Debug)]
pub struct TestData<T> {
data: VecDeque<T>,
error: Option<ShellError>,
flushed: bool,
}
impl<T> Default for TestData<T> {
fn default() -> Self {
TestData {
data: VecDeque::new(),
error: None,
flushed: false,
}
}
}
impl<I, O> PluginRead<I> for TestCase<I, O> {
fn read(&mut self) -> Result<Option<I>, ShellError> {
let mut lock = self.r#in.lock().expect(FAILED);
if let Some(err) = lock.error.take() {
Err(err)
} else {
Ok(lock.data.pop_front())
}
}
}
impl<I, O> PluginWrite<O> for TestCase<I, O>
where
I: Send + Clone,
O: Send + Clone,
{
fn write(&self, data: &O) -> Result<(), ShellError> {
let mut lock = self.out.lock().expect(FAILED);
lock.flushed = false;
if let Some(err) = lock.error.take() {
Err(err)
} else {
lock.data.push_back(data.clone());
Ok(())
}
}
fn flush(&self) -> Result<(), ShellError> {
let mut lock = self.out.lock().expect(FAILED);
lock.flushed = true;
Ok(())
}
}
#[allow(dead_code)]
impl<I, O> TestCase<I, O> {
pub fn new() -> TestCase<I, O> {
TestCase {
r#in: Default::default(),
out: Default::default(),
}
}
/// Clear the read buffer.
pub fn clear(&self) {
self.r#in.lock().expect(FAILED).data.truncate(0);
}
/// Add input that will be read by the interface.
pub fn add(&self, input: impl Into<I>) {
self.r#in.lock().expect(FAILED).data.push_back(input.into());
}
/// Add multiple inputs that will be read by the interface.
pub fn extend(&self, inputs: impl IntoIterator<Item = I>) {
self.r#in.lock().expect(FAILED).data.extend(inputs);
}
/// Return an error from the next read operation.
pub fn set_read_error(&self, err: ShellError) {
self.r#in.lock().expect(FAILED).error = Some(err);
}
/// Return an error from the next write operation.
pub fn set_write_error(&self, err: ShellError) {
self.out.lock().expect(FAILED).error = Some(err);
}
/// Get the next output that was written.
pub fn next_written(&self) -> Option<O> {
self.out.lock().expect(FAILED).data.pop_front()
}
/// Iterator over written data.
pub fn written(&self) -> impl Iterator<Item = O> + '_ {
std::iter::from_fn(|| self.next_written())
}
/// Returns true if the writer was flushed after the last write operation.
pub fn was_flushed(&self) -> bool {
self.out.lock().expect(FAILED).flushed
}
/// Returns true if the reader has unconsumed reads.
pub fn has_unconsumed_read(&self) -> bool {
!self.r#in.lock().expect(FAILED).data.is_empty()
}
/// Returns true if the writer has unconsumed writes.
pub fn has_unconsumed_write(&self) -> bool {
!self.out.lock().expect(FAILED).data.is_empty()
}
}
impl<I, O> Default for TestCase<I, O> {
fn default() -> Self {
Self::new()
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/interface/mod.rs | crates/nu-plugin-core/src/interface/mod.rs | //! Implements the stream multiplexing interface for both the plugin side and the engine side.
use nu_plugin_protocol::{ByteStreamInfo, ListStreamInfo, PipelineDataHeader, StreamMessage};
use nu_protocol::{
ByteStream, ListStream, PipelineData, Reader, ShellError, Signals, engine::Sequence,
shell_error::io::IoError,
};
use std::{
io::{Read, Write},
sync::Mutex,
thread,
};
pub mod stream;
use crate::Encoder;
use self::stream::{StreamManager, StreamManagerHandle, StreamWriter, WriteStreamMessage};
pub mod test_util;
#[cfg(test)]
mod tests;
/// The maximum number of list stream values to send without acknowledgement. This should be tuned
/// with consideration for memory usage.
const LIST_STREAM_HIGH_PRESSURE: i32 = 100;
/// The maximum number of raw stream buffers to send without acknowledgement. This should be tuned
/// with consideration for memory usage.
const RAW_STREAM_HIGH_PRESSURE: i32 = 50;
/// Read input/output from the stream.
pub trait PluginRead<T> {
/// Returns `Ok(None)` on end of stream.
fn read(&mut self) -> Result<Option<T>, ShellError>;
}
impl<R, E, T> PluginRead<T> for (R, E)
where
R: std::io::BufRead,
E: Encoder<T>,
{
fn read(&mut self) -> Result<Option<T>, ShellError> {
self.1.decode(&mut self.0)
}
}
impl<R, T> PluginRead<T> for &mut R
where
R: PluginRead<T>,
{
fn read(&mut self) -> Result<Option<T>, ShellError> {
(**self).read()
}
}
/// Write input/output to the stream.
///
/// The write should be atomic, without interference from other threads.
pub trait PluginWrite<T>: Send + Sync {
fn write(&self, data: &T) -> Result<(), ShellError>;
/// Flush any internal buffers, if applicable.
fn flush(&self) -> Result<(), ShellError>;
/// True if this output is stdout, so that plugins can avoid using stdout for their own purpose
fn is_stdout(&self) -> bool {
false
}
}
impl<E, T> PluginWrite<T> for (std::io::Stdout, E)
where
E: Encoder<T>,
{
fn write(&self, data: &T) -> Result<(), ShellError> {
let mut lock = self.0.lock();
self.1.encode(data, &mut lock)
}
fn flush(&self) -> Result<(), ShellError> {
self.0.lock().flush().map_err(|err| {
ShellError::Io(IoError::new_internal(
err,
"PluginWrite could not flush",
nu_protocol::location!(),
))
})
}
fn is_stdout(&self) -> bool {
true
}
}
impl<W, E, T> PluginWrite<T> for (Mutex<W>, E)
where
W: std::io::Write + Send,
E: Encoder<T>,
{
fn write(&self, data: &T) -> Result<(), ShellError> {
let mut lock = self.0.lock().map_err(|_| ShellError::NushellFailed {
msg: "writer mutex poisoned".into(),
})?;
self.1.encode(data, &mut *lock)
}
fn flush(&self) -> Result<(), ShellError> {
let mut lock = self.0.lock().map_err(|_| ShellError::NushellFailed {
msg: "writer mutex poisoned".into(),
})?;
lock.flush().map_err(|err| {
ShellError::Io(IoError::new_internal(
err,
"PluginWrite could not flush",
nu_protocol::location!(),
))
})
}
}
impl<W, T> PluginWrite<T> for &W
where
W: PluginWrite<T>,
{
fn write(&self, data: &T) -> Result<(), ShellError> {
(**self).write(data)
}
fn flush(&self) -> Result<(), ShellError> {
(**self).flush()
}
fn is_stdout(&self) -> bool {
(**self).is_stdout()
}
}
/// An interface manager handles I/O and state management for communication between a plugin and
/// the engine. See `PluginInterfaceManager` in `nu-plugin-engine` for communication from the engine
/// side to a plugin, or `EngineInterfaceManager` in `nu-plugin` for communication from the plugin
/// side to the engine.
///
/// There is typically one [`InterfaceManager`] consuming input from a background thread, and
/// managing shared state.
pub trait InterfaceManager {
/// The corresponding interface type.
type Interface: Interface + 'static;
/// The input message type.
type Input;
/// Make a new interface that communicates with this [`InterfaceManager`].
fn get_interface(&self) -> Self::Interface;
/// Consume an input message.
///
/// When implementing, call [`.consume_stream_message()`](Self::consume_stream_message) for any encapsulated
/// [`StreamMessage`]s received.
fn consume(&mut self, input: Self::Input) -> Result<(), ShellError>;
/// Get the [`StreamManager`] for handling operations related to stream messages.
fn stream_manager(&self) -> &StreamManager;
/// Prepare [`PipelineData`] after reading. This is called by `read_pipeline_data()` as
/// a hook so that values that need special handling can be taken care of.
fn prepare_pipeline_data(&self, data: PipelineData) -> Result<PipelineData, ShellError>;
/// Consume an input stream message.
///
/// This method is provided for implementors to use.
fn consume_stream_message(&mut self, message: StreamMessage) -> Result<(), ShellError> {
self.stream_manager().handle_message(message)
}
/// Generate `PipelineData` for reading a stream, given a [`PipelineDataHeader`] that was
/// received from the other side.
///
/// This method is provided for implementors to use.
fn read_pipeline_data(
&self,
header: PipelineDataHeader,
signals: &Signals,
) -> Result<PipelineData, ShellError> {
self.prepare_pipeline_data(match header {
PipelineDataHeader::Empty => PipelineData::empty(),
PipelineDataHeader::Value(value, metadata) => PipelineData::value(value, metadata),
PipelineDataHeader::ListStream(info) => {
let handle = self.stream_manager().get_handle();
let reader = handle.read_stream(info.id, self.get_interface())?;
let ls = ListStream::new(reader, info.span, signals.clone());
PipelineData::list_stream(ls, info.metadata)
}
PipelineDataHeader::ByteStream(info) => {
let handle = self.stream_manager().get_handle();
let reader = handle.read_stream(info.id, self.get_interface())?;
let bs =
ByteStream::from_result_iter(reader, info.span, signals.clone(), info.type_);
PipelineData::byte_stream(bs, info.metadata)
}
})
}
}
/// An interface provides an API for communicating with a plugin or the engine and facilitates
/// stream I/O. See `PluginInterface` in `nu-plugin-engine` for the API from the engine side to a
/// plugin, or `EngineInterface` in `nu-plugin` for the API from the plugin side to the engine.
///
/// There can be multiple copies of the interface managed by a single [`InterfaceManager`].
pub trait Interface: Clone + Send {
/// The output message type, which must be capable of encapsulating a [`StreamMessage`].
type Output: From<StreamMessage>;
/// Any context required to construct [`PipelineData`]. Can be `()` if not needed.
type DataContext;
/// Write an output message.
fn write(&self, output: Self::Output) -> Result<(), ShellError>;
/// Flush the output buffer, so messages are visible to the other side.
fn flush(&self) -> Result<(), ShellError>;
/// Get the sequence for generating new [`StreamId`](nu_plugin_protocol::StreamId)s.
fn stream_id_sequence(&self) -> &Sequence;
/// Get the [`StreamManagerHandle`] for doing stream operations.
fn stream_manager_handle(&self) -> &StreamManagerHandle;
/// Prepare [`PipelineData`] to be written. This is called by `init_write_pipeline_data()` as
/// a hook so that values that need special handling can be taken care of.
fn prepare_pipeline_data(
&self,
data: PipelineData,
context: &Self::DataContext,
) -> Result<PipelineData, ShellError>;
/// Initialize a write for [`PipelineData`]. This returns two parts: the header, which can be
/// embedded in the particular message that references the stream, and a writer, which will
/// write out all of the data in the pipeline when `.write()` is called.
///
/// Note that not all [`PipelineData`] starts a stream. You should call `write()` anyway, as
/// it will automatically handle this case.
///
/// This method is provided for implementors to use.
fn init_write_pipeline_data(
&self,
data: PipelineData,
context: &Self::DataContext,
) -> Result<(PipelineDataHeader, PipelineDataWriter<Self>), ShellError> {
// Allocate a stream id and a writer
let new_stream = |high_pressure_mark: i32| {
// Get a free stream id
let id = self.stream_id_sequence().next()?;
// Create the writer
let writer =
self.stream_manager_handle()
.write_stream(id, self.clone(), high_pressure_mark)?;
Ok::<_, ShellError>((id, writer))
};
match self.prepare_pipeline_data(data, context)? {
PipelineData::Value(value, metadata) => Ok((
PipelineDataHeader::Value(value, metadata),
PipelineDataWriter::None,
)),
PipelineData::Empty => Ok((PipelineDataHeader::Empty, PipelineDataWriter::None)),
PipelineData::ListStream(stream, metadata) => {
let (id, writer) = new_stream(LIST_STREAM_HIGH_PRESSURE)?;
Ok((
PipelineDataHeader::ListStream(ListStreamInfo {
id,
span: stream.span(),
metadata,
}),
PipelineDataWriter::ListStream(writer, stream),
))
}
PipelineData::ByteStream(stream, metadata) => {
let span = stream.span();
let type_ = stream.type_();
if let Some(reader) = stream.reader() {
let (id, writer) = new_stream(RAW_STREAM_HIGH_PRESSURE)?;
let header = PipelineDataHeader::ByteStream(ByteStreamInfo {
id,
span,
type_,
metadata,
});
Ok((header, PipelineDataWriter::ByteStream(writer, reader)))
} else {
Ok((PipelineDataHeader::Empty, PipelineDataWriter::None))
}
}
}
}
}
impl<T> WriteStreamMessage for T
where
T: Interface,
{
fn write_stream_message(&mut self, msg: StreamMessage) -> Result<(), ShellError> {
self.write(msg.into())
}
fn flush(&mut self) -> Result<(), ShellError> {
<Self as Interface>::flush(self)
}
}
/// Completes the write operation for a [`PipelineData`]. You must call
/// [`PipelineDataWriter::write()`] to write all of the data contained within the streams.
#[derive(Default)]
#[must_use]
pub enum PipelineDataWriter<W: WriteStreamMessage> {
#[default]
None,
ListStream(StreamWriter<W>, ListStream),
ByteStream(StreamWriter<W>, Reader),
}
impl<W> PipelineDataWriter<W>
where
W: WriteStreamMessage + Send + 'static,
{
/// Write all of the data in each of the streams. This method waits for completion.
pub fn write(self) -> Result<(), ShellError> {
match self {
// If no stream was contained in the PipelineData, do nothing.
PipelineDataWriter::None => Ok(()),
// Write a list stream.
PipelineDataWriter::ListStream(mut writer, stream) => {
writer.write_all(stream)?;
Ok(())
}
// Write a byte stream.
PipelineDataWriter::ByteStream(mut writer, mut reader) => {
let span = reader.span();
let buf = &mut [0; 8192];
writer.write_all(std::iter::from_fn(move || match reader.read(buf) {
Ok(0) => None,
Ok(len) => Some(Ok(buf[..len].to_vec())),
Err(err) => Some(Err(ShellError::from(IoError::new(err, span, None)))),
}))?;
Ok(())
}
}
}
/// Write all of the data in each of the streams. This method returns immediately; any necessary
/// write will happen in the background. If a thread was spawned, its handle is returned.
pub fn write_background(
self,
) -> Result<Option<thread::JoinHandle<Result<(), ShellError>>>, ShellError> {
match self {
PipelineDataWriter::None => Ok(None),
_ => Ok(Some(
thread::Builder::new()
.name("plugin stream background writer".into())
.spawn(move || {
let result = self.write();
if let Err(ref err) = result {
// Assume that the background thread error probably won't be handled and log it
// here just in case.
log::warn!("Error while writing pipeline in background: {err}");
}
result
})
.map_err(|err| {
IoError::new_internal(
err,
"Could not spawn plugin stream background writer",
nu_protocol::location!(),
)
})?,
)),
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/interface/stream/tests.rs | crates/nu-plugin-core/src/interface/stream/tests.rs | use std::{
sync::{
Arc,
atomic::{AtomicBool, Ordering::Relaxed},
mpsc,
},
time::{Duration, Instant},
};
use super::{StreamManager, StreamReader, StreamWriter, StreamWriterSignal, WriteStreamMessage};
use nu_plugin_protocol::{StreamData, StreamMessage};
use nu_protocol::{ShellError, Value};
// Should be long enough to definitely complete any quick operation, but not so long that tests are
// slow to complete. 10 ms is a pretty long time
const WAIT_DURATION: Duration = Duration::from_millis(10);
// Maximum time to wait for a condition to be true
const MAX_WAIT_DURATION: Duration = Duration::from_millis(500);
/// Wait for a condition to be true, or panic if the duration exceeds MAX_WAIT_DURATION
#[track_caller]
fn wait_for_condition(mut cond: impl FnMut() -> bool, message: &str) {
// Early check
if cond() {
return;
}
let start = Instant::now();
loop {
std::thread::sleep(Duration::from_millis(10));
if cond() {
return;
}
let elapsed = Instant::now().saturating_duration_since(start);
if elapsed > MAX_WAIT_DURATION {
panic!(
"{message}: Waited {:.2}sec, which is more than the maximum of {:.2}sec",
elapsed.as_secs_f64(),
MAX_WAIT_DURATION.as_secs_f64(),
);
}
}
}
#[derive(Debug, Clone, Default)]
struct TestSink(Vec<StreamMessage>);
impl WriteStreamMessage for TestSink {
fn write_stream_message(&mut self, msg: StreamMessage) -> Result<(), ShellError> {
self.0.push(msg);
Ok(())
}
fn flush(&mut self) -> Result<(), ShellError> {
Ok(())
}
}
impl WriteStreamMessage for mpsc::Sender<StreamMessage> {
fn write_stream_message(&mut self, msg: StreamMessage) -> Result<(), ShellError> {
self.send(msg).map_err(|err| ShellError::NushellFailed {
msg: err.to_string(),
})
}
fn flush(&mut self) -> Result<(), ShellError> {
Ok(())
}
}
#[test]
fn reader_recv_list_messages() -> Result<(), ShellError> {
let (tx, rx) = mpsc::channel();
let mut reader = StreamReader::new(0, rx, TestSink::default());
tx.send(Ok(Some(StreamData::List(Value::test_int(5)))))
.unwrap();
drop(tx);
assert_eq!(Some(Value::test_int(5)), reader.recv()?);
Ok(())
}
#[test]
fn list_reader_recv_wrong_type() -> Result<(), ShellError> {
let (tx, rx) = mpsc::channel();
let mut reader = StreamReader::<Value, _>::new(0, rx, TestSink::default());
tx.send(Ok(Some(StreamData::Raw(Ok(vec![10, 20])))))
.unwrap();
tx.send(Ok(Some(StreamData::List(Value::test_nothing()))))
.unwrap();
drop(tx);
reader.recv().expect_err("should be an error");
reader.recv().expect("should be able to recover");
Ok(())
}
#[test]
fn reader_recv_raw_messages() -> Result<(), ShellError> {
let (tx, rx) = mpsc::channel();
let mut reader =
StreamReader::<Result<Vec<u8>, ShellError>, _>::new(0, rx, TestSink::default());
tx.send(Ok(Some(StreamData::Raw(Ok(vec![10, 20])))))
.unwrap();
drop(tx);
assert_eq!(Some(vec![10, 20]), reader.recv()?.transpose()?);
Ok(())
}
#[test]
fn raw_reader_recv_wrong_type() -> Result<(), ShellError> {
let (tx, rx) = mpsc::channel();
let mut reader =
StreamReader::<Result<Vec<u8>, ShellError>, _>::new(0, rx, TestSink::default());
tx.send(Ok(Some(StreamData::List(Value::test_nothing()))))
.unwrap();
tx.send(Ok(Some(StreamData::Raw(Ok(vec![10, 20])))))
.unwrap();
drop(tx);
reader.recv().expect_err("should be an error");
reader.recv().expect("should be able to recover");
Ok(())
}
#[test]
fn reader_recv_acknowledge() -> Result<(), ShellError> {
let (tx, rx) = mpsc::channel();
let mut reader = StreamReader::<Value, _>::new(0, rx, TestSink::default());
tx.send(Ok(Some(StreamData::List(Value::test_int(5)))))
.unwrap();
tx.send(Ok(Some(StreamData::List(Value::test_int(6)))))
.unwrap();
drop(tx);
reader.recv()?;
reader.recv()?;
let wrote = &reader.writer.0;
assert!(wrote.len() >= 2);
assert!(
matches!(wrote[0], StreamMessage::Ack(0)),
"0 = {:?}",
wrote[0]
);
assert!(
matches!(wrote[1], StreamMessage::Ack(0)),
"1 = {:?}",
wrote[1]
);
Ok(())
}
#[test]
fn reader_recv_end_of_stream() -> Result<(), ShellError> {
let (tx, rx) = mpsc::channel();
let mut reader = StreamReader::<Value, _>::new(0, rx, TestSink::default());
tx.send(Ok(Some(StreamData::List(Value::test_int(5)))))
.unwrap();
tx.send(Ok(None)).unwrap();
drop(tx);
assert!(reader.recv()?.is_some(), "actual message");
assert!(reader.recv()?.is_none(), "on close");
assert!(reader.recv()?.is_none(), "after close");
Ok(())
}
#[test]
fn reader_iter_fuse_on_error() -> Result<(), ShellError> {
let (tx, rx) = mpsc::channel();
let mut reader = StreamReader::<Value, _>::new(0, rx, TestSink::default());
drop(tx); // should cause error, because we didn't explicitly signal the end
assert!(
reader.next().is_some_and(|e| e.is_error()),
"should be error the first time"
);
assert!(reader.next().is_none(), "should be closed the second time");
Ok(())
}
#[test]
fn reader_drop() {
let (_tx, rx) = mpsc::channel();
// Flag set if drop message is received.
struct Check(Arc<AtomicBool>);
impl WriteStreamMessage for Check {
fn write_stream_message(&mut self, msg: StreamMessage) -> Result<(), ShellError> {
assert!(matches!(msg, StreamMessage::Drop(1)), "got {msg:?}");
self.0.store(true, Relaxed);
Ok(())
}
fn flush(&mut self) -> Result<(), ShellError> {
Ok(())
}
}
let flag = Arc::new(AtomicBool::new(false));
let reader = StreamReader::<Value, _>::new(1, rx, Check(flag.clone()));
drop(reader);
assert!(flag.load(Relaxed));
}
#[test]
fn writer_write_all_stops_if_dropped() -> Result<(), ShellError> {
let signal = Arc::new(StreamWriterSignal::new(20));
let id = 1337;
let mut writer = StreamWriter::new(id, signal.clone(), TestSink::default());
// Simulate this by having it consume a stream that will actually do the drop halfway through
let iter = (0..5).map(Value::test_int).chain({
let mut n = 5;
std::iter::from_fn(move || {
// produces numbers 5..10, but drops for the first one
if n == 5 {
signal.set_dropped().unwrap();
}
if n < 10 {
let value = Value::test_int(n);
n += 1;
Some(value)
} else {
None
}
})
});
writer.write_all(iter)?;
assert!(writer.is_dropped()?);
let wrote = &writer.writer.0;
assert_eq!(5, wrote.len(), "length wrong: {wrote:?}");
for (n, message) in (0..5).zip(wrote) {
match message {
StreamMessage::Data(msg_id, StreamData::List(value)) => {
assert_eq!(id, *msg_id, "id");
assert_eq!(Value::test_int(n), *value, "value");
}
other => panic!("unexpected message: {other:?}"),
}
}
Ok(())
}
#[test]
fn writer_end() -> Result<(), ShellError> {
let signal = Arc::new(StreamWriterSignal::new(20));
let mut writer = StreamWriter::new(9001, signal.clone(), TestSink::default());
writer.end()?;
writer
.write(Value::test_int(2))
.expect_err("shouldn't be able to write after end");
writer.end().expect("end twice should be ok");
let wrote = &writer.writer.0;
assert!(
matches!(wrote.last(), Some(StreamMessage::End(9001))),
"didn't write end message: {wrote:?}"
);
Ok(())
}
#[test]
fn signal_set_dropped() -> Result<(), ShellError> {
let signal = StreamWriterSignal::new(4);
assert!(!signal.is_dropped()?);
signal.set_dropped()?;
assert!(signal.is_dropped()?);
Ok(())
}
#[test]
fn signal_notify_sent_false_if_unacknowledged() -> Result<(), ShellError> {
let signal = StreamWriterSignal::new(2);
assert!(signal.notify_sent()?);
for _ in 0..100 {
assert!(!signal.notify_sent()?);
}
Ok(())
}
#[test]
fn signal_notify_sent_never_false_if_flowing() -> Result<(), ShellError> {
let signal = StreamWriterSignal::new(1);
for _ in 0..100 {
signal.notify_acknowledged()?;
}
for _ in 0..100 {
assert!(signal.notify_sent()?);
}
Ok(())
}
#[test]
fn signal_wait_for_drain_blocks_on_unacknowledged() -> Result<(), ShellError> {
let signal = StreamWriterSignal::new(50);
std::thread::scope(|scope| {
let spawned = scope.spawn(|| {
for _ in 0..100 {
if !signal.notify_sent()? {
signal.wait_for_drain()?;
}
}
Ok(())
});
std::thread::sleep(WAIT_DURATION);
assert!(!spawned.is_finished(), "didn't block");
for _ in 0..100 {
signal.notify_acknowledged()?;
}
wait_for_condition(|| spawned.is_finished(), "blocked at end");
spawned.join().unwrap()
})
}
#[test]
fn signal_wait_for_drain_unblocks_on_dropped() -> Result<(), ShellError> {
let signal = StreamWriterSignal::new(1);
std::thread::scope(|scope| {
let spawned = scope.spawn(|| {
while !signal.is_dropped()? {
if !signal.notify_sent()? {
signal.wait_for_drain()?;
}
}
Ok(())
});
std::thread::sleep(WAIT_DURATION);
assert!(!spawned.is_finished(), "didn't block");
signal.set_dropped()?;
wait_for_condition(|| spawned.is_finished(), "still blocked at end");
spawned.join().unwrap()
})
}
#[test]
fn stream_manager_single_stream_read_scenario() -> Result<(), ShellError> {
let manager = StreamManager::new();
let handle = manager.get_handle();
let (tx, rx) = mpsc::channel();
let readable = handle.read_stream::<Value, _>(2, tx)?;
let expected_values = vec![Value::test_int(40), Value::test_string("hello")];
for value in &expected_values {
manager.handle_message(StreamMessage::Data(2, value.clone().into()))?;
}
manager.handle_message(StreamMessage::End(2))?;
let values = readable.collect::<Vec<Value>>();
assert_eq!(expected_values, values);
// Now check the sent messages on consumption
// Should be Ack for each message, then Drop
for _ in &expected_values {
match rx.try_recv().expect("failed to receive Ack") {
StreamMessage::Ack(2) => (),
other => panic!("should have been an Ack: {other:?}"),
}
}
match rx.try_recv().expect("failed to receive Drop") {
StreamMessage::Drop(2) => (),
other => panic!("should have been a Drop: {other:?}"),
}
Ok(())
}
#[test]
fn stream_manager_multi_stream_read_scenario() -> Result<(), ShellError> {
let manager = StreamManager::new();
let handle = manager.get_handle();
let (tx, rx) = mpsc::channel();
let readable_list = handle.read_stream::<Value, _>(2, tx.clone())?;
let readable_raw = handle.read_stream::<Result<Vec<u8>, _>, _>(3, tx)?;
let expected_values = (1..100).map(Value::test_int).collect::<Vec<_>>();
let expected_raw_buffers = (1..100).map(|n| vec![n]).collect::<Vec<Vec<u8>>>();
for (value, buf) in expected_values.iter().zip(&expected_raw_buffers) {
manager.handle_message(StreamMessage::Data(2, value.clone().into()))?;
manager.handle_message(StreamMessage::Data(3, StreamData::Raw(Ok(buf.clone()))))?;
}
manager.handle_message(StreamMessage::End(2))?;
manager.handle_message(StreamMessage::End(3))?;
let values = readable_list.collect::<Vec<Value>>();
let bufs = readable_raw.collect::<Result<Vec<Vec<u8>>, _>>()?;
for (expected_value, value) in expected_values.iter().zip(&values) {
assert_eq!(expected_value, value, "in List stream");
}
for (expected_buf, buf) in expected_raw_buffers.iter().zip(&bufs) {
assert_eq!(expected_buf, buf, "in Raw stream");
}
// Now check the sent messages on consumption
// Should be Ack for each message, then Drop
for _ in &expected_values {
match rx.try_recv().expect("failed to receive Ack") {
StreamMessage::Ack(2) => (),
other => panic!("should have been an Ack(2): {other:?}"),
}
}
match rx.try_recv().expect("failed to receive Drop") {
StreamMessage::Drop(2) => (),
other => panic!("should have been a Drop(2): {other:?}"),
}
for _ in &expected_values {
match rx.try_recv().expect("failed to receive Ack") {
StreamMessage::Ack(3) => (),
other => panic!("should have been an Ack(3): {other:?}"),
}
}
match rx.try_recv().expect("failed to receive Drop") {
StreamMessage::Drop(3) => (),
other => panic!("should have been a Drop(3): {other:?}"),
}
// Should be end of stream
assert!(
rx.try_recv().is_err(),
"more messages written to stream than expected"
);
Ok(())
}
#[test]
fn stream_manager_write_scenario() -> Result<(), ShellError> {
let manager = StreamManager::new();
let handle = manager.get_handle();
let (tx, rx) = mpsc::channel();
let mut writable = handle.write_stream(4, tx, 100)?;
let expected_values = vec![b"hello".to_vec(), b"world".to_vec(), b"test".to_vec()];
for value in &expected_values {
writable.write(Ok::<_, ShellError>(value.clone()))?;
}
// Now try signalling ack
assert_eq!(
expected_values.len() as i32,
writable.signal.lock()?.unacknowledged,
"unacknowledged initial count",
);
manager.handle_message(StreamMessage::Ack(4))?;
assert_eq!(
expected_values.len() as i32 - 1,
writable.signal.lock()?.unacknowledged,
"unacknowledged post-Ack count",
);
// ...and Drop
manager.handle_message(StreamMessage::Drop(4))?;
assert!(writable.is_dropped()?);
// Drop the StreamWriter...
drop(writable);
// now check what was actually written
for value in &expected_values {
match rx.try_recv().expect("failed to receive Data") {
StreamMessage::Data(4, StreamData::Raw(Ok(received))) => {
assert_eq!(*value, received);
}
other @ StreamMessage::Data(..) => panic!("wrong Data for {value:?}: {other:?}"),
other => panic!("should have been Data: {other:?}"),
}
}
match rx.try_recv().expect("failed to receive End") {
StreamMessage::End(4) => (),
other => panic!("should have been End: {other:?}"),
}
Ok(())
}
#[test]
fn stream_manager_broadcast_read_error() -> Result<(), ShellError> {
let manager = StreamManager::new();
let handle = manager.get_handle();
let mut readable0 = handle.read_stream::<Value, _>(0, TestSink::default())?;
let mut readable1 = handle.read_stream::<Result<Vec<u8>, _>, _>(1, TestSink::default())?;
let error = ShellError::PluginFailedToDecode {
msg: "test decode error".into(),
};
manager.broadcast_read_error(error.clone())?;
drop(manager);
assert_eq!(
error.to_string(),
readable0
.recv()
.transpose()
.expect("nothing received from readable0")
.expect_err("not an error received from readable0")
.to_string()
);
assert_eq!(
error.to_string(),
readable1
.next()
.expect("nothing received from readable1")
.expect_err("not an error received from readable1")
.to_string()
);
Ok(())
}
#[test]
fn stream_manager_drop_writers_on_drop() -> Result<(), ShellError> {
let manager = StreamManager::new();
let handle = manager.get_handle();
let writable = handle.write_stream(4, TestSink::default(), 100)?;
assert!(!writable.is_dropped()?);
drop(manager);
assert!(writable.is_dropped()?);
Ok(())
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/interface/stream/mod.rs | crates/nu-plugin-core/src/interface/stream/mod.rs | use nu_plugin_protocol::{StreamData, StreamId, StreamMessage};
use nu_protocol::{ShellError, Span, Value};
use std::{
collections::{BTreeMap, btree_map},
iter::FusedIterator,
marker::PhantomData,
sync::{Arc, Condvar, Mutex, MutexGuard, Weak, mpsc},
};
#[cfg(test)]
mod tests;
/// Receives messages from a stream read from input by a [`StreamManager`].
///
/// The receiver reads for messages of type `Result<Option<StreamData>, ShellError>` from the
/// channel, which is managed by a [`StreamManager`]. Signalling for end-of-stream is explicit
/// through `Ok(Some)`.
///
/// Failing to receive is an error. When end-of-stream is received, the `receiver` is set to `None`
/// and all further calls to `next()` return `None`.
///
/// The type `T` must implement [`FromShellError`], so that errors in the stream can be represented,
/// and `TryFrom<StreamData>` to convert it to the correct type.
///
/// For each message read, it sends [`StreamMessage::Ack`] to the writer. When dropped,
/// it sends [`StreamMessage::Drop`].
#[derive(Debug)]
pub struct StreamReader<T, W>
where
W: WriteStreamMessage,
{
id: StreamId,
receiver: Option<mpsc::Receiver<Result<Option<StreamData>, ShellError>>>,
writer: W,
/// Iterator requires the item type to be fixed, so we have to keep it as part of the type,
/// even though we're actually receiving dynamic data.
marker: PhantomData<fn() -> T>,
}
impl<T, W> StreamReader<T, W>
where
T: TryFrom<StreamData, Error = ShellError>,
W: WriteStreamMessage,
{
/// Create a new StreamReader from parts
fn new(
id: StreamId,
receiver: mpsc::Receiver<Result<Option<StreamData>, ShellError>>,
writer: W,
) -> StreamReader<T, W> {
StreamReader {
id,
receiver: Some(receiver),
writer,
marker: PhantomData,
}
}
/// Receive a message from the channel, or return an error if:
///
/// * the channel couldn't be received from
/// * an error was sent on the channel
/// * the message received couldn't be converted to `T`
pub fn recv(&mut self) -> Result<Option<T>, ShellError> {
let connection_lost = || ShellError::GenericError {
error: "Stream ended unexpectedly".into(),
msg: "connection lost before explicit end of stream".into(),
span: None,
help: None,
inner: vec![],
};
if let Some(ref rx) = self.receiver {
// Try to receive a message first
let msg = match rx.try_recv() {
Ok(msg) => msg?,
Err(mpsc::TryRecvError::Empty) => {
// The receiver doesn't have any messages waiting for us. It's possible that the
// other side hasn't seen our acknowledgements. Let's flush the writer and then
// wait
self.writer.flush()?;
rx.recv().map_err(|_| connection_lost())??
}
Err(mpsc::TryRecvError::Disconnected) => return Err(connection_lost()),
};
if let Some(data) = msg {
// Acknowledge the message
self.writer
.write_stream_message(StreamMessage::Ack(self.id))?;
// Try to convert it into the correct type
Ok(Some(data.try_into()?))
} else {
// Remove the receiver, so that future recv() calls always return Ok(None)
self.receiver = None;
Ok(None)
}
} else {
// Closed already
Ok(None)
}
}
}
impl<T, W> Iterator for StreamReader<T, W>
where
T: FromShellError + TryFrom<StreamData, Error = ShellError>,
W: WriteStreamMessage,
{
type Item = T;
fn next(&mut self) -> Option<T> {
// Converting the error to the value here makes the implementation a lot easier
match self.recv() {
Ok(option) => option,
Err(err) => {
// Drop the receiver so we don't keep returning errors
self.receiver = None;
Some(T::from_shell_error(err))
}
}
}
}
// Guaranteed not to return anything after the end
impl<T, W> FusedIterator for StreamReader<T, W>
where
T: FromShellError + TryFrom<StreamData, Error = ShellError>,
W: WriteStreamMessage,
{
}
impl<T, W> Drop for StreamReader<T, W>
where
W: WriteStreamMessage,
{
fn drop(&mut self) {
if let Err(err) = self
.writer
.write_stream_message(StreamMessage::Drop(self.id))
.and_then(|_| self.writer.flush())
{
log::warn!("Failed to send message to drop stream: {err}");
}
}
}
/// Values that can contain a `ShellError` to signal an error has occurred.
pub trait FromShellError {
fn from_shell_error(err: ShellError) -> Self;
}
// For List streams.
impl FromShellError for Value {
fn from_shell_error(err: ShellError) -> Self {
Value::error(err, Span::unknown())
}
}
// For Raw streams, mostly.
impl<T> FromShellError for Result<T, ShellError> {
fn from_shell_error(err: ShellError) -> Self {
Err(err)
}
}
/// Writes messages to a stream, with flow control.
///
/// The `signal` contained
#[derive(Debug)]
pub struct StreamWriter<W: WriteStreamMessage> {
id: StreamId,
signal: Arc<StreamWriterSignal>,
writer: W,
ended: bool,
}
impl<W> StreamWriter<W>
where
W: WriteStreamMessage,
{
fn new(id: StreamId, signal: Arc<StreamWriterSignal>, writer: W) -> StreamWriter<W> {
StreamWriter {
id,
signal,
writer,
ended: false,
}
}
/// Check if the stream was dropped from the other end. Recommended to do this before calling
/// [`.write()`](Self::write), especially in a loop.
pub fn is_dropped(&self) -> Result<bool, ShellError> {
self.signal.is_dropped()
}
/// Write a single piece of data to the stream.
///
/// Error if something failed with the write, or if [`.end()`](Self::end) was already called
/// previously.
pub fn write(&mut self, data: impl Into<StreamData>) -> Result<(), ShellError> {
if !self.ended {
self.writer
.write_stream_message(StreamMessage::Data(self.id, data.into()))?;
// Flush after each data message to ensure they do predictably appear on the other side
// when they're generated
//
// TODO: make the buffering configurable, as this is a factor for performance
self.writer.flush()?;
// This implements flow control, so we don't write too many messages:
if !self.signal.notify_sent()? {
self.signal.wait_for_drain()
} else {
Ok(())
}
} else {
Err(ShellError::GenericError {
error: "Wrote to a stream after it ended".into(),
msg: format!(
"tried to write to stream {} after it was already ended",
self.id
),
span: None,
help: Some("this may be a bug in the nu-plugin crate".into()),
inner: vec![],
})
}
}
/// Write a full iterator to the stream. Note that this doesn't end the stream, so you should
/// still call [`.end()`](Self::end).
///
/// If the stream is dropped from the other end, the iterator will not be fully consumed, and
/// writing will terminate.
///
/// Returns `Ok(true)` if the iterator was fully consumed, or `Ok(false)` if a drop interrupted
/// the stream from the other side.
pub fn write_all<T>(&mut self, data: impl IntoIterator<Item = T>) -> Result<bool, ShellError>
where
T: Into<StreamData>,
{
// Check before starting
if self.is_dropped()? {
return Ok(false);
}
for item in data {
// Check again after each item is consumed from the iterator, just in case the iterator
// takes a while to produce a value
if self.is_dropped()? {
return Ok(false);
}
self.write(item)?;
}
Ok(true)
}
/// End the stream. Recommend doing this instead of relying on `Drop` so that you can catch the
/// error.
pub fn end(&mut self) -> Result<(), ShellError> {
if !self.ended {
// Set the flag first so we don't double-report in the Drop
self.ended = true;
self.writer
.write_stream_message(StreamMessage::End(self.id))?;
self.writer.flush()
} else {
Ok(())
}
}
}
impl<W> Drop for StreamWriter<W>
where
W: WriteStreamMessage,
{
fn drop(&mut self) {
// Make sure we ended the stream
if let Err(err) = self.end() {
log::warn!("Error while ending stream in Drop for StreamWriter: {err}");
}
}
}
/// Stores stream state for a writer, and can be blocked on to wait for messages to be acknowledged.
/// A key part of managing stream lifecycle and flow control.
#[derive(Debug)]
pub struct StreamWriterSignal {
mutex: Mutex<StreamWriterSignalState>,
change_cond: Condvar,
}
#[derive(Debug)]
pub struct StreamWriterSignalState {
/// Stream has been dropped and consumer is no longer interested in any messages.
dropped: bool,
/// Number of messages that have been sent without acknowledgement.
unacknowledged: i32,
/// Max number of messages to send before waiting for acknowledgement.
high_pressure_mark: i32,
}
impl StreamWriterSignal {
/// Create a new signal.
///
/// If `notify_sent()` is called more than `high_pressure_mark` times, it will wait until
/// `notify_acknowledge()` is called by another thread enough times to bring the number of
/// unacknowledged sent messages below that threshold.
fn new(high_pressure_mark: i32) -> StreamWriterSignal {
assert!(high_pressure_mark > 0);
StreamWriterSignal {
mutex: Mutex::new(StreamWriterSignalState {
dropped: false,
unacknowledged: 0,
high_pressure_mark,
}),
change_cond: Condvar::new(),
}
}
fn lock(&self) -> Result<MutexGuard<'_, StreamWriterSignalState>, ShellError> {
self.mutex.lock().map_err(|_| ShellError::NushellFailed {
msg: "StreamWriterSignal mutex poisoned due to panic".into(),
})
}
/// True if the stream was dropped and the consumer is no longer interested in it. Indicates
/// that no more messages should be sent, other than `End`.
pub fn is_dropped(&self) -> Result<bool, ShellError> {
Ok(self.lock()?.dropped)
}
/// Notify the writers that the stream has been dropped, so they can stop writing.
pub fn set_dropped(&self) -> Result<(), ShellError> {
let mut state = self.lock()?;
state.dropped = true;
// Unblock the writers so they can terminate
self.change_cond.notify_all();
Ok(())
}
/// Track that a message has been sent. Returns `Ok(true)` if more messages can be sent,
/// or `Ok(false)` if the high pressure mark has been reached and
/// [`.wait_for_drain()`](Self::wait_for_drain) should be called to block.
pub fn notify_sent(&self) -> Result<bool, ShellError> {
let mut state = self.lock()?;
state.unacknowledged =
state
.unacknowledged
.checked_add(1)
.ok_or_else(|| ShellError::NushellFailed {
msg: "Overflow in counter: too many unacknowledged messages".into(),
})?;
Ok(state.unacknowledged < state.high_pressure_mark)
}
/// Wait for acknowledgements before sending more data. Also returns if the stream is dropped.
pub fn wait_for_drain(&self) -> Result<(), ShellError> {
let mut state = self.lock()?;
while !state.dropped && state.unacknowledged >= state.high_pressure_mark {
state = self
.change_cond
.wait(state)
.map_err(|_| ShellError::NushellFailed {
msg: "StreamWriterSignal mutex poisoned due to panic".into(),
})?;
}
Ok(())
}
/// Notify the writers that a message has been acknowledged, so they can continue to write
/// if they were waiting.
pub fn notify_acknowledged(&self) -> Result<(), ShellError> {
let mut state = self.lock()?;
state.unacknowledged =
state
.unacknowledged
.checked_sub(1)
.ok_or_else(|| ShellError::NushellFailed {
msg: "Underflow in counter: too many message acknowledgements".into(),
})?;
// Unblock the writer
self.change_cond.notify_one();
Ok(())
}
}
/// A sink for a [`StreamMessage`]
pub trait WriteStreamMessage {
fn write_stream_message(&mut self, msg: StreamMessage) -> Result<(), ShellError>;
fn flush(&mut self) -> Result<(), ShellError>;
}
#[derive(Debug, Default)]
struct StreamManagerState {
reading_streams: BTreeMap<StreamId, mpsc::Sender<Result<Option<StreamData>, ShellError>>>,
writing_streams: BTreeMap<StreamId, Weak<StreamWriterSignal>>,
}
impl StreamManagerState {
/// Lock the state, or return a [`ShellError`] if the mutex is poisoned.
fn lock(
state: &Mutex<StreamManagerState>,
) -> Result<MutexGuard<'_, StreamManagerState>, ShellError> {
state.lock().map_err(|_| ShellError::NushellFailed {
msg: "StreamManagerState mutex poisoned due to a panic".into(),
})
}
}
#[derive(Debug)]
pub struct StreamManager {
state: Arc<Mutex<StreamManagerState>>,
}
impl StreamManager {
/// Create a new StreamManager.
pub fn new() -> StreamManager {
StreamManager {
state: Default::default(),
}
}
fn lock(&self) -> Result<MutexGuard<'_, StreamManagerState>, ShellError> {
StreamManagerState::lock(&self.state)
}
/// Create a new handle to the StreamManager for registering streams.
pub fn get_handle(&self) -> StreamManagerHandle {
StreamManagerHandle {
state: Arc::downgrade(&self.state),
}
}
/// Process a stream message, and update internal state accordingly.
pub fn handle_message(&self, message: StreamMessage) -> Result<(), ShellError> {
let mut state = self.lock()?;
match message {
StreamMessage::Data(id, data) => {
if let Some(sender) = state.reading_streams.get(&id) {
// We should ignore the error on send. This just means the reader has dropped,
// but it will have sent a Drop message to the other side, and we will receive
// an End message at which point we can remove the channel.
let _ = sender.send(Ok(Some(data)));
Ok(())
} else {
Err(ShellError::PluginFailedToDecode {
msg: format!("received Data for unknown stream {id}"),
})
}
}
StreamMessage::End(id) => {
if let Some(sender) = state.reading_streams.remove(&id) {
// We should ignore the error on the send, because the reader might have dropped
// already
let _ = sender.send(Ok(None));
Ok(())
} else {
Err(ShellError::PluginFailedToDecode {
msg: format!("received End for unknown stream {id}"),
})
}
}
StreamMessage::Drop(id) => {
if let Some(signal) = state.writing_streams.remove(&id)
&& let Some(signal) = signal.upgrade()
{
// This will wake blocked writers so they can stop writing, so it's ok
signal.set_dropped()?;
}
// It's possible that the stream has already finished writing and we don't have it
// anymore, so we fall through to Ok
Ok(())
}
StreamMessage::Ack(id) => {
if let Some(signal) = state.writing_streams.get(&id) {
if let Some(signal) = signal.upgrade() {
// This will wake up a blocked writer
signal.notify_acknowledged()?;
} else {
// We know it doesn't exist, so might as well remove it
state.writing_streams.remove(&id);
}
}
// It's possible that the stream has already finished writing and we don't have it
// anymore, so we fall through to Ok
Ok(())
}
}
}
/// Broadcast an error to all stream readers. This is useful for error propagation.
pub fn broadcast_read_error(&self, error: ShellError) -> Result<(), ShellError> {
let state = self.lock()?;
for channel in state.reading_streams.values() {
// Ignore send errors.
let _ = channel.send(Err(error.clone()));
}
Ok(())
}
// If the `StreamManager` is dropped, we should let all of the stream writers know that they
// won't be able to write anymore. We don't need to do anything about the readers though
// because they'll know when the `Sender` is dropped automatically
fn drop_all_writers(&self) -> Result<(), ShellError> {
let mut state = self.lock()?;
let writers = std::mem::take(&mut state.writing_streams);
for (_, signal) in writers {
if let Some(signal) = signal.upgrade() {
// more important that we send to all than handling an error
let _ = signal.set_dropped();
}
}
Ok(())
}
}
impl Default for StreamManager {
fn default() -> Self {
Self::new()
}
}
impl Drop for StreamManager {
fn drop(&mut self) {
if let Err(err) = self.drop_all_writers() {
log::warn!("error during Drop for StreamManager: {err}")
}
}
}
/// A [`StreamManagerHandle`] supports operations for interacting with the [`StreamManager`].
///
/// Streams can be registered for reading, returning a [`StreamReader`], or for writing, returning
/// a [`StreamWriter`].
#[derive(Debug, Clone)]
pub struct StreamManagerHandle {
state: Weak<Mutex<StreamManagerState>>,
}
impl StreamManagerHandle {
/// Because the handle only has a weak reference to the [`StreamManager`] state, we have to
/// first try to upgrade to a strong reference and then lock. This function wraps those two
/// operations together, handling errors appropriately.
fn with_lock<T, F>(&self, f: F) -> Result<T, ShellError>
where
F: FnOnce(MutexGuard<StreamManagerState>) -> Result<T, ShellError>,
{
let upgraded = self
.state
.upgrade()
.ok_or_else(|| ShellError::NushellFailed {
msg: "StreamManager is no longer alive".into(),
})?;
let guard = upgraded.lock().map_err(|_| ShellError::NushellFailed {
msg: "StreamManagerState mutex poisoned due to a panic".into(),
})?;
f(guard)
}
/// Register a new stream for reading, and return a [`StreamReader`] that can be used to iterate
/// on the values received. A [`StreamMessage`] writer is required for writing control messages
/// back to the producer.
pub fn read_stream<T, W>(
&self,
id: StreamId,
writer: W,
) -> Result<StreamReader<T, W>, ShellError>
where
T: TryFrom<StreamData, Error = ShellError>,
W: WriteStreamMessage,
{
let (tx, rx) = mpsc::channel();
self.with_lock(|mut state| {
// Must be exclusive
if let btree_map::Entry::Vacant(e) = state.reading_streams.entry(id) {
e.insert(tx);
Ok(())
} else {
Err(ShellError::GenericError {
error: format!("Failed to acquire reader for stream {id}"),
msg: "tried to get a reader for a stream that's already being read".into(),
span: None,
help: Some("this may be a bug in the nu-plugin crate".into()),
inner: vec![],
})
}
})?;
Ok(StreamReader::new(id, rx, writer))
}
/// Register a new stream for writing, and return a [`StreamWriter`] that can be used to send
/// data to the stream.
///
/// The `high_pressure_mark` value controls how many messages can be written without receiving
/// an acknowledgement before any further attempts to write will wait for the consumer to
/// acknowledge them. This prevents overwhelming the reader.
pub fn write_stream<W>(
&self,
id: StreamId,
writer: W,
high_pressure_mark: i32,
) -> Result<StreamWriter<W>, ShellError>
where
W: WriteStreamMessage,
{
let signal = Arc::new(StreamWriterSignal::new(high_pressure_mark));
self.with_lock(|mut state| {
// Remove dead writing streams
state
.writing_streams
.retain(|_, signal| signal.strong_count() > 0);
// Must be exclusive
if let btree_map::Entry::Vacant(e) = state.writing_streams.entry(id) {
e.insert(Arc::downgrade(&signal));
Ok(())
} else {
Err(ShellError::GenericError {
error: format!("Failed to acquire writer for stream {id}"),
msg: "tried to get a writer for a stream that's already being written".into(),
span: None,
help: Some("this may be a bug in the nu-plugin crate".into()),
inner: vec![],
})
}
})?;
Ok(StreamWriter::new(id, signal, writer))
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/communication_mode/mod.rs | crates/nu-plugin-core/src/communication_mode/mod.rs | use std::ffi::OsStr;
use std::io::{Stdin, Stdout};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use nu_protocol::ShellError;
#[cfg(feature = "local-socket")] // unused without that feature
use nu_protocol::shell_error::io::IoError;
#[cfg(feature = "local-socket")]
mod local_socket;
#[cfg(feature = "local-socket")]
use local_socket::*;
/// The type of communication used between the plugin and the engine.
///
/// `Stdio` is required to be supported by all plugins, and is attempted initially. If the
/// `local-socket` feature is enabled and the plugin supports it, `LocalSocket` may be attempted.
///
/// Local socket communication has the benefit of not tying up stdio, so it's more compatible with
/// plugins that want to take user input from the terminal in some way.
#[derive(Debug, Clone)]
pub enum CommunicationMode {
/// Communicate using `stdin` and `stdout`.
Stdio,
/// Communicate using an operating system-specific local socket.
#[cfg(feature = "local-socket")]
LocalSocket(std::ffi::OsString),
}
impl CommunicationMode {
/// Generate a new local socket communication mode based on the given plugin exe path.
#[cfg(feature = "local-socket")]
pub fn local_socket(plugin_exe: &std::path::Path) -> CommunicationMode {
use std::hash::{Hash, Hasher};
use std::time::SystemTime;
// Generate the unique ID based on the plugin path and the current time. The actual
// algorithm here is not very important, we just want this to be relatively unique very
// briefly. Using the default hasher in the stdlib means zero extra dependencies.
let mut hasher = std::collections::hash_map::DefaultHasher::new();
plugin_exe.hash(&mut hasher);
SystemTime::now().hash(&mut hasher);
let unique_id = format!("{:016x}", hasher.finish());
CommunicationMode::LocalSocket(make_local_socket_name(&unique_id))
}
pub fn args(&self) -> Vec<&OsStr> {
match self {
CommunicationMode::Stdio => vec![OsStr::new("--stdio")],
#[cfg(feature = "local-socket")]
CommunicationMode::LocalSocket(path) => {
vec![OsStr::new("--local-socket"), path.as_os_str()]
}
}
}
pub fn setup_command_io(&self, command: &mut Command) {
match self {
CommunicationMode::Stdio => {
// Both stdout and stdin are piped so we can receive information from the plugin
command.stdin(Stdio::piped());
command.stdout(Stdio::piped());
}
#[cfg(feature = "local-socket")]
CommunicationMode::LocalSocket(_) => {
// Stdio can be used by the plugin to talk to the terminal in local socket mode,
// which is the big benefit
command.stdin(Stdio::inherit());
command.stdout(Stdio::inherit());
}
}
}
pub fn serve(&self) -> Result<PreparedServerCommunication, ShellError> {
match self {
// Nothing to set up for stdio - we just take it from the child.
CommunicationMode::Stdio => Ok(PreparedServerCommunication::Stdio),
// For sockets: we need to create the server so that the child won't fail to connect.
#[cfg(feature = "local-socket")]
CommunicationMode::LocalSocket(name) => {
use interprocess::local_socket::ListenerOptions;
let listener = interpret_local_socket_name(name)
.and_then(|name| ListenerOptions::new().name(name).create_sync())
.map_err(|err| {
IoError::new_internal(
err,
format!(
"Could not interpret local socket name {:?}",
name.to_string_lossy()
),
nu_protocol::location!(),
)
})?;
Ok(PreparedServerCommunication::LocalSocket { listener })
}
}
}
pub fn connect_as_client(&self) -> Result<ClientCommunicationIo, ShellError> {
match self {
CommunicationMode::Stdio => Ok(ClientCommunicationIo::Stdio(
std::io::stdin(),
std::io::stdout(),
)),
#[cfg(feature = "local-socket")]
CommunicationMode::LocalSocket(name) => {
// Connect to the specified socket.
let get_socket = || {
use interprocess::local_socket as ls;
use ls::traits::Stream;
interpret_local_socket_name(name)
.and_then(|name| ls::Stream::connect(name))
.map_err(|err| {
ShellError::Io(IoError::new_internal(
err,
format!(
"Could not interpret local socket name {:?}",
name.to_string_lossy()
),
nu_protocol::location!(),
))
})
};
// Reverse order from the server: read in, write out
let read_in = get_socket()?;
let write_out = get_socket()?;
Ok(ClientCommunicationIo::LocalSocket { read_in, write_out })
}
}
}
}
/// The result of [`CommunicationMode::serve()`], which acts as an intermediate stage for
/// communication modes that require some kind of socket binding to occur before the client process
/// can be started. Call [`.connect()`](Self::connect) once the client process has been started.
///
/// The socket may be cleaned up on `Drop` if applicable.
pub enum PreparedServerCommunication {
/// Will take stdin and stdout from the process on [`.connect()`](Self::connect).
Stdio,
/// Contains the listener to accept connections on. On Unix, the socket is unlinked on `Drop`.
#[cfg(feature = "local-socket")]
LocalSocket {
listener: interprocess::local_socket::Listener,
},
}
impl PreparedServerCommunication {
pub fn connect(&self, child: &mut Child) -> Result<ServerCommunicationIo, ShellError> {
match self {
PreparedServerCommunication::Stdio => {
let stdin = child
.stdin
.take()
.ok_or_else(|| ShellError::PluginFailedToLoad {
msg: "Plugin missing stdin writer".into(),
})?;
let stdout = child
.stdout
.take()
.ok_or_else(|| ShellError::PluginFailedToLoad {
msg: "Plugin missing stdout writer".into(),
})?;
Ok(ServerCommunicationIo::Stdio(stdin, stdout))
}
#[cfg(feature = "local-socket")]
PreparedServerCommunication::LocalSocket { listener, .. } => {
use interprocess::local_socket::traits::{
Listener, ListenerNonblockingMode, Stream,
};
use std::time::{Duration, Instant};
const RETRY_PERIOD: Duration = Duration::from_millis(1);
const TIMEOUT: Duration = Duration::from_secs(10);
let start = Instant::now();
// Use a loop to try to get two clients from the listener: one for read (the plugin
// output) and one for write (the plugin input)
//
// Be non-blocking on Accept only, so we can timeout.
listener
.set_nonblocking(ListenerNonblockingMode::Accept)
.map_err(|err| {
IoError::new_internal(
err,
"Could not set non-blocking mode accept for listener",
nu_protocol::location!(),
)
})?;
let mut get_socket = || {
let mut result = None;
while let Ok(None) = child.try_wait() {
match listener.accept() {
Ok(stream) => {
// Success! Ensure the stream is in nonblocking mode though, for
// good measure. Had an issue without this on macOS.
stream.set_nonblocking(false).map_err(|err| {
IoError::new_internal(
err,
"Could not disable non-blocking mode for listener",
nu_protocol::location!(),
)
})?;
result = Some(stream);
break;
}
Err(err) => {
if !is_would_block_err(&err) {
// `WouldBlock` is ok, just means it's not ready yet, but some other
// kind of error should be reported
return Err(ShellError::Io(IoError::new_internal(
err,
"Accepting new data from listener failed",
nu_protocol::location!(),
)));
}
}
}
if Instant::now().saturating_duration_since(start) > TIMEOUT {
return Err(ShellError::PluginFailedToLoad {
msg: "Plugin timed out while waiting to connect to socket".into(),
});
} else {
std::thread::sleep(RETRY_PERIOD);
}
}
if let Some(stream) = result {
Ok(stream)
} else {
// The process may have exited
Err(ShellError::PluginFailedToLoad {
msg: "Plugin exited without connecting".into(),
})
}
};
// Input stream always comes before output
let write_in = get_socket()?;
let read_out = get_socket()?;
Ok(ServerCommunicationIo::LocalSocket { read_out, write_in })
}
}
}
}
/// The required streams for communication from the engine side, i.e. the server in socket terms.
pub enum ServerCommunicationIo {
Stdio(ChildStdin, ChildStdout),
#[cfg(feature = "local-socket")]
LocalSocket {
read_out: interprocess::local_socket::Stream,
write_in: interprocess::local_socket::Stream,
},
}
/// The required streams for communication from the plugin side, i.e. the client in socket terms.
pub enum ClientCommunicationIo {
Stdio(Stdin, Stdout),
#[cfg(feature = "local-socket")]
LocalSocket {
read_in: interprocess::local_socket::Stream,
write_out: interprocess::local_socket::Stream,
},
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/communication_mode/local_socket/tests.rs | crates/nu-plugin-core/src/communication_mode/local_socket/tests.rs | use super::make_local_socket_name;
#[test]
fn local_socket_path_contains_pid() {
let name = make_local_socket_name("test-string")
.to_string_lossy()
.into_owned();
println!("{name}");
assert!(name.to_string().contains(&std::process::id().to_string()));
}
#[test]
fn local_socket_path_contains_provided_name() {
let name = make_local_socket_name("test-string")
.to_string_lossy()
.into_owned();
println!("{name}");
assert!(name.to_string().contains("test-string"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-core/src/communication_mode/local_socket/mod.rs | crates/nu-plugin-core/src/communication_mode/local_socket/mod.rs | use std::ffi::{OsStr, OsString};
#[cfg(test)]
pub(crate) mod tests;
/// Generate a name to be used for a local socket specific to this `nu` process, described by the
/// given `unique_id`, which should be unique to the purpose of the socket.
///
/// On Unix, this is a path, which should generally be 100 characters or less for compatibility. On
/// Windows, this is a name within the `\\.\pipe` namespace.
#[cfg(unix)]
pub fn make_local_socket_name(unique_id: &str) -> OsString {
// Prefer to put it in XDG_RUNTIME_DIR if set, since that's user-local
let mut base = if let Some(runtime_dir) = std::env::var_os("XDG_RUNTIME_DIR") {
std::path::PathBuf::from(runtime_dir)
} else {
// Use std::env::temp_dir() for portability, especially since on Android this is probably
// not `/tmp`
std::env::temp_dir()
};
let socket_name = format!("nu.{}.{}.sock", std::process::id(), unique_id);
base.push(socket_name);
base.into()
}
/// Interpret a local socket name for use with `interprocess`.
#[cfg(unix)]
pub fn interpret_local_socket_name(
name: &OsStr,
) -> Result<interprocess::local_socket::Name<'_>, std::io::Error> {
use interprocess::local_socket::{GenericFilePath, ToFsName};
name.to_fs_name::<GenericFilePath>()
}
/// Generate a name to be used for a local socket specific to this `nu` process, described by the
/// given `unique_id`, which should be unique to the purpose of the socket.
///
/// On Unix, this is a path, which should generally be 100 characters or less for compatibility. On
/// Windows, this is a name within the `\\.\pipe` namespace.
#[cfg(windows)]
pub fn make_local_socket_name(unique_id: &str) -> OsString {
format!("nu.{}.{}", std::process::id(), unique_id).into()
}
/// Interpret a local socket name for use with `interprocess`.
#[cfg(windows)]
pub fn interpret_local_socket_name(
name: &OsStr,
) -> Result<interprocess::local_socket::Name<'_>, std::io::Error> {
use interprocess::local_socket::{GenericNamespaced, ToNsName};
name.to_ns_name::<GenericNamespaced>()
}
/// Determine if the error is just due to the listener not being ready yet in asynchronous mode
#[cfg(not(windows))]
pub fn is_would_block_err(err: &std::io::Error) -> bool {
err.kind() == std::io::ErrorKind::WouldBlock
}
/// Determine if the error is just due to the listener not being ready yet in asynchronous mode
#[cfg(windows)]
pub fn is_would_block_err(err: &std::io::Error) -> bool {
err.kind() == std::io::ErrorKind::WouldBlock
|| err.raw_os_error().is_some_and(|e| {
// Windows returns this error when trying to accept a pipe in non-blocking mode
e as i64 == windows::Win32::Foundation::ERROR_PIPE_LISTENING.0 as i64
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/lib.rs | crates/nu_plugin_formats/src/lib.rs | mod from;
mod to;
use nu_plugin::{Plugin, PluginCommand};
use from::eml::FromEml;
use from::ics::FromIcs;
use from::ini::FromIni;
use from::plist::FromPlist;
use from::vcf::FromVcf;
use to::plist::IntoPlist;
pub struct FormatCmdsPlugin;
impl Plugin for FormatCmdsPlugin {
fn version(&self) -> String {
env!("CARGO_PKG_VERSION").into()
}
fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> {
vec![
Box::new(FromEml),
Box::new(FromIcs),
Box::new(FromIni),
Box::new(FromVcf),
Box::new(FromPlist),
Box::new(IntoPlist),
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/main.rs | crates/nu_plugin_formats/src/main.rs | use nu_plugin::{MsgPackSerializer, serve_plugin};
use nu_plugin_formats::FormatCmdsPlugin;
fn main() {
serve_plugin(&FormatCmdsPlugin, MsgPackSerializer {})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/from/vcf.rs | crates/nu_plugin_formats/src/from/vcf.rs | use crate::FormatCmdsPlugin;
use ical::{parser::vcard::component::*, property::Property};
use indexmap::IndexMap;
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{
Category, Example, LabeledError, ShellError, Signature, Span, Type, Value, record,
};
pub struct FromVcf;
impl SimplePluginCommand for FromVcf {
type Plugin = FormatCmdsPlugin;
fn name(&self) -> &str {
"from vcf"
}
fn description(&self) -> &str {
"Parse text as .vcf and create table."
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::String, Type::table())])
.category(Category::Formats)
}
fn examples(&self) -> Vec<Example<'_>> {
examples()
}
fn run(
&self,
_plugin: &FormatCmdsPlugin,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
let span = input.span();
let input_string = input.coerce_str()?;
let head = call.head;
let input_string = input_string
.lines()
.enumerate()
.map(|(i, x)| {
if i == 0 {
x.trim().to_string()
} else if x.len() > 1 && (x.starts_with(' ') || x.starts_with('\t')) {
x[1..].trim_end().to_string()
} else {
format!("\n{}", x.trim())
}
})
.collect::<String>();
let input_bytes = input_string.as_bytes();
let cursor = std::io::Cursor::new(input_bytes);
let parser = ical::VcardParser::new(cursor);
let iter = parser.map(move |contact| match contact {
Ok(c) => contact_to_value(c, head),
Err(e) => Value::error(
ShellError::UnsupportedInput {
msg: format!("input cannot be parsed as .vcf ({e})"),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
},
span,
),
});
let collected: Vec<_> = iter.collect();
Ok(Value::list(collected, head))
}
}
pub fn examples() -> Vec<Example<'static>> {
vec![Example {
example: "'BEGIN:VCARD
N:Foo
FN:Bar
EMAIL:foo@bar.com
END:VCARD' | from vcf",
description: "Converts ics formatted string to table",
result: Some(Value::test_list(vec![Value::test_record(record! {
"properties" => Value::test_list(
vec![
Value::test_record(record! {
"name" => Value::test_string("N"),
"value" => Value::test_string("Foo"),
"params" => Value::nothing(Span::test_data()),
}),
Value::test_record(record! {
"name" => Value::test_string("FN"),
"value" => Value::test_string("Bar"),
"params" => Value::nothing(Span::test_data()),
}),
Value::test_record(record! {
"name" => Value::test_string("EMAIL"),
"value" => Value::test_string("foo@bar.com"),
"params" => Value::nothing(Span::test_data()),
}),
],
),
})])),
}]
}
fn contact_to_value(contact: VcardContact, span: Span) -> Value {
Value::record(
record! { "properties" => properties_to_value(contact.properties, span) },
span,
)
}
fn properties_to_value(properties: Vec<Property>, span: Span) -> Value {
Value::list(
properties
.into_iter()
.map(|prop| {
let name = Value::string(prop.name, span);
let value = match prop.value {
Some(val) => Value::string(val, span),
None => Value::nothing(span),
};
let params = match prop.params {
Some(param_list) => params_to_value(param_list, span),
None => Value::nothing(span),
};
Value::record(
record! {
"name" => name,
"value" => value,
"params" => params,
},
span,
)
})
.collect::<Vec<Value>>(),
span,
)
}
fn params_to_value(params: Vec<(String, Vec<String>)>, span: Span) -> Value {
let mut row = IndexMap::new();
for (param_name, param_values) in params {
let values: Vec<Value> = param_values
.into_iter()
.map(|val| Value::string(val, span))
.collect();
let values = Value::list(values, span);
row.insert(param_name, values);
}
Value::record(row.into_iter().collect(), span)
}
#[test]
fn test_examples() -> Result<(), nu_protocol::ShellError> {
use nu_plugin_test_support::PluginTest;
PluginTest::new("formats", crate::FormatCmdsPlugin.into())?.test_command_examples(&FromVcf)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/from/ics.rs | crates/nu_plugin_formats/src/from/ics.rs | use crate::FormatCmdsPlugin;
use ical::{parser::ical::component::*, property::Property};
use indexmap::IndexMap;
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{
Category, Example, LabeledError, ShellError, Signature, Span, Type, Value, record,
};
use std::io::BufReader;
pub struct FromIcs;
impl SimplePluginCommand for FromIcs {
type Plugin = FormatCmdsPlugin;
fn name(&self) -> &str {
"from ics"
}
fn description(&self) -> &str {
"Parse text as .ics and create table."
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::String, Type::table())])
.category(Category::Formats)
}
fn examples(&self) -> Vec<Example<'_>> {
examples()
}
fn run(
&self,
_plugin: &FormatCmdsPlugin,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
let span = input.span();
let input_string = input.coerce_str()?;
let head = call.head;
let input_string = input_string
.lines()
.enumerate()
.map(|(i, x)| {
if i == 0 {
x.trim().to_string()
} else if x.len() > 1 && (x.starts_with(' ') || x.starts_with('\t')) {
x[1..].trim_end().to_string()
} else {
format!("\n{}", x.trim())
}
})
.collect::<String>();
let input_bytes = input_string.as_bytes();
let buf_reader = BufReader::new(input_bytes);
let parser = ical::IcalParser::new(buf_reader);
let mut output = vec![];
for calendar in parser {
match calendar {
Ok(c) => output.push(calendar_to_value(c, head)),
Err(e) => output.push(Value::error(
ShellError::UnsupportedInput {
msg: format!("input cannot be parsed as .ics ({e})"),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
},
span,
)),
}
}
Ok(Value::list(output, head))
}
}
pub fn examples() -> Vec<Example<'static>> {
vec![Example {
example: "'BEGIN:VCALENDAR
END:VCALENDAR' | from ics",
description: "Converts ics formatted string to table",
result: Some(Value::test_list(vec![Value::test_record(record! {
"properties" => Value::test_list(vec![]),
"events" => Value::test_list(vec![]),
"alarms" => Value::test_list(vec![]),
"to-Dos" => Value::test_list(vec![]),
"journals" => Value::test_list(vec![]),
"free-busys" => Value::test_list(vec![]),
"timezones" => Value::test_list(vec![]),
})])),
}]
}
fn calendar_to_value(calendar: IcalCalendar, span: Span) -> Value {
Value::record(
record! {
"properties" => properties_to_value(calendar.properties, span),
"events" => events_to_value(calendar.events, span),
"alarms" => alarms_to_value(calendar.alarms, span),
"to-Dos" => todos_to_value(calendar.todos, span),
"journals" => journals_to_value(calendar.journals, span),
"free-busys" => free_busys_to_value(calendar.free_busys, span),
"timezones" => timezones_to_value(calendar.timezones, span),
},
span,
)
}
fn events_to_value(events: Vec<IcalEvent>, span: Span) -> Value {
Value::list(
events
.into_iter()
.map(|event| {
Value::record(
record! {
"properties" => properties_to_value(event.properties, span),
"alarms" => alarms_to_value(event.alarms, span),
},
span,
)
})
.collect::<Vec<Value>>(),
span,
)
}
fn alarms_to_value(alarms: Vec<IcalAlarm>, span: Span) -> Value {
Value::list(
alarms
.into_iter()
.map(|alarm| {
Value::record(
record! { "properties" => properties_to_value(alarm.properties, span), },
span,
)
})
.collect::<Vec<Value>>(),
span,
)
}
fn todos_to_value(todos: Vec<IcalTodo>, span: Span) -> Value {
Value::list(
todos
.into_iter()
.map(|todo| {
Value::record(
record! {
"properties" => properties_to_value(todo.properties, span),
"alarms" => alarms_to_value(todo.alarms, span),
},
span,
)
})
.collect::<Vec<Value>>(),
span,
)
}
fn journals_to_value(journals: Vec<IcalJournal>, span: Span) -> Value {
Value::list(
journals
.into_iter()
.map(|journal| {
Value::record(
record! { "properties" => properties_to_value(journal.properties, span), },
span,
)
})
.collect::<Vec<Value>>(),
span,
)
}
fn free_busys_to_value(free_busys: Vec<IcalFreeBusy>, span: Span) -> Value {
Value::list(
free_busys
.into_iter()
.map(|free_busy| {
Value::record(
record! { "properties" => properties_to_value(free_busy.properties, span) },
span,
)
})
.collect::<Vec<Value>>(),
span,
)
}
fn timezones_to_value(timezones: Vec<IcalTimeZone>, span: Span) -> Value {
Value::list(
timezones
.into_iter()
.map(|timezone| {
Value::record(
record! {
"properties" => properties_to_value(timezone.properties, span),
"transitions" => timezone_transitions_to_value(timezone.transitions, span),
},
span,
)
})
.collect::<Vec<Value>>(),
span,
)
}
fn timezone_transitions_to_value(transitions: Vec<IcalTimeZoneTransition>, span: Span) -> Value {
Value::list(
transitions
.into_iter()
.map(|transition| {
Value::record(
record! { "properties" => properties_to_value(transition.properties, span) },
span,
)
})
.collect::<Vec<Value>>(),
span,
)
}
fn properties_to_value(properties: Vec<Property>, span: Span) -> Value {
Value::list(
properties
.into_iter()
.map(|prop| {
let name = Value::string(prop.name, span);
let value = match prop.value {
Some(val) => Value::string(val, span),
None => Value::nothing(span),
};
let params = match prop.params {
Some(param_list) => params_to_value(param_list, span),
None => Value::nothing(span),
};
Value::record(
record! {
"name" => name,
"value" => value,
"params" => params,
},
span,
)
})
.collect::<Vec<Value>>(),
span,
)
}
fn params_to_value(params: Vec<(String, Vec<String>)>, span: Span) -> Value {
let mut row = IndexMap::new();
for (param_name, param_values) in params {
let values: Vec<Value> = param_values
.into_iter()
.map(|val| Value::string(val, span))
.collect();
let values = Value::list(values, span);
row.insert(param_name, values);
}
Value::record(row.into_iter().collect(), span)
}
#[test]
fn test_examples() -> Result<(), nu_protocol::ShellError> {
use nu_plugin_test_support::PluginTest;
PluginTest::new("formats", crate::FormatCmdsPlugin.into())?.test_command_examples(&FromIcs)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/from/ini.rs | crates/nu_plugin_formats/src/from/ini.rs | use crate::FormatCmdsPlugin;
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{
Category, Example, LabeledError, Record, ShellError, Signature, Type, Value, record,
};
pub struct FromIni;
impl SimplePluginCommand for FromIni {
type Plugin = FormatCmdsPlugin;
fn name(&self) -> &str {
"from ini"
}
fn description(&self) -> &str {
"Parse text as .ini and create table."
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::String, Type::record())])
.category(Category::Formats)
}
fn examples(&self) -> Vec<Example<'_>> {
examples()
}
fn run(
&self,
_plugin: &FormatCmdsPlugin,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
let span = input.span();
let input_string = input.coerce_str()?;
let head = call.head;
let ini_config: Result<ini::Ini, ini::ParseError> = ini::Ini::load_from_str(&input_string);
match ini_config {
Ok(config) => {
let mut sections = Record::new();
for (section, properties) in config.iter() {
let mut section_record = Record::new();
// section's key value pairs
for (key, value) in properties.iter() {
section_record.push(key, Value::string(value, span));
}
let section_record = Value::record(section_record, span);
// section
match section {
Some(section_name) => {
sections.push(section_name, section_record);
}
None => {
// Section (None) allows for key value pairs without a section
if !properties.is_empty() {
sections.push(String::new(), section_record);
}
}
}
}
// all sections with all its key value pairs
Ok(Value::record(sections, span))
}
Err(err) => Err(ShellError::UnsupportedInput {
msg: format!("Could not load ini: {err}"),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
}
.into()),
}
}
}
pub fn examples() -> Vec<Example<'static>> {
vec![Example {
example: "'[foo]
a=1
b=2' | from ini",
description: "Converts ini formatted string to record",
result: Some(Value::test_record(record! {
"foo" => Value::test_record(record! {
"a" => Value::test_string("1"),
"b" => Value::test_string("2"),
}),
})),
}]
}
#[test]
fn test_examples() -> Result<(), nu_protocol::ShellError> {
use nu_plugin_test_support::PluginTest;
PluginTest::new("formats", crate::FormatCmdsPlugin.into())?.test_command_examples(&FromIni)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/from/mod.rs | crates/nu_plugin_formats/src/from/mod.rs | pub(crate) mod eml;
pub(crate) mod ics;
pub(crate) mod ini;
pub(crate) mod plist;
pub(crate) mod vcf;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/from/plist.rs | crates/nu_plugin_formats/src/from/plist.rs | use std::time::SystemTime;
use chrono::{DateTime, FixedOffset, Offset, Utc};
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand, SimplePluginCommand};
use nu_protocol::{
Category, Example, LabeledError, Record, Signature, Span, Value as NuValue, record,
};
use plist::{Date as PlistDate, Dictionary, Value as PlistValue};
use crate::FormatCmdsPlugin;
pub struct FromPlist;
impl SimplePluginCommand for FromPlist {
type Plugin = FormatCmdsPlugin;
fn name(&self) -> &str {
"from plist"
}
fn description(&self) -> &str {
"Convert plist to Nushell values"
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
example: r#"'<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>a</key>
<integer>3</integer>
</dict>
</plist>' | from plist"#,
description: "Convert a table into a plist file",
result: Some(NuValue::test_record(record!( "a" => NuValue::test_int(3)))),
}]
}
fn signature(&self) -> Signature {
Signature::build(PluginCommand::name(self)).category(Category::Formats)
}
fn run(
&self,
_plugin: &FormatCmdsPlugin,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &NuValue,
) -> Result<NuValue, LabeledError> {
match input {
NuValue::String { val, .. } => {
let plist = plist::from_bytes(val.as_bytes())
.map_err(|e| build_label_error(format!("{e}"), input.span()))?;
let converted = convert_plist_value(&plist, call.head)?;
Ok(converted)
}
NuValue::Binary { val, .. } => {
let plist = plist::from_bytes(val)
.map_err(|e| build_label_error(format!("{e}"), input.span()))?;
let converted = convert_plist_value(&plist, call.head)?;
Ok(converted)
}
_ => Err(build_label_error(
format!("Invalid input, must be string not: {input:?}"),
call.head,
)),
}
}
}
fn build_label_error(msg: impl Into<String>, span: Span) -> LabeledError {
LabeledError::new("Could not load plist").with_label(msg, span)
}
fn convert_plist_value(plist_val: &PlistValue, span: Span) -> Result<NuValue, LabeledError> {
match plist_val {
PlistValue::String(s) => Ok(NuValue::string(s.to_owned(), span)),
PlistValue::Boolean(b) => Ok(NuValue::bool(*b, span)),
PlistValue::Real(r) => Ok(NuValue::float(*r, span)),
PlistValue::Date(d) => Ok(NuValue::date(convert_date(d), span)),
PlistValue::Integer(i) => {
let signed = i
.as_signed()
.ok_or_else(|| build_label_error(format!("Cannot convert {i} to i64"), span))?;
Ok(NuValue::int(signed, span))
}
PlistValue::Uid(uid) => Ok(NuValue::float(uid.get() as f64, span)),
PlistValue::Data(data) => Ok(NuValue::binary(data.to_owned(), span)),
PlistValue::Array(arr) => Ok(NuValue::list(convert_array(arr, span)?, span)),
PlistValue::Dictionary(dict) => Ok(convert_dict(dict, span)?),
_ => Ok(NuValue::nothing(span)),
}
}
fn convert_dict(dict: &Dictionary, span: Span) -> Result<NuValue, LabeledError> {
let cols: Vec<String> = dict.keys().cloned().collect();
let vals: Result<Vec<NuValue>, LabeledError> = dict
.values()
.map(|v| convert_plist_value(v, span))
.collect();
Ok(NuValue::record(
Record::from_raw_cols_vals(cols, vals?, span, span)?,
span,
))
}
fn convert_array(plist_array: &[PlistValue], span: Span) -> Result<Vec<NuValue>, LabeledError> {
plist_array
.iter()
.map(|v| convert_plist_value(v, span))
.collect()
}
pub fn convert_date(plist_date: &PlistDate) -> DateTime<FixedOffset> {
// In the docs the plist date object is listed as a utc timestamp, so this
// conversion should be fine
let plist_sys_time: SystemTime = plist_date.to_owned().into();
let utc_date: DateTime<Utc> = plist_sys_time.into();
let utc_offset = utc_date.offset().fix();
utc_date.with_timezone(&utc_offset)
}
#[cfg(test)]
mod test {
use super::*;
use chrono::Datelike;
use plist::Uid;
use std::time::SystemTime;
use nu_plugin_test_support::PluginTest;
use nu_protocol::ShellError;
#[test]
fn test_convert_string() {
let plist_val = PlistValue::String("hello".to_owned());
let result = convert_plist_value(&plist_val, Span::test_data());
assert_eq!(
result,
Ok(NuValue::string("hello".to_owned(), Span::test_data()))
);
}
#[test]
fn test_convert_boolean() {
let plist_val = PlistValue::Boolean(true);
let result = convert_plist_value(&plist_val, Span::test_data());
assert_eq!(result, Ok(NuValue::bool(true, Span::test_data())));
}
#[test]
fn test_convert_real() {
let plist_val = PlistValue::Real(3.5);
let result = convert_plist_value(&plist_val, Span::test_data());
assert_eq!(result, Ok(NuValue::float(3.5, Span::test_data())));
}
#[test]
fn test_convert_integer() {
let plist_val = PlistValue::Integer(42.into());
let result = convert_plist_value(&plist_val, Span::test_data());
assert_eq!(result, Ok(NuValue::int(42, Span::test_data())));
}
#[test]
fn test_convert_uid() {
let v = 12345678_u64;
let uid = Uid::new(v);
let plist_val = PlistValue::Uid(uid);
let result = convert_plist_value(&plist_val, Span::test_data());
assert_eq!(result, Ok(NuValue::float(v as f64, Span::test_data())));
}
#[test]
fn test_convert_data() {
let data = vec![0x41, 0x42, 0x43];
let plist_val = PlistValue::Data(data.clone());
let result = convert_plist_value(&plist_val, Span::test_data());
assert_eq!(result, Ok(NuValue::binary(data, Span::test_data())));
}
#[test]
fn test_convert_date() {
let epoch = SystemTime::UNIX_EPOCH;
let plist_date = epoch.into();
let datetime = convert_date(&plist_date);
assert_eq!(1970, datetime.year());
assert_eq!(1, datetime.month());
assert_eq!(1, datetime.day());
}
#[test]
fn test_convert_dict() {
let mut dict = Dictionary::new();
dict.insert("a".to_string(), PlistValue::String("c".to_string()));
dict.insert("b".to_string(), PlistValue::String("d".to_string()));
let nu_dict = convert_dict(&dict, Span::test_data()).unwrap();
assert_eq!(
nu_dict,
NuValue::record(
Record::from_raw_cols_vals(
vec!["a".to_string(), "b".to_string()],
vec![
NuValue::string("c".to_string(), Span::test_data()),
NuValue::string("d".to_string(), Span::test_data())
],
Span::test_data(),
Span::test_data(),
)
.expect("failed to create record"),
Span::test_data(),
)
);
}
#[test]
fn test_convert_array() {
let arr = vec![
PlistValue::String("a".into()),
PlistValue::String("b".into()),
];
let nu_arr = convert_array(&arr, Span::test_data()).unwrap();
assert_eq!(
nu_arr,
vec![
NuValue::string("a".to_string(), Span::test_data()),
NuValue::string("b".to_string(), Span::test_data())
]
);
}
#[test]
fn test_examples() -> Result<(), ShellError> {
let plugin = FormatCmdsPlugin {};
let cmd = FromPlist {};
let mut plugin_test = PluginTest::new("polars", plugin.into())?;
plugin_test.test_command_examples(&cmd)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/from/eml.rs | crates/nu_plugin_formats/src/from/eml.rs | use crate::FormatCmdsPlugin;
use eml_parser::EmlParser;
use eml_parser::eml::*;
use indexmap::IndexMap;
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{
Category, Example, LabeledError, ShellError, Signature, Span, SyntaxShape, Type, Value, record,
};
const DEFAULT_BODY_PREVIEW: usize = 50;
pub struct FromEml;
impl SimplePluginCommand for FromEml {
type Plugin = FormatCmdsPlugin;
fn name(&self) -> &str {
"from eml"
}
fn description(&self) -> &str {
"Parse text as .eml and create record."
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::String, Type::record())])
.named(
"preview-body",
SyntaxShape::Int,
"How many bytes of the body to preview",
Some('b'),
)
.category(Category::Formats)
}
fn examples(&self) -> Vec<Example<'_>> {
examples()
}
fn run(
&self,
_plugin: &FormatCmdsPlugin,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
let preview_body: usize = call
.get_flag::<i64>("preview-body")?
.map(|l| if l < 0 { 0 } else { l as usize })
.unwrap_or(DEFAULT_BODY_PREVIEW);
from_eml(input, preview_body, call.head)
}
}
pub fn examples() -> Vec<Example<'static>> {
vec![
Example {
description: "Convert eml structured data into record",
example: "'From: test@email.com
Subject: Welcome
To: someone@somewhere.com
Test' | from eml",
result: Some(Value::test_record(record! {
"Subject" => Value::test_string("Welcome"),
"From" => Value::test_record(record! {
"Name" => Value::nothing(Span::test_data()),
"Address" => Value::test_string("test@email.com"),
}),
"To" => Value::test_record(record! {
"Name" => Value::nothing(Span::test_data()),
"Address" => Value::test_string("someone@somewhere.com"),
}),
"Body" => Value::test_string("Test"),
})),
},
Example {
description: "Convert eml structured data into record",
example: "'From: test@email.com
Subject: Welcome
To: someone@somewhere.com
Test' | from eml -b 1",
result: Some(Value::test_record(record! {
"Subject" => Value::test_string("Welcome"),
"From" => Value::test_record(record! {
"Name" => Value::nothing(Span::test_data()),
"Address" => Value::test_string("test@email.com"),
}),
"To" => Value::test_record(record! {
"Name" => Value::nothing(Span::test_data()),
"Address" => Value::test_string("someone@somewhere.com"),
}),
"Body" => Value::test_string("T"),
})),
},
]
}
fn emailaddress_to_value(span: Span, email_address: &EmailAddress) -> Value {
let (n, a) = match email_address {
EmailAddress::AddressOnly { address } => {
(Value::nothing(span), Value::string(address, span))
}
EmailAddress::NameAndEmailAddress { name, address } => {
(Value::string(name, span), Value::string(address, span))
}
};
Value::record(
record! {
"Name" => n,
"Address" => a,
},
span,
)
}
fn headerfieldvalue_to_value(head: Span, value: &HeaderFieldValue) -> Value {
use HeaderFieldValue::*;
match value {
SingleEmailAddress(address) => emailaddress_to_value(head, address),
MultipleEmailAddresses(addresses) => Value::list(
addresses
.iter()
.map(|a| emailaddress_to_value(head, a))
.collect(),
head,
),
Unstructured(s) => Value::string(s, head),
Empty => Value::nothing(head),
}
}
fn from_eml(input: &Value, body_preview: usize, head: Span) -> Result<Value, LabeledError> {
let value = input.coerce_string()?;
let eml = EmlParser::from_string(value)
.with_body_preview(body_preview)
.parse()
.map_err(|_| ShellError::CantConvert {
to_type: "structured eml data".into(),
from_type: "string".into(),
span: head,
help: None,
})?;
let mut collected = IndexMap::new();
if let Some(subj) = eml.subject {
collected.insert("Subject".to_string(), Value::string(subj, head));
}
if let Some(from) = eml.from {
collected.insert("From".to_string(), headerfieldvalue_to_value(head, &from));
}
if let Some(to) = eml.to {
collected.insert("To".to_string(), headerfieldvalue_to_value(head, &to));
}
for HeaderField { name, value } in &eml.headers {
collected.insert(name.to_string(), headerfieldvalue_to_value(head, value));
}
if let Some(body) = eml.body {
collected.insert("Body".to_string(), Value::string(body, head));
}
Ok(Value::record(collected.into_iter().collect(), head))
}
#[test]
fn test_examples() -> Result<(), nu_protocol::ShellError> {
use nu_plugin_test_support::PluginTest;
PluginTest::new("formats", crate::FormatCmdsPlugin.into())?.test_command_examples(&FromEml)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/to/mod.rs | crates/nu_plugin_formats/src/to/mod.rs | pub(crate) mod plist;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_formats/src/to/plist.rs | crates/nu_plugin_formats/src/to/plist.rs | use crate::FormatCmdsPlugin;
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand, SimplePluginCommand};
use nu_protocol::{Category, Example, LabeledError, Record, Signature, Span, Value as NuValue};
use plist::Value as PlistValue;
use std::time::SystemTime;
pub(crate) struct IntoPlist;
impl SimplePluginCommand for IntoPlist {
type Plugin = FormatCmdsPlugin;
fn name(&self) -> &str {
"to plist"
}
fn description(&self) -> &str {
"Convert Nu values into plist"
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
example: "{ a: 3 } | to plist",
description: "Convert a table into a plist file",
result: None,
}]
}
fn signature(&self) -> Signature {
Signature::build(PluginCommand::name(self))
.switch("binary", "Output plist in binary format", Some('b'))
.category(Category::Formats)
}
fn run(
&self,
_plugin: &FormatCmdsPlugin,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &NuValue,
) -> Result<NuValue, LabeledError> {
let plist_val = convert_nu_value(input)?;
let mut out = Vec::new();
if call.has_flag("binary")? {
plist::to_writer_binary(&mut out, &plist_val)
.map_err(|e| build_label_error(format!("{e}"), input.span()))?;
Ok(NuValue::binary(out, input.span()))
} else {
plist::to_writer_xml(&mut out, &plist_val)
.map_err(|e| build_label_error(format!("{e}"), input.span()))?;
Ok(NuValue::string(
String::from_utf8(out)
.map_err(|e| build_label_error(format!("{e}"), input.span()))?,
input.span(),
))
}
}
}
fn build_label_error(msg: String, span: Span) -> LabeledError {
LabeledError::new("Cannot convert plist").with_label(msg, span)
}
fn convert_nu_value(nu_val: &NuValue) -> Result<PlistValue, LabeledError> {
let span = Span::test_data();
match nu_val {
NuValue::String { val, .. } => Ok(PlistValue::String(val.to_owned())),
NuValue::Bool { val, .. } => Ok(PlistValue::Boolean(*val)),
NuValue::Float { val, .. } => Ok(PlistValue::Real(*val)),
NuValue::Int { val, .. } => Ok(PlistValue::Integer((*val).into())),
NuValue::Binary { val, .. } => Ok(PlistValue::Data(val.to_owned())),
NuValue::Record { val, .. } => convert_nu_dict(val),
NuValue::List { vals, .. } => Ok(PlistValue::Array(
vals.iter()
.map(convert_nu_value)
.collect::<Result<_, _>>()?,
)),
NuValue::Date { val, .. } => Ok(PlistValue::Date(SystemTime::from(val.to_owned()).into())),
NuValue::Filesize { val, .. } => Ok(PlistValue::Integer(val.get().into())),
_ => Err(build_label_error(
format!("{nu_val:?} is not convertible"),
span,
)),
}
}
fn convert_nu_dict(record: &Record) -> Result<PlistValue, LabeledError> {
Ok(PlistValue::Dictionary(
record
.iter()
.map(|(k, v)| convert_nu_value(v).map(|v| (k.to_owned(), v)))
.collect::<Result<_, _>>()?,
))
}
#[cfg(test)]
mod test {
use nu_plugin_test_support::PluginTest;
use nu_protocol::ShellError;
use super::*;
#[test]
fn test_examples() -> Result<(), ShellError> {
let plugin = FormatCmdsPlugin {};
let cmd = IntoPlist {};
let mut plugin_test = PluginTest::new("polars", plugin.into())?;
plugin_test.test_command_examples(&cmd)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/config_files.rs | crates/nu-cli/src/config_files.rs | use crate::util::eval_source;
#[cfg(feature = "plugin")]
use nu_path::canonicalize_with;
#[cfg(feature = "plugin")]
use nu_protocol::{ParseError, PluginRegistryFile, Spanned, engine::StateWorkingSet};
use nu_protocol::{
PipelineData,
engine::{EngineState, Stack},
report_shell_error,
};
#[cfg(feature = "plugin")]
use nu_utils::perf;
use std::path::PathBuf;
#[cfg(feature = "plugin")]
const PLUGIN_FILE: &str = "plugin.msgpackz";
#[cfg(feature = "plugin")]
const OLD_PLUGIN_FILE: &str = "plugin.nu";
#[cfg(feature = "plugin")]
pub fn read_plugin_file(engine_state: &mut EngineState, plugin_file: Option<Spanned<String>>) {
use nu_protocol::{ShellError, shell_error::io::IoError};
use std::path::Path;
let span = plugin_file.as_ref().map(|s| s.span);
// Check and warn + abort if this is a .nu plugin file
if plugin_file
.as_ref()
.and_then(|p| Path::new(&p.item).extension())
.is_some_and(|ext| ext == "nu")
{
report_shell_error(
None,
engine_state,
&ShellError::GenericError {
error: "Wrong plugin file format".into(),
msg: ".nu plugin files are no longer supported".into(),
span,
help: Some("please recreate this file in the new .msgpackz format".into()),
inner: vec![],
},
);
return;
}
let mut start_time = std::time::Instant::now();
// Reading signatures from plugin registry file
// The plugin.msgpackz file stores the parsed signature collected from each registered plugin
add_plugin_file(engine_state, plugin_file.clone());
perf!(
"add plugin file to engine_state",
start_time,
engine_state
.get_config()
.use_ansi_coloring
.get(engine_state)
);
start_time = std::time::Instant::now();
let plugin_path = engine_state.plugin_path.clone();
if let Some(plugin_path) = plugin_path {
// Open the plugin file
let mut file = match std::fs::File::open(&plugin_path) {
Ok(file) => file,
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
log::warn!("Plugin file not found: {}", plugin_path.display());
// Try migration of an old plugin file if this wasn't a custom plugin file
if plugin_file.is_none() && migrate_old_plugin_file(engine_state) {
let Ok(file) = std::fs::File::open(&plugin_path) else {
log::warn!("Failed to load newly migrated plugin file");
return;
};
file
} else {
return;
}
} else {
report_shell_error(
None,
engine_state,
&ShellError::Io(IoError::new_internal_with_path(
err,
"Could not open plugin registry file",
nu_protocol::location!(),
plugin_path,
)),
);
return;
}
}
};
// Abort if the file is empty.
if file.metadata().is_ok_and(|m| m.len() == 0) {
log::warn!(
"Not reading plugin file because it's empty: {}",
plugin_path.display()
);
return;
}
// Read the contents of the plugin file
let contents = match PluginRegistryFile::read_from(&mut file, span) {
Ok(contents) => contents,
Err(err) => {
log::warn!("Failed to read plugin registry file: {err:?}");
report_shell_error(
None,
engine_state,
&ShellError::GenericError {
error: format!(
"Error while reading plugin registry file: {}",
plugin_path.display()
),
msg: "plugin path defined here".into(),
span,
help: Some(
"you might try deleting the file and registering all of your \
plugins again"
.into(),
),
inner: vec![],
},
);
return;
}
};
perf!(
&format!("read plugin file {}", plugin_path.display()),
start_time,
engine_state
.get_config()
.use_ansi_coloring
.get(engine_state)
);
start_time = std::time::Instant::now();
let mut working_set = StateWorkingSet::new(engine_state);
nu_plugin_engine::load_plugin_file(&mut working_set, &contents, span);
if let Err(err) = engine_state.merge_delta(working_set.render()) {
report_shell_error(None, engine_state, &err);
return;
}
perf!(
&format!("load plugin file {}", plugin_path.display()),
start_time,
engine_state
.get_config()
.use_ansi_coloring
.get(engine_state)
);
}
}
#[cfg(feature = "plugin")]
pub fn add_plugin_file(engine_state: &mut EngineState, plugin_file: Option<Spanned<String>>) {
use std::path::Path;
use nu_protocol::report_parse_error;
if let Ok(cwd) = engine_state.cwd_as_string(None) {
if let Some(plugin_file) = plugin_file {
let path = Path::new(&plugin_file.item);
let path_dir = path.parent().unwrap_or(path);
// Just try to canonicalize the directory of the plugin file first.
if let Ok(path_dir) = canonicalize_with(path_dir, &cwd) {
// Try to canonicalize the actual filename, but it's ok if that fails. The file doesn't
// have to exist.
let path = path_dir.join(path.file_name().unwrap_or(path.as_os_str()));
let path = canonicalize_with(&path, &cwd).unwrap_or(path);
engine_state.plugin_path = Some(path)
} else {
// It's an error if the directory for the plugin file doesn't exist.
report_parse_error(
None,
&StateWorkingSet::new(engine_state),
&ParseError::FileNotFound(
path_dir.to_string_lossy().into_owned(),
plugin_file.span,
),
);
}
} else if let Some(plugin_path) = nu_path::nu_config_dir() {
// Path to store plugins signatures
let mut plugin_path =
canonicalize_with(&plugin_path, &cwd).unwrap_or(plugin_path.into());
plugin_path.push(PLUGIN_FILE);
let plugin_path = canonicalize_with(&plugin_path, &cwd).unwrap_or(plugin_path);
engine_state.plugin_path = Some(plugin_path);
}
}
}
pub fn eval_config_contents(
config_path: PathBuf,
engine_state: &mut EngineState,
stack: &mut Stack,
strict_mode: bool,
) {
if config_path.exists() & config_path.is_file() {
let config_filename = config_path.to_string_lossy();
if let Ok(contents) = std::fs::read(&config_path) {
// Set the current active file to the config file.
let prev_file = engine_state.file.take();
engine_state.file = Some(config_path.clone());
// TODO: ignore this error?
let exit_code = eval_source(
engine_state,
stack,
&contents,
&config_filename,
PipelineData::empty(),
false,
);
if exit_code != 0 && strict_mode {
std::process::exit(exit_code)
}
// Restore the current active file.
engine_state.file = prev_file;
// Merge the environment in case env vars changed in the config
if let Err(e) = engine_state.merge_env(stack) {
report_shell_error(Some(stack), engine_state, &e);
}
}
}
}
#[cfg(feature = "plugin")]
pub fn migrate_old_plugin_file(engine_state: &EngineState) -> bool {
use nu_protocol::{
PluginExample, PluginIdentity, PluginRegistryItem, PluginRegistryItemData, PluginSignature,
ShellError, shell_error::io::IoError,
};
use std::collections::BTreeMap;
let start_time = std::time::Instant::now();
let Ok(cwd) = engine_state.cwd_as_string(None) else {
return false;
};
let Some(config_dir) =
nu_path::nu_config_dir().and_then(|dir| nu_path::canonicalize_with(dir, &cwd).ok())
else {
return false;
};
let Ok(old_plugin_file_path) = nu_path::canonicalize_with(OLD_PLUGIN_FILE, &config_dir) else {
return false;
};
let old_contents = match std::fs::read(&old_plugin_file_path) {
Ok(old_contents) => old_contents,
Err(err) => {
report_shell_error(
None,
engine_state,
&ShellError::GenericError {
error: "Can't read old plugin file to migrate".into(),
msg: "".into(),
span: None,
help: Some(err.to_string()),
inner: vec![],
},
);
return false;
}
};
// Make a copy of the engine state, because we'll read the newly generated file
let mut engine_state = engine_state.clone();
let mut stack = Stack::new();
if eval_source(
&mut engine_state,
&mut stack,
&old_contents,
&old_plugin_file_path.to_string_lossy(),
PipelineData::empty(),
false,
) != 0
{
return false;
}
// Now that the plugin commands are loaded, we just have to generate the file
let mut contents = PluginRegistryFile::new();
let mut groups = BTreeMap::<PluginIdentity, Vec<PluginSignature>>::new();
for decl in engine_state.plugin_decls() {
if let Some(identity) = decl.plugin_identity() {
groups
.entry(identity.clone())
.or_default()
.push(PluginSignature {
sig: decl.signature(),
examples: decl
.examples()
.into_iter()
.map(PluginExample::from)
.collect(),
})
}
}
for (identity, commands) in groups {
contents.upsert_plugin(PluginRegistryItem {
name: identity.name().to_owned(),
filename: identity.filename().to_owned(),
shell: identity.shell().map(|p| p.to_owned()),
data: PluginRegistryItemData::Valid {
metadata: Default::default(),
commands,
},
});
}
// Write the new file
let new_plugin_file_path = config_dir.join(PLUGIN_FILE);
if let Err(err) = std::fs::File::create(&new_plugin_file_path)
.map_err(|err| {
IoError::new_internal_with_path(
err,
"Could not create new plugin file",
nu_protocol::location!(),
new_plugin_file_path.clone(),
)
})
.map_err(ShellError::from)
.and_then(|file| contents.write_to(file, None))
{
report_shell_error(
None,
&engine_state,
&ShellError::GenericError {
error: "Failed to save migrated plugin file".into(),
msg: "".into(),
span: None,
help: Some("ensure `$nu.plugin-path` is writable".into()),
inner: vec![err],
},
);
return false;
}
if engine_state.is_interactive {
eprintln!(
"Your old plugin.nu file has been migrated to the new format: {}",
new_plugin_file_path.display()
);
eprintln!(
"The plugin.nu file has not been removed. If `plugin list` looks okay, \
you may do so manually."
);
}
perf!(
"migrate old plugin file",
start_time,
engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
true
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/prompt_update.rs | crates/nu-cli/src/prompt_update.rs | use crate::NushellPrompt;
use log::{trace, warn};
use nu_engine::ClosureEvalOnce;
use nu_protocol::{
Config, PipelineData, Value,
engine::{EngineState, Stack},
report_shell_error,
};
use reedline::Prompt;
// Name of environment variable where the prompt could be stored
pub(crate) const PROMPT_COMMAND: &str = "PROMPT_COMMAND";
pub(crate) const PROMPT_COMMAND_RIGHT: &str = "PROMPT_COMMAND_RIGHT";
pub(crate) const PROMPT_INDICATOR: &str = "PROMPT_INDICATOR";
pub(crate) const PROMPT_INDICATOR_VI_INSERT: &str = "PROMPT_INDICATOR_VI_INSERT";
pub(crate) const PROMPT_INDICATOR_VI_NORMAL: &str = "PROMPT_INDICATOR_VI_NORMAL";
pub(crate) const PROMPT_MULTILINE_INDICATOR: &str = "PROMPT_MULTILINE_INDICATOR";
pub(crate) const TRANSIENT_PROMPT_COMMAND: &str = "TRANSIENT_PROMPT_COMMAND";
pub(crate) const TRANSIENT_PROMPT_COMMAND_RIGHT: &str = "TRANSIENT_PROMPT_COMMAND_RIGHT";
pub(crate) const TRANSIENT_PROMPT_INDICATOR: &str = "TRANSIENT_PROMPT_INDICATOR";
pub(crate) const TRANSIENT_PROMPT_INDICATOR_VI_INSERT: &str =
"TRANSIENT_PROMPT_INDICATOR_VI_INSERT";
pub(crate) const TRANSIENT_PROMPT_INDICATOR_VI_NORMAL: &str =
"TRANSIENT_PROMPT_INDICATOR_VI_NORMAL";
pub(crate) const TRANSIENT_PROMPT_MULTILINE_INDICATOR: &str =
"TRANSIENT_PROMPT_MULTILINE_INDICATOR";
// Store all these Ansi Escape Markers here so they can be reused easily
// According to Daniel Imms @Tyriar, we need to do these this way:
// <133 A><prompt><133 B><command><133 C><command output>
pub(crate) const PRE_PROMPT_MARKER: &str = "\x1b]133;A\x1b\\";
pub(crate) const POST_PROMPT_MARKER: &str = "\x1b]133;B\x1b\\";
pub(crate) const PRE_EXECUTION_MARKER: &str = "\x1b]133;C\x1b\\";
pub(crate) const POST_EXECUTION_MARKER_PREFIX: &str = "\x1b]133;D;";
pub(crate) const POST_EXECUTION_MARKER_SUFFIX: &str = "\x1b\\";
// OSC633 is the same as OSC133 but specifically for VSCode
pub(crate) const VSCODE_PRE_PROMPT_MARKER: &str = "\x1b]633;A\x1b\\";
pub(crate) const VSCODE_POST_PROMPT_MARKER: &str = "\x1b]633;B\x1b\\";
pub(crate) const VSCODE_PRE_EXECUTION_MARKER: &str = "\x1b]633;C\x1b\\";
//"\x1b]633;D;{}\x1b\\"
pub(crate) const VSCODE_POST_EXECUTION_MARKER_PREFIX: &str = "\x1b]633;D;";
pub(crate) const VSCODE_POST_EXECUTION_MARKER_SUFFIX: &str = "\x1b\\";
//"\x1b]633;E;{}\x1b\\"
pub(crate) const VSCODE_COMMANDLINE_MARKER_PREFIX: &str = "\x1b]633;E;";
pub(crate) const VSCODE_COMMANDLINE_MARKER_SUFFIX: &str = "\x1b\\";
// "\x1b]633;P;Cwd={}\x1b\\"
pub(crate) const VSCODE_CWD_PROPERTY_MARKER_PREFIX: &str = "\x1b]633;P;Cwd=";
pub(crate) const VSCODE_CWD_PROPERTY_MARKER_SUFFIX: &str = "\x1b\\";
pub(crate) const RESET_APPLICATION_MODE: &str = "\x1b[?1l";
fn get_prompt_string(
prompt: &str,
config: &Config,
engine_state: &EngineState,
stack: &mut Stack,
) -> Option<String> {
stack
.get_env_var(engine_state, prompt)
.and_then(|v| match v {
Value::Closure { val, .. } => {
let result = ClosureEvalOnce::new(engine_state, stack, val.as_ref().clone())
.run_with_input(PipelineData::empty());
trace!(
"get_prompt_string (block) {}:{}:{}",
file!(),
line!(),
column!()
);
result
.map_err(|err| {
report_shell_error(None, engine_state, &err);
})
.ok()
}
Value::String { .. } => Some(PipelineData::value(v.clone(), None)),
_ => None,
})
.and_then(|pipeline_data| {
let output = pipeline_data.collect_string("", config).ok();
let ansi_output = output.map(|mut x| {
// Always reset the color at the start of the right prompt
// to ensure there is no ansi bleed over
if x.is_empty() && prompt == PROMPT_COMMAND_RIGHT {
x.insert_str(0, "\x1b[0m")
};
x
});
// Let's keep this for debugging purposes with nu --log-level warn
warn!("{}:{}:{} {:?}", file!(), line!(), column!(), ansi_output);
ansi_output
})
}
pub(crate) fn update_prompt(
config: &Config,
engine_state: &EngineState,
stack: &mut Stack,
nu_prompt: &mut NushellPrompt,
) {
let configured_left_prompt_string =
match get_prompt_string(PROMPT_COMMAND, config, engine_state, stack) {
Some(s) => s,
None => "".to_string(),
};
// Now that we have the prompt string lets ansify it.
// <133 A><prompt><133 B><command><133 C><command output>
let left_prompt_string = if config.shell_integration.osc633 {
if stack
.get_env_var(engine_state, "TERM_PROGRAM")
.and_then(|v| v.as_str().ok())
== Some("vscode")
{
// We're in vscode and we have osc633 enabled
Some(format!(
"{VSCODE_PRE_PROMPT_MARKER}{configured_left_prompt_string}{VSCODE_POST_PROMPT_MARKER}"
))
} else if config.shell_integration.osc133 {
// If we're in VSCode but we don't find the env var, but we have osc133 set, then use it
Some(format!(
"{PRE_PROMPT_MARKER}{configured_left_prompt_string}{POST_PROMPT_MARKER}"
))
} else {
configured_left_prompt_string.into()
}
} else if config.shell_integration.osc133 {
Some(format!(
"{PRE_PROMPT_MARKER}{configured_left_prompt_string}{POST_PROMPT_MARKER}"
))
} else {
configured_left_prompt_string.into()
};
let right_prompt_string = get_prompt_string(PROMPT_COMMAND_RIGHT, config, engine_state, stack);
let prompt_indicator_string = get_prompt_string(PROMPT_INDICATOR, config, engine_state, stack);
let prompt_multiline_string =
get_prompt_string(PROMPT_MULTILINE_INDICATOR, config, engine_state, stack);
let prompt_vi_insert_string =
get_prompt_string(PROMPT_INDICATOR_VI_INSERT, config, engine_state, stack);
let prompt_vi_normal_string =
get_prompt_string(PROMPT_INDICATOR_VI_NORMAL, config, engine_state, stack);
// apply the other indicators
nu_prompt.update_all_prompt_strings(
left_prompt_string,
right_prompt_string,
prompt_indicator_string,
prompt_multiline_string,
(prompt_vi_insert_string, prompt_vi_normal_string),
config.render_right_prompt_on_last_line,
);
trace!("update_prompt {}:{}:{}", file!(), line!(), column!());
}
/// Construct the transient prompt based on the normal nu_prompt
pub(crate) fn make_transient_prompt(
config: &Config,
engine_state: &EngineState,
stack: &mut Stack,
nu_prompt: &NushellPrompt,
) -> Box<dyn Prompt> {
let mut nu_prompt = nu_prompt.clone();
if let Some(s) = get_prompt_string(TRANSIENT_PROMPT_COMMAND, config, engine_state, stack) {
nu_prompt.update_prompt_left(Some(s))
}
if let Some(s) = get_prompt_string(TRANSIENT_PROMPT_COMMAND_RIGHT, config, engine_state, stack)
{
nu_prompt.update_prompt_right(Some(s), config.render_right_prompt_on_last_line)
}
if let Some(s) = get_prompt_string(TRANSIENT_PROMPT_INDICATOR, config, engine_state, stack) {
nu_prompt.update_prompt_indicator(Some(s))
}
if let Some(s) = get_prompt_string(
TRANSIENT_PROMPT_INDICATOR_VI_INSERT,
config,
engine_state,
stack,
) {
nu_prompt.update_prompt_vi_insert(Some(s))
}
if let Some(s) = get_prompt_string(
TRANSIENT_PROMPT_INDICATOR_VI_NORMAL,
config,
engine_state,
stack,
) {
nu_prompt.update_prompt_vi_normal(Some(s))
}
if let Some(s) = get_prompt_string(
TRANSIENT_PROMPT_MULTILINE_INDICATOR,
config,
engine_state,
stack,
) {
nu_prompt.update_prompt_multiline(Some(s))
}
Box::new(nu_prompt)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/lib.rs | crates/nu-cli/src/lib.rs | #![doc = include_str!("../README.md")]
mod commands;
mod completions;
mod config_files;
mod eval_cmds;
mod eval_file;
mod menus;
mod nu_highlight;
mod print;
mod prompt;
mod prompt_update;
mod reedline_config;
mod repl;
mod syntax_highlight;
mod util;
mod validation;
pub use commands::add_cli_context;
pub use completions::{FileCompletion, NuCompleter, SemanticSuggestion, SuggestionKind};
pub use config_files::eval_config_contents;
pub use eval_cmds::{EvaluateCommandsOpts, evaluate_commands};
pub use eval_file::evaluate_file;
pub use menus::NuHelpCompleter;
pub use nu_highlight::NuHighlight;
pub use print::Print;
pub use prompt::NushellPrompt;
pub use repl::evaluate_repl;
pub use syntax_highlight::NuHighlighter;
pub use util::{eval_source, gather_parent_env_vars};
pub use validation::NuValidator;
#[cfg(feature = "plugin")]
pub use config_files::add_plugin_file;
#[cfg(feature = "plugin")]
pub use config_files::migrate_old_plugin_file;
#[cfg(feature = "plugin")]
pub use config_files::read_plugin_file;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/repl.rs | crates/nu-cli/src/repl.rs | use crate::prompt_update::{
POST_EXECUTION_MARKER_PREFIX, POST_EXECUTION_MARKER_SUFFIX, PRE_EXECUTION_MARKER,
RESET_APPLICATION_MODE, VSCODE_COMMANDLINE_MARKER_PREFIX, VSCODE_COMMANDLINE_MARKER_SUFFIX,
VSCODE_CWD_PROPERTY_MARKER_PREFIX, VSCODE_CWD_PROPERTY_MARKER_SUFFIX,
VSCODE_POST_EXECUTION_MARKER_PREFIX, VSCODE_POST_EXECUTION_MARKER_SUFFIX,
VSCODE_PRE_EXECUTION_MARKER,
};
use crate::{
NuHighlighter, NuValidator, NushellPrompt,
completions::NuCompleter,
nu_highlight::NoOpHighlighter,
prompt_update,
reedline_config::{KeybindingsMode, add_menus, create_keybindings},
util::eval_source,
};
use crossterm::cursor::SetCursorStyle;
use log::{error, trace, warn};
use miette::{ErrReport, IntoDiagnostic, Result};
use nu_cmd_base::util::get_editor;
use nu_color_config::StyleComputer;
#[allow(deprecated)]
use nu_engine::env_to_strings;
use nu_engine::exit::cleanup_exit;
use nu_parser::{lex, parse, trim_quotes_str};
use nu_protocol::shell_error::io::IoError;
use nu_protocol::{BannerKind, shell_error};
use nu_protocol::{
HistoryConfig, HistoryFileFormat, PipelineData, ShellError, Span, Spanned, Value,
config::NuCursorShape,
engine::{EngineState, Stack, StateWorkingSet},
report_shell_error,
};
use nu_utils::{
filesystem::{PermissionResult, have_permission},
perf,
};
#[cfg(feature = "sqlite")]
use reedline::SqliteBackedHistory;
use reedline::{
CursorConfig, CwdAwareHinter, DefaultCompleter, EditCommand, Emacs, FileBackedHistory,
HistorySessionId, Reedline, Vi,
};
use std::sync::atomic::Ordering;
use std::{
collections::HashMap,
env::temp_dir,
io::{self, IsTerminal, Write},
panic::{AssertUnwindSafe, catch_unwind},
path::{Path, PathBuf},
sync::Arc,
time::{Duration, Instant},
};
use sysinfo::System;
/// The main REPL loop, including spinning up the prompt itself.
pub fn evaluate_repl(
engine_state: &mut EngineState,
stack: Stack,
prerun_command: Option<Spanned<String>>,
load_std_lib: Option<Spanned<String>>,
entire_start_time: Instant,
) -> Result<()> {
// throughout this code, we hold this stack uniquely.
// During the main REPL loop, we hand ownership of this value to an Arc,
// so that it may be read by various reedline plugins. During this, we
// can't modify the stack, but at the end of the loop we take back ownership
// from the Arc. This lets us avoid copying stack variables needlessly
let mut unique_stack = stack.clone();
let config = engine_state.get_config();
let use_color = config.use_ansi_coloring.get(engine_state);
let mut entry_num = 0;
// Let's grab the shell_integration configs
let shell_integration_osc2 = config.shell_integration.osc2;
let shell_integration_osc7 = config.shell_integration.osc7;
let shell_integration_osc9_9 = config.shell_integration.osc9_9;
let shell_integration_osc133 = config.shell_integration.osc133;
let shell_integration_osc633 = config.shell_integration.osc633;
let nu_prompt = NushellPrompt::new(
shell_integration_osc133,
shell_integration_osc633,
engine_state.clone(),
stack.clone(),
);
// seed env vars
unique_stack.add_env_var(
"CMD_DURATION_MS".into(),
Value::string("0823", Span::unknown()),
);
unique_stack.set_last_exit_code(0, Span::unknown());
let mut line_editor = get_line_editor(engine_state, use_color)?;
let temp_file = temp_dir().join(format!("{}.nu", uuid::Uuid::new_v4()));
if let Some(s) = prerun_command {
eval_source(
engine_state,
&mut unique_stack,
s.item.as_bytes(),
&format!("entry #{entry_num}"),
PipelineData::empty(),
false,
);
engine_state.merge_env(&mut unique_stack)?;
}
confirm_stdin_is_terminal()?;
let hostname = System::host_name();
if shell_integration_osc2 {
run_shell_integration_osc2(None, engine_state, &mut unique_stack, use_color);
}
if shell_integration_osc7 {
run_shell_integration_osc7(
hostname.as_deref(),
engine_state,
&mut unique_stack,
use_color,
);
}
if shell_integration_osc9_9 {
run_shell_integration_osc9_9(engine_state, &mut unique_stack, use_color);
}
if shell_integration_osc633 {
// escape a few things because this says so
// https://code.visualstudio.com/docs/terminal/shell-integration#_vs-code-custom-sequences-osc-633-st
let cmd_text = line_editor.current_buffer_contents().to_string();
let replaced_cmd_text = escape_special_vscode_bytes(&cmd_text)?;
run_shell_integration_osc633(
engine_state,
&mut unique_stack,
use_color,
replaced_cmd_text,
);
}
engine_state.set_startup_time(entire_start_time.elapsed().as_nanos() as i64);
// Regenerate the $nu constant to contain the startup time and any other potential updates
engine_state.generate_nu_constant();
if load_std_lib.is_none() {
match engine_state.get_config().show_banner {
BannerKind::None => {}
BannerKind::Short => {
eval_source(
engine_state,
&mut unique_stack,
r#"banner --short"#.as_bytes(),
"show short banner",
PipelineData::empty(),
false,
);
}
BannerKind::Full => {
eval_source(
engine_state,
&mut unique_stack,
r#"banner"#.as_bytes(),
"show_banner",
PipelineData::empty(),
false,
);
}
}
}
kitty_protocol_healthcheck(engine_state);
// Setup initial engine_state and stack state
let mut previous_engine_state = engine_state.clone();
let mut previous_stack_arc = Arc::new(unique_stack);
loop {
// clone these values so that they can be moved by AssertUnwindSafe
// If there is a panic within this iteration the last engine_state and stack
// will be used
let mut current_engine_state = previous_engine_state.clone();
// for the stack, we are going to hold to create a child stack instead,
// avoiding an expensive copy
let current_stack = Stack::with_parent(previous_stack_arc.clone());
let temp_file_cloned = temp_file.clone();
let mut nu_prompt_cloned = nu_prompt.clone();
let iteration_panic_state = catch_unwind(AssertUnwindSafe(|| {
let (continue_loop, current_stack, line_editor) = loop_iteration(LoopContext {
engine_state: &mut current_engine_state,
stack: current_stack,
line_editor,
nu_prompt: &mut nu_prompt_cloned,
temp_file: &temp_file_cloned,
use_color,
entry_num: &mut entry_num,
hostname: hostname.as_deref(),
});
// pass the most recent version of the line_editor back
(
continue_loop,
current_engine_state,
current_stack,
line_editor,
)
}));
match iteration_panic_state {
Ok((continue_loop, mut es, s, le)) => {
// We apply the changes from the updated stack back onto our previous stack
let mut merged_stack = Stack::with_changes_from_child(previous_stack_arc, s);
// Check if new variables were created (indicating potential variable shadowing)
let prev_total_vars = previous_engine_state.num_vars();
let curr_total_vars = es.num_vars();
let new_variables_created = curr_total_vars > prev_total_vars;
if new_variables_created {
// New variables created, clean up stack to prevent memory leaks
es.cleanup_stack_variables(&mut merged_stack);
}
previous_stack_arc = Arc::new(merged_stack);
// setup state for the next iteration of the repl loop
previous_engine_state = es;
line_editor = le;
if !continue_loop {
break;
}
}
Err(_) => {
// line_editor is lost in the error case so reconstruct a new one
line_editor = get_line_editor(engine_state, use_color)?;
}
}
}
Ok(())
}
fn escape_special_vscode_bytes(input: &str) -> Result<String, ShellError> {
let bytes = input
.chars()
.flat_map(|c| {
let mut buf = [0; 4]; // Buffer to hold UTF-8 bytes of the character
let c_bytes = c.encode_utf8(&mut buf); // Get UTF-8 bytes for the character
if c_bytes.len() == 1 {
let byte = c_bytes.as_bytes()[0];
match byte {
// Escape bytes below 0x20
b if b < 0x20 => format!("\\x{byte:02X}").into_bytes(),
// Escape semicolon as \x3B
b';' => "\\x3B".to_string().into_bytes(),
// Escape backslash as \\
b'\\' => "\\\\".to_string().into_bytes(),
// Otherwise, return the character unchanged
_ => vec![byte],
}
} else {
// pass through multi-byte characters unchanged
c_bytes.bytes().collect()
}
})
.collect();
String::from_utf8(bytes).map_err(|err| ShellError::CantConvert {
to_type: "string".to_string(),
from_type: "bytes".to_string(),
span: Span::unknown(),
help: Some(format!(
"Error {err}, Unable to convert {input} to escaped bytes"
)),
})
}
fn get_line_editor(engine_state: &mut EngineState, use_color: bool) -> Result<Reedline> {
let mut start_time = std::time::Instant::now();
let mut line_editor = Reedline::create();
// Now that reedline is created, get the history session id and store it in engine_state
store_history_id_in_engine(engine_state, &line_editor);
perf!("setup reedline", start_time, use_color);
if let Some(history) = engine_state.history_config() {
start_time = std::time::Instant::now();
line_editor = setup_history(engine_state, line_editor, history)?;
perf!("setup history", start_time, use_color);
}
Ok(line_editor)
}
struct LoopContext<'a> {
engine_state: &'a mut EngineState,
stack: Stack,
line_editor: Reedline,
nu_prompt: &'a mut NushellPrompt,
temp_file: &'a Path,
use_color: bool,
entry_num: &'a mut usize,
hostname: Option<&'a str>,
}
/// Perform one iteration of the REPL loop
/// Result is bool: continue loop, current reedline
#[inline]
fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
use nu_cmd_base::hook;
use reedline::Signal;
let loop_start_time = std::time::Instant::now();
let LoopContext {
engine_state,
mut stack,
line_editor,
nu_prompt,
temp_file,
use_color,
entry_num,
hostname,
} = ctx;
let mut start_time = std::time::Instant::now();
// Before doing anything, merge the environment from the previous REPL iteration into the
// permanent state.
if let Err(err) = engine_state.merge_env(&mut stack) {
report_shell_error(None, engine_state, &err);
}
perf!("merge env", start_time, use_color);
start_time = std::time::Instant::now();
engine_state.reset_signals();
perf!("reset signals", start_time, use_color);
start_time = std::time::Instant::now();
// Check all the environment variables they ask for
// fire the "env_change" hook
if let Err(error) = hook::eval_env_change_hook(
&engine_state.get_config().hooks.env_change.clone(),
engine_state,
&mut stack,
) {
report_shell_error(None, engine_state, &error)
}
perf!("env-change hook", start_time, use_color);
start_time = std::time::Instant::now();
// Next, right before we start our prompt and take input from the user, fire the "pre_prompt" hook
if let Err(err) = hook::eval_hooks(
engine_state,
&mut stack,
vec![],
&engine_state.get_config().hooks.pre_prompt.clone(),
"pre_prompt",
) {
report_shell_error(None, engine_state, &err);
}
perf!("pre-prompt hook", start_time, use_color);
let engine_reference = Arc::new(engine_state.clone());
let config = stack.get_config(engine_state);
start_time = std::time::Instant::now();
// Find the configured cursor shapes for each mode
let cursor_config = CursorConfig {
vi_insert: map_nucursorshape_to_cursorshape(config.cursor_shape.vi_insert),
vi_normal: map_nucursorshape_to_cursorshape(config.cursor_shape.vi_normal),
emacs: map_nucursorshape_to_cursorshape(config.cursor_shape.emacs),
};
perf!("get config/cursor config", start_time, use_color);
start_time = std::time::Instant::now();
// at this line we have cloned the state for the completer and the transient prompt
// until we drop those, we cannot use the stack in the REPL loop itself
// See STACK-REFERENCE to see where we have taken a reference
let stack_arc = Arc::new(stack);
let mut line_editor = line_editor
.use_kitty_keyboard_enhancement(config.use_kitty_protocol)
// try to enable bracketed paste
// It doesn't work on windows system: https://github.com/crossterm-rs/crossterm/issues/737
.use_bracketed_paste(cfg!(not(target_os = "windows")) && config.bracketed_paste)
.with_highlighter(Box::new(NuHighlighter {
engine_state: engine_reference.clone(),
// STACK-REFERENCE 1
stack: stack_arc.clone(),
}))
.with_validator(Box::new(NuValidator {
engine_state: engine_reference.clone(),
}))
.with_completer(Box::new(NuCompleter::new(
engine_reference.clone(),
// STACK-REFERENCE 2
stack_arc.clone(),
)))
.with_quick_completions(config.completions.quick)
.with_partial_completions(config.completions.partial)
.with_ansi_colors(config.use_ansi_coloring.get(engine_state))
.with_cwd(Some(
engine_state
.cwd(None)
.map(|cwd| cwd.into_std_path_buf())
.unwrap_or_default()
.to_string_lossy()
.to_string(),
))
.with_cursor_config(cursor_config)
.with_visual_selection_style(nu_ansi_term::Style {
is_reverse: true,
..Default::default()
});
perf!("reedline builder", start_time, use_color);
let style_computer = StyleComputer::from_config(engine_state, &stack_arc);
start_time = std::time::Instant::now();
line_editor = if config.use_ansi_coloring.get(engine_state) && config.show_hints {
line_editor.with_hinter(Box::new({
// As of Nov 2022, "hints" color_config closures only get `null` passed in.
let style = style_computer.compute("hints", &Value::nothing(Span::unknown()));
CwdAwareHinter::default().with_style(style)
}))
} else {
line_editor.disable_hints()
};
perf!("reedline coloring/style_computer", start_time, use_color);
start_time = std::time::Instant::now();
trace!("adding menus");
line_editor =
add_menus(line_editor, engine_reference, &stack_arc, config).unwrap_or_else(|e| {
report_shell_error(None, engine_state, &e);
Reedline::create()
});
perf!("reedline adding menus", start_time, use_color);
start_time = std::time::Instant::now();
let buffer_editor = get_editor(engine_state, &stack_arc, Span::unknown());
line_editor = if let Ok((cmd, args)) = buffer_editor {
let mut command = std::process::Command::new(cmd);
let envs = env_to_strings(engine_state, &stack_arc).unwrap_or_else(|e| {
warn!("Couldn't convert environment variable values to strings: {e}");
HashMap::default()
});
command.args(args).envs(envs);
line_editor.with_buffer_editor(command, temp_file.to_path_buf())
} else {
line_editor
};
perf!("reedline buffer_editor", start_time, use_color);
if let Some(history) = engine_state.history_config() {
start_time = std::time::Instant::now();
if history.sync_on_enter
&& let Err(e) = line_editor.sync_history()
{
warn!("Failed to sync history: {e}");
}
perf!("sync_history", start_time, use_color);
}
start_time = std::time::Instant::now();
// Changing the line editor based on the found keybindings
line_editor = setup_keybindings(engine_state, line_editor);
perf!("keybindings", start_time, use_color);
start_time = std::time::Instant::now();
let config = &engine_state.get_config().clone();
prompt_update::update_prompt(
config,
engine_state,
&mut Stack::with_parent(stack_arc.clone()),
nu_prompt,
);
let transient_prompt = prompt_update::make_transient_prompt(
config,
engine_state,
&mut Stack::with_parent(stack_arc.clone()),
nu_prompt,
);
perf!("update_prompt", start_time, use_color);
*entry_num += 1;
start_time = std::time::Instant::now();
line_editor = line_editor.with_transient_prompt(transient_prompt);
let input = line_editor.read_line(nu_prompt);
// we got our inputs, we can now drop our stack references
// This lists all of the stack references that we have cleaned up
line_editor = line_editor
// CLEAR STACK-REFERENCE 1
.with_highlighter(Box::<NoOpHighlighter>::default())
// CLEAR STACK-REFERENCE 2
.with_completer(Box::<DefaultCompleter>::default())
// Ensure immediately accept is always cleared
.with_immediately_accept(false);
// Let's grab the shell_integration configs
let shell_integration_osc2 = config.shell_integration.osc2;
let shell_integration_osc7 = config.shell_integration.osc7;
let shell_integration_osc9_9 = config.shell_integration.osc9_9;
let shell_integration_osc133 = config.shell_integration.osc133;
let shell_integration_osc633 = config.shell_integration.osc633;
let shell_integration_reset_application_mode = config.shell_integration.reset_application_mode;
// TODO: we may clone the stack, this can lead to major performance issues
// so we should avoid it or making stack cheaper to clone.
let mut stack = Arc::unwrap_or_clone(stack_arc);
perf!("line_editor setup", start_time, use_color);
let line_editor_input_time = std::time::Instant::now();
match input {
Ok(Signal::Success(repl_cmd_line_text)) => {
let history_supports_meta = match engine_state.history_config().map(|h| h.file_format) {
#[cfg(feature = "sqlite")]
Some(HistoryFileFormat::Sqlite) => true,
_ => false,
};
if history_supports_meta {
prepare_history_metadata(
&repl_cmd_line_text,
hostname,
engine_state,
&mut line_editor,
);
}
// For pre_exec_hook
start_time = Instant::now();
// Right before we start running the code the user gave us, fire the `pre_execution`
// hook
{
// Set the REPL buffer to the current command for the "pre_execution" hook
let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
repl.buffer = repl_cmd_line_text.to_string();
drop(repl);
if let Err(err) = hook::eval_hooks(
engine_state,
&mut stack,
vec![],
&engine_state.get_config().hooks.pre_execution.clone(),
"pre_execution",
) {
report_shell_error(None, engine_state, &err);
}
}
perf!("pre_execution_hook", start_time, use_color);
let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
repl.cursor_pos = line_editor.current_insertion_point();
repl.buffer = line_editor.current_buffer_contents().to_string();
drop(repl);
if shell_integration_osc633 {
if stack
.get_env_var(engine_state, "TERM_PROGRAM")
.and_then(|v| v.as_str().ok())
== Some("vscode")
{
start_time = Instant::now();
run_ansi_sequence(VSCODE_PRE_EXECUTION_MARKER);
perf!(
"pre_execute_marker (633;C) ansi escape sequence",
start_time,
use_color
);
} else if shell_integration_osc133 {
start_time = Instant::now();
run_ansi_sequence(PRE_EXECUTION_MARKER);
perf!(
"pre_execute_marker (133;C) ansi escape sequence",
start_time,
use_color
);
}
} else if shell_integration_osc133 {
start_time = Instant::now();
run_ansi_sequence(PRE_EXECUTION_MARKER);
perf!(
"pre_execute_marker (133;C) ansi escape sequence",
start_time,
use_color
);
}
// Actual command execution logic starts from here
let cmd_execution_start_time = Instant::now();
match parse_operation(repl_cmd_line_text.clone(), engine_state, &stack) {
Ok(operation) => match operation {
ReplOperation::AutoCd { cwd, target, span } => {
do_auto_cd(target, cwd, &mut stack, engine_state, span);
run_finaliziation_ansi_sequence(
&stack,
engine_state,
use_color,
shell_integration_osc633,
shell_integration_osc133,
);
}
ReplOperation::RunCommand(cmd) => {
line_editor = do_run_cmd(
&cmd,
&mut stack,
engine_state,
line_editor,
shell_integration_osc2,
*entry_num,
use_color,
);
run_finaliziation_ansi_sequence(
&stack,
engine_state,
use_color,
shell_integration_osc633,
shell_integration_osc133,
);
}
// as the name implies, we do nothing in this case
ReplOperation::DoNothing => {}
},
Err(ref e) => error!("Error parsing operation: {e}"),
}
let cmd_duration = cmd_execution_start_time.elapsed();
stack.add_env_var(
"CMD_DURATION_MS".into(),
Value::string(format!("{}", cmd_duration.as_millis()), Span::unknown()),
);
if history_supports_meta
&& let Err(e) = fill_in_result_related_history_metadata(
&repl_cmd_line_text,
engine_state,
cmd_duration,
&mut stack,
&mut line_editor,
)
{
warn!("Could not fill in result related history metadata: {e}");
}
if shell_integration_osc2 {
run_shell_integration_osc2(None, engine_state, &mut stack, use_color);
}
if shell_integration_osc7 {
run_shell_integration_osc7(hostname, engine_state, &mut stack, use_color);
}
if shell_integration_osc9_9 {
run_shell_integration_osc9_9(engine_state, &mut stack, use_color);
}
if shell_integration_osc633 {
run_shell_integration_osc633(
engine_state,
&mut stack,
use_color,
repl_cmd_line_text,
);
}
if shell_integration_reset_application_mode {
run_shell_integration_reset_application_mode();
}
line_editor = flush_engine_state_repl_buffer(engine_state, line_editor);
}
Ok(Signal::CtrlC) => {
// `Reedline` clears the line content. New prompt is shown
run_finaliziation_ansi_sequence(
&stack,
engine_state,
use_color,
shell_integration_osc633,
shell_integration_osc133,
);
}
Ok(Signal::CtrlD) => {
// When exiting clear to a new line
run_finaliziation_ansi_sequence(
&stack,
engine_state,
use_color,
shell_integration_osc633,
shell_integration_osc133,
);
println!();
cleanup_exit((), engine_state, 0);
// if cleanup_exit didn't exit, we should keep running
return (true, stack, line_editor);
}
Err(err) => {
let message = err.to_string();
if !message.contains("duration") {
eprintln!("Error: {err:?}");
// TODO: Identify possible error cases where a hard failure is preferable
// Ignoring and reporting could hide bigger problems
// e.g. https://github.com/nushell/nushell/issues/6452
// Alternatively only allow that expected failures let the REPL loop
}
run_finaliziation_ansi_sequence(
&stack,
engine_state,
use_color,
shell_integration_osc633,
shell_integration_osc133,
);
}
}
perf!(
"processing line editor input",
line_editor_input_time,
use_color
);
perf!(
"time between prompts in line editor loop",
loop_start_time,
use_color
);
(true, stack, line_editor)
}
///
/// Put in history metadata not related to the result of running the command
///
fn prepare_history_metadata(
s: &str,
hostname: Option<&str>,
engine_state: &EngineState,
line_editor: &mut Reedline,
) {
if !s.is_empty() && line_editor.has_last_command_context() {
let result = line_editor
.update_last_command_context(&|mut c| {
c.start_timestamp = Some(chrono::Utc::now());
c.hostname = hostname.map(str::to_string);
c.cwd = engine_state
.cwd(None)
.ok()
.map(|path| path.to_string_lossy().to_string());
c
})
.into_diagnostic();
if let Err(e) = result {
warn!("Could not prepare history metadata: {e}");
}
}
}
///
/// Fills in history item metadata based on the execution result (notably duration and exit code)
///
fn fill_in_result_related_history_metadata(
s: &str,
engine_state: &EngineState,
cmd_duration: Duration,
stack: &mut Stack,
line_editor: &mut Reedline,
) -> Result<()> {
if !s.is_empty() && line_editor.has_last_command_context() {
line_editor
.update_last_command_context(&|mut c| {
c.duration = Some(cmd_duration);
c.exit_status = stack
.get_env_var(engine_state, "LAST_EXIT_CODE")
.and_then(|e| e.as_int().ok());
c
})
.into_diagnostic()?; // todo: don't stop repl if error here?
}
Ok(())
}
/// The kinds of operations you can do in a single loop iteration of the REPL
enum ReplOperation {
/// "auto-cd": change directory by typing it in directly
AutoCd {
/// the current working directory
cwd: String,
/// the target
target: PathBuf,
/// span information for debugging
span: Span,
},
/// run a command
RunCommand(String),
/// do nothing (usually through an empty string)
DoNothing,
}
///
/// Parses one "REPL line" of input, to try and derive intent.
/// Notably, this is where we detect whether the user is attempting an
/// "auto-cd" (writing a relative path directly instead of `cd path`)
///
/// Returns the ReplOperation we believe the user wants to do
///
fn parse_operation(
s: String,
engine_state: &EngineState,
stack: &Stack,
) -> Result<ReplOperation, ErrReport> {
let tokens = lex(s.as_bytes(), 0, &[], &[], false);
// Check if this is a single call to a directory, if so auto-cd
let cwd = engine_state
.cwd(Some(stack))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
let mut orig = s.clone();
if orig.starts_with('`') {
orig = trim_quotes_str(&orig).to_string()
}
let path = nu_path::expand_path_with(&orig, &cwd, true);
if looks_like_path(&orig) && path.is_dir() && tokens.0.len() == 1 {
Ok(ReplOperation::AutoCd {
cwd,
target: path,
span: tokens.0[0].span,
})
} else if !s.trim().is_empty() {
Ok(ReplOperation::RunCommand(s))
} else {
Ok(ReplOperation::DoNothing)
}
}
///
/// Execute an "auto-cd" operation, changing the current working directory.
///
fn do_auto_cd(
path: PathBuf,
cwd: String,
stack: &mut Stack,
engine_state: &mut EngineState,
span: Span,
) {
let path = {
if !path.exists() {
report_shell_error(
Some(stack),
engine_state,
&ShellError::Io(IoError::new_with_additional_context(
shell_error::io::ErrorKind::DirectoryNotFound,
span,
PathBuf::from(&path),
"Cannot change directory",
)),
);
}
path.to_string_lossy().to_string()
};
if let PermissionResult::PermissionDenied = have_permission(path.clone()) {
report_shell_error(
Some(stack),
engine_state,
&ShellError::Io(IoError::new_with_additional_context(
shell_error::io::ErrorKind::from_std(std::io::ErrorKind::PermissionDenied),
span,
PathBuf::from(path),
"Cannot change directory",
)),
);
return;
}
stack.add_env_var("OLDPWD".into(), Value::string(cwd.clone(), Span::unknown()));
//FIXME: this only changes the current scope, but instead this environment variable
//should probably be a block that loads the information from the state in the overlay
if let Err(err) = stack.set_cwd(&path) {
report_shell_error(Some(stack), engine_state, &err);
return;
};
let cwd = Value::string(cwd, span);
let shells = stack.get_env_var(engine_state, "NUSHELL_SHELLS");
let mut shells = if let Some(v) = shells {
v.clone().into_list().unwrap_or_else(|_| vec![cwd])
} else {
vec![cwd]
};
let current_shell = stack.get_env_var(engine_state, "NUSHELL_CURRENT_SHELL");
let current_shell = if let Some(v) = current_shell {
v.as_int().unwrap_or_default() as usize
} else {
0
};
let last_shell = stack.get_env_var(engine_state, "NUSHELL_LAST_SHELL");
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/reedline_config.rs | crates/nu-cli/src/reedline_config.rs | use crate::{NuHelpCompleter, menus::NuMenuCompleter};
use crossterm::event::{KeyCode, KeyModifiers};
use nu_ansi_term::Style;
use nu_color_config::{color_record_to_nustyle, lookup_ansi_color_style};
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
Config, EditBindings, FromValue, ParsedKeybinding, ParsedMenu, PipelineData, Record,
ShellError, Span, Type, Value,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
extract_value,
};
use reedline::{
ColumnarMenu, DescriptionMenu, DescriptionMode, EditCommand, IdeMenu, Keybindings, ListMenu,
MenuBuilder, Reedline, ReedlineEvent, ReedlineMenu, TextObject, TextObjectScope,
TextObjectType, TraversalDirection, default_emacs_keybindings, default_vi_insert_keybindings,
default_vi_normal_keybindings,
};
use std::sync::Arc;
const DEFAULT_COMPLETION_MENU: &str = r#"
{
name: completion_menu
only_buffer_difference: false
marker: "| "
type: {
layout: columnar
columns: 4
col_width: 20
col_padding: 2
tab_traversal: "horizontal"
}
style: {
text: green,
selected_text: green_reverse
description_text: yellow
}
}"#;
const DEFAULT_IDE_COMPLETION_MENU: &str = r#"
{
name: ide_completion_menu
only_buffer_difference: false
marker: "| "
type: {
layout: ide
min_completion_width: 0,
max_completion_width: 50,
max_completion_height: 10, # will be limited by the available lines in the terminal
padding: 0,
border: true,
cursor_offset: 0,
description_mode: "prefer_right"
min_description_width: 15
max_description_width: 50
max_description_height: 10
description_offset: 1
# If true, the cursor pos will be corrected, so the suggestions match up with the typed text
#
# C:\> str
# str join
# str trim
# str split
correct_cursor_pos: false
}
style: {
text: green
selected_text: { attr: r }
description_text: yellow
match_text: { attr: u }
selected_match_text: { attr: ur }
}
}"#;
const DEFAULT_HISTORY_MENU: &str = r#"
{
name: history_menu
only_buffer_difference: true
marker: "? "
type: {
layout: list
page_size: 10
}
style: {
text: green,
selected_text: green_reverse
description_text: yellow
}
}"#;
const DEFAULT_HELP_MENU: &str = r#"
{
name: help_menu
only_buffer_difference: true
marker: "? "
type: {
layout: description
columns: 4
col_width: 20
col_padding: 2
selection_rows: 4
description_rows: 15
}
style: {
text: green,
selected_text: green_reverse
description_text: yellow
}
}"#;
// Adds all menus to line editor
pub(crate) fn add_menus(
mut line_editor: Reedline,
engine_state_ref: Arc<EngineState>,
stack: &Stack,
config: Arc<Config>,
) -> Result<Reedline, ShellError> {
//log::trace!("add_menus: config: {:#?}", &config);
line_editor = line_editor.clear_menus();
for menu in &config.menus {
line_editor = add_menu(
line_editor,
menu,
engine_state_ref.clone(),
stack,
config.clone(),
)?
}
// Checking if the default menus have been added from the config file
let default_menus = [
("completion_menu", DEFAULT_COMPLETION_MENU),
("ide_completion_menu", DEFAULT_IDE_COMPLETION_MENU),
("history_menu", DEFAULT_HISTORY_MENU),
("help_menu", DEFAULT_HELP_MENU),
];
let mut engine_state = (*engine_state_ref).clone();
let mut menu_eval_results = vec![];
for (name, definition) in default_menus {
if !config
.menus
.iter()
.any(|menu| menu.name.to_expanded_string("", &config) == name)
{
let (block, delta) = {
let mut working_set = StateWorkingSet::new(&engine_state);
let output = parse(
&mut working_set,
Some(name), // format!("entry #{}", entry_num)
definition.as_bytes(),
true,
);
(output, working_set.render())
};
engine_state.merge_delta(delta)?;
let mut temp_stack = Stack::new().collect_value();
let input = PipelineData::empty();
menu_eval_results.push(eval_block::<WithoutDebug>(
&engine_state,
&mut temp_stack,
&block,
input,
)?);
}
}
let new_engine_state_ref = Arc::new(engine_state);
for res in menu_eval_results.into_iter().map(|p| p.body) {
if let PipelineData::Value(value, None) = res {
line_editor = add_menu(
line_editor,
&ParsedMenu::from_value(value)?,
new_engine_state_ref.clone(),
stack,
config.clone(),
)?;
}
}
Ok(line_editor)
}
fn add_menu(
line_editor: Reedline,
menu: &ParsedMenu,
engine_state: Arc<EngineState>,
stack: &Stack,
config: Arc<Config>,
) -> Result<Reedline, ShellError> {
let span = menu.r#type.span();
if let Value::Record { val, .. } = &menu.r#type {
let layout = extract_value("layout", val, span)?.to_expanded_string("", &config);
match layout.as_str() {
"columnar" => add_columnar_menu(line_editor, menu, engine_state, stack, &config),
"list" => add_list_menu(line_editor, menu, engine_state, stack, config),
"ide" => add_ide_menu(line_editor, menu, engine_state, stack, config),
"description" => add_description_menu(line_editor, menu, engine_state, stack, config),
str => Err(ShellError::InvalidValue {
valid: "'columnar', 'list', 'ide', or 'description'".into(),
actual: format!("'{str}'"),
span,
}),
}
} else {
Err(ShellError::RuntimeTypeMismatch {
expected: Type::record(),
actual: menu.r#type.get_type(),
span,
})
}
}
fn get_style(record: &Record, name: &'static str, span: Span) -> Option<Style> {
extract_value(name, record, span)
.ok()
.map(|text| match text {
Value::String { val, .. } => lookup_ansi_color_style(val),
Value::Record { .. } => color_record_to_nustyle(text),
_ => lookup_ansi_color_style("green"),
})
}
fn set_menu_style<M: MenuBuilder>(mut menu: M, style: &Value) -> M {
let span = style.span();
let Value::Record { val, .. } = &style else {
return menu;
};
if let Some(style) = get_style(val, "text", span) {
menu = menu.with_text_style(style);
}
if let Some(style) = get_style(val, "selected_text", span) {
menu = menu.with_selected_text_style(style);
}
if let Some(style) = get_style(val, "description_text", span) {
menu = menu.with_description_text_style(style);
}
if let Some(style) = get_style(val, "match_text", span) {
menu = menu.with_match_text_style(style);
}
if let Some(style) = get_style(val, "selected_match_text", span) {
menu = menu.with_selected_match_text_style(style);
}
menu
}
// Adds a columnar menu to the editor engine
pub(crate) fn add_columnar_menu(
line_editor: Reedline,
menu: &ParsedMenu,
engine_state: Arc<EngineState>,
stack: &Stack,
config: &Config,
) -> Result<Reedline, ShellError> {
let span = menu.r#type.span();
let name = menu.name.to_expanded_string("", config);
let mut columnar_menu = ColumnarMenu::default().with_name(&name);
if let Value::Record { val, .. } = &menu.r#type {
columnar_menu = match extract_value("columns", val, span) {
Ok(columns) => {
let columns = columns.as_int()?;
columnar_menu.with_columns(columns as u16)
}
Err(_) => columnar_menu,
};
columnar_menu = match extract_value("col_width", val, span) {
Ok(col_width) => {
let col_width = col_width.as_int()?;
columnar_menu.with_column_width(Some(col_width as usize))
}
Err(_) => columnar_menu.with_column_width(None),
};
columnar_menu = match extract_value("col_padding", val, span) {
Ok(col_padding) => {
let col_padding = col_padding.as_int()?;
columnar_menu.with_column_padding(col_padding as usize)
}
Err(_) => columnar_menu,
};
columnar_menu = match extract_value("tab_traversal", val, span) {
Ok(tab_traversal) => match tab_traversal.coerce_str()?.as_ref() {
"vertical" => columnar_menu.with_traversal_direction(TraversalDirection::Vertical),
"horizontal" => {
columnar_menu.with_traversal_direction(TraversalDirection::Horizontal)
}
str => {
return Err(ShellError::InvalidValue {
valid: "'horizontal' or 'vertical'".into(),
actual: format!("'{str}'"),
span: tab_traversal.span(),
});
}
},
Err(_) => columnar_menu,
};
}
columnar_menu = set_menu_style(columnar_menu, &menu.style);
let marker = menu.marker.to_expanded_string("", config);
columnar_menu = columnar_menu.with_marker(&marker);
let only_buffer_difference = menu.only_buffer_difference.as_bool()?;
columnar_menu = columnar_menu.with_only_buffer_difference(only_buffer_difference);
let completer = if let Some(closure) = &menu.source {
let menu_completer = NuMenuCompleter::new(
closure.block_id,
span,
stack.captures_to_stack(closure.captures.clone()),
engine_state,
only_buffer_difference,
);
ReedlineMenu::WithCompleter {
menu: Box::new(columnar_menu),
completer: Box::new(menu_completer),
}
} else {
ReedlineMenu::EngineCompleter(Box::new(columnar_menu))
};
Ok(line_editor.with_menu(completer))
}
// Adds a search menu to the line editor
pub(crate) fn add_list_menu(
line_editor: Reedline,
menu: &ParsedMenu,
engine_state: Arc<EngineState>,
stack: &Stack,
config: Arc<Config>,
) -> Result<Reedline, ShellError> {
let name = menu.name.to_expanded_string("", &config);
let mut list_menu = ListMenu::default().with_name(&name);
let span = menu.r#type.span();
if let Value::Record { val, .. } = &menu.r#type {
list_menu = match extract_value("page_size", val, span) {
Ok(page_size) => {
let page_size = page_size.as_int()?;
list_menu.with_page_size(page_size as usize)
}
Err(_) => list_menu,
};
}
list_menu = set_menu_style(list_menu, &menu.style);
let marker = menu.marker.to_expanded_string("", &config);
list_menu = list_menu.with_marker(&marker);
let only_buffer_difference = menu.only_buffer_difference.as_bool()?;
list_menu = list_menu.with_only_buffer_difference(only_buffer_difference);
let completer = if let Some(closure) = &menu.source {
let menu_completer = NuMenuCompleter::new(
closure.block_id,
span,
stack.captures_to_stack(closure.captures.clone()),
engine_state,
only_buffer_difference,
);
ReedlineMenu::WithCompleter {
menu: Box::new(list_menu),
completer: Box::new(menu_completer),
}
} else {
ReedlineMenu::HistoryMenu(Box::new(list_menu))
};
Ok(line_editor.with_menu(completer))
}
// Adds an IDE menu to the line editor
pub(crate) fn add_ide_menu(
line_editor: Reedline,
menu: &ParsedMenu,
engine_state: Arc<EngineState>,
stack: &Stack,
config: Arc<Config>,
) -> Result<Reedline, ShellError> {
let span = menu.r#type.span();
let name = menu.name.to_expanded_string("", &config);
let mut ide_menu = IdeMenu::default().with_name(&name);
if let Value::Record { val, .. } = &menu.r#type {
ide_menu = match extract_value("min_completion_width", val, span) {
Ok(min_completion_width) => {
let min_completion_width = min_completion_width.as_int()?;
ide_menu.with_min_completion_width(min_completion_width as u16)
}
Err(_) => ide_menu,
};
ide_menu = match extract_value("max_completion_width", val, span) {
Ok(max_completion_width) => {
let max_completion_width = max_completion_width.as_int()?;
ide_menu.with_max_completion_width(max_completion_width as u16)
}
Err(_) => ide_menu,
};
ide_menu = match extract_value("max_completion_height", val, span) {
Ok(max_completion_height) => {
let max_completion_height = max_completion_height.as_int()?;
ide_menu.with_max_completion_height(max_completion_height as u16)
}
Err(_) => ide_menu.with_max_completion_height(10u16),
};
ide_menu = match extract_value("padding", val, span) {
Ok(padding) => {
let padding = padding.as_int()?;
ide_menu.with_padding(padding as u16)
}
Err(_) => ide_menu,
};
ide_menu = match extract_value("border", val, span) {
Ok(border) => {
if let Ok(border) = border.as_bool() {
if border {
ide_menu.with_default_border()
} else {
ide_menu
}
} else if let Ok(border_chars) = border.as_record() {
let top_right = extract_value("top_right", border_chars, span)?.as_char()?;
let top_left = extract_value("top_left", border_chars, span)?.as_char()?;
let bottom_right =
extract_value("bottom_right", border_chars, span)?.as_char()?;
let bottom_left =
extract_value("bottom_left", border_chars, span)?.as_char()?;
let horizontal = extract_value("horizontal", border_chars, span)?.as_char()?;
let vertical = extract_value("vertical", border_chars, span)?.as_char()?;
ide_menu.with_border(
top_right,
top_left,
bottom_right,
bottom_left,
horizontal,
vertical,
)
} else {
return Err(ShellError::RuntimeTypeMismatch {
expected: Type::custom("bool or record"),
actual: border.get_type(),
span: border.span(),
});
}
}
Err(_) => ide_menu.with_default_border(),
};
ide_menu = match extract_value("cursor_offset", val, span) {
Ok(cursor_offset) => {
let cursor_offset = cursor_offset.as_int()?;
ide_menu.with_cursor_offset(cursor_offset as i16)
}
Err(_) => ide_menu,
};
ide_menu = match extract_value("description_mode", val, span) {
Ok(description_mode) => match description_mode.coerce_str()?.as_ref() {
"left" => ide_menu.with_description_mode(DescriptionMode::Left),
"right" => ide_menu.with_description_mode(DescriptionMode::Right),
"prefer_right" => ide_menu.with_description_mode(DescriptionMode::PreferRight),
str => {
return Err(ShellError::InvalidValue {
valid: "'left', 'right', or 'prefer_right'".into(),
actual: format!("'{str}'"),
span: description_mode.span(),
});
}
},
Err(_) => ide_menu,
};
ide_menu = match extract_value("min_description_width", val, span) {
Ok(min_description_width) => {
let min_description_width = min_description_width.as_int()?;
ide_menu.with_min_description_width(min_description_width as u16)
}
Err(_) => ide_menu,
};
ide_menu = match extract_value("max_description_width", val, span) {
Ok(max_description_width) => {
let max_description_width = max_description_width.as_int()?;
ide_menu.with_max_description_width(max_description_width as u16)
}
Err(_) => ide_menu,
};
ide_menu = match extract_value("max_description_height", val, span) {
Ok(max_description_height) => {
let max_description_height = max_description_height.as_int()?;
ide_menu.with_max_description_height(max_description_height as u16)
}
Err(_) => ide_menu,
};
ide_menu = match extract_value("description_offset", val, span) {
Ok(description_padding) => {
let description_padding = description_padding.as_int()?;
ide_menu.with_description_offset(description_padding as u16)
}
Err(_) => ide_menu,
};
ide_menu = match extract_value("correct_cursor_pos", val, span) {
Ok(correct_cursor_pos) => {
let correct_cursor_pos = correct_cursor_pos.as_bool()?;
ide_menu.with_correct_cursor_pos(correct_cursor_pos)
}
Err(_) => ide_menu,
};
}
ide_menu = set_menu_style(ide_menu, &menu.style);
let marker = menu.marker.to_expanded_string("", &config);
ide_menu = ide_menu.with_marker(&marker);
let only_buffer_difference = menu.only_buffer_difference.as_bool()?;
ide_menu = ide_menu.with_only_buffer_difference(only_buffer_difference);
let completer = if let Some(closure) = &menu.source {
let menu_completer = NuMenuCompleter::new(
closure.block_id,
span,
stack.captures_to_stack(closure.captures.clone()),
engine_state,
only_buffer_difference,
);
ReedlineMenu::WithCompleter {
menu: Box::new(ide_menu),
completer: Box::new(menu_completer),
}
} else {
ReedlineMenu::EngineCompleter(Box::new(ide_menu))
};
Ok(line_editor.with_menu(completer))
}
// Adds a description menu to the line editor
pub(crate) fn add_description_menu(
line_editor: Reedline,
menu: &ParsedMenu,
engine_state: Arc<EngineState>,
stack: &Stack,
config: Arc<Config>,
) -> Result<Reedline, ShellError> {
let name = menu.name.to_expanded_string("", &config);
let mut description_menu = DescriptionMenu::default().with_name(&name);
let span = menu.r#type.span();
if let Value::Record { val, .. } = &menu.r#type {
description_menu = match extract_value("columns", val, span) {
Ok(columns) => {
let columns = columns.as_int()?;
description_menu.with_columns(columns as u16)
}
Err(_) => description_menu,
};
description_menu = match extract_value("col_width", val, span) {
Ok(col_width) => {
let col_width = col_width.as_int()?;
description_menu.with_column_width(Some(col_width as usize))
}
Err(_) => description_menu.with_column_width(None),
};
description_menu = match extract_value("col_padding", val, span) {
Ok(col_padding) => {
let col_padding = col_padding.as_int()?;
description_menu.with_column_padding(col_padding as usize)
}
Err(_) => description_menu,
};
description_menu = match extract_value("selection_rows", val, span) {
Ok(selection_rows) => {
let selection_rows = selection_rows.as_int()?;
description_menu.with_selection_rows(selection_rows as u16)
}
Err(_) => description_menu,
};
description_menu = match extract_value("description_rows", val, span) {
Ok(description_rows) => {
let description_rows = description_rows.as_int()?;
description_menu.with_description_rows(description_rows as usize)
}
Err(_) => description_menu,
};
}
description_menu = set_menu_style(description_menu, &menu.style);
let marker = menu.marker.to_expanded_string("", &config);
description_menu = description_menu.with_marker(&marker);
let only_buffer_difference = menu.only_buffer_difference.as_bool()?;
description_menu = description_menu.with_only_buffer_difference(only_buffer_difference);
let completer = if let Some(closure) = &menu.source {
let menu_completer = NuMenuCompleter::new(
closure.block_id,
span,
stack.captures_to_stack(closure.captures.clone()),
engine_state,
only_buffer_difference,
);
ReedlineMenu::WithCompleter {
menu: Box::new(description_menu),
completer: Box::new(menu_completer),
}
} else {
let menu_completer = NuHelpCompleter::new(engine_state, config);
ReedlineMenu::WithCompleter {
menu: Box::new(description_menu),
completer: Box::new(menu_completer),
}
};
Ok(line_editor.with_menu(completer))
}
fn add_menu_keybindings(keybindings: &mut Keybindings) {
// Completer menu keybindings
keybindings.add_binding(
KeyModifiers::NONE,
KeyCode::Tab,
ReedlineEvent::UntilFound(vec![
ReedlineEvent::Menu("completion_menu".to_string()),
ReedlineEvent::MenuNext,
ReedlineEvent::Edit(vec![EditCommand::Complete]),
]),
);
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char(' '),
ReedlineEvent::UntilFound(vec![
ReedlineEvent::Menu("ide_completion_menu".to_string()),
ReedlineEvent::MenuNext,
ReedlineEvent::Edit(vec![EditCommand::Complete]),
]),
);
keybindings.add_binding(
KeyModifiers::SHIFT,
KeyCode::BackTab,
ReedlineEvent::MenuPrevious,
);
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('r'),
ReedlineEvent::Menu("history_menu".to_string()),
);
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('x'),
ReedlineEvent::MenuPageNext,
);
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('z'),
ReedlineEvent::UntilFound(vec![
ReedlineEvent::MenuPagePrevious,
ReedlineEvent::Edit(vec![EditCommand::Undo]),
]),
);
// Help menu keybinding
keybindings.add_binding(
KeyModifiers::NONE,
KeyCode::F(1),
ReedlineEvent::Menu("help_menu".to_string()),
);
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('q'),
ReedlineEvent::SearchHistory,
);
}
pub enum KeybindingsMode {
Emacs(Keybindings),
Vi {
insert_keybindings: Keybindings,
normal_keybindings: Keybindings,
},
}
pub(crate) fn create_keybindings(config: &Config) -> Result<KeybindingsMode, ShellError> {
let parsed_keybindings = &config.keybindings;
let mut emacs_keybindings = default_emacs_keybindings();
let mut insert_keybindings = default_vi_insert_keybindings();
let mut normal_keybindings = default_vi_normal_keybindings();
match config.edit_mode {
EditBindings::Emacs => {
add_menu_keybindings(&mut emacs_keybindings);
}
EditBindings::Vi => {
add_menu_keybindings(&mut insert_keybindings);
add_menu_keybindings(&mut normal_keybindings);
}
}
for keybinding in parsed_keybindings {
add_keybinding(
&keybinding.mode,
keybinding,
config,
&mut emacs_keybindings,
&mut insert_keybindings,
&mut normal_keybindings,
)?
}
match config.edit_mode {
EditBindings::Emacs => Ok(KeybindingsMode::Emacs(emacs_keybindings)),
EditBindings::Vi => Ok(KeybindingsMode::Vi {
insert_keybindings,
normal_keybindings,
}),
}
}
fn add_keybinding(
mode: &Value,
keybinding: &ParsedKeybinding,
config: &Config,
emacs_keybindings: &mut Keybindings,
insert_keybindings: &mut Keybindings,
normal_keybindings: &mut Keybindings,
) -> Result<(), ShellError> {
let span = mode.span();
match &mode {
Value::String { val, .. } => match val.as_str() {
str if str.eq_ignore_ascii_case("emacs") => {
add_parsed_keybinding(emacs_keybindings, keybinding, config)
}
str if str.eq_ignore_ascii_case("vi_insert") => {
add_parsed_keybinding(insert_keybindings, keybinding, config)
}
str if str.eq_ignore_ascii_case("vi_normal") => {
add_parsed_keybinding(normal_keybindings, keybinding, config)
}
str => Err(ShellError::InvalidValue {
valid: "'emacs', 'vi_insert', or 'vi_normal'".into(),
actual: format!("'{str}'"),
span,
}),
},
Value::List { vals, .. } => {
for inner_mode in vals {
add_keybinding(
inner_mode,
keybinding,
config,
emacs_keybindings,
insert_keybindings,
normal_keybindings,
)?
}
Ok(())
}
v => Err(ShellError::RuntimeTypeMismatch {
expected: Type::custom("string or list<string>"),
actual: v.get_type(),
span: v.span(),
}),
}
}
fn add_parsed_keybinding(
keybindings: &mut Keybindings,
keybinding: &ParsedKeybinding,
config: &Config,
) -> Result<(), ShellError> {
let Ok(modifier_str) = keybinding.modifier.as_str() else {
return Err(ShellError::RuntimeTypeMismatch {
expected: Type::String,
actual: keybinding.modifier.get_type(),
span: keybinding.modifier.span(),
});
};
let mut modifier = KeyModifiers::NONE;
if !str::eq_ignore_ascii_case(modifier_str, "none") {
for part in modifier_str.split('_') {
match part.to_ascii_lowercase().as_str() {
"control" => modifier |= KeyModifiers::CONTROL,
"shift" => modifier |= KeyModifiers::SHIFT,
"alt" => modifier |= KeyModifiers::ALT,
"super" => modifier |= KeyModifiers::SUPER,
"hyper" => modifier |= KeyModifiers::HYPER,
"meta" => modifier |= KeyModifiers::META,
_ => {
return Err(ShellError::InvalidValue {
valid: "'control', 'shift', 'alt', 'super', 'hyper', 'meta', or 'none'"
.into(),
actual: format!("'{part}'"),
span: keybinding.modifier.span(),
});
}
}
}
}
let Ok(keycode) = keybinding.keycode.as_str() else {
return Err(ShellError::RuntimeTypeMismatch {
expected: Type::String,
actual: keybinding.keycode.get_type(),
span: keybinding.keycode.span(),
});
};
let keycode_lower = keycode.to_ascii_lowercase();
let keycode = if let Some(rest) = keycode_lower.strip_prefix("char_") {
let error = |valid: &str, actual: &str| ShellError::InvalidValue {
valid: valid.into(),
actual: actual.into(),
span: keybinding.keycode.span(),
};
let mut char_iter = rest.chars();
let char = match (char_iter.next(), char_iter.next()) {
(Some(char), None) => char,
(Some('u'), Some(_)) => {
// This will never panic as we know there are at least two symbols
let Ok(code_point) = u32::from_str_radix(&rest[1..], 16) else {
return Err(error("a valid hex code", keycode));
};
char::from_u32(code_point).ok_or(error("a valid Unicode code point", keycode))?
}
_ => return Err(error("'char_<char>' or 'char_u<hex code>'", keycode)),
};
KeyCode::Char(char)
} else {
match keycode_lower.as_str() {
"backspace" => KeyCode::Backspace,
"enter" => KeyCode::Enter,
"space" => KeyCode::Char(' '),
"down" => KeyCode::Down,
"up" => KeyCode::Up,
"left" => KeyCode::Left,
"right" => KeyCode::Right,
"home" => KeyCode::Home,
"end" => KeyCode::End,
"pageup" => KeyCode::PageUp,
"pagedown" => KeyCode::PageDown,
"tab" => KeyCode::Tab,
"backtab" => KeyCode::BackTab,
"delete" => KeyCode::Delete,
"insert" => KeyCode::Insert,
c if c.starts_with('f') => c[1..]
.parse()
.ok()
.filter(|num| (1..=35).contains(num))
.map(KeyCode::F)
.ok_or(ShellError::InvalidValue {
valid: "'f1', 'f2', ..., or 'f35'".into(),
actual: format!("'{keycode}'"),
span: keybinding.keycode.span(),
})?,
"null" => KeyCode::Null,
"esc" | "escape" => KeyCode::Esc,
_ => {
return Err(ShellError::InvalidValue {
valid: "a crossterm KeyCode".into(),
actual: format!("'{keycode}'"),
span: keybinding.keycode.span(),
});
}
}
};
if let Some(event) = parse_event(&keybinding.event, config)? {
keybindings.add_binding(modifier, keycode, event);
} else {
keybindings.remove_binding(modifier, keycode);
}
Ok(())
}
enum EventType<'config> {
Send(&'config Value),
Edit(&'config Value),
Until(&'config Value),
}
impl<'config> EventType<'config> {
fn try_from_record(record: &'config Record, span: Span) -> Result<Self, ShellError> {
extract_value("send", record, span)
.map(Self::Send)
.or_else(|_| extract_value("edit", record, span).map(Self::Edit))
.or_else(|_| extract_value("until", record, span).map(Self::Until))
.map_err(|_| ShellError::MissingRequiredColumn {
column: "'send', 'edit', or 'until'",
span,
})
}
}
fn parse_event(value: &Value, config: &Config) -> Result<Option<ReedlineEvent>, ShellError> {
let span = value.span();
match value {
Value::Record { val: record, .. } => match EventType::try_from_record(record, span)? {
EventType::Send(value) => event_from_record(
value
.to_expanded_string("", config)
.to_ascii_lowercase()
.as_str(),
record,
config,
span,
)
.map(Some),
EventType::Edit(value) => {
let edit = edit_from_record(
value
.to_expanded_string("", config)
.to_ascii_lowercase()
.as_str(),
record,
config,
span,
)?;
Ok(Some(ReedlineEvent::Edit(vec![edit])))
}
EventType::Until(value) => match value {
Value::List { vals, .. } => {
let events = vals
.iter()
.map(|value| match parse_event(value, config) {
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/validation.rs | crates/nu-cli/src/validation.rs | use nu_parser::parse;
use nu_protocol::{
ParseError,
engine::{EngineState, StateWorkingSet},
};
use reedline::{ValidationResult, Validator};
use std::sync::Arc;
pub struct NuValidator {
pub engine_state: Arc<EngineState>,
}
impl Validator for NuValidator {
fn validate(&self, line: &str) -> ValidationResult {
let mut working_set = StateWorkingSet::new(&self.engine_state);
parse(&mut working_set, None, line.as_bytes(), false);
if matches!(
working_set.parse_errors.first(),
Some(ParseError::UnexpectedEof(..))
) {
ValidationResult::Incomplete
} else {
ValidationResult::Complete
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/util.rs | crates/nu-cli/src/util.rs | #![allow(clippy::byte_char_slices)]
use nu_cmd_base::hook::eval_hook;
use nu_engine::{eval_block, eval_block_with_early_return};
use nu_parser::{Token, TokenContents, lex, parse, unescape_unquote_string};
use nu_protocol::{
PipelineData, ShellError, Span, Value,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
process::check_exit_status_future,
report_error::report_compile_error,
report_parse_error, report_parse_warning, report_shell_error,
};
#[cfg(windows)]
use nu_utils::enable_vt_processing;
use nu_utils::{escape_quote_string, perf};
use std::path::Path;
// This will collect environment variables from std::env and adds them to a stack.
//
// In order to ensure the values have spans, it first creates a dummy file, writes the collected
// env vars into it (in a "NAME"="value" format, quite similar to the output of the Unix 'env'
// tool), then uses the file to get the spans. The file stays in memory, no filesystem IO is done.
//
// The "PWD" env value will be forced to `init_cwd`.
// The reason to use `init_cwd`:
//
// While gathering parent env vars, the parent `PWD` may not be the same as `current working directory`.
// Consider to the following command as the case (assume we execute command inside `/tmp`):
//
// tmux split-window -v -c "#{pane_current_path}"
//
// Here nu execute external command `tmux`, and tmux starts a new `nushell`, with `init_cwd` value "#{pane_current_path}".
// But at the same time `PWD` still remains to be `/tmp`.
//
// In this scenario, the new `nushell`'s PWD should be "#{pane_current_path}" rather init_cwd.
pub fn gather_parent_env_vars(engine_state: &mut EngineState, init_cwd: &Path) {
gather_env_vars(std::env::vars(), engine_state, init_cwd);
}
fn gather_env_vars(
vars: impl Iterator<Item = (String, String)>,
engine_state: &mut EngineState,
init_cwd: &Path,
) {
fn report_capture_error(engine_state: &EngineState, env_str: &str, msg: &str) {
report_shell_error(
None,
engine_state,
&ShellError::GenericError {
error: format!("Environment variable was not captured: {env_str}"),
msg: "".into(),
span: None,
help: Some(msg.into()),
inner: vec![],
},
);
}
fn put_env_to_fake_file(name: &str, val: &str, fake_env_file: &mut String) {
fake_env_file.push_str(&escape_quote_string(name));
fake_env_file.push('=');
fake_env_file.push_str(&escape_quote_string(val));
fake_env_file.push('\n');
}
let mut fake_env_file = String::new();
// Write all the env vars into a fake file
for (name, val) in vars {
put_env_to_fake_file(&name, &val, &mut fake_env_file);
}
match init_cwd.to_str() {
Some(cwd) => {
put_env_to_fake_file("PWD", cwd, &mut fake_env_file);
}
None => {
// Could not capture current working directory
report_shell_error(
None,
engine_state,
&ShellError::GenericError {
error: "Current directory is not a valid utf-8 path".into(),
msg: "".into(),
span: None,
help: Some(format!(
"Retrieving current directory failed: {init_cwd:?} not a valid utf-8 path"
)),
inner: vec![],
},
);
}
}
// Lex the fake file, assign spans to all environment variables and add them
// to stack
let span_offset = engine_state.next_span_start();
engine_state.add_file(
"Host Environment Variables".into(),
fake_env_file.as_bytes().into(),
);
let (tokens, _) = lex(fake_env_file.as_bytes(), span_offset, &[], &[], true);
for token in tokens {
if let Token {
contents: TokenContents::Item,
span: full_span,
} = token
{
let contents = engine_state.get_span_contents(full_span);
let (parts, _) = lex(contents, full_span.start, &[], &[b'='], true);
let name = if let Some(Token {
contents: TokenContents::Item,
span,
}) = parts.first()
{
let mut working_set = StateWorkingSet::new(engine_state);
let bytes = working_set.get_span_contents(*span);
if bytes.len() < 2 {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
"Got empty name.",
);
continue;
}
let (bytes, err) = unescape_unquote_string(bytes, *span);
if let Some(err) = err {
working_set.error(err);
}
if !working_set.parse_errors.is_empty() {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
"Got unparsable name.",
);
continue;
}
bytes
} else {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
"Got empty name.",
);
continue;
};
let value = if let Some(Token {
contents: TokenContents::Item,
span,
}) = parts.get(2)
{
let mut working_set = StateWorkingSet::new(engine_state);
let bytes = working_set.get_span_contents(*span);
if bytes.len() < 2 {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
"Got empty value.",
);
continue;
}
let (bytes, err) = unescape_unquote_string(bytes, *span);
if let Some(err) = err {
working_set.error(err);
}
if !working_set.parse_errors.is_empty() {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
"Got unparsable value.",
);
continue;
}
Value::string(bytes, *span)
} else {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
"Got empty value.",
);
continue;
};
// stack.add_env_var(name, value);
engine_state.add_env_var(name, value);
}
}
}
/// Print a pipeline with formatting applied based on display_output hook.
///
/// This function should be preferred when printing values resulting from a completed evaluation.
/// For values printed as part of a command's execution, such as values printed by the `print` command,
/// the `PipelineData::print_table` function should be preferred instead as it is not config-dependent.
///
/// `no_newline` controls if we need to attach newline character to output.
pub fn print_pipeline(
engine_state: &mut EngineState,
stack: &mut Stack,
pipeline: PipelineData,
no_newline: bool,
) -> Result<(), ShellError> {
if let Some(hook) = stack.get_config(engine_state).hooks.display_output.clone() {
let pipeline = eval_hook(
engine_state,
stack,
Some(pipeline),
vec![],
&hook,
"display_output",
)?;
pipeline.print_raw(engine_state, no_newline, false)
} else {
// if display_output isn't set, we should still prefer to print with some formatting
pipeline.print_table(engine_state, stack, no_newline, false)
}
}
pub fn eval_source(
engine_state: &mut EngineState,
stack: &mut Stack,
source: &[u8],
fname: &str,
input: PipelineData,
allow_return: bool,
) -> i32 {
let start_time = std::time::Instant::now();
let exit_code = match evaluate_source(engine_state, stack, source, fname, input, allow_return) {
Ok(failed) => {
let code = failed.into();
stack.set_last_exit_code(code, Span::unknown());
code
}
Err(err) => {
report_shell_error(Some(stack), engine_state, &err);
let code = err.exit_code();
stack.set_last_error(&err);
code.unwrap_or(0)
}
};
// reset vt processing, aka ansi because illbehaved externals can break it
#[cfg(windows)]
{
let _ = enable_vt_processing();
}
perf!(
&format!("eval_source {}", &fname),
start_time,
engine_state
.get_config()
.use_ansi_coloring
.get(engine_state)
);
exit_code
}
fn evaluate_source(
engine_state: &mut EngineState,
stack: &mut Stack,
source: &[u8],
fname: &str,
input: PipelineData,
allow_return: bool,
) -> Result<bool, ShellError> {
let (block, delta) = {
let mut working_set = StateWorkingSet::new(engine_state);
let output = parse(
&mut working_set,
Some(fname), // format!("entry #{}", entry_num)
source,
false,
);
if let Some(warning) = working_set.parse_warnings.first() {
report_parse_warning(Some(stack), &working_set, warning);
}
if let Some(err) = working_set.parse_errors.first() {
report_parse_error(Some(stack), &working_set, err);
return Ok(true);
}
if let Some(err) = working_set.compile_errors.first() {
report_compile_error(Some(stack), &working_set, err);
return Ok(true);
}
(output, working_set.render())
};
engine_state.merge_delta(delta)?;
let pipeline = if allow_return {
eval_block_with_early_return::<WithoutDebug>(engine_state, stack, &block, input)
} else {
eval_block::<WithoutDebug>(engine_state, stack, &block, input)
}?;
let pipeline_data = pipeline.body;
let no_newline = matches!(&pipeline_data, &PipelineData::ByteStream(..));
print_pipeline(engine_state, stack, pipeline_data, no_newline)?;
let pipefail = nu_experimental::PIPE_FAIL.get();
if !pipefail {
return Ok(false);
}
// After print pipeline, need to check exit status to implement pipeline feature.
check_exit_status_future(pipeline.exit).map(|_| false)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_gather_env_vars() {
let mut engine_state = EngineState::new();
let symbols = r##" !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"##;
gather_env_vars(
[
("FOO".into(), "foo".into()),
("SYMBOLS".into(), symbols.into()),
(symbols.into(), "symbols".into()),
]
.into_iter(),
&mut engine_state,
Path::new("t"),
);
let env = engine_state.render_env_vars();
assert!(matches!(env.get("FOO"), Some(&Value::String { val, .. }) if val == "foo"));
assert!(matches!(env.get("SYMBOLS"), Some(&Value::String { val, .. }) if val == symbols));
assert!(matches!(env.get(symbols), Some(&Value::String { val, .. }) if val == "symbols"));
assert!(env.contains_key("PWD"));
assert_eq!(env.len(), 4);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/prompt.rs | crates/nu-cli/src/prompt.rs | use crate::prompt_update::{
POST_PROMPT_MARKER, PRE_PROMPT_MARKER, VSCODE_POST_PROMPT_MARKER, VSCODE_PRE_PROMPT_MARKER,
};
use nu_protocol::engine::{EngineState, Stack};
#[cfg(windows)]
use nu_utils::enable_vt_processing;
use reedline::{
DefaultPrompt, Prompt, PromptEditMode, PromptHistorySearch, PromptHistorySearchStatus,
PromptViMode,
};
use std::borrow::Cow;
/// Nushell prompt definition
#[derive(Clone)]
pub struct NushellPrompt {
shell_integration_osc133: bool,
shell_integration_osc633: bool,
left_prompt_string: Option<String>,
right_prompt_string: Option<String>,
default_prompt_indicator: Option<String>,
default_vi_insert_prompt_indicator: Option<String>,
default_vi_normal_prompt_indicator: Option<String>,
default_multiline_indicator: Option<String>,
render_right_prompt_on_last_line: bool,
engine_state: EngineState,
stack: Stack,
}
impl NushellPrompt {
pub fn new(
shell_integration_osc133: bool,
shell_integration_osc633: bool,
engine_state: EngineState,
stack: Stack,
) -> NushellPrompt {
NushellPrompt {
shell_integration_osc133,
shell_integration_osc633,
left_prompt_string: None,
right_prompt_string: None,
default_prompt_indicator: None,
default_vi_insert_prompt_indicator: None,
default_vi_normal_prompt_indicator: None,
default_multiline_indicator: None,
render_right_prompt_on_last_line: false,
engine_state,
stack,
}
}
pub fn update_prompt_left(&mut self, prompt_string: Option<String>) {
self.left_prompt_string = prompt_string;
}
pub fn update_prompt_right(
&mut self,
prompt_string: Option<String>,
render_right_prompt_on_last_line: bool,
) {
self.right_prompt_string = prompt_string;
self.render_right_prompt_on_last_line = render_right_prompt_on_last_line;
}
pub fn update_prompt_indicator(&mut self, prompt_indicator_string: Option<String>) {
self.default_prompt_indicator = prompt_indicator_string;
}
pub fn update_prompt_vi_insert(&mut self, prompt_vi_insert_string: Option<String>) {
self.default_vi_insert_prompt_indicator = prompt_vi_insert_string;
}
pub fn update_prompt_vi_normal(&mut self, prompt_vi_normal_string: Option<String>) {
self.default_vi_normal_prompt_indicator = prompt_vi_normal_string;
}
pub fn update_prompt_multiline(&mut self, prompt_multiline_indicator_string: Option<String>) {
self.default_multiline_indicator = prompt_multiline_indicator_string;
}
pub fn update_all_prompt_strings(
&mut self,
left_prompt_string: Option<String>,
right_prompt_string: Option<String>,
prompt_indicator_string: Option<String>,
prompt_multiline_indicator_string: Option<String>,
prompt_vi: (Option<String>, Option<String>),
render_right_prompt_on_last_line: bool,
) {
let (prompt_vi_insert_string, prompt_vi_normal_string) = prompt_vi;
self.left_prompt_string = left_prompt_string;
self.right_prompt_string = right_prompt_string;
self.default_prompt_indicator = prompt_indicator_string;
self.default_multiline_indicator = prompt_multiline_indicator_string;
self.default_vi_insert_prompt_indicator = prompt_vi_insert_string;
self.default_vi_normal_prompt_indicator = prompt_vi_normal_string;
self.render_right_prompt_on_last_line = render_right_prompt_on_last_line;
}
fn default_wrapped_custom_string(&self, str: String) -> String {
format!("({str})")
}
}
impl Prompt for NushellPrompt {
fn render_prompt_left(&self) -> Cow<'_, str> {
#[cfg(windows)]
{
let _ = enable_vt_processing();
}
if let Some(prompt_string) = &self.left_prompt_string {
prompt_string.replace('\n', "\r\n").into()
} else {
let default = DefaultPrompt::default();
let prompt = default
.render_prompt_left()
.to_string()
.replace('\n', "\r\n");
if self.shell_integration_osc633 {
if self
.stack
.get_env_var(&self.engine_state, "TERM_PROGRAM")
.and_then(|v| v.as_str().ok())
== Some("vscode")
{
// We're in vscode and we have osc633 enabled
format!("{VSCODE_PRE_PROMPT_MARKER}{prompt}{VSCODE_POST_PROMPT_MARKER}").into()
} else if self.shell_integration_osc133 {
// If we're in VSCode but we don't find the env var, but we have osc133 set, then use it
format!("{PRE_PROMPT_MARKER}{prompt}{POST_PROMPT_MARKER}").into()
} else {
prompt.into()
}
} else if self.shell_integration_osc133 {
format!("{PRE_PROMPT_MARKER}{prompt}{POST_PROMPT_MARKER}").into()
} else {
prompt.into()
}
}
}
fn render_prompt_right(&self) -> Cow<'_, str> {
if let Some(prompt_string) = &self.right_prompt_string {
prompt_string.replace('\n', "\r\n").into()
} else {
let default = DefaultPrompt::default();
default
.render_prompt_right()
.to_string()
.replace('\n', "\r\n")
.into()
}
}
fn render_prompt_indicator(&self, edit_mode: PromptEditMode) -> Cow<'_, str> {
match edit_mode {
PromptEditMode::Default => match &self.default_prompt_indicator {
Some(indicator) => indicator,
None => "> ",
}
.into(),
PromptEditMode::Emacs => match &self.default_prompt_indicator {
Some(indicator) => indicator,
None => "> ",
}
.into(),
PromptEditMode::Vi(vi_mode) => match vi_mode {
PromptViMode::Normal => match &self.default_vi_normal_prompt_indicator {
Some(indicator) => indicator,
None => "> ",
},
PromptViMode::Insert => match &self.default_vi_insert_prompt_indicator {
Some(indicator) => indicator,
None => ": ",
},
}
.into(),
PromptEditMode::Custom(str) => self.default_wrapped_custom_string(str).into(),
}
}
fn render_prompt_multiline_indicator(&self) -> Cow<'_, str> {
match &self.default_multiline_indicator {
Some(indicator) => indicator,
None => "::: ",
}
.into()
}
fn render_prompt_history_search_indicator(
&self,
history_search: PromptHistorySearch,
) -> Cow<'_, str> {
let prefix = match history_search.status {
PromptHistorySearchStatus::Passing => "",
PromptHistorySearchStatus::Failing => "failing ",
};
Cow::Owned(format!(
"({}reverse-search: {})",
prefix, history_search.term
))
}
fn right_prompt_on_last_line(&self) -> bool {
self.render_right_prompt_on_last_line
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/nu_highlight.rs | crates/nu-cli/src/nu_highlight.rs | use std::sync::Arc;
use nu_engine::command_prelude::*;
use reedline::{Highlighter, StyledText};
use crate::syntax_highlight::highlight_syntax;
#[derive(Clone)]
pub struct NuHighlight;
impl Command for NuHighlight {
fn name(&self) -> &str {
"nu-highlight"
}
fn signature(&self) -> Signature {
Signature::build("nu-highlight")
.category(Category::Strings)
.switch(
"reject-garbage",
"Return an error if invalid syntax (garbage) was encountered",
Some('r'),
)
.input_output_types(vec![(Type::String, Type::String)])
}
fn description(&self) -> &str {
"Syntax highlight the input string."
}
fn search_terms(&self) -> Vec<&str> {
vec!["syntax", "color", "convert"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let reject_garbage = call.has_flag(engine_state, stack, "reject-garbage")?;
let head = call.head;
let signals = engine_state.signals();
let engine_state = Arc::new(engine_state.clone());
let stack = Arc::new(stack.clone());
input.map(
move |x| match x.coerce_into_string() {
Ok(line) => {
let result = highlight_syntax(&engine_state, &stack, &line, line.len());
let highlights = match (reject_garbage, result.found_garbage) {
(false, _) => result.text,
(true, None) => result.text,
(true, Some(span)) => {
let error = ShellError::OutsideSpannedLabeledError {
src: line,
error: "encountered invalid syntax while highlighting".into(),
msg: "invalid syntax".into(),
span,
};
return Value::error(error, head);
}
};
Value::string(highlights.render_simple(), head)
}
Err(err) => Value::error(err, head),
},
signals,
)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Describe the type of a string",
example: "'let x = 3' | nu-highlight",
result: None,
}]
}
}
/// A highlighter that does nothing
///
/// Used to remove highlighting from a reedline instance
/// (letting NuHighlighter structs be dropped)
#[derive(Default)]
pub struct NoOpHighlighter {}
impl Highlighter for NoOpHighlighter {
fn highlight(&self, _line: &str, _cursor: usize) -> reedline::StyledText {
StyledText::new()
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/eval_file.rs | crates/nu-cli/src/eval_file.rs | use crate::util::{eval_source, print_pipeline};
use log::{info, trace};
use nu_engine::eval_block;
use nu_parser::parse;
use nu_path::canonicalize_with;
use nu_protocol::{
PipelineData, ShellError, Span, Value,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
report_error::report_compile_error,
report_parse_error, report_parse_warning,
shell_error::io::*,
};
use std::{path::PathBuf, sync::Arc};
/// Entry point for evaluating a file.
///
/// If the file contains a main command, it is invoked with `args` and the pipeline data from `input`;
/// otherwise, the pipeline data is forwarded to the first command in the file, and `args` are ignored.
pub fn evaluate_file(
path: String,
args: &[String],
engine_state: &mut EngineState,
stack: &mut Stack,
input: PipelineData,
) -> Result<(), ShellError> {
let cwd = engine_state.cwd_as_string(Some(stack))?;
let file_path = {
match canonicalize_with(&path, cwd) {
Ok(t) => Ok(t),
Err(err) => {
let cmdline = format!("nu {path} {}", args.join(" "));
let mut working_set = StateWorkingSet::new(engine_state);
let file_id = working_set.add_file("<commandline>".into(), cmdline.as_bytes());
let span = working_set
.get_span_for_file(file_id)
.subspan(3, path.len() + 3)
.expect("<commandline> to contain script path");
engine_state.merge_delta(working_set.render())?;
let e = IoError::new(err.not_found_as(NotFound::File), span, PathBuf::from(&path));
Err(e)
}
}
}?;
let file_path_str = file_path
.to_str()
.ok_or_else(|| ShellError::NonUtf8Custom {
msg: format!(
"Input file name '{}' is not valid UTF8",
file_path.to_string_lossy()
),
span: Span::unknown(),
})?;
let file = std::fs::read(&file_path).map_err(|err| {
IoError::new_internal_with_path(
err.not_found_as(NotFound::File),
"Could not read file",
nu_protocol::location!(),
file_path.clone(),
)
})?;
engine_state.file = Some(file_path.clone());
let parent = file_path.parent().ok_or_else(|| {
IoError::new_internal_with_path(
ErrorKind::DirectoryNotFound,
"The file path does not have a parent",
nu_protocol::location!(),
file_path.clone(),
)
})?;
stack.add_env_var(
"FILE_PWD".to_string(),
Value::string(parent.to_string_lossy(), Span::unknown()),
);
stack.add_env_var(
"CURRENT_FILE".to_string(),
Value::string(file_path.to_string_lossy(), Span::unknown()),
);
stack.add_env_var(
"PROCESS_PATH".to_string(),
Value::string(path, Span::unknown()),
);
let source_filename = file_path
.file_name()
.expect("internal error: missing filename");
let mut working_set = StateWorkingSet::new(engine_state);
trace!("parsing file: {file_path_str}");
let block = parse(&mut working_set, Some(file_path_str), &file, false);
if let Some(warning) = working_set.parse_warnings.first() {
report_parse_warning(None, &working_set, warning);
}
// If any parse errors were found, report the first error and exit.
if let Some(err) = working_set.parse_errors.first() {
report_parse_error(None, &working_set, err);
std::process::exit(1);
}
if let Some(err) = working_set.compile_errors.first() {
report_compile_error(None, &working_set, err);
std::process::exit(1);
}
// Look for blocks whose name starts with "main" and replace it with the filename.
for block in working_set.delta.blocks.iter_mut().map(Arc::make_mut) {
if block.signature.name == "main" {
block.signature.name = source_filename.to_string_lossy().to_string();
} else if block.signature.name.starts_with("main ") {
block.signature.name =
source_filename.to_string_lossy().to_string() + " " + &block.signature.name[5..];
}
}
// Merge the changes into the engine state.
engine_state.merge_delta(working_set.delta)?;
// Check if the file contains a main command.
let exit_code = if engine_state.find_decl(b"main", &[]).is_some() {
// Evaluate the file, but don't run main yet.
let pipeline =
match eval_block::<WithoutDebug>(engine_state, stack, &block, PipelineData::empty())
.map(|p| p.body)
{
Ok(data) => data,
Err(ShellError::Return { .. }) => {
// Allow early return before main is run.
return Ok(());
}
Err(err) => return Err(err),
};
// Print the pipeline output of the last command of the file.
print_pipeline(engine_state, stack, pipeline, true)?;
// Invoke the main command with arguments.
// Arguments with whitespaces are quoted, thus can be safely concatenated by whitespace.
let args = format!("main {}", args.join(" "));
eval_source(
engine_state,
stack,
args.as_bytes(),
"<commandline>",
input,
true,
)
} else {
eval_source(engine_state, stack, &file, file_path_str, input, true)
};
if exit_code != 0 {
std::process::exit(exit_code);
}
info!("evaluate {}:{}:{}", file!(), line!(), column!());
Ok(())
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/eval_cmds.rs | crates/nu-cli/src/eval_cmds.rs | use log::info;
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
PipelineData, ShellError, Spanned, Value,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
process::check_exit_status_future,
report_error::report_compile_error,
report_parse_error, report_parse_warning,
};
use std::sync::Arc;
use crate::util::print_pipeline;
#[derive(Default)]
pub struct EvaluateCommandsOpts {
pub table_mode: Option<Value>,
pub error_style: Option<Value>,
pub no_newline: bool,
}
/// Run a command (or commands) given to us by the user
pub fn evaluate_commands(
commands: &Spanned<String>,
engine_state: &mut EngineState,
stack: &mut Stack,
input: PipelineData,
opts: EvaluateCommandsOpts,
) -> Result<(), ShellError> {
let EvaluateCommandsOpts {
table_mode,
error_style,
no_newline,
} = opts;
// Handle the configured error style early
if let Some(e_style) = error_style {
match e_style.coerce_str()?.parse() {
Ok(e_style) => {
Arc::make_mut(&mut engine_state.config).error_style = e_style;
}
Err(err) => {
return Err(ShellError::GenericError {
error: "Invalid value for `--error-style`".into(),
msg: err.into(),
span: Some(e_style.span()),
help: None,
inner: vec![],
});
}
}
}
// Parse the source code
let (block, delta) = {
if let Some(ref t_mode) = table_mode {
Arc::make_mut(&mut engine_state.config).table.mode =
t_mode.coerce_str()?.parse().unwrap_or_default();
}
let mut working_set = StateWorkingSet::new(engine_state);
let output = parse(&mut working_set, None, commands.item.as_bytes(), false);
if let Some(warning) = working_set.parse_warnings.first() {
report_parse_warning(Some(stack), &working_set, warning);
}
if let Some(err) = working_set.parse_errors.first() {
report_parse_error(Some(stack), &working_set, err);
std::process::exit(1);
}
if let Some(err) = working_set.compile_errors.first() {
report_compile_error(Some(stack), &working_set, err);
std::process::exit(1);
}
(output, working_set.render())
};
// Update permanent state
engine_state.merge_delta(delta)?;
// Run the block
let pipeline = eval_block::<WithoutDebug>(engine_state, stack, &block, input)?;
let pipeline_data = pipeline.body;
if let PipelineData::Value(Value::Error { error, .. }, ..) = pipeline_data {
return Err(*error);
}
if let Some(t_mode) = table_mode {
Arc::make_mut(&mut engine_state.config).table.mode =
t_mode.coerce_str()?.parse().unwrap_or_default();
}
print_pipeline(engine_state, stack, pipeline_data, no_newline)?;
info!("evaluate {}:{}:{}", file!(), line!(), column!());
let pipefail = nu_experimental::PIPE_FAIL.get();
if !pipefail {
return Ok(());
}
// After print pipeline, need to check exit status to implement pipeline feature.
check_exit_status_future(pipeline.exit)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/syntax_highlight.rs | crates/nu-cli/src/syntax_highlight.rs | use log::trace;
use nu_ansi_term::Style;
use nu_color_config::{get_matching_brackets_style, get_shape_color};
use nu_engine::env;
use nu_parser::{FlatShape, flatten_block, parse};
use nu_protocol::{
Span,
ast::{Block, Expr, Expression, PipelineRedirection, RecordItem},
engine::{EngineState, Stack, StateWorkingSet},
};
use reedline::{Highlighter, StyledText};
use std::sync::Arc;
pub struct NuHighlighter {
pub engine_state: Arc<EngineState>,
pub stack: Arc<Stack>,
}
impl Highlighter for NuHighlighter {
fn highlight(&self, line: &str, cursor: usize) -> StyledText {
let result = highlight_syntax(&self.engine_state, &self.stack, line, cursor);
result.text
}
}
/// Result of a syntax highlight operation
#[derive(Default)]
pub(crate) struct HighlightResult {
/// The highlighted text
pub(crate) text: StyledText,
/// The span of any garbage that was highlighted
pub(crate) found_garbage: Option<Span>,
}
pub(crate) fn highlight_syntax(
engine_state: &EngineState,
stack: &Stack,
line: &str,
cursor: usize,
) -> HighlightResult {
trace!("highlighting: {line}");
let config = stack.get_config(engine_state);
let highlight_resolved_externals = config.highlight_resolved_externals;
let mut working_set = StateWorkingSet::new(engine_state);
let block = parse(&mut working_set, None, line.as_bytes(), false);
// TODO: Traverse::flat_map based highlighting?
let shapes = flatten_block(&working_set, &block);
let global_span_offset = engine_state.next_span_start();
let mut result = HighlightResult::default();
let mut last_seen_span_end = global_span_offset;
let global_cursor_offset = cursor + global_span_offset;
let matching_brackets_pos = find_matching_brackets(
line,
&working_set,
&block,
global_span_offset,
global_cursor_offset,
);
for (raw_span, flat_shape) in &shapes {
// NOTE: Currently we expand aliases while flattening for tasks such as completion
// https://github.com/nushell/nushell/issues/16944
let span = if let FlatShape::External(alias_span) = flat_shape {
alias_span
} else {
raw_span
};
if span.end <= last_seen_span_end
|| last_seen_span_end < global_span_offset
|| span.start < global_span_offset
{
// We've already output something for this span
// so just skip this one
continue;
}
if span.start > last_seen_span_end {
let gap = line
[(last_seen_span_end - global_span_offset)..(span.start - global_span_offset)]
.to_string();
result.text.push((Style::new(), gap));
}
let next_token =
line[(span.start - global_span_offset)..(span.end - global_span_offset)].to_string();
let mut add_colored_token = |shape: &FlatShape, text: String| {
result
.text
.push((get_shape_color(shape.as_str(), &config), text));
};
match flat_shape {
FlatShape::Garbage => {
result.found_garbage.get_or_insert_with(|| {
Span::new(
span.start - global_span_offset,
span.end - global_span_offset,
)
});
add_colored_token(flat_shape, next_token)
}
FlatShape::External(_) => {
let mut true_shape = flat_shape.clone();
// Highlighting externals has a config point because of concerns that using which to resolve
// externals may slow down things too much.
if highlight_resolved_externals {
// use `raw_span` here for aliased external calls
let str_contents = working_set.get_span_contents(*raw_span);
let str_word = String::from_utf8_lossy(str_contents).to_string();
let paths = env::path_str(engine_state, stack, *raw_span).ok();
let res = if let Ok(cwd) = engine_state.cwd(Some(stack)) {
which::which_in(str_word, paths.as_ref(), cwd).ok()
} else {
which::which_in_global(str_word, paths.as_ref())
.ok()
.and_then(|mut i| i.next())
};
if res.is_some() {
true_shape = FlatShape::ExternalResolved;
}
}
add_colored_token(&true_shape, next_token);
}
FlatShape::List
| FlatShape::Table
| FlatShape::Record
| FlatShape::Block
| FlatShape::Closure => {
let spans = split_span_by_highlight_positions(
line,
*span,
&matching_brackets_pos,
global_span_offset,
);
for (part, highlight) in spans {
let start = part.start - span.start;
let end = part.end - span.start;
let text = next_token[start..end].to_string();
let mut style = get_shape_color(flat_shape.as_str(), &config);
if highlight {
style = get_matching_brackets_style(style, &config);
}
result.text.push((style, text));
}
}
_ => add_colored_token(flat_shape, next_token),
}
last_seen_span_end = span.end;
}
let remainder = line[(last_seen_span_end - global_span_offset)..].to_string();
if !remainder.is_empty() {
result.text.push((Style::new(), remainder));
}
result
}
fn split_span_by_highlight_positions(
line: &str,
span: Span,
highlight_positions: &[usize],
global_span_offset: usize,
) -> Vec<(Span, bool)> {
let mut start = span.start;
let mut result: Vec<(Span, bool)> = Vec::new();
for pos in highlight_positions {
if start <= *pos && pos < &span.end {
if start < *pos {
result.push((Span::new(start, *pos), false));
}
let span_str = &line[pos - global_span_offset..span.end - global_span_offset];
let end = span_str
.chars()
.next()
.map(|c| pos + get_char_length(c))
.unwrap_or(pos + 1);
result.push((Span::new(*pos, end), true));
start = end;
}
}
if start < span.end {
result.push((Span::new(start, span.end), false));
}
result
}
fn find_matching_brackets(
line: &str,
working_set: &StateWorkingSet,
block: &Block,
global_span_offset: usize,
global_cursor_offset: usize,
) -> Vec<usize> {
const BRACKETS: &str = "{}[]()";
// calculate first bracket position
let global_end_offset = line.len() + global_span_offset;
let global_bracket_pos =
if global_cursor_offset == global_end_offset && global_end_offset > global_span_offset {
// cursor is at the end of a non-empty string -- find block end at the previous position
if let Some(last_char) = line.chars().last() {
global_cursor_offset - get_char_length(last_char)
} else {
global_cursor_offset
}
} else {
// cursor is in the middle of a string -- find block end at the current position
global_cursor_offset
};
// check that position contains bracket
let match_idx = global_bracket_pos - global_span_offset;
if match_idx >= line.len()
|| !BRACKETS.contains(get_char_at_index(line, match_idx).unwrap_or_default())
{
return Vec::new();
}
// find matching bracket by finding matching block end
let matching_block_end = find_matching_block_end_in_block(
line,
working_set,
block,
global_span_offset,
global_bracket_pos,
);
if let Some(pos) = matching_block_end {
let matching_idx = pos - global_span_offset;
if BRACKETS.contains(get_char_at_index(line, matching_idx).unwrap_or_default()) {
return if global_bracket_pos < pos {
vec![global_bracket_pos, pos]
} else {
vec![pos, global_bracket_pos]
};
}
}
Vec::new()
}
fn find_matching_block_end_in_block(
line: &str,
working_set: &StateWorkingSet,
block: &Block,
global_span_offset: usize,
global_cursor_offset: usize,
) -> Option<usize> {
for p in &block.pipelines {
for e in &p.elements {
if e.expr.span.contains(global_cursor_offset)
&& let Some(pos) = find_matching_block_end_in_expr(
line,
working_set,
&e.expr,
global_span_offset,
global_cursor_offset,
)
{
return Some(pos);
}
if let Some(redirection) = e.redirection.as_ref() {
match redirection {
PipelineRedirection::Single { target, .. }
| PipelineRedirection::Separate { out: target, .. }
| PipelineRedirection::Separate { err: target, .. }
if target.span().contains(global_cursor_offset) =>
{
if let Some(pos) = target.expr().and_then(|expr| {
find_matching_block_end_in_expr(
line,
working_set,
expr,
global_span_offset,
global_cursor_offset,
)
}) {
return Some(pos);
}
}
_ => {}
}
}
}
}
None
}
fn find_matching_block_end_in_expr(
line: &str,
working_set: &StateWorkingSet,
expression: &Expression,
global_span_offset: usize,
global_cursor_offset: usize,
) -> Option<usize> {
if expression.span.contains(global_cursor_offset) && expression.span.start >= global_span_offset
{
let expr_first = expression.span.start;
let span_str = &line
[expression.span.start - global_span_offset..expression.span.end - global_span_offset];
let expr_last = span_str
.chars()
.last()
.map(|c| expression.span.end - get_char_length(c))
.unwrap_or(expression.span.start);
return match &expression.expr {
// TODO: Can't these be handled with an `_ => None` branch? Refactor
Expr::Bool(_) => None,
Expr::Int(_) => None,
Expr::Float(_) => None,
Expr::Binary(_) => None,
Expr::Range(..) => None,
Expr::Var(_) => None,
Expr::VarDecl(_) => None,
Expr::ExternalCall(..) => None,
Expr::Operator(_) => None,
Expr::UnaryNot(_) => None,
Expr::Keyword(..) => None,
Expr::ValueWithUnit(..) => None,
Expr::DateTime(_) => None,
Expr::Filepath(_, _) => None,
Expr::Directory(_, _) => None,
Expr::GlobPattern(_, _) => None,
Expr::String(_) => None,
Expr::RawString(_) => None,
Expr::CellPath(_) => None,
Expr::ImportPattern(_) => None,
Expr::Overlay(_) => None,
Expr::Signature(_) => None,
Expr::MatchBlock(_) => None,
Expr::Nothing => None,
Expr::Garbage => None,
Expr::AttributeBlock(ab) => ab
.attributes
.iter()
.find_map(|attr| {
find_matching_block_end_in_expr(
line,
working_set,
&attr.expr,
global_span_offset,
global_cursor_offset,
)
})
.or_else(|| {
find_matching_block_end_in_expr(
line,
working_set,
&ab.item,
global_span_offset,
global_cursor_offset,
)
}),
Expr::Table(table) => {
if expr_last == global_cursor_offset {
// cursor is at table end
Some(expr_first)
} else if expr_first == global_cursor_offset {
// cursor is at table start
Some(expr_last)
} else {
// cursor is inside table
table
.columns
.iter()
.chain(table.rows.iter().flat_map(AsRef::as_ref))
.find_map(|expr| {
find_matching_block_end_in_expr(
line,
working_set,
expr,
global_span_offset,
global_cursor_offset,
)
})
}
}
Expr::Record(exprs) => {
if expr_last == global_cursor_offset {
// cursor is at record end
Some(expr_first)
} else if expr_first == global_cursor_offset {
// cursor is at record start
Some(expr_last)
} else {
// cursor is inside record
exprs.iter().find_map(|expr| match expr {
RecordItem::Pair(k, v) => find_matching_block_end_in_expr(
line,
working_set,
k,
global_span_offset,
global_cursor_offset,
)
.or_else(|| {
find_matching_block_end_in_expr(
line,
working_set,
v,
global_span_offset,
global_cursor_offset,
)
}),
RecordItem::Spread(_, record) => find_matching_block_end_in_expr(
line,
working_set,
record,
global_span_offset,
global_cursor_offset,
),
})
}
}
Expr::Call(call) => call.arguments.iter().find_map(|arg| {
arg.expr().and_then(|expr| {
find_matching_block_end_in_expr(
line,
working_set,
expr,
global_span_offset,
global_cursor_offset,
)
})
}),
Expr::FullCellPath(b) => find_matching_block_end_in_expr(
line,
working_set,
&b.head,
global_span_offset,
global_cursor_offset,
),
Expr::BinaryOp(lhs, op, rhs) => [lhs, op, rhs].into_iter().find_map(|expr| {
find_matching_block_end_in_expr(
line,
working_set,
expr,
global_span_offset,
global_cursor_offset,
)
}),
Expr::Collect(_, expr) => find_matching_block_end_in_expr(
line,
working_set,
expr,
global_span_offset,
global_cursor_offset,
),
Expr::Block(block_id)
| Expr::Closure(block_id)
| Expr::RowCondition(block_id)
| Expr::Subexpression(block_id) => {
if expr_last == global_cursor_offset {
// cursor is at block end
Some(expr_first)
} else if expr_first == global_cursor_offset {
// cursor is at block start
Some(expr_last)
} else {
// cursor is inside block
let nested_block = working_set.get_block(*block_id);
find_matching_block_end_in_block(
line,
working_set,
nested_block,
global_span_offset,
global_cursor_offset,
)
}
}
Expr::StringInterpolation(exprs) | Expr::GlobInterpolation(exprs, _) => {
exprs.iter().find_map(|expr| {
find_matching_block_end_in_expr(
line,
working_set,
expr,
global_span_offset,
global_cursor_offset,
)
})
}
Expr::List(list) => {
if expr_last == global_cursor_offset {
// cursor is at list end
Some(expr_first)
} else if expr_first == global_cursor_offset {
// cursor is at list start
Some(expr_last)
} else {
list.iter().find_map(|item| {
find_matching_block_end_in_expr(
line,
working_set,
item.expr(),
global_span_offset,
global_cursor_offset,
)
})
}
}
};
}
None
}
fn get_char_at_index(s: &str, index: usize) -> Option<char> {
s[index..].chars().next()
}
fn get_char_length(c: char) -> usize {
c.to_string().len()
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/print.rs | crates/nu-cli/src/print.rs | use nu_engine::command_prelude::*;
use nu_protocol::ByteStreamSource;
#[derive(Clone)]
pub struct Print;
impl Command for Print {
fn name(&self) -> &str {
"print"
}
fn signature(&self) -> Signature {
Signature::build("print")
.input_output_types(vec![
(Type::Nothing, Type::Nothing),
(Type::Any, Type::Nothing),
])
.allow_variants_without_examples(true)
.rest("rest", SyntaxShape::Any, "the values to print")
.switch(
"no-newline",
"print without inserting a newline for the line ending",
Some('n'),
)
.switch("stderr", "print to stderr instead of stdout", Some('e'))
.switch(
"raw",
"print without formatting (including binary data)",
Some('r'),
)
.category(Category::Strings)
}
fn description(&self) -> &str {
"Print the given values to stdout."
}
fn extra_description(&self) -> &str {
r#"Unlike `echo`, this command does not return any value (`print | describe` will return "nothing").
Since this command has no output, there is no point in piping it with other commands.
`print` may be used inside blocks of code (e.g.: hooks) to display text during execution without interfering with the pipeline."#
}
fn search_terms(&self) -> Vec<&str> {
vec!["display"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
mut input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args: Vec<Value> = call.rest(engine_state, stack, 0)?;
let no_newline = call.has_flag(engine_state, stack, "no-newline")?;
let raw = call.has_flag(engine_state, stack, "raw")?;
// if we're in the LSP *always* print to stderr
let to_stderr = if engine_state.is_lsp {
true
} else {
call.has_flag(engine_state, stack, "stderr")?
};
// This will allow for easy printing of pipelines as well
if !args.is_empty() {
for arg in args {
if raw {
arg.into_pipeline_data()
.print_raw(engine_state, no_newline, to_stderr)?;
} else {
arg.into_pipeline_data().print_table(
engine_state,
stack,
no_newline,
to_stderr,
)?;
}
}
} else if !input.is_nothing() {
if let PipelineData::ByteStream(stream, _) = &mut input
&& let ByteStreamSource::Child(child) = stream.source_mut()
{
child.ignore_error(true);
}
if raw {
input.print_raw(engine_state, no_newline, to_stderr)?;
} else {
input.print_table(engine_state, stack, no_newline, to_stderr)?;
}
}
Ok(PipelineData::empty())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Print 'hello world'",
example: r#"print "hello world""#,
result: None,
},
Example {
description: "Print the sum of 2 and 3",
example: r#"print (2 + 3)"#,
result: None,
},
Example {
description: "Print 'ABC' from binary data",
example: r#"0x[41 42 43] | print --raw"#,
result: None,
},
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/keybindings.rs | crates/nu-cli/src/commands/keybindings.rs | use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct Keybindings;
impl Command for Keybindings {
fn name(&self) -> &str {
"keybindings"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Platform)
.input_output_types(vec![(Type::Nothing, Type::String)])
}
fn description(&self) -> &str {
"Keybindings related commands."
}
fn extra_description(&self) -> &str {
r#"You must use one of the following subcommands. Using this command as-is will only produce this help message.
For more information on input and keybindings, check:
https://www.nushell.sh/book/line_editor.html"#
}
fn search_terms(&self) -> Vec<&str> {
vec!["shortcut", "hotkey"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/default_context.rs | crates/nu-cli/src/commands/default_context.rs | use crate::commands::*;
use nu_protocol::engine::{EngineState, StateWorkingSet};
pub fn add_cli_context(mut engine_state: EngineState) -> EngineState {
let delta = {
let mut working_set = StateWorkingSet::new(&engine_state);
macro_rules! bind_command {
( $( $command:expr ),* $(,)? ) => {
$( working_set.add_decl(Box::new($command)); )*
};
}
bind_command! {
Commandline,
CommandlineEdit,
CommandlineGetCursor,
CommandlineSetCursor,
History,
Keybindings,
KeybindingsDefault,
KeybindingsList,
KeybindingsListen,
};
#[cfg(feature = "sqlite")]
bind_command! {
HistoryImport,
HistorySession
};
working_set.render()
};
if let Err(err) = engine_state.merge_delta(delta) {
eprintln!("Error creating CLI command context: {err:?}");
}
engine_state
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/keybindings_default.rs | crates/nu-cli/src/commands/keybindings_default.rs | use nu_engine::command_prelude::*;
use reedline::get_reedline_default_keybindings;
#[derive(Clone)]
pub struct KeybindingsDefault;
impl Command for KeybindingsDefault {
fn name(&self) -> &str {
"keybindings default"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Platform)
.input_output_types(vec![(Type::Nothing, Type::table())])
}
fn description(&self) -> &str {
"List default keybindings."
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Get list with default keybindings",
example: "keybindings default",
result: None,
}]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let records = get_reedline_default_keybindings()
.into_iter()
.map(|(mode, modifier, code, event)| {
Value::record(
record! {
"mode" => Value::string(mode, call.head),
"modifier" => Value::string(modifier, call.head),
"code" => Value::string(code, call.head),
"event" => Value::string(event, call.head),
},
call.head,
)
})
.collect();
Ok(Value::list(records, call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/mod.rs | crates/nu-cli/src/commands/mod.rs | mod commandline;
mod default_context;
mod history;
mod keybindings;
mod keybindings_default;
mod keybindings_list;
mod keybindings_listen;
pub use commandline::{Commandline, CommandlineEdit, CommandlineGetCursor, CommandlineSetCursor};
pub use history::*;
pub use keybindings::Keybindings;
pub use keybindings_default::KeybindingsDefault;
pub use keybindings_list::KeybindingsList;
pub use keybindings_listen::KeybindingsListen;
pub use default_context::add_cli_context;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/keybindings_listen.rs | crates/nu-cli/src/commands/keybindings_listen.rs | use crossterm::{
QueueableCommand, event::Event, event::KeyCode, event::KeyEvent, execute, terminal,
};
use nu_engine::command_prelude::*;
use nu_protocol::{Config, shell_error::io::IoError};
use std::io::{Write, stdout};
#[derive(Clone)]
pub struct KeybindingsListen;
impl Command for KeybindingsListen {
fn name(&self) -> &str {
"keybindings listen"
}
fn description(&self) -> &str {
"Get input from the user."
}
fn extra_description(&self) -> &str {
"This is an internal debugging tool. For better output, try `input listen --types [key]`"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Platform)
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.allow_variants_without_examples(true)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
println!("Type any key combination to see key details. Press ESC to abort.");
match print_events(&stack.get_config(engine_state)) {
Ok(v) => Ok(v.into_pipeline_data()),
Err(e) => {
terminal::disable_raw_mode().map_err(|err| {
IoError::new_internal(
err,
"Could not disable raw mode",
nu_protocol::location!(),
)
})?;
Err(ShellError::GenericError {
error: "Error with input".into(),
msg: "".into(),
span: None,
help: Some(e.to_string()),
inner: vec![],
})
}
}
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Type and see key event codes",
example: "keybindings listen",
result: None,
}]
}
}
pub fn print_events(config: &Config) -> Result<Value, ShellError> {
stdout().flush().map_err(|err| {
IoError::new_internal(err, "Could not flush stdout", nu_protocol::location!())
})?;
terminal::enable_raw_mode().map_err(|err| {
IoError::new_internal(err, "Could not enable raw mode", nu_protocol::location!())
})?;
if config.use_kitty_protocol {
if let Ok(false) = crossterm::terminal::supports_keyboard_enhancement() {
println!("WARN: The terminal doesn't support use_kitty_protocol config.\r");
}
// enable kitty protocol
//
// Note that, currently, only the following support this protocol:
// * [kitty terminal](https://sw.kovidgoyal.net/kitty/)
// * [foot terminal](https://codeberg.org/dnkl/foot/issues/319)
// * [WezTerm terminal](https://wezfurlong.org/wezterm/config/lua/config/enable_kitty_keyboard.html)
// * [notcurses library](https://github.com/dankamongmen/notcurses/issues/2131)
// * [neovim text editor](https://github.com/neovim/neovim/pull/18181)
// * [kakoune text editor](https://github.com/mawww/kakoune/issues/4103)
// * [dte text editor](https://gitlab.com/craigbarnes/dte/-/issues/138)
//
// Refer to https://sw.kovidgoyal.net/kitty/keyboard-protocol/ if you're curious.
let _ = execute!(
stdout(),
crossterm::event::PushKeyboardEnhancementFlags(
crossterm::event::KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
)
);
}
let mut stdout = std::io::BufWriter::new(std::io::stderr());
loop {
let event = crossterm::event::read().map_err(|err| {
IoError::new_internal(err, "Could not read event", nu_protocol::location!())
})?;
if event == Event::Key(KeyCode::Esc.into()) {
break;
}
// stdout.queue(crossterm::style::Print(format!("event: {:?}", &event)))?;
// stdout.queue(crossterm::style::Print("\r\n"))?;
// Get a record
let v = print_events_helper(event)?;
// Print out the record
let o = match v {
Value::Record { val, .. } => val
.iter()
.map(|(x, y)| format!("{}: {}", x, y.to_expanded_string("", config)))
.collect::<Vec<String>>()
.join(", "),
_ => "".to_string(),
};
stdout.queue(crossterm::style::Print(o)).map_err(|err| {
IoError::new_internal(
err,
"Could not print output record",
nu_protocol::location!(),
)
})?;
stdout
.queue(crossterm::style::Print("\r\n"))
.map_err(|err| {
IoError::new_internal(err, "Could not print linebreak", nu_protocol::location!())
})?;
stdout.flush().map_err(|err| {
IoError::new_internal(err, "Could not flush", nu_protocol::location!())
})?;
}
if config.use_kitty_protocol {
let _ = execute!(
std::io::stdout(),
crossterm::event::PopKeyboardEnhancementFlags
);
}
terminal::disable_raw_mode().map_err(|err| {
IoError::new_internal(err, "Could not disable raw mode", nu_protocol::location!())
})?;
Ok(Value::nothing(Span::unknown()))
}
// this fn is totally ripped off from crossterm's examples
// it's really a diagnostic routine to see if crossterm is
// even seeing the events. if you press a key and no events
// are printed, it's a good chance your terminal is eating
// those events.
fn print_events_helper(event: Event) -> Result<Value, ShellError> {
if let Event::Key(KeyEvent {
code,
modifiers,
kind,
state,
}) = event
{
match code {
KeyCode::Char(c) => {
let record = record! {
"char" => Value::string(format!("{c}"), Span::unknown()),
"code" => Value::string(format!("{:#08x}", u32::from(c)), Span::unknown()),
"modifier" => Value::string(format!("{modifiers:?}"), Span::unknown()),
"flags" => Value::string(format!("{modifiers:#08b}"), Span::unknown()),
"kind" => Value::string(format!("{kind:?}"), Span::unknown()),
"state" => Value::string(format!("{state:?}"), Span::unknown()),
};
Ok(Value::record(record, Span::unknown()))
}
_ => {
let record = record! {
"code" => Value::string(format!("{code:?}"), Span::unknown()),
"modifier" => Value::string(format!("{modifiers:?}"), Span::unknown()),
"flags" => Value::string(format!("{modifiers:#08b}"), Span::unknown()),
"kind" => Value::string(format!("{kind:?}"), Span::unknown()),
"state" => Value::string(format!("{state:?}"), Span::unknown()),
};
Ok(Value::record(record, Span::unknown()))
}
}
} else {
let record = record! { "event" => Value::string(format!("{event:?}"), Span::unknown()) };
Ok(Value::record(record, Span::unknown()))
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/keybindings_list.rs | crates/nu-cli/src/commands/keybindings_list.rs | use nu_engine::command_prelude::*;
use reedline::{
get_reedline_edit_commands, get_reedline_keybinding_modifiers, get_reedline_keycodes,
get_reedline_prompt_edit_modes, get_reedline_reedline_events,
};
#[derive(Clone)]
pub struct KeybindingsList;
impl Command for KeybindingsList {
fn name(&self) -> &str {
"keybindings list"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Nothing, Type::table())])
.switch("modifiers", "list of modifiers", Some('m'))
.switch("keycodes", "list of keycodes", Some('k'))
.switch("modes", "list of edit modes", Some('o'))
.switch("events", "list of reedline event", Some('e'))
.switch("edits", "list of edit commands", Some('d'))
.category(Category::Platform)
}
fn description(&self) -> &str {
"List available options that can be used to create keybindings."
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Get list of key modifiers",
example: "keybindings list --modifiers",
result: None,
},
Example {
description: "Get list of reedline events and edit commands",
example: "keybindings list -e -d",
result: None,
},
Example {
description: "Get list with all the available options",
example: "keybindings list",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let all_options = ["modifiers", "keycodes", "edits", "modes", "events"];
let presence = all_options
.iter()
.map(|option| call.has_flag(engine_state, stack, option))
.collect::<Result<Vec<_>, ShellError>>()?;
let no_option_specified = presence.iter().all(|present| !*present);
let records = all_options
.iter()
.zip(presence)
.filter(|(_, present)| no_option_specified || *present)
.flat_map(|(option, _)| get_records(option, call.head))
.collect();
Ok(Value::list(records, call.head).into_pipeline_data())
}
}
fn get_records(entry_type: &str, span: Span) -> Vec<Value> {
let values = match entry_type {
"modifiers" => get_reedline_keybinding_modifiers().sorted(),
"keycodes" => get_reedline_keycodes().sorted(),
"edits" => get_reedline_edit_commands().sorted(),
"modes" => get_reedline_prompt_edit_modes().sorted(),
"events" => get_reedline_reedline_events().sorted(),
_ => Vec::new(),
};
values
.iter()
.map(|edit| edit.split('\n'))
.flat_map(|edit| edit.map(|edit| convert_to_record(edit, entry_type, span)))
.collect()
}
fn convert_to_record(edit: &str, entry_type: &str, span: Span) -> Value {
Value::record(
record! {
"type" => Value::string(entry_type, span),
"name" => Value::string(edit, span),
},
span,
)
}
// Helper to sort a vec and return a vec
trait SortedImpl {
fn sorted(self) -> Self;
}
impl<E> SortedImpl for Vec<E>
where
E: std::cmp::Ord,
{
fn sorted(mut self) -> Self {
self.sort();
self
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/history/history_import.rs | crates/nu-cli/src/commands/history/history_import.rs | use std::path::{Path, PathBuf};
use nu_engine::command_prelude::*;
use nu_protocol::{
HistoryFileFormat,
shell_error::{self, io::IoError},
};
use reedline::{
FileBackedHistory, History, HistoryItem, ReedlineError, SearchQuery, SqliteBackedHistory,
};
use super::fields;
#[derive(Clone)]
pub struct HistoryImport;
impl Command for HistoryImport {
fn name(&self) -> &str {
"history import"
}
fn description(&self) -> &str {
"Import command line history."
}
fn extra_description(&self) -> &str {
r#"Can import history from input, either successive command lines or more detailed records. If providing records, available fields are:
command, start_timestamp, hostname, cwd, duration, exit_status.
If no input is provided, will import all history items from existing history in the other format: if current history is stored in sqlite, it will store it in plain text and vice versa.
Note that history item IDs are ignored when importing from file."#
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("history import")
.category(Category::History)
.input_output_types(vec![
(Type::Nothing, Type::Nothing),
(Type::String, Type::Nothing),
(Type::List(Box::new(Type::String)), Type::Nothing),
(Type::table(), Type::Nothing),
])
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
example: "history import",
description: "Append all items from history in the other format to the current history",
result: None,
},
Example {
example: "echo foo | history import",
description: "Append `foo` to the current history",
result: None,
},
Example {
example: "[[ command cwd ]; [ foo /home ]] | history import",
description: "Append `foo` ran from `/home` to the current history",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let ok = Ok(Value::nothing(call.head).into_pipeline_data());
let Some(history) = engine_state.history_config() else {
return ok;
};
let Some(current_history_path) = history.file_path() else {
return Err(ShellError::ConfigDirNotFound { span });
};
if let Some(bak_path) = backup(¤t_history_path, span)? {
println!("Backed history to {}", bak_path.display());
}
match input {
PipelineData::Empty => {
let other_format = match history.file_format {
HistoryFileFormat::Sqlite => HistoryFileFormat::Plaintext,
HistoryFileFormat::Plaintext => HistoryFileFormat::Sqlite,
};
let src = new_backend(other_format, None, call.head)?;
let mut dst =
new_backend(history.file_format, Some(current_history_path), call.head)?;
let items = src
.search(SearchQuery::everything(
reedline::SearchDirection::Forward,
None,
))
.map_err(error_from_reedline)?
.into_iter()
.map(Ok);
import(dst.as_mut(), items)
}
_ => {
let input = input.into_iter().map(item_from_value);
import(
new_backend(history.file_format, Some(current_history_path), call.head)?
.as_mut(),
input,
)
}
}?;
ok
}
}
fn new_backend(
format: HistoryFileFormat,
path: Option<PathBuf>,
span: Span,
) -> Result<Box<dyn History>, ShellError> {
let path = match path {
Some(path) => path,
None => {
let Some(mut path) = nu_path::nu_config_dir() else {
return Err(ShellError::ConfigDirNotFound { span });
};
path.push(format.default_file_name());
path.into_std_path_buf()
}
};
fn map(
result: Result<impl History + 'static, ReedlineError>,
) -> Result<Box<dyn History>, ShellError> {
result
.map(|x| Box::new(x) as Box<dyn History>)
.map_err(error_from_reedline)
}
match format {
// Use a reasonably large value for maximum capacity.
HistoryFileFormat::Plaintext => map(FileBackedHistory::with_file(0xfffffff, path)),
HistoryFileFormat::Sqlite => map(SqliteBackedHistory::with_file(path, None, None)),
}
}
fn import(
dst: &mut dyn History,
src: impl Iterator<Item = Result<HistoryItem, ShellError>>,
) -> Result<(), ShellError> {
for item in src {
let mut item = item?;
item.id = None;
dst.save(item).map_err(error_from_reedline)?;
}
Ok(())
}
fn error_from_reedline(e: ReedlineError) -> ShellError {
// TODO: Should we add a new ShellError variant?
ShellError::GenericError {
error: "Reedline error".to_owned(),
msg: format!("{e}"),
span: None,
help: None,
inner: Vec::new(),
}
}
fn item_from_value(v: Value) -> Result<HistoryItem, ShellError> {
let span = v.span();
match v {
Value::Record { val, .. } => item_from_record(val.into_owned(), span),
Value::String { val, .. } => Ok(HistoryItem {
command_line: val,
id: None,
start_timestamp: None,
session_id: None,
hostname: None,
cwd: None,
duration: None,
exit_status: None,
more_info: None,
}),
_ => Err(ShellError::UnsupportedInput {
msg: "Only list and record inputs are supported".to_owned(),
input: v.get_type().to_string(),
msg_span: span,
input_span: span,
}),
}
}
fn item_from_record(mut rec: Record, span: Span) -> Result<HistoryItem, ShellError> {
let cmd = match rec.remove(fields::COMMAND_LINE) {
Some(v) => v.as_str()?.to_owned(),
None => {
return Err(ShellError::TypeMismatch {
err_message: format!("missing column: {}", fields::COMMAND_LINE),
span,
});
}
};
fn get<T>(
rec: &mut Record,
field: &'static str,
f: impl FnOnce(Value) -> Result<T, ShellError>,
) -> Result<Option<T>, ShellError> {
rec.remove(field).map(f).transpose()
}
let rec = &mut rec;
let item = HistoryItem {
command_line: cmd,
id: None,
start_timestamp: get(rec, fields::START_TIMESTAMP, |v| Ok(v.as_date()?.to_utc()))?,
hostname: get(rec, fields::HOSTNAME, |v| Ok(v.as_str()?.to_owned()))?,
cwd: get(rec, fields::CWD, |v| Ok(v.as_str()?.to_owned()))?,
exit_status: get(rec, fields::EXIT_STATUS, |v| v.as_int())?,
duration: get(rec, fields::DURATION, |v| duration_from_value(v, span))?,
more_info: None,
// TODO: Currently reedline doesn't let you create session IDs.
session_id: None,
};
if !rec.is_empty() {
let cols = rec.columns().map(|s| s.as_str()).collect::<Vec<_>>();
return Err(ShellError::TypeMismatch {
err_message: format!("unsupported column names: {}", cols.join(", ")),
span,
});
}
Ok(item)
}
fn duration_from_value(v: Value, span: Span) -> Result<std::time::Duration, ShellError> {
chrono::Duration::nanoseconds(v.as_duration()?)
.to_std()
.map_err(|_| ShellError::NeedsPositiveValue { span })
}
fn find_backup_path(path: &Path, span: Span) -> Result<PathBuf, ShellError> {
let Ok(mut bak_path) = path.to_path_buf().into_os_string().into_string() else {
// This isn't fundamentally problem, but trying to work with OsString is a nightmare.
return Err(ShellError::GenericError {
error: "History path not UTF-8".to_string(),
msg: "History path must be representable as UTF-8".to_string(),
span: Some(span),
help: None,
inner: vec![],
});
};
bak_path.push_str(".bak");
if !Path::new(&bak_path).exists() {
return Ok(bak_path.into());
}
let base_len = bak_path.len();
for i in 1..100 {
use std::fmt::Write;
bak_path.truncate(base_len);
write!(&mut bak_path, ".{i}").ok();
if !Path::new(&bak_path).exists() {
return Ok(PathBuf::from(bak_path));
}
}
Err(ShellError::GenericError {
error: "Too many backup files".to_string(),
msg: "Found too many existing backup files".to_string(),
span: Some(span),
help: None,
inner: vec![],
})
}
fn backup(path: &Path, span: Span) -> Result<Option<PathBuf>, ShellError> {
match path.metadata() {
Ok(md) if md.is_file() => (),
Ok(_) => {
return Err(IoError::new_with_additional_context(
shell_error::io::ErrorKind::NotAFile,
span,
PathBuf::from(path),
"history path exists but is not a file",
)
.into());
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => {
return Err(IoError::new_internal(
e,
"Could not get metadata",
nu_protocol::location!(),
)
.into());
}
}
let bak_path = find_backup_path(path, span)?;
std::fs::copy(path, &bak_path).map_err(|err| {
IoError::new_internal(
err.not_found_as(NotFound::File),
"Could not copy backup",
nu_protocol::location!(),
)
})?;
Ok(Some(bak_path))
}
#[cfg(test)]
mod tests {
use chrono::DateTime;
use rstest::rstest;
use super::*;
#[test]
fn test_item_from_value_string() -> Result<(), ShellError> {
let item = item_from_value(Value::string("foo", Span::unknown()))?;
assert_eq!(
item,
HistoryItem {
command_line: "foo".to_string(),
id: None,
start_timestamp: None,
session_id: None,
hostname: None,
cwd: None,
duration: None,
exit_status: None,
more_info: None
}
);
Ok(())
}
#[test]
fn test_item_from_value_record() {
let span = Span::unknown();
let rec = new_record(&[
("command", Value::string("foo", span)),
(
"start_timestamp",
Value::date(
DateTime::parse_from_rfc3339("1996-12-19T16:39:57-08:00").unwrap(),
span,
),
),
("hostname", Value::string("localhost", span)),
("cwd", Value::string("/home/test", span)),
("duration", Value::duration(100_000_000, span)),
("exit_status", Value::int(42, span)),
]);
let item = item_from_value(rec).unwrap();
assert_eq!(
item,
HistoryItem {
command_line: "foo".to_string(),
id: None,
start_timestamp: Some(
DateTime::parse_from_rfc3339("1996-12-19T16:39:57-08:00")
.unwrap()
.to_utc()
),
hostname: Some("localhost".to_string()),
cwd: Some("/home/test".to_string()),
duration: Some(std::time::Duration::from_nanos(100_000_000)),
exit_status: Some(42),
session_id: None,
more_info: None
}
);
}
#[test]
fn test_item_from_value_record_extra_field() {
let span = Span::unknown();
let rec = new_record(&[
("command_line", Value::string("foo", span)),
("id_nonexistent", Value::int(1, span)),
]);
assert!(item_from_value(rec).is_err());
}
#[test]
fn test_item_from_value_record_bad_type() {
let span = Span::unknown();
let rec = new_record(&[
("command_line", Value::string("foo", span)),
("id", Value::string("one".to_string(), span)),
]);
assert!(item_from_value(rec).is_err());
}
fn new_record(rec: &[(&'static str, Value)]) -> Value {
let span = Span::unknown();
let rec = Record::from_raw_cols_vals(
rec.iter().map(|(col, _)| col.to_string()).collect(),
rec.iter().map(|(_, val)| val.clone()).collect(),
span,
span,
)
.unwrap();
Value::record(rec, span)
}
#[rstest]
#[case::no_backup(&["history.dat"], "history.dat.bak")]
#[case::backup_exists(&["history.dat", "history.dat.bak"], "history.dat.bak.1")]
#[case::multiple_backups_exists( &["history.dat", "history.dat.bak", "history.dat.bak.1"], "history.dat.bak.2")]
fn test_find_backup_path(#[case] existing: &[&str], #[case] want: &str) {
let dir = tempfile::tempdir().unwrap();
for name in existing {
std::fs::File::create_new(dir.path().join(name)).unwrap();
}
let got = find_backup_path(&dir.path().join("history.dat"), Span::test_data()).unwrap();
assert_eq!(got, dir.path().join(want))
}
#[test]
fn test_backup() {
let dir = tempfile::tempdir().unwrap();
let mut history = std::fs::File::create_new(dir.path().join("history.dat")).unwrap();
use std::io::Write;
write!(&mut history, "123").unwrap();
let want_bak_path = dir.path().join("history.dat.bak");
assert_eq!(
backup(&dir.path().join("history.dat"), Span::test_data()),
Ok(Some(want_bak_path.clone()))
);
let got_data = String::from_utf8(std::fs::read(want_bak_path).unwrap()).unwrap();
assert_eq!(got_data, "123");
}
#[test]
fn test_backup_no_file() {
let dir = tempfile::tempdir().unwrap();
let bak_path = backup(&dir.path().join("history.dat"), Span::test_data()).unwrap();
assert!(bak_path.is_none());
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/history/fields.rs | crates/nu-cli/src/commands/history/fields.rs | // Each const is named after a HistoryItem field, and the value is the field name to be displayed to
// the user (or accept during import).
pub const COMMAND_LINE: &str = "command";
#[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
mod sqlite_only_fields {
pub const START_TIMESTAMP: &str = "start_timestamp";
pub const HOSTNAME: &str = "hostname";
pub const CWD: &str = "cwd";
pub const EXIT_STATUS: &str = "exit_status";
pub const DURATION: &str = "duration";
pub const SESSION_ID: &str = "session_id";
}
#[cfg_attr(not(feature = "sqlite"), allow(unused))]
pub use sqlite_only_fields::*;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/history/mod.rs | crates/nu-cli/src/commands/history/mod.rs | mod fields;
mod history_;
pub use history_::History;
// if more history formats are added, will need to reconsider this
#[cfg(feature = "sqlite")]
mod history_import;
#[cfg(feature = "sqlite")]
mod history_session;
#[cfg(feature = "sqlite")]
pub use history_import::HistoryImport;
#[cfg(feature = "sqlite")]
pub use history_session::HistorySession;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/history/history_.rs | crates/nu-cli/src/commands/history/history_.rs | use nu_engine::command_prelude::*;
use nu_protocol::{
HistoryFileFormat,
shell_error::{self, io::IoError},
};
use reedline::{FileBackedHistory, History as ReedlineHistory, SearchDirection, SearchQuery};
#[cfg(feature = "sqlite")]
use reedline::{HistoryItem, SqliteBackedHistory};
use super::fields;
#[derive(Clone)]
pub struct History;
impl Command for History {
fn name(&self) -> &str {
"history"
}
fn description(&self) -> &str {
"Get the command history."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("history")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.allow_variants_without_examples(true)
.switch("clear", "Clears out the history entries", Some('c'))
.switch(
"long",
"Show long listing of entries for sqlite history",
Some('l'),
)
.category(Category::History)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let Some(history) = engine_state.history_config() else {
return Ok(PipelineData::empty());
};
// todo for sqlite history this command should be an alias to `open ~/.config/nushell/history.sqlite3 | get history`
let Some(history_path) = history.file_path() else {
return Err(ShellError::ConfigDirNotFound { span: head });
};
if call.has_flag(engine_state, stack, "clear")? {
let _ = std::fs::remove_file(history_path);
// TODO: FIXME also clear the auxiliary files when using sqlite
return Ok(PipelineData::empty());
}
#[cfg_attr(not(feature = "sqlite"), allow(unused_variables))]
let long = call.has_flag(engine_state, stack, "long")?;
let signals = engine_state.signals().clone();
let history_reader: Option<Box<dyn ReedlineHistory>> = match history.file_format {
#[cfg(feature = "sqlite")]
HistoryFileFormat::Sqlite => {
SqliteBackedHistory::with_file(history_path.clone(), None, None)
.map(|inner| {
let boxed: Box<dyn ReedlineHistory> = Box::new(inner);
boxed
})
.ok()
}
// this variant should never happen, the config value is handled in the `UpdateFromValue` impl
#[cfg(not(feature = "sqlite"))]
HistoryFileFormat::Sqlite => {
return Err(ShellError::GenericError {
error: "Could not open history reader".into(),
msg: "SQLite is not supported".to_string(),
span: Some(call.head),
help: "Compile Nushell with `sqlite` feature".to_string().into(),
inner: vec![],
});
}
HistoryFileFormat::Plaintext => {
FileBackedHistory::with_file(history.max_size as usize, history_path.clone())
.map(|inner| {
let boxed: Box<dyn ReedlineHistory> = Box::new(inner);
boxed
})
.ok()
}
};
match history.file_format {
HistoryFileFormat::Plaintext => Ok(history_reader
.and_then(|h| {
h.search(SearchQuery::everything(SearchDirection::Forward, None))
.ok()
})
.map(move |entries| {
entries.into_iter().enumerate().map(move |(idx, entry)| {
Value::record(
record! {
fields::COMMAND_LINE => Value::string(entry.command_line, head),
// TODO: This name is inconsistent with create_history_record.
"index" => Value::int(idx as i64, head),
},
head,
)
})
})
.ok_or(IoError::new(
shell_error::io::ErrorKind::FileNotFound,
head,
history_path,
))?
.into_pipeline_data(head, signals)),
// this variant should never happen, the config value is handled in the `UpdateFromValue` impl
#[cfg(not(feature = "sqlite"))]
HistoryFileFormat::Sqlite => {
return Err(ShellError::GenericError {
error: "Could not open history reader".into(),
msg: "SQLite is not supported".to_string(),
span: Some(call.head),
help: "Compile Nushell with `sqlite` feature".to_string().into(),
inner: vec![],
});
}
#[cfg(feature = "sqlite")]
HistoryFileFormat::Sqlite => Ok(history_reader
.and_then(|h| {
h.search(SearchQuery::everything(SearchDirection::Forward, None))
.ok()
})
.map(move |entries| {
entries.into_iter().enumerate().map(move |(idx, entry)| {
create_sqlite_history_record(idx, entry, long, head)
})
})
.ok_or(IoError::new(
shell_error::io::ErrorKind::FileNotFound,
head,
history_path,
))?
.into_pipeline_data(head, signals)),
}
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
example: "history | length",
description: "Get current history length",
result: None,
},
Example {
example: "history | last 5",
description: "Show last 5 commands you have ran",
result: None,
},
Example {
example: "history | where command =~ cargo | get command",
description: "Search all the commands from history that contains 'cargo'",
result: None,
},
]
}
}
#[cfg(feature = "sqlite")]
fn create_sqlite_history_record(idx: usize, entry: HistoryItem, long: bool, head: Span) -> Value {
//1. Format all the values
//2. Create a record of either short or long columns and values
let item_id_value = Value::int(
entry
.id
.and_then(|id| id.to_string().parse::<i64>().ok())
.unwrap_or_default(),
head,
);
let start_timestamp_value = Value::date(
entry.start_timestamp.unwrap_or_default().fixed_offset(),
head,
);
let command_value = Value::string(entry.command_line, head);
let session_id_value = Value::int(
entry
.session_id
.and_then(|id| id.to_string().parse::<i64>().ok())
.unwrap_or_default(),
head,
);
let hostname_value = Value::string(entry.hostname.unwrap_or_default(), head);
let cwd_value = Value::string(entry.cwd.unwrap_or_default(), head);
let duration_value = Value::duration(
entry
.duration
.and_then(|d| d.as_nanos().try_into().ok())
.unwrap_or(0),
head,
);
let exit_status_value = Value::int(entry.exit_status.unwrap_or(0), head);
let index_value = Value::int(idx as i64, head);
if long {
Value::record(
record! {
"item_id" => item_id_value,
fields::START_TIMESTAMP => start_timestamp_value,
fields::COMMAND_LINE => command_value,
fields::SESSION_ID => session_id_value,
fields::HOSTNAME => hostname_value,
fields::CWD => cwd_value,
fields::DURATION => duration_value,
fields::EXIT_STATUS => exit_status_value,
"idx" => index_value,
},
head,
)
} else {
Value::record(
record! {
fields::START_TIMESTAMP => start_timestamp_value,
fields::COMMAND_LINE => command_value,
fields::CWD => cwd_value,
fields::DURATION => duration_value,
fields::EXIT_STATUS => exit_status_value,
},
head,
)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/history/history_session.rs | crates/nu-cli/src/commands/history/history_session.rs | use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct HistorySession;
impl Command for HistorySession {
fn name(&self) -> &str {
"history session"
}
fn description(&self) -> &str {
"Get the command history session."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("history session")
.category(Category::History)
.input_output_types(vec![(Type::Nothing, Type::Int)])
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
example: "history session",
description: "Get current history session",
result: None,
}]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::int(engine_state.history_session_id, call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/commandline/commandline_.rs | crates/nu-cli/src/commands/commandline/commandline_.rs | use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct Commandline;
impl Command for Commandline {
fn name(&self) -> &str {
"commandline"
}
fn signature(&self) -> Signature {
Signature::build("commandline")
.input_output_types(vec![(Type::Nothing, Type::String)])
.category(Category::Core)
}
fn description(&self) -> &str {
"View the current command line input buffer."
}
fn search_terms(&self) -> Vec<&str> {
vec!["repl", "interactive"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let repl = engine_state.repl_state.lock().expect("repl state mutex");
Ok(Value::string(repl.buffer.clone(), call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/commandline/set_cursor.rs | crates/nu-cli/src/commands/commandline/set_cursor.rs | use nu_engine::command_prelude::*;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Clone)]
pub struct CommandlineSetCursor;
impl Command for CommandlineSetCursor {
fn name(&self) -> &str {
"commandline set-cursor"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.switch(
"end",
"set the current cursor position to the end of the buffer",
Some('e'),
)
.optional("pos", SyntaxShape::Int, "Cursor position to be set.")
.category(Category::Core)
}
fn description(&self) -> &str {
"Set the current cursor position."
}
fn search_terms(&self) -> Vec<&str> {
vec!["repl", "interactive"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
if let Some(pos) = call.opt::<i64>(engine_state, stack, 0)? {
repl.cursor_pos = if pos <= 0 {
0usize
} else {
repl.buffer
.grapheme_indices(true)
.map(|(i, _c)| i)
.nth(pos as usize)
.unwrap_or(repl.buffer.len())
};
Ok(Value::nothing(call.head).into_pipeline_data())
} else if call.has_flag(engine_state, stack, "end")? {
repl.cursor_pos = repl.buffer.len();
Ok(Value::nothing(call.head).into_pipeline_data())
} else {
Err(ShellError::GenericError {
error: "Required a positional argument or a flag".to_string(),
msg: "".to_string(),
span: None,
help: None,
inner: vec![],
})
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/commandline/mod.rs | crates/nu-cli/src/commands/commandline/mod.rs | mod commandline_;
mod edit;
mod get_cursor;
mod set_cursor;
pub use commandline_::Commandline;
pub use edit::CommandlineEdit;
pub use get_cursor::CommandlineGetCursor;
pub use set_cursor::CommandlineSetCursor;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/commandline/edit.rs | crates/nu-cli/src/commands/commandline/edit.rs | use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct CommandlineEdit;
impl Command for CommandlineEdit {
fn name(&self) -> &str {
"commandline edit"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.switch(
"append",
"appends the string to the end of the buffer",
Some('a'),
)
.switch(
"insert",
"inserts the string into the buffer at the cursor position",
Some('i'),
)
.switch(
"replace",
"replaces the current contents of the buffer (default)",
Some('r'),
)
.switch(
"accept",
"immediately executes the result after edit",
Some('A'),
)
.required(
"str",
SyntaxShape::String,
"The string to perform the operation with.",
)
.category(Category::Core)
}
fn description(&self) -> &str {
"Modify the current command line input buffer."
}
fn search_terms(&self) -> Vec<&str> {
vec!["repl", "interactive"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let str: String = call.req(engine_state, stack, 0)?;
let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
if call.has_flag(engine_state, stack, "append")? {
repl.buffer.push_str(&str);
} else if call.has_flag(engine_state, stack, "insert")? {
let cursor_pos = repl.cursor_pos;
repl.buffer.insert_str(cursor_pos, &str);
repl.cursor_pos += str.len();
} else {
repl.buffer = str;
repl.cursor_pos = repl.buffer.len();
}
repl.accept = call.has_flag(engine_state, stack, "accept")?;
Ok(Value::nothing(call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/commands/commandline/get_cursor.rs | crates/nu-cli/src/commands/commandline/get_cursor.rs | use nu_engine::command_prelude::*;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Clone)]
pub struct CommandlineGetCursor;
impl Command for CommandlineGetCursor {
fn name(&self) -> &str {
"commandline get-cursor"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Nothing, Type::Int)])
.allow_variants_without_examples(true)
.category(Category::Core)
}
fn description(&self) -> &str {
"Get the current cursor position."
}
fn search_terms(&self) -> Vec<&str> {
vec!["repl", "interactive"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let repl = engine_state.repl_state.lock().expect("repl state mutex");
let char_pos = repl
.buffer
.grapheme_indices(true)
.chain(std::iter::once((repl.buffer.len(), "")))
.position(|(i, _c)| i == repl.cursor_pos)
.expect("Cursor position isn't on a grapheme boundary");
match i64::try_from(char_pos) {
Ok(pos) => Ok(Value::int(pos, call.head).into_pipeline_data()),
Err(e) => Err(ShellError::GenericError {
error: "Failed to convert cursor position to int".to_string(),
msg: e.to_string(),
span: None,
help: None,
inner: vec![],
}),
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/completion_common.rs | crates/nu-cli/src/completions/completion_common.rs | use super::{MatchAlgorithm, completion_options::NuMatcher};
use crate::completions::CompletionOptions;
use nu_ansi_term::Style;
use nu_engine::env_to_string;
use nu_path::dots::expand_ndots;
use nu_path::{expand_to_real_path, home_dir};
use nu_protocol::{
Span,
engine::{EngineState, Stack, StateWorkingSet},
};
use nu_utils::IgnoreCaseExt;
use nu_utils::get_ls_colors;
use std::path::{Component, MAIN_SEPARATOR as SEP, Path, PathBuf, is_separator};
#[derive(Clone, Default)]
pub struct PathBuiltFromString {
cwd: PathBuf,
parts: Vec<String>,
isdir: bool,
}
/// Recursively goes through paths that match a given `partial`.
/// built: State struct for a valid matching path built so far.
///
/// `want_directory`: Whether we want only directories as completion matches.
/// Some commands like `cd` can only be run on directories whereas others
/// like `ls` can be run on regular files as well.
///
/// `isdir`: whether the current partial path has a trailing slash.
/// Parsing a path string into a pathbuf loses that bit of information.
///
/// `enable_exact_match`: Whether match algorithm is Prefix and all previous components
/// of the path matched a directory exactly.
fn complete_rec(
partial: &[&str],
built_paths: &[PathBuiltFromString],
options: &CompletionOptions,
want_directory: bool,
isdir: bool,
enable_exact_match: bool,
) -> Vec<PathBuiltFromString> {
let has_more = !partial.is_empty() && (partial.len() > 1 || isdir);
if let Some((&base, rest)) = partial.split_first()
&& base.chars().all(|c| c == '.')
&& has_more
{
let built_paths: Vec<_> = built_paths
.iter()
.map(|built| {
let mut built = built.clone();
built.parts.push(base.to_string());
built.isdir = true;
built
})
.collect();
return complete_rec(
rest,
&built_paths,
options,
want_directory,
isdir,
enable_exact_match,
);
}
let prefix = partial.first().unwrap_or(&"");
let mut matcher = NuMatcher::new(prefix, options, true);
let mut exact_match = None;
// Only relevant for case insensitive matching
let mut multiple_exact_matches = false;
for built in built_paths {
let mut path = built.cwd.clone();
for part in &built.parts {
path.push(part);
}
let Ok(result) = path.read_dir() else {
continue;
};
for entry in result.filter_map(|e| e.ok()) {
let entry_name = entry.file_name().to_string_lossy().into_owned();
let entry_isdir = entry.path().is_dir();
let mut built = built.clone();
built.parts.push(entry_name.clone());
// Symlinks to directories shouldn't have a trailing slash (#13275)
built.isdir = entry_isdir && !entry.path().is_symlink();
if !want_directory || entry_isdir {
if enable_exact_match && !multiple_exact_matches && has_more {
let matches = if options.case_sensitive {
entry_name.eq(prefix)
} else {
entry_name.eq_ignore_case(prefix)
};
if matches {
if exact_match.is_none() {
exact_match = Some(built.clone());
} else {
multiple_exact_matches = true;
}
}
}
matcher.add(entry_name, built);
}
}
}
// Don't show longer completions if we have a single exact match (#13204, #14794)
if !multiple_exact_matches && let Some(built) = exact_match {
return complete_rec(
&partial[1..],
&[built],
options,
want_directory,
isdir,
true,
);
}
if has_more {
let mut completions = vec![];
for (built, _) in matcher.results() {
completions.extend(complete_rec(
&partial[1..],
&[built],
options,
want_directory,
isdir,
false,
));
}
completions
} else {
matcher
.results()
.into_iter()
.map(|(built, _)| built)
.collect()
}
}
#[derive(Debug)]
enum OriginalCwd {
None,
Home,
Prefix(String),
}
impl OriginalCwd {
fn apply(&self, mut p: PathBuiltFromString, path_separator: char) -> String {
match self {
Self::None => {}
Self::Home => p.parts.insert(0, "~".to_string()),
Self::Prefix(s) => p.parts.insert(0, s.clone()),
};
let mut ret = p.parts.join(&path_separator.to_string());
if p.isdir {
ret.push(path_separator);
}
ret
}
}
pub fn surround_remove(partial: &str) -> String {
for c in ['`', '"', '\''] {
if partial.starts_with(c) {
let ret = partial.strip_prefix(c).unwrap_or(partial);
return match ret.split(c).collect::<Vec<_>>()[..] {
[inside] => inside.to_string(),
[inside, outside] if inside.ends_with(is_separator) => format!("{inside}{outside}"),
_ => ret.to_string(),
};
}
}
partial.to_string()
}
pub struct FileSuggestion {
pub span: nu_protocol::Span,
pub path: String,
pub style: Option<Style>,
pub is_dir: bool,
}
/// # Parameters
/// * `cwds` - A list of directories in which to search. The only reason this isn't a single string
/// is because dotnu_completions searches in multiple directories at once
pub fn complete_item(
want_directory: bool,
span: nu_protocol::Span,
partial: &str,
cwds: &[impl AsRef<str>],
options: &CompletionOptions,
engine_state: &EngineState,
stack: &Stack,
) -> Vec<FileSuggestion> {
let cleaned_partial = surround_remove(partial);
let isdir = cleaned_partial.ends_with(is_separator);
let expanded_partial = expand_ndots(Path::new(&cleaned_partial));
let should_collapse_dots = expanded_partial != Path::new(&cleaned_partial);
let mut partial = expanded_partial.to_string_lossy().to_string();
#[cfg(unix)]
let path_separator = SEP;
#[cfg(windows)]
let path_separator = cleaned_partial
.chars()
.rfind(|c: &char| is_separator(*c))
.unwrap_or(SEP);
// Handle the trailing dot case
if cleaned_partial.ends_with(&format!("{path_separator}.")) {
partial.push_str(&format!("{path_separator}."));
}
let cwd_pathbufs: Vec<_> = cwds
.iter()
.map(|cwd| Path::new(cwd.as_ref()).to_path_buf())
.collect();
let ls_colors = (engine_state.config.completions.use_ls_colors
&& engine_state.config.use_ansi_coloring.get(engine_state))
.then(|| {
let ls_colors_env_str = stack
.get_env_var(engine_state, "LS_COLORS")
.and_then(|v| env_to_string("LS_COLORS", v, engine_state, stack).ok());
get_ls_colors(ls_colors_env_str)
});
let mut cwds = cwd_pathbufs.clone();
let mut prefix_len = 0;
let mut original_cwd = OriginalCwd::None;
let mut components = Path::new(&partial).components().peekable();
match components.peek().cloned() {
Some(c @ Component::Prefix(..)) => {
// windows only by definition
cwds = vec![[c, Component::RootDir].iter().collect()];
prefix_len = c.as_os_str().len();
original_cwd = OriginalCwd::Prefix(c.as_os_str().to_string_lossy().into_owned());
}
Some(c @ Component::RootDir) => {
// This is kind of a hack. When joining an empty string with the rest,
// we add the slash automagically
cwds = vec![PathBuf::from(c.as_os_str())];
prefix_len = 1;
original_cwd = OriginalCwd::Prefix(String::new());
}
Some(Component::Normal(home)) if home.to_string_lossy() == "~" => {
cwds = home_dir()
.map(|dir| vec![dir.into()])
.unwrap_or(cwd_pathbufs);
prefix_len = 1;
original_cwd = OriginalCwd::Home;
}
_ => {}
};
let after_prefix = &partial[prefix_len..];
let partial: Vec<_> = after_prefix
.strip_prefix(is_separator)
.unwrap_or(after_prefix)
.split(is_separator)
.filter(|s| !s.is_empty())
.collect();
complete_rec(
partial.as_slice(),
&cwds
.into_iter()
.map(|cwd| PathBuiltFromString {
cwd,
parts: Vec::new(),
isdir: false,
})
.collect::<Vec<_>>(),
options,
want_directory,
isdir,
options.match_algorithm == MatchAlgorithm::Prefix,
)
.into_iter()
.map(|mut p| {
if should_collapse_dots {
p = collapse_ndots(p);
}
let is_dir = p.isdir;
let path = original_cwd.apply(p, path_separator);
let real_path = expand_to_real_path(&path);
let metadata = std::fs::symlink_metadata(&real_path).ok();
let style = ls_colors.as_ref().map(|lsc| {
lsc.style_for_path_with_metadata(&real_path, metadata.as_ref())
.map(lscolors::Style::to_nu_ansi_term_style)
.unwrap_or_default()
});
FileSuggestion {
span,
path: escape_path(path),
style,
is_dir,
}
})
.collect()
}
// Fix files or folders with quotes or hashes
pub fn escape_path(path: String) -> String {
// make glob pattern have the highest priority.
if nu_glob::is_glob(path.as_str()) || path.contains('`') {
// expand home `~` for https://github.com/nushell/nushell/issues/13905
let pathbuf = nu_path::expand_tilde(path);
let path = pathbuf.to_string_lossy();
if path.contains('\'') {
// decide to use double quotes
// Path as Debug will do the escaping for `"`, `\`
format!("{path:?}")
} else {
format!("'{path}'")
}
} else {
let contaminated =
path.contains(['\'', '"', ' ', '#', '(', ')', '{', '}', '[', ']', '|', ';']);
let maybe_flag = path.starts_with('-');
let maybe_variable = path.starts_with('$');
let maybe_number = path.parse::<f64>().is_ok();
if contaminated || maybe_flag || maybe_variable || maybe_number {
format!("`{path}`")
} else {
path
}
}
}
pub struct AdjustView {
pub prefix: String,
pub span: Span,
pub readjusted: bool,
}
pub fn adjust_if_intermediate(
prefix: &str,
working_set: &StateWorkingSet,
mut span: nu_protocol::Span,
) -> AdjustView {
let span_contents = String::from_utf8_lossy(working_set.get_span_contents(span)).to_string();
let mut prefix = prefix.to_string();
// A difference of 1 because of the cursor's unicode code point in between.
// Using .chars().count() because unicode and Windows.
let readjusted = span_contents.chars().count() - prefix.chars().count() > 1;
if readjusted {
let remnant: String = span_contents
.chars()
.skip(prefix.chars().count() + 1)
.take_while(|&c| !is_separator(c))
.collect();
prefix.push_str(&remnant);
span = Span::new(span.start, span.start + prefix.chars().count() + 1);
}
AdjustView {
prefix,
span,
readjusted,
}
}
/// Collapse multiple ".." components into n-dots.
///
/// It performs the reverse operation of `expand_ndots`, collapsing sequences of ".." into n-dots,
/// such as "..." and "....".
///
/// The resulting path will use platform-specific path separators, regardless of what path separators were used in the input.
fn collapse_ndots(path: PathBuiltFromString) -> PathBuiltFromString {
let mut result = PathBuiltFromString {
parts: Vec::with_capacity(path.parts.len()),
isdir: path.isdir,
cwd: path.cwd,
};
let mut dot_count = 0;
for part in path.parts {
if part == ".." {
dot_count += 1;
} else {
if dot_count > 0 {
result.parts.push(".".repeat(dot_count + 1));
dot_count = 0;
}
result.parts.push(part);
}
}
// Add any remaining dots
if dot_count > 0 {
result.parts.push(".".repeat(dot_count + 1));
}
result
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.