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