1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use super::get_var;
use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{Signature, SyntaxShape};
use nu_source::Tagged;
use nu_test_support::NATIVE_PATH_ENV_SEPARATOR;
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"pathvar remove"
}
fn signature(&self) -> Signature {
Signature::build("pathvar remove")
.required(
"index",
SyntaxShape::Int,
"index of the path to remove (starting at 0)",
)
.named(
"var",
SyntaxShape::String,
"Use a different variable than PATH",
Some('v'),
)
}
fn usage(&self) -> &str {
"Remove a path from the pathvar"
}
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
remove(args)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Remove the second path from the pathvar",
example: "pathvar remove 1",
result: None,
}]
}
}
pub fn remove(args: CommandArgs) -> Result<OutputStream, ShellError> {
let ctx = &args.context;
let var = get_var(&args)?;
let index_to_remove_arg: Tagged<u64> = args.req(0)?;
let index_to_remove = index_to_remove_arg.item as usize;
if let Some(old_pathvar) = ctx.scope.get_env(&var) {
let mut paths: Vec<&str> = old_pathvar.split(NATIVE_PATH_ENV_SEPARATOR).collect();
if index_to_remove >= paths.len() {
return Err(ShellError::labeled_error(
"Index out of bounds",
format!("the index must be between 0 and {}", paths.len() - 1),
index_to_remove_arg.tag,
));
}
paths.remove(index_to_remove);
ctx.scope.add_env_var(
&var.item,
paths.join(&NATIVE_PATH_ENV_SEPARATOR.to_string()),
);
Ok(OutputStream::empty())
} else {
Err(ShellError::unexpected(&format!(
"Variable {} not set",
&var.item
)))
}
}