1use super::PathSubcommandArguments;
2use nu_engine::command_prelude::*;
3use nu_protocol::engine::StateWorkingSet;
4use std::path::{Path, PathBuf};
5
6struct Arguments {
7 append: Vec<Spanned<String>>,
8}
9
10impl PathSubcommandArguments for Arguments {}
11
12#[derive(Clone)]
13pub struct PathJoin;
14
15impl Command for PathJoin {
16 fn name(&self) -> &str {
17 "path join"
18 }
19
20 fn signature(&self) -> Signature {
21 Signature::build("path join")
22 .input_output_types(vec![
23 (Type::String, Type::String),
24 (Type::List(Box::new(Type::String)), Type::String),
25 (Type::record(), Type::String),
26 (Type::table(), Type::List(Box::new(Type::String))),
27 ])
28 .rest(
29 "append",
30 SyntaxShape::String,
31 "Path to append to the input.",
32 )
33 .category(Category::Path)
34 }
35
36 fn description(&self) -> &str {
37 "Join a structured path or a list of path parts."
38 }
39
40 fn extra_description(&self) -> &str {
41 r#"Optionally, append an additional path to the result. It is designed to accept
42the output of 'path parse' and 'path split' subcommands."#
43 }
44
45 fn is_const(&self) -> bool {
46 true
47 }
48
49 fn run(
50 &self,
51 engine_state: &EngineState,
52 stack: &mut Stack,
53 call: &Call,
54 input: PipelineData,
55 ) -> Result<PipelineData, ShellError> {
56 let args = Arguments {
57 append: call.rest(engine_state, stack, 0)?,
58 };
59
60 run(call, &args, input)
61 }
62
63 fn run_const(
64 &self,
65 working_set: &StateWorkingSet,
66 call: &Call,
67 input: PipelineData,
68 ) -> Result<PipelineData, ShellError> {
69 let args = Arguments {
70 append: call.rest_const(working_set, 0)?,
71 };
72
73 run(call, &args, input)
74 }
75
76 #[cfg(windows)]
77 fn examples(&self) -> Vec<Example<'_>> {
78 vec![
79 Example {
80 description: "Append a filename to a path",
81 example: r"'C:\Users\viking' | path join spam.txt",
82 result: Some(Value::test_string(r"C:\Users\viking\spam.txt")),
83 },
84 Example {
85 description: "Append a filename to a path",
86 example: r"'C:\Users\viking' | path join spams this_spam.txt",
87 result: Some(Value::test_string(r"C:\Users\viking\spams\this_spam.txt")),
88 },
89 Example {
90 description: "Use relative paths, e.g. '..' will go up one directory",
91 example: r"'C:\Users\viking' | path join .. folder",
92 result: Some(Value::test_string(r"C:\Users\viking\..\folder")),
93 },
94 Example {
95 description: "Use absolute paths, e.g. '/' will bring you to the top level directory",
96 example: r"'C:\Users\viking' | path join / folder",
97 result: Some(Value::test_string(r"C:/folder")),
98 },
99 Example {
100 description: "Join a list of parts into a path",
101 example: r"[ 'C:' '\' 'Users' 'viking' 'spam.txt' ] | path join",
102 result: Some(Value::test_string(r"C:\Users\viking\spam.txt")),
103 },
104 Example {
105 description: "Join a structured path into a path",
106 example: r"{ parent: 'C:\Users\viking', stem: 'spam', extension: 'txt' } | path join",
107 result: Some(Value::test_string(r"C:\Users\viking\spam.txt")),
108 },
109 Example {
110 description: "Join a table of structured paths into a list of paths",
111 example: r"[ [parent stem extension]; ['C:\Users\viking' 'spam' 'txt']] | path join",
112 result: Some(Value::list(
113 vec![Value::test_string(r"C:\Users\viking\spam.txt")],
114 Span::test_data(),
115 )),
116 },
117 ]
118 }
119
120 #[cfg(not(windows))]
121 fn examples(&self) -> Vec<Example<'_>> {
122 vec![
123 Example {
124 description: "Append a filename to a path",
125 example: r"'/home/viking' | path join spam.txt",
126 result: Some(Value::test_string(r"/home/viking/spam.txt")),
127 },
128 Example {
129 description: "Append a filename to a path",
130 example: r"'/home/viking' | path join spams this_spam.txt",
131 result: Some(Value::test_string(r"/home/viking/spams/this_spam.txt")),
132 },
133 Example {
134 description: "Use relative paths, e.g. '..' will go up one directory",
135 example: r"'/home/viking' | path join .. folder",
136 result: Some(Value::test_string(r"/home/viking/../folder")),
137 },
138 Example {
139 description: "Use absolute paths, e.g. '/' will bring you to the top level directory",
140 example: r"'/home/viking' | path join / folder",
141 result: Some(Value::test_string(r"/folder")),
142 },
143 Example {
144 description: "Join a list of parts into a path",
145 example: r"[ '/' 'home' 'viking' 'spam.txt' ] | path join",
146 result: Some(Value::test_string(r"/home/viking/spam.txt")),
147 },
148 Example {
149 description: "Join a structured path into a path",
150 example: r"{ parent: '/home/viking', stem: 'spam', extension: 'txt' } | path join",
151 result: Some(Value::test_string(r"/home/viking/spam.txt")),
152 },
153 Example {
154 description: "Join a table of structured paths into a list of paths",
155 example: r"[[ parent stem extension ]; [ '/home/viking' 'spam' 'txt' ]] | path join",
156 result: Some(Value::list(
157 vec![Value::test_string(r"/home/viking/spam.txt")],
158 Span::test_data(),
159 )),
160 },
161 ]
162 }
163}
164
165fn run(call: &Call, args: &Arguments, input: PipelineData) -> Result<PipelineData, ShellError> {
166 let head = call.head;
167
168 let metadata = input.metadata();
169
170 match input {
171 PipelineData::Value(val, md) => Ok(PipelineData::value(handle_value(val, args, head), md)),
172 PipelineData::ListStream(stream, ..) => Ok(PipelineData::value(
173 handle_value(stream.into_value()?, args, head),
174 metadata,
175 )),
176 PipelineData::ByteStream(stream, ..) => Ok(PipelineData::value(
177 handle_value(stream.into_value()?, args, head),
178 metadata,
179 )),
180 PipelineData::Empty => Err(ShellError::PipelineEmpty { dst_span: head }),
181 }
182}
183
184fn handle_value(v: Value, args: &Arguments, head: Span) -> Value {
185 let span = v.span();
186 match v {
187 Value::String { ref val, .. } => join_single(Path::new(val), head, args),
188 Value::Record { val, .. } => join_record(&val, head, span, args),
189 Value::List { vals, .. } => join_list(&vals, head, span, args),
190
191 _ => super::handle_invalid_values(v, head),
192 }
193}
194
195fn join_single(path: &Path, head: Span, args: &Arguments) -> Value {
196 let mut result = path.to_path_buf();
197 for path_to_append in &args.append {
198 result.push(&path_to_append.item)
199 }
200
201 Value::string(result.to_string_lossy(), head)
202}
203
204fn join_list(parts: &[Value], head: Span, span: Span, args: &Arguments) -> Value {
205 let path: Result<PathBuf, ShellError> = parts.iter().map(Value::coerce_string).collect();
206
207 match path {
208 Ok(ref path) => join_single(path, head, args),
209 Err(_) => {
210 let records: Result<Vec<_>, ShellError> = parts.iter().map(Value::as_record).collect();
211 match records {
212 Ok(vals) => {
213 let vals = vals
214 .iter()
215 .map(|r| join_record(r, head, span, args))
216 .collect();
217
218 Value::list(vals, span)
219 }
220 Err(ShellError::CantConvert { from_type, .. }) => Value::error(
221 ShellError::OnlySupportsThisInputType {
222 exp_input_type: "string or record".into(),
223 wrong_type: from_type,
224 dst_span: head,
225 src_span: span,
226 },
227 span,
228 ),
229 Err(_) => Value::error(
230 ShellError::NushellFailed {
231 msg: "failed to join path".into(),
232 },
233 span,
234 ),
235 }
236 }
237 }
238}
239
240fn join_record(record: &Record, head: Span, span: Span, args: &Arguments) -> Value {
241 match merge_record(record, head, span) {
242 Ok(p) => join_single(p.as_path(), head, args),
243 Err(error) => Value::error(error, span),
244 }
245}
246
247fn merge_record(record: &Record, head: Span, span: Span) -> Result<PathBuf, ShellError> {
248 for key in record.columns() {
249 if !super::ALLOWED_COLUMNS.contains(&key.as_str()) {
250 let allowed_cols = super::ALLOWED_COLUMNS.join(", ");
251 return Err(ShellError::UnsupportedInput {
252 msg: format!(
253 "Column '{key}' is not valid for a structured path. Allowed columns on this platform are: {allowed_cols}"
254 ),
255 input: "value originates from here".into(),
256 msg_span: head,
257 input_span: span,
258 });
259 }
260 }
261
262 let mut result = PathBuf::new();
263
264 #[cfg(windows)]
265 if let Some(val) = record.get("prefix") {
266 let p = val.coerce_str()?;
267 if !p.is_empty() {
268 result.push(p.as_ref());
269 }
270 }
271
272 if let Some(val) = record.get("parent") {
273 let p = val.coerce_str()?;
274 if !p.is_empty() {
275 result.push(p.as_ref());
276 }
277 }
278
279 let mut basename = String::new();
280 if let Some(val) = record.get("stem") {
281 let p = val.coerce_str()?;
282 if !p.is_empty() {
283 basename.push_str(&p);
284 }
285 }
286
287 if let Some(val) = record.get("extension") {
288 let p = val.coerce_str()?;
289 if !p.is_empty() {
290 basename.push('.');
291 basename.push_str(&p);
292 }
293 }
294
295 if !basename.is_empty() {
296 result.push(basename);
297 }
298
299 Ok(result)
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 #[test]
307 fn test_examples() {
308 use crate::test_examples;
309
310 test_examples(PathJoin {})
311 }
312}