nu_command/filesystem/
utouch.rs

1use chrono::{DateTime, FixedOffset};
2use filetime::FileTime;
3use nu_engine::command_prelude::*;
4use nu_glob::{glob, is_glob};
5use nu_path::expand_path_with;
6use nu_protocol::{NuGlob, shell_error::io::IoError};
7use std::path::PathBuf;
8use uu_touch::{ChangeTimes, InputFile, Options, Source, error::TouchError};
9use uucore::{localized_help_template, translate};
10
11#[derive(Clone)]
12pub struct UTouch;
13
14impl Command for UTouch {
15    fn name(&self) -> &str {
16        "touch"
17    }
18
19    fn search_terms(&self) -> Vec<&str> {
20        vec!["create", "file", "coreutils"]
21    }
22
23    fn signature(&self) -> Signature {
24        Signature::build("touch")
25            .input_output_types(vec![ (Type::Nothing, Type::Nothing) ])
26            .rest(
27                "files",
28                SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Filepath]),
29                "The file(s) to create. '-' is used to represent stdout."
30            )
31            .named(
32                "reference",
33                SyntaxShape::Filepath,
34                "Use the access and modification times of the reference file/directory instead of the current time",
35                Some('r'),
36            )
37            .named(
38                "timestamp",
39                SyntaxShape::DateTime,
40                "Use the given timestamp instead of the current time",
41                Some('t')
42            )
43            .named(
44                "date",
45                SyntaxShape::String,
46                "Use the given time instead of the current time. This can be a full timestamp or it can be relative to either the current time or reference file time (if given). For more information, see https://www.gnu.org/software/coreutils/manual/html_node/touch-invocation.html",
47                Some('d')
48            )
49            .switch(
50                "modified",
51                "Change only the modification time (if used with -a, access time is changed too)",
52                Some('m'),
53            )
54            .switch(
55                "access",
56                "Change only the access time (if used with -m, modification time is changed too)",
57                Some('a'),
58            )
59            .switch(
60                "no-create",
61                "Don't create the file if it doesn't exist",
62                Some('c'),
63            )
64            .switch(
65                "no-deref",
66                "Affect each symbolic link instead of any referenced file (only for systems that can change the timestamps of a symlink). Ignored if touching stdout",
67                Some('s'),
68            )
69            .category(Category::FileSystem)
70    }
71
72    fn description(&self) -> &str {
73        "Creates one or more files."
74    }
75
76    fn run(
77        &self,
78        engine_state: &EngineState,
79        stack: &mut Stack,
80        call: &Call,
81        _input: PipelineData,
82    ) -> Result<PipelineData, ShellError> {
83        // setup the uutils error translation
84        let _ = localized_help_template("touch");
85
86        let change_mtime: bool = call.has_flag(engine_state, stack, "modified")?;
87        let change_atime: bool = call.has_flag(engine_state, stack, "access")?;
88        let no_create: bool = call.has_flag(engine_state, stack, "no-create")?;
89        let no_deref: bool = call.has_flag(engine_state, stack, "no-deref")?;
90        let file_globs = call.rest::<Spanned<NuGlob>>(engine_state, stack, 0)?;
91        let cwd = engine_state.cwd(Some(stack))?;
92
93        if file_globs.is_empty() {
94            return Err(ShellError::MissingParameter {
95                param_name: "requires file paths".to_string(),
96                span: call.head,
97            });
98        }
99
100        let (reference_file, reference_span) = if let Some(reference) =
101            call.get_flag::<Spanned<PathBuf>>(engine_state, stack, "reference")?
102        {
103            (Some(reference.item), Some(reference.span))
104        } else {
105            (None, None)
106        };
107        let (date_str, date_span) =
108            if let Some(date) = call.get_flag::<Spanned<String>>(engine_state, stack, "date")? {
109                (Some(date.item), Some(date.span))
110            } else {
111                (None, None)
112            };
113        let timestamp: Option<Spanned<DateTime<FixedOffset>>> =
114            call.get_flag(engine_state, stack, "timestamp")?;
115
116        let source = if let Some(timestamp) = timestamp {
117            if let Some(reference_span) = reference_span {
118                return Err(ShellError::IncompatibleParameters {
119                    left_message: "timestamp given".to_string(),
120                    left_span: timestamp.span,
121                    right_message: "reference given".to_string(),
122                    right_span: reference_span,
123                });
124            }
125            if let Some(date_span) = date_span {
126                return Err(ShellError::IncompatibleParameters {
127                    left_message: "timestamp given".to_string(),
128                    left_span: timestamp.span,
129                    right_message: "date given".to_string(),
130                    right_span: date_span,
131                });
132            }
133            Source::Timestamp(FileTime::from_unix_time(
134                timestamp.item.timestamp(),
135                timestamp.item.timestamp_subsec_nanos(),
136            ))
137        } else if let Some(reference_file) = reference_file {
138            let reference_file = expand_path_with(reference_file, &cwd, true);
139            Source::Reference(reference_file)
140        } else {
141            Source::Now
142        };
143
144        let change_times = if change_atime && !change_mtime {
145            ChangeTimes::AtimeOnly
146        } else if change_mtime && !change_atime {
147            ChangeTimes::MtimeOnly
148        } else {
149            ChangeTimes::Both
150        };
151
152        let mut input_files = Vec::new();
153        for file_glob in &file_globs {
154            if file_glob.item.as_ref() == "-" {
155                input_files.push(InputFile::Stdout);
156            } else {
157                let file_path =
158                    expand_path_with(file_glob.item.as_ref(), &cwd, file_glob.item.is_expand());
159
160                if !file_glob.item.is_expand() {
161                    input_files.push(InputFile::Path(file_path));
162                    continue;
163                }
164
165                let mut expanded_globs =
166                    glob(&file_path.to_string_lossy(), engine_state.signals().clone())
167                        .unwrap_or_else(|_| {
168                            panic!(
169                                "Failed to process file path: {}",
170                                &file_path.to_string_lossy()
171                            )
172                        })
173                        .peekable();
174
175                if expanded_globs.peek().is_none() {
176                    let file_name = file_path.file_name().unwrap_or_else(|| {
177                        panic!(
178                            "Failed to process file path: {}",
179                            &file_path.to_string_lossy()
180                        )
181                    });
182
183                    if is_glob(&file_name.to_string_lossy()) {
184                        return Err(ShellError::GenericError {
185                            error: format!(
186                                "No matches found for glob {}",
187                                file_name.to_string_lossy()
188                            ),
189                            msg: "No matches found for glob".into(),
190                            span: Some(file_glob.span),
191                            help: Some(format!(
192                                "Use quotes if you want to create a file named {}",
193                                file_name.to_string_lossy()
194                            )),
195                            inner: vec![],
196                        });
197                    }
198
199                    input_files.push(InputFile::Path(file_path));
200                    continue;
201                }
202
203                input_files.extend(expanded_globs.filter_map(Result::ok).map(InputFile::Path));
204            }
205        }
206
207        if let Err(err) = uu_touch::touch(
208            &input_files,
209            &Options {
210                no_create,
211                no_deref,
212                source,
213                date: date_str,
214                change_times,
215                strict: true,
216            },
217        ) {
218            let nu_err = match err {
219                TouchError::TouchFileError { path, index, error } => ShellError::GenericError {
220                    error: format!("Could not touch {}", path.display()),
221                    msg: translate!(&error.to_string()),
222                    span: Some(file_globs[index].span),
223                    help: None,
224                    inner: Vec::new(),
225                },
226                TouchError::InvalidDateFormat(date) => ShellError::IncorrectValue {
227                    msg: format!("Invalid date: {date}"),
228                    val_span: date_span.expect("touch should've been given a date"),
229                    call_span: call.head,
230                },
231                TouchError::ReferenceFileInaccessible(reference_path, io_err) => {
232                    let span = reference_span.expect("touch should've been given a reference file");
233                    ShellError::Io(IoError::new_with_additional_context(
234                        io_err,
235                        span,
236                        reference_path,
237                        "failed to read metadata",
238                    ))
239                }
240                _ => ShellError::GenericError {
241                    error: format!("{err}"),
242                    msg: translate!(&err.to_string()),
243                    span: Some(call.head),
244                    help: None,
245                    inner: Vec::new(),
246                },
247            };
248            return Err(nu_err);
249        }
250
251        Ok(PipelineData::empty())
252    }
253
254    fn examples(&self) -> Vec<Example<'_>> {
255        vec![
256            Example {
257                description: "Creates \"fixture.json\"",
258                example: "touch fixture.json",
259                result: None,
260            },
261            Example {
262                description: "Creates files a, b and c",
263                example: "touch a b c",
264                result: None,
265            },
266            Example {
267                description: r#"Changes the last modified time of "fixture.json" to today's date"#,
268                example: "touch -m fixture.json",
269                result: None,
270            },
271            Example {
272                description: r#"Changes the last modified and accessed time of all files with the .json extension to today's date"#,
273                example: "touch *.json",
274                result: None,
275            },
276            Example {
277                description: "Changes the last accessed and modified times of files a, b and c to the current time but yesterday",
278                example: r#"touch -d "yesterday" a b c"#,
279                result: None,
280            },
281            Example {
282                description: r#"Changes the last modified time of files d and e to "fixture.json"'s last modified time"#,
283                example: r#"touch -m -r fixture.json d e"#,
284                result: None,
285            },
286            Example {
287                description: r#"Changes the last accessed time of "fixture.json" to a datetime"#,
288                example: r#"touch -a -t 2019-08-24T12:30:30 fixture.json"#,
289                result: None,
290            },
291            Example {
292                description: r#"Change the last accessed and modified times of stdout"#,
293                example: r#"touch -"#,
294                result: None,
295            },
296            Example {
297                description: r#"Changes the last accessed and modified times of file a to 1 month before "fixture.json"'s last modified time"#,
298                example: r#"touch -r fixture.json -d "-1 month" a"#,
299                result: None,
300            },
301        ]
302    }
303}