Skip to main content

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::generic::GenericError, 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::Generic(
185                            GenericError::new(
186                                format!(
187                                    "No matches found for glob {}",
188                                    file_name.to_string_lossy()
189                                ),
190                                "No matches found for glob",
191                                file_glob.span,
192                            )
193                            .with_help(format!(
194                                "Use quotes if you want to create a file named {}",
195                                file_name.to_string_lossy()
196                            )),
197                        ));
198                    }
199
200                    input_files.push(InputFile::Path(file_path));
201                    continue;
202                }
203
204                input_files.extend(expanded_globs.filter_map(Result::ok).map(InputFile::Path));
205            }
206        }
207
208        if let Err(err) = uu_touch::touch(
209            &input_files,
210            &Options {
211                no_create,
212                no_deref,
213                source,
214                date: date_str,
215                change_times,
216                strict: true,
217            },
218        ) {
219            let nu_err = match err {
220                TouchError::TouchFileError { path, index, error } => {
221                    ShellError::Generic(GenericError::new(
222                        format!("Could not touch {}", path.display()),
223                        translate!(&error.to_string()),
224                        file_globs[index].span,
225                    ))
226                }
227                TouchError::InvalidDateFormat(date) => ShellError::IncorrectValue {
228                    msg: format!("Invalid date: {date}"),
229                    val_span: date_span.expect("touch should've been given a date"),
230                    call_span: call.head,
231                },
232                TouchError::ReferenceFileInaccessible(reference_path, io_err) => {
233                    let span = reference_span.expect("touch should've been given a reference file");
234                    ShellError::Io(IoError::new_with_additional_context(
235                        io_err,
236                        span,
237                        reference_path,
238                        "failed to read metadata",
239                    ))
240                }
241                _ => ShellError::Generic(GenericError::new(
242                    format!("{err}"),
243                    translate!(&err.to_string()),
244                    call.head,
245                )),
246            };
247            return Err(nu_err);
248        }
249
250        Ok(PipelineData::empty())
251    }
252
253    fn examples(&self) -> Vec<Example<'_>> {
254        vec![
255            Example {
256                description: "Creates \"fixture.json\".",
257                example: "touch fixture.json",
258                result: None,
259            },
260            Example {
261                description: "Creates files a, b and c.",
262                example: "touch a b c",
263                result: None,
264            },
265            Example {
266                description: r#"Changes the last modified time of "fixture.json" to today's date."#,
267                example: "touch -m fixture.json",
268                result: None,
269            },
270            Example {
271                description: "Changes the last modified and accessed time of all files with the .json extension to today's date.",
272                example: "touch *.json",
273                result: None,
274            },
275            Example {
276                description: "Changes the last accessed and modified times of files a, b and c to the current time but yesterday.",
277                example: r#"touch -d "yesterday" a b c"#,
278                result: None,
279            },
280            Example {
281                description: r#"Changes the last modified time of files d and e to "fixture.json"'s last modified time."#,
282                example: "touch -m -r fixture.json d e",
283                result: None,
284            },
285            Example {
286                description: r#"Changes the last accessed time of "fixture.json" to a datetime."#,
287                example: "touch -a -t 2019-08-24T12:30:30 fixture.json",
288                result: None,
289            },
290            Example {
291                description: "Change the last accessed and modified times of stdout.",
292                example: "touch -",
293                result: None,
294            },
295            Example {
296                description: r#"Changes the last accessed and modified times of file a to 1 month before "fixture.json"'s last modified time."#,
297                example: r#"touch -r fixture.json -d "-1 month" a"#,
298                result: None,
299            },
300        ]
301    }
302}