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