1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use super::{operate, PathSubcommandArguments};
use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{ColumnPath, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value};
use nu_source::Tagged;
#[cfg(windows)]
use std::path::Component;
use std::path::Path;
pub struct PathParse;
struct PathParseArguments {
rest: Vec<ColumnPath>,
extension: Option<Tagged<String>>,
}
impl PathSubcommandArguments for PathParseArguments {
fn get_column_paths(&self) -> &Vec<ColumnPath> {
&self.rest
}
}
impl WholeStreamCommand for PathParse {
fn name(&self) -> &str {
"path parse"
}
fn signature(&self) -> Signature {
Signature::build("path parse")
.rest(SyntaxShape::ColumnPath, "Optionally operate by column path")
.named(
"extension",
SyntaxShape::String,
"Manually supply the extension (without the dot)",
Some('e'),
)
}
fn usage(&self) -> &str {
"Convert a path into structured data."
}
fn extra_usage(&self) -> &str {
r#"Each path is split into a table with 'parent', 'stem' and 'extension' fields.
On Windows, an extra 'prefix' column is added."#
}
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
let tag = args.call_info.name_tag.clone();
let cmd_args = Arc::new(PathParseArguments {
rest: args.rest(0)?,
extension: args.get_flag("extension")?,
});
Ok(operate(args.input, &action, tag.span, cmd_args))
}
#[cfg(windows)]
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Parse a single path",
example: r"echo 'C:\Users\viking\spam.txt' | path parse",
result: None,
},
Example {
description: "Replace a complex extension",
example: r"echo 'C:\Users\viking\spam.tar.gz' | path parse -e tar.gz | update extension { 'txt' }",
result: None,
},
Example {
description: "Ignore the extension",
example: r"echo 'C:\Users\viking.d' | path parse -e ''",
result: None,
},
Example {
description: "Parse all paths under the 'name' column",
example: r"ls | path parse name",
result: None,
},
]
}
#[cfg(not(windows))]
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Parse a path",
example: r"echo '/home/viking/spam.txt' | path parse",
result: None,
},
Example {
description: "Replace a complex extension",
example: r"echo '/home/viking/spam.tar.gz' | path parse -e tar.gz | update extension { 'txt' }",
result: None,
},
Example {
description: "Ignore the extension",
example: r"echo '/etc/conf.d' | path parse -e ''",
result: None,
},
Example {
description: "Parse all paths under the 'name' column",
example: r"ls | path parse name",
result: None,
},
]
}
}
fn action(path: &Path, tag: Tag, args: &PathParseArguments) -> Value {
let mut dict = TaggedDictBuilder::new(&tag);
#[cfg(windows)]
{
let prefix = match path.components().next() {
Some(Component::Prefix(prefix_component)) => {
prefix_component.as_os_str().to_string_lossy()
}
_ => "".into(),
};
dict.insert_untagged("prefix", UntaggedValue::string(prefix));
}
let parent = path.parent().unwrap_or_else(|| "".as_ref());
dict.insert_untagged("parent", UntaggedValue::filepath(parent));
let basename = path
.file_name()
.unwrap_or_else(|| "".as_ref())
.to_string_lossy();
match &args.extension {
Some(Tagged { item: ext, .. }) => {
let ext_with_dot = [".", ext].concat();
if basename.ends_with(&ext_with_dot) && !ext.is_empty() {
let stem = basename.trim_end_matches(&ext_with_dot);
dict.insert_untagged("stem", UntaggedValue::string(stem));
dict.insert_untagged("extension", UntaggedValue::string(ext));
} else {
dict.insert_untagged("stem", UntaggedValue::string(basename));
dict.insert_untagged("extension", UntaggedValue::string(""));
}
}
None => {
let stem = path
.file_stem()
.unwrap_or_else(|| "".as_ref())
.to_string_lossy();
let extension = path
.extension()
.unwrap_or_else(|| "".as_ref())
.to_string_lossy();
dict.insert_untagged("stem", UntaggedValue::string(stem));
dict.insert_untagged("extension", UntaggedValue::string(extension));
}
}
dict.into_value()
}
#[cfg(test)]
mod tests {
use super::PathParse;
use super::ShellError;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
test_examples(PathParse {})
}
}