Debian Codegraph @

tests/by-util/test_touch.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore (formats) cymdhm cymdhms datetime filestat mdhm mdhms mktime preopen strtime tzdb ymdhm ymdhms
7
8 use filetime::FileTime;
9 #[cfg(not(target_os = "freebsd"))]
10 use filetime::set_symlink_file_times;
11 use jiff::{fmt::strtime, tz::TimeZone};
12 use std::fs::remove_file;
13 use std::path::PathBuf;
14 use uutests::at_and_ucmd;
15 use uutests::new_ucmd;
16 use uutests::util::{AtPath, TestScenario};
17 use uutests::util_name;
18
19 fn get_file_times(at: &AtPath, path: &str) -> (FileTime, FileTime) {
20 let m = at.metadata(path);
21 (
22 FileTime::from_last_access_time(&m),
23 FileTime::from_last_modification_time(&m),
24 )
25 }
26
27 #[cfg(not(target_os = "freebsd"))]
28 fn get_symlink_times(at: &AtPath, path: &str) -> (FileTime, FileTime) {
29 let m = at.symlink_metadata(path);
30 (
31 FileTime::from_last_access_time(&m),
32 FileTime::from_last_modification_time(&m),
33 )
34 }
35
36 fn set_file_times(at: &AtPath, path: &str, atime: FileTime, mtime: FileTime) {
37 filetime::set_file_times(at.plus_as_string(path), atime, mtime).unwrap();
38 }
39
40 fn str_to_filetime(format: &str, s: &str) -> FileTime {
41 let tm = strtime::parse(format, s).unwrap();
42 let dt = tm.to_datetime().unwrap();
43 let ts = dt.to_zoned(TimeZone::UTC).unwrap().timestamp();
44 FileTime::from_unix_time(ts.as_second(), ts.subsec_nanosecond() as u32)
45 }
46
47 #[test]
48 fn test_invalid_arg() {
49 new_ucmd!().arg("--definitely-invalid").fails_with_code(1);
50 }
51
52 #[test]
53 fn test_touch_default() {
54 let (at, mut ucmd) = at_and_ucmd!();
55 let file = "test_touch_default_file";
56
57 ucmd.arg(file).succeeds().no_stderr();
58
59 assert!(at.file_exists(file));
60 }
61
62 #[test]
63 fn test_touch_no_create_file_absent() {
64 let (at, mut ucmd) = at_and_ucmd!();
65 let file = "test_touch_no_create_file_absent";
66
67 ucmd.arg("-c").arg(file).succeeds().no_stderr();
68
69 assert!(!at.file_exists(file));
70 }
71
72 #[test]
73 fn test_touch_no_create_file_exists() {
74 let (at, mut ucmd) = at_and_ucmd!();
75 let file = "test_touch_no_create_file_exists";
76
77 at.touch(file);
78 assert!(at.file_exists(file));
79
80 ucmd.arg("-c").arg(file).succeeds().no_stderr();
81
82 assert!(at.file_exists(file));
83 }
84
85 #[test]
86 fn test_touch_set_mdhm_time() {
87 let (at, mut ucmd) = at_and_ucmd!();
88 let file = "test_touch_set_mdhm_time";
89
90 ucmd.args(&["-t", "01011234", file]).succeeds().no_stderr();
91
92 assert!(at.file_exists(file));
93
94 let start_of_year = str_to_filetime(
95 "%Y%m%d%H%M",
96 &format!("{}01010000", time::OffsetDateTime::now_utc().year()),
97 );
98 let (atime, mtime) = get_file_times(&at, file);
99 assert_eq!(atime, mtime);
100 assert_eq!(atime.unix_seconds() - start_of_year.unix_seconds(), 45240);
101 assert_eq!(mtime.unix_seconds() - start_of_year.unix_seconds(), 45240);
102 }
103
104 #[test]
105 fn test_touch_set_mdhms_time() {
106 let (at, mut ucmd) = at_and_ucmd!();
107 let file = "test_touch_set_mdhms_time";
108
109 ucmd.args(&["-t", "01011234.56", file])
110 .succeeds()
111 .no_stderr();
112
113 assert!(at.file_exists(file));
114
115 let start_of_year = str_to_filetime(
116 "%Y%m%d%H%M.%S",
117 &format!("{}01010000.00", time::OffsetDateTime::now_utc().year()),
118 );
119 let (atime, mtime) = get_file_times(&at, file);
120 assert_eq!(atime, mtime);
121 assert_eq!(atime.unix_seconds() - start_of_year.unix_seconds(), 45296);
122 assert_eq!(mtime.unix_seconds() - start_of_year.unix_seconds(), 45296);
123 }
124
125 #[test]
126 #[cfg(target_pointer_width = "64")]
127 fn test_touch_2_digit_years_68() {
128 // 68 and before are 20xx
129 // it will fail on 32 bits, because of wraparound for anything after
130 // 2038-01-19
131 let (at, mut ucmd) = at_and_ucmd!();
132 let file = "test_touch_set_two_digit_68_time";
133
134 ucmd.args(&["-t", "6801010000", file])
135 .succeeds()
136 .no_output();
137
138 assert!(at.file_exists(file));
139
140 // January 1, 2068, 00:00:00
141 let expected = FileTime::from_unix_time(3_092_601_600, 0);
142 let (atime, mtime) = get_file_times(&at, file);
143 assert_eq!(atime, mtime);
144 assert_eq!(atime, expected);
145 assert_eq!(mtime, expected);
146 }
147
148 #[test]
149 fn test_touch_2_digit_years_2038() {
150 // Same as test_touch_2_digit_years_68 but for 32 bits systems
151 // we test a date before the y2038 bug
152 let (at, mut ucmd) = at_and_ucmd!();
153 let file = "test_touch_set_two_digit_68_time";
154
155 ucmd.args(&["-t", "3801010000", file])
156 .succeeds()
157 .no_output();
158
159 assert!(at.file_exists(file));
160
161 // January 1, 2038, 00:00:00
162 let expected = FileTime::from_unix_time(2_145_916_800, 0);
163 let (atime, mtime) = get_file_times(&at, file);
164 assert_eq!(atime, mtime);
165 assert_eq!(atime, expected);
166 assert_eq!(mtime, expected);
167 }
168
169 #[test]
170 #[cfg_attr(
171 wasi_runner,
172 ignore = "WASI: pre-epoch timestamps not representable by path_filestat_set_times"
173 )]
174 fn test_touch_2_digit_years_69() {
175 // 69 and after are 19xx
176 let (at, mut ucmd) = at_and_ucmd!();
177 let file = "test_touch_set_two_digit_69_time";
178
179 ucmd.args(&["-t", "6901010000", file])
180 .succeeds()
181 .no_output();
182
183 assert!(at.file_exists(file));
184 // January 1, 1969, 00:00:00
185 let expected = FileTime::from_unix_time(-31_536_000, 0);
186 let (atime, mtime) = get_file_times(&at, file);
187 assert_eq!(atime, mtime);
188 assert_eq!(atime, expected);
189 assert_eq!(mtime, expected);
190 }
191
192 #[test]
193 fn test_touch_set_ymdhm_time() {
194 let (at, mut ucmd) = at_and_ucmd!();
195 let file = "test_touch_set_ymdhm_time";
196
197 ucmd.args(&["-t", "1501011234", file])
198 .succeeds()
199 .no_stderr();
200
201 assert!(at.file_exists(file));
202
203 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501010000");
204 let (atime, mtime) = get_file_times(&at, file);
205 assert_eq!(atime, mtime);
206 assert_eq!(atime.unix_seconds() - start_of_year.unix_seconds(), 45240);
207 assert_eq!(mtime.unix_seconds() - start_of_year.unix_seconds(), 45240);
208 }
209
210 #[test]
211 fn test_touch_set_ymdhms_time() {
212 let (at, mut ucmd) = at_and_ucmd!();
213 let file = "test_touch_set_ymdhms_time";
214
215 ucmd.args(&["-t", "1501011234.56", file])
216 .succeeds()
217 .no_stderr();
218
219 assert!(at.file_exists(file));
220
221 let start_of_year = str_to_filetime("%Y%m%d%H%M.%S", "201501010000.00");
222 let (atime, mtime) = get_file_times(&at, file);
223 assert_eq!(atime, mtime);
224 assert_eq!(atime.unix_seconds() - start_of_year.unix_seconds(), 45296);
225 assert_eq!(mtime.unix_seconds() - start_of_year.unix_seconds(), 45296);
226 }
227
228 #[test]
229 fn test_touch_set_cymdhm_time() {
230 let (at, mut ucmd) = at_and_ucmd!();
231 let file = "test_touch_set_cymdhm_time";
232
233 ucmd.args(&["-t", "201501011234", file])
234 .succeeds()
235 .no_stderr();
236
237 assert!(at.file_exists(file));
238
239 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501010000");
240 let (atime, mtime) = get_file_times(&at, file);
241 assert_eq!(atime, mtime);
242 assert_eq!(atime.unix_seconds() - start_of_year.unix_seconds(), 45240);
243 assert_eq!(mtime.unix_seconds() - start_of_year.unix_seconds(), 45240);
244 }
245
246 #[test]
247 fn test_touch_set_cymdhms_time() {
248 let (at, mut ucmd) = at_and_ucmd!();
249 let file = "test_touch_set_cymdhms_time";
250
251 ucmd.args(&["-t", "201501011234.56", file])
252 .succeeds()
253 .no_stderr();
254
255 assert!(at.file_exists(file));
256
257 let start_of_year = str_to_filetime("%Y%m%d%H%M.%S", "201501010000.00");
258 let (atime, mtime) = get_file_times(&at, file);
259 assert_eq!(atime, mtime);
260 assert_eq!(atime.unix_seconds() - start_of_year.unix_seconds(), 45296);
261 assert_eq!(mtime.unix_seconds() - start_of_year.unix_seconds(), 45296);
262 }
263
264 #[test]
265 fn test_touch_set_only_atime() {
266 let atime_args = [
267 "-a",
268 "--time=access",
269 "--time=atime",
270 "--time=atim", // spell-checker:disable-line
271 "--time=a",
272 "--time=use",
273 ];
274 let file = "test_touch_set_only_atime";
275
276 for atime_arg in atime_args {
277 let (at, mut ucmd) = at_and_ucmd!();
278
279 ucmd.args(&["-t", "201501011234", atime_arg, file])
280 .succeeds()
281 .no_stderr();
282
283 assert!(at.file_exists(file));
284
285 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501010000");
286 let (atime, mtime) = get_file_times(&at, file);
287 assert_ne!(atime, mtime);
288 assert_eq!(atime.unix_seconds() - start_of_year.unix_seconds(), 45240);
289 }
290 }
291
292 #[test]
293 fn test_touch_set_only_mtime_failed() {
294 let file = "test_touch_set_only_mtime";
295
296 new_ucmd!()
297 .args(&["-t", "2015010112342", "-m", file])
298 .fails();
299 }
300
301 #[test]
302 fn test_touch_set_both_time_and_reference() {
303 let (at, mut ucmd) = at_and_ucmd!();
304 let ref_file = "test_touch_reference";
305 let file = "test_touch_set_both_time_and_reference";
306
307 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501010000");
308
309 at.touch(ref_file);
310 set_file_times(&at, ref_file, start_of_year, start_of_year);
311 assert!(at.file_exists(ref_file));
312
313 ucmd.args(&["-t", "2015010112342", "-r", ref_file, file])
314 .fails();
315 }
316
317 #[test]
318 fn test_touch_set_both_date_and_reference() {
319 let (at, mut ucmd) = at_and_ucmd!();
320 let ref_file = "test_touch_reference";
321 let file = "test_touch_set_both_date_and_reference";
322
323 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501011234");
324
325 at.touch(ref_file);
326 set_file_times(&at, ref_file, start_of_year, start_of_year);
327 assert!(at.file_exists(ref_file));
328
329 ucmd.args(&["-d", "Thu Jan 01 12:34:00 2015", "-r", ref_file, file])
330 .succeeds()
331 .no_stderr();
332 let (atime, mtime) = get_file_times(&at, file);
333 assert_eq!(atime, start_of_year);
334 assert_eq!(mtime, start_of_year);
335 }
336
337 #[test]
338 fn test_touch_set_both_offset_date_and_reference() {
339 let (at, mut ucmd) = at_and_ucmd!();
340 let ref_file = "test_touch_reference";
341 let file = "test_touch_set_both_date_and_reference";
342
343 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501011234");
344 let five_days_later = str_to_filetime("%Y%m%d%H%M", "201501061234");
345
346 at.touch(ref_file);
347 set_file_times(&at, ref_file, start_of_year, start_of_year);
348 assert!(at.file_exists(ref_file));
349
350 ucmd.args(&["-d", "+5 days", "-r", ref_file, file])
351 .succeeds()
352 .no_stderr();
353 let (atime, mtime) = get_file_times(&at, file);
354 assert_eq!(atime, five_days_later);
355 assert_eq!(mtime, five_days_later);
356 }
357
358 #[test]
359 fn test_touch_set_both_time_and_date() {
360 let file = "test_touch_set_both_time_and_date";
361
362 new_ucmd!()
363 .args(&[
364 "-t",
365 "2015010112342",
366 "-d",
367 "Thu Jan 01 12:34:00 2015",
368 file,
369 ])
370 .fails();
371 }
372
373 #[test]
374 fn test_touch_set_only_mtime() {
375 let mtime_args = ["-m", "--time=modify", "--time=mtime", "--time=m"];
376 let file = "test_touch_set_only_mtime";
377
378 for mtime_arg in mtime_args {
379 let (at, mut ucmd) = at_and_ucmd!();
380
381 ucmd.args(&["-t", "201501011234", mtime_arg, file])
382 .succeeds()
383 .no_stderr();
384
385 assert!(at.file_exists(file));
386
387 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501010000");
388 let (atime, mtime) = get_file_times(&at, file);
389 assert_ne!(atime, mtime);
390 assert_eq!(mtime.unix_seconds() - start_of_year.unix_seconds(), 45240);
391 }
392 }
393
394 #[test]
395 fn test_touch_set_both() {
396 let (at, mut ucmd) = at_and_ucmd!();
397 let file = "test_touch_set_both";
398
399 ucmd.args(&["-t", "201501011234", "-a", "-m", file])
400 .succeeds()
401 .no_stderr();
402
403 assert!(at.file_exists(file));
404
405 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501010000");
406 let (atime, mtime) = get_file_times(&at, file);
407 assert_eq!(atime, mtime);
408 assert_eq!(atime.unix_seconds() - start_of_year.unix_seconds(), 45240);
409 assert_eq!(mtime.unix_seconds() - start_of_year.unix_seconds(), 45240);
410 }
411
412 #[test]
413 // FixME: Fails on freebsd because of a different nanos
414 #[cfg(not(target_os = "freebsd"))]
415 fn test_touch_no_dereference() {
416 let (at, mut ucmd) = at_and_ucmd!();
417 let file_a = "test_touch_no_dereference_a";
418 let file_b = "test_touch_no_dereference_b";
419 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501010000");
420 let end_of_year = str_to_filetime("%Y%m%d%H%M", "201512312359");
421
422 at.touch(file_a);
423 set_file_times(&at, file_a, start_of_year, start_of_year);
424 at.symlink_file(file_a, file_b);
425 assert!(at.file_exists(file_a));
426 assert!(at.is_symlink(file_b));
427
428 ucmd.args(&["-t", "201512312359", "-h", file_b])
429 .succeeds()
430 .no_stderr();
431
432 let (atime, mtime) = get_symlink_times(&at, file_b);
433 assert_eq!(atime, mtime);
434 assert_eq!(atime, end_of_year);
435 assert_eq!(mtime, end_of_year);
436
437 let (atime, mtime) = get_file_times(&at, file_a);
438 assert_eq!(atime, mtime);
439 assert_eq!(atime, start_of_year);
440 assert_eq!(mtime, start_of_year);
441 }
442
443 #[test]
444 fn test_touch_reference() {
445 let scenario = TestScenario::new(util_name!());
446 let (at, mut _ucmd) = (scenario.fixtures.clone(), scenario.ucmd());
447 let file_a = "test_touch_reference_a";
448 let file_b = "test_touch_reference_b";
449 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501010000");
450
451 at.touch(file_a);
452 set_file_times(&at, file_a, start_of_year, start_of_year);
453 assert!(at.file_exists(file_a));
454 for opt in ["-r", "--ref", "--reference"] {
455 scenario
456 .ccmd("touch")
457 .args(&[opt, file_a, file_b])
458 .succeeds()
459 .no_stderr();
460
461 assert!(at.file_exists(file_b));
462
463 let (atime, mtime) = get_file_times(&at, file_b);
464 assert_eq!(atime, mtime);
465 assert_eq!(atime, start_of_year);
466 assert_eq!(mtime, start_of_year);
467 let _ = remove_file(file_b);
468 }
469 }
470
471 #[test]
472 fn test_touch_reference_dangling() {
473 let temp_dir = tempfile::tempdir().unwrap();
474 let nonexistent_target = temp_dir.path().join("nonexistent_target");
475 let dangling_symlink = temp_dir.path().join("test_touch_reference_dangling");
476
477 #[cfg(not(windows))]
478 {
479 std::os::unix::fs::symlink(&nonexistent_target, &dangling_symlink).unwrap();
480 }
481 #[cfg(windows)]
482 {
483 std::os::windows::fs::symlink_file(&nonexistent_target, &dangling_symlink).unwrap();
484 }
485
486 new_ucmd!()
487 .args(&[
488 "--reference",
489 dangling_symlink.to_str().unwrap(),
490 "some_file",
491 ])
492 .fails()
493 .stderr_contains("touch: failed to get attributes of");
494 }
495
496 #[test]
497 fn test_touch_set_date() {
498 let (at, mut ucmd) = at_and_ucmd!();
499 let file = "test_touch_set_date";
500
501 ucmd.args(&["-d", "Thu Jan 01 12:34:00 2015", file])
502 .succeeds()
503 .no_stderr();
504
505 assert!(at.file_exists(file));
506
507 let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501011234");
508 let (atime, mtime) = get_file_times(&at, file);
509 assert_eq!(atime, mtime);
510 assert_eq!(atime, start_of_year);
511 assert_eq!(mtime, start_of_year);
512 }
513
514 #[test]
515 fn test_touch_set_date2() {
516 let (at, mut ucmd) = at_and_ucmd!();
517 let file = "test_touch_set_date";
518
519 ucmd.args(&["-d", "2000-01-23", file])
520 .succeeds()
521 .no_stderr();
522
523 assert!(at.file_exists(file));
524
525 let start_of_year = str_to_filetime("%Y%m%d%H%M", "200001230000");
526 let (atime, mtime) = get_file_times(&at, file);
527 assert_eq!(atime, mtime);
528 assert_eq!(atime, start_of_year);
529 assert_eq!(mtime, start_of_year);
530 }
531
532 #[test]
533 fn test_touch_set_date3() {
534 let (at, mut ucmd) = at_and_ucmd!();
535 let file = "test_touch_set_date";
536
537 ucmd.args(&["-d", "@1623786360", file])
538 .succeeds()
539 .no_stderr();
540
541 assert!(at.file_exists(file));
542
543 let expected = FileTime::from_unix_time(1_623_786_360, 0);
544 let (atime, mtime) = get_file_times(&at, file);
545 assert_eq!(atime, mtime);
546 assert_eq!(atime, expected);
547 assert_eq!(mtime, expected);
548 }
549
550 #[test]
551 fn test_touch_set_date4() {
552 let (at, mut ucmd) = at_and_ucmd!();
553 let file = "test_touch_set_date";
554
555 ucmd.args(&["-d", "1970-01-01 18:43:33", file])
556 .succeeds()
557 .no_stderr();
558
559 assert!(at.file_exists(file));
560
561 let expected = FileTime::from_unix_time(67413, 0);
562 let (atime, mtime) = get_file_times(&at, file);
563 assert_eq!(atime, mtime);
564 assert_eq!(atime, expected);
565 assert_eq!(mtime, expected);
566 }
567
568 #[test]
569 fn test_touch_set_date5() {
570 let (at, mut ucmd) = at_and_ucmd!();
571 let file = "test_touch_set_date";
572
573 ucmd.args(&["-d", "1970-01-01 18:43:33.023456789", file])
574 .succeeds()
575 .no_stderr();
576
577 assert!(at.file_exists(file));
578
579 // Slightly different result on Windows for nano seconds
580 // TODO: investigate
581 #[cfg(windows)]
582 let expected = FileTime::from_unix_time(67413, 23_456_700);
583 #[cfg(not(windows))]
584 let expected = FileTime::from_unix_time(67413, 23_456_789);
585
586 let (atime, mtime) = get_file_times(&at, file);
587 assert_eq!(atime, mtime);
588 assert_eq!(atime, expected);
589 assert_eq!(mtime, expected);
590 }
591
592 #[test]
593 fn test_touch_set_date6() {
594 let (at, mut ucmd) = at_and_ucmd!();
595 let file = "test_touch_set_date";
596
597 ucmd.args(&["-d", "2000-01-01 00:00", file])
598 .succeeds()
599 .no_stderr();
600
601 assert!(at.file_exists(file));
602
603 let expected = FileTime::from_unix_time(946_684_800, 0);
604
605 let (atime, mtime) = get_file_times(&at, file);
606 assert_eq!(atime, mtime);
607 assert_eq!(atime, expected);
608 assert_eq!(mtime, expected);
609 }
610
611 #[test]
612 fn test_touch_set_date7() {
613 let (at, mut ucmd) = at_and_ucmd!();
614 let file = "test_touch_set_date";
615
616 ucmd.args(&["-d", "2004-01-16 12:00 +0000", file])
617 .succeeds()
618 .no_stderr();
619
620 assert!(at.file_exists(file));
621
622 let expected = FileTime::from_unix_time(1_074_254_400, 0);
623
624 let (atime, mtime) = get_file_times(&at, file);
625 assert_eq!(atime, mtime);
626 assert_eq!(atime, expected);
627 assert_eq!(mtime, expected);
628 }
629
630 #[test]
631 #[cfg_attr(
632 wasi_runner,
633 ignore = "WASI: no tzdb; TZ env var is not honoured so timezone-dependent timestamps differ"
634 )]
635 fn test_touch_set_date_without_leading_zeroes() {
636 let (at, mut ucmd) = at_and_ucmd!();
637 let file = "test_touch_set_date_without_leading_zeroes";
638
639 ucmd.env("TZ", "UTC-8")
640 .args(&["-d", "2026-6-27 13:12", file])
641 .succeeds()
642 .no_stderr();
643
644 let expected = FileTime::from_unix_time(1_782_537_120, 0);
645 let (atime, mtime) = get_file_times(&at, file);
646 assert_eq!(atime, expected);
647 assert_eq!(mtime, expected);
648 }
649
650 /// Regression test for https://github.com/uutils/coreutils/issues/11804
651 ///
652 /// Setting a pre-epoch date like `0000-01-01` used to panic on 32-bit targets
653 /// because the i64 Unix timestamp (~-62 billion) overflowed the i32 `tv_sec`
654 /// expected by the old nix-based implementation. After switching to rustix
655 /// (which uses i64 `tv_sec` natively), this should succeed on all targets.
656 #[test]
657 #[cfg(unix)]
658 #[cfg_attr(
659 wasi_runner,
660 ignore = "WASI: pre-epoch timestamps not representable by path_filestat_set_times"
661 )]
662 fn test_touch_set_date_year_zero() {
663 let (at, mut ucmd) = at_and_ucmd!();
664 let file = "test_touch_year_zero";
665
666 ucmd.args(&["-d", "0000-01-01", file])
667 .succeeds()
668 .no_stderr();
669
670 assert!(at.file_exists(file));
671 }
672
673 /// Test for setting the date by a relative time unit.
674 #[test]
675 fn test_touch_set_date_relative_smoke() {
676 // From the GNU documentation:
677 //
678 // > The unit of time displacement may be selected by the string
679 // > ‘year’ or ‘month’ for moving by whole years or months. These
680 // > are fuzzy units, as years and months are not all of equal
681 // > duration. More precise units are ‘fortnight’ which is worth 14
682 // > days, ‘week’ worth 7 days, ‘day’ worth 24 hours, ‘hour’ worth
683 // > 60 minutes, ‘minute’ or ‘min’ worth 60 seconds, and ‘second’ or
684 // > ‘sec’ worth one second. An ‘s’ suffix on these units is
685 // > accepted and ignored.
686 //
687 let times = [
688 // "-1 year", "+1 year", "-1 years", "+1 years",
689 // "-1 month", "+1 month", "-1 months", "+1 months",
690 "-1 fortnight",
691 "+1 fortnight",
692 "-1 fortnights",
693 "+1 fortnights",
694 "fortnight",
695 "fortnights",
696 "-1 week",
697 "+1 week",
698 "-1 weeks",
699 "+1 weeks",
700 "week",
701 "weeks",
702 "-1 day",
703 "+1 day",
704 "-1 days",
705 "+1 days",
706 "day",
707 "days",
708 "-1 hour",
709 "+1 hour",
710 "-1 hours",
711 "+1 hours",
712 "hour",
713 "hours",
714 "-1 minute",
715 "+1 minute",
716 "-1 minutes",
717 "+1 minutes",
718 "minute",
719 "minutes",
720 "-1 min",
721 "+1 min",
722 "-1 mins",
723 "+1 mins",
724 "min",
725 "mins",
726 "-1 second",
727 "+1 second",
728 "-1 seconds",
729 "+1 seconds",
730 "second",
731 "seconds",
732 "-1 sec",
733 "+1 sec",
734 "-1 secs",
735 "+1 secs",
736 "sec",
737 "secs",
738 ];
739 for time in times {
740 let (at, mut ucmd) = at_and_ucmd!();
741 at.touch("f");
742 ucmd.args(&["-d", time, "f"]).succeeds().no_output();
743 }
744
745 // From the GNU documentation:
746 //
747 // > The string ‘tomorrow’ is worth one day in the future
748 // > (equivalent to ‘day’), the string ‘yesterday’ is worth one day
749 // > in the past (equivalent to ‘day ago’).
750 //
751 let times = [
752 "yesterday",
753 "tomorrow",
754 "now",
755 "2 seconds",
756 "2 years 1 week",
757 "2 days ago",
758 "2 months 1 second",
759 "a",
760 ];
761 for time in times {
762 let (at, mut ucmd) = at_and_ucmd!();
763 at.touch("f");
764 ucmd.args(&["-d", time, "f"]).succeeds().no_output();
765 }
766 }
767
768 #[test]
769 fn test_touch_set_date_wrong_format() {
770 let file = "test_touch_set_date_wrong_format";
771
772 new_ucmd!()
773 .args(&["-d", "2005-43-21", file])
774 .fails()
775 .stderr_contains("Unable to parse date: 2005-43-21");
776 }
777
778 #[test]
779 fn test_touch_mtime_dst_succeeds() {
780 let (at, mut ucmd) = at_and_ucmd!();
781 let file = "test_touch_set_mtime_dst_succeeds";
782
783 ucmd.args(&["-m", "-t", "202103140300", file])
784 .succeeds()
785 .no_stderr();
786
787 assert!(at.file_exists(file));
788
789 let target_time = str_to_filetime("%Y%m%d%H%M", "202103140300");
790 let (_, mtime) = get_file_times(&at, file);
791 assert_eq!(target_time, mtime);
792 }
793
794 #[test]
795 #[cfg(unix)]
796 #[cfg_attr(
797 wasi_runner,
798 ignore = "WASI: no tzdb; TZ env var is not honoured so DST validation is skipped"
799 )]
800 fn test_touch_mtime_dst_fails() {
801 let file = "test_touch_set_mtime_dst_fails";
802
803 // Some timezones use daylight savings time, this leads to problems if the
804 // specified time is within the jump forward. In EST (UTC-5), there is a
805 // jump from 1:59AM to 3:00AM on, March 8 2020, so any thing in-between is
806 // invalid.
807 // See https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
808 // for information on the TZ variable, which where the string is copied from.
809 new_ucmd!()
810 .env("TZ", "EST+5EDT,M3.2.0/2,M11.1.0/2")
811 .args(&["-m", "-t", "202003080200", file])
812 .fails();
813 }
814
815 #[test]
816 #[cfg(unix)]
817 #[cfg_attr(
818 wasi_runner,
819 ignore = "WASI: guest root is a writable preopen, not the protected system root"
820 )]
821 fn test_touch_system_fails() {
822 let file = "/";
823 new_ucmd!()
824 .args(&[file])
825 .fails()
826 .stderr_contains("setting times of '/'");
827 }
828
829 #[test]
830 #[cfg(unix)]
831 #[cfg_attr(wasi_runner, ignore = "WASI: no FIFO support")]
832 fn test_touch_fifo() {
833 // touch must not hang on a reader-less FIFO and must update its times.
834 let (at, mut ucmd) = at_and_ucmd!();
835 at.mkfifo("fifo");
836 ucmd.args(&["-d", "2020-01-01 00:00:00", "fifo"])
837 .succeeds()
838 .no_output();
839 assert!(at.is_fifo("fifo"));
840 }
841
842 #[test]
843 #[cfg(unix)]
844 #[cfg_attr(wasi_runner, ignore = "WASI: no stdout-to-file redirection")]
845 fn test_touch_dash_updates_stdout_file() {
846 // `touch -` must update the times of the file open as stdout (fd 1), even
847 // when it is read-only, and set them to "now" rather than a 1970 sentinel.
848 use std::fs::File;
849 use std::time::SystemTime;
850
851 let (at, mut ucmd) = at_and_ucmd!();
852 at.touch("c");
853 // Age the file so the update to "now" is detectable.
854 let old = FileTime::from_unix_time(1_000_000, 0);
855 filetime::set_file_times(at.plus("c"), old, old).unwrap();
856
857 let file = File::open(at.plus("c")).unwrap();
858 ucmd.set_stdout(file).arg("-").succeeds();
859
860 let mtime = at.metadata("c").modified().unwrap();
861 let age = SystemTime::now().duration_since(mtime).unwrap();
862 assert!(age.as_secs() < 60, "touch - left mtime stale: {age:?}");
863 }
864
865 #[test]
866 #[cfg(not(windows))]
867 fn test_touch_trailing_slash() {
868 let file = "no-file/";
869 new_ucmd!().args(&[file]).fails().stderr_only(format!(
870 "touch: cannot touch '{file}': No such file or directory\n"
871 ));
872 }
873
874 #[test]
875 #[cfg(windows)]
876 fn test_touch_trailing_slash_windows() {
877 let file = "no-file/";
878 new_ucmd!()
879 .args(&[file])
880 .fails()
881 .stderr_contains(format!("touch: cannot touch '{file}'"));
882 }
883
884 #[test]
885 fn test_touch_no_such_file_error_msg() {
886 let dirname = "nonexistent";
887 let filename = "file";
888 let path = PathBuf::from(dirname).join(filename);
889 let path_str = path.to_str().unwrap();
890
891 new_ucmd!().arg(&path).fails().stderr_only(format!(
892 "touch: cannot touch '{path_str}': No such file or directory\n"
893 ));
894 }
895
896 #[test]
897 #[cfg(not(any(target_os = "freebsd", target_os = "openbsd")))]
898 #[cfg_attr(wasi_runner, ignore = "WASI: touch - (stdout) is unsupported")]
899 fn test_touch_changes_time_of_file_in_stdout() {
900 // command like: `touch - 1< ./c`
901 // should change the timestamp of c
902
903 let (at, mut ucmd) = at_and_ucmd!();
904 let file = "test_touch_changes_time_of_file_in_stdout";
905
906 at.touch(file);
907 assert!(at.file_exists(file));
908 let (_, mtime) = get_file_times(&at, file);
909
910 ucmd.args(&["-"])
911 .set_stdout(at.make_file(file))
912 .succeeds()
913 .no_stderr();
914
915 let (_, mtime_after) = get_file_times(&at, file);
916 assert_ne!(mtime_after, mtime);
917 }
918
919 #[test]
920 #[cfg(unix)]
921 #[cfg_attr(
922 wasi_runner,
923 ignore = "WASI: filesystem permission errors surface as ENOENT rather than EACCES"
924 )]
925 fn test_touch_permission_denied_error_msg() {
926 let (at, mut ucmd) = at_and_ucmd!();
927
928 let dirname = "dir_with_read_only_access";
929 let filename = "file";
930 let path = PathBuf::from(dirname).join(filename);
931 let path_str = path.to_str().unwrap();
932
933 // create dest without write permissions
934 at.mkdir(dirname);
935 at.set_readonly(dirname);
936
937 let full_path = at.plus_as_string(path_str);
938 ucmd.arg(&full_path).fails().stderr_only(format!(
939 "touch: cannot touch '{full_path}': Permission denied\n",
940 ));
941 }
942
943 #[test]
944 fn test_touch_no_args() {
945 let mut ucmd = new_ucmd!();
946 ucmd.fails().no_stdout().usage_error("missing file operand");
947 }
948
949 #[test]
950 fn test_no_dereference_no_file() {
951 new_ucmd!()
952 .args(&["-h", "not-a-file"])
953 .fails()
954 .stderr_contains("setting times of 'not-a-file': No such file or directory");
955 new_ucmd!()
956 .args(&["-h", "not-a-file-1", "not-a-file-2"])
957 .fails()
958 .stderr_contains("setting times of 'not-a-file-1': No such file or directory")
959 .stderr_contains("setting times of 'not-a-file-2': No such file or directory");
960 }
961
962 #[test]
963 fn test_touch_leap_second() {
964 let (at, mut ucmd) = at_and_ucmd!();
965 let file = "test_touch_leap_sec";
966
967 ucmd.args(&["-t", "197001010000.60", file])
968 .succeeds()
969 .no_stderr();
970
971 assert!(at.file_exists(file));
972
973 let epoch = str_to_filetime("%Y%m%d%H%M", "197001010000");
974 let (atime, mtime) = get_file_times(&at, file);
975 assert_eq!(atime, mtime);
976 assert_eq!(atime.unix_seconds() - epoch.unix_seconds(), 60);
977 assert_eq!(mtime.unix_seconds() - epoch.unix_seconds(), 60);
978 }
979
980 #[test]
981 #[cfg(not(windows))]
982 // File::create doesn't support trailing separator in Windows
983 fn test_touch_trailing_slash_no_create() {
984 let (at, mut ucmd) = at_and_ucmd!();
985 at.touch("file");
986 ucmd.args(&["-c", "file/"]).fails_with_code(1);
987
988 let (at, mut ucmd) = at_and_ucmd!();
989 ucmd.args(&["-c", "no-file/"]).succeeds();
990 assert!(
991 !at.file_exists("no-file") && !at.dir_exists("no-file") && !at.symlink_exists("no-file")
992 );
993
994 let (at, mut ucmd) = at_and_ucmd!();
995 at.relative_symlink_file("nowhere", "dangling");
996 ucmd.args(&["-c", "dangling/"]).succeeds();
997 assert!(!at.file_exists("nowhere"));
998 assert!(at.symlink_exists("dangling"));
999
1000 let (at, mut ucmd) = at_and_ucmd!();
1001 at.relative_symlink_file("loop", "loop");
1002 ucmd.args(&["-c", "loop/"]).fails_with_code(1);
1003 assert!(!at.file_exists("loop"));
1004
1005 #[cfg(not(target_vendor = "apple"))]
1006 // MacOS supports trailing slash for symlinks to files
1007 {
1008 let (at, mut ucmd) = at_and_ucmd!();
1009 at.touch("file2");
1010 at.relative_symlink_file("file2", "link1");
1011 ucmd.args(&["-c", "link1/"]).fails_with_code(1);
1012 assert!(at.file_exists("file2"));
1013 assert!(at.symlink_exists("link1"));
1014 }
1015
1016 let (at, mut ucmd) = at_and_ucmd!();
1017 at.mkdir("dir");
1018 ucmd.args(&["-c", "dir/"]).succeeds();
1019
1020 let (at, mut ucmd) = at_and_ucmd!();
1021 at.mkdir("dir2");
1022 at.relative_symlink_dir("dir2", "link2");
1023 ucmd.args(&["-c", "link2/"]).succeeds();
1024 }
1025
1026 #[test]
1027 fn test_touch_no_dereference_ref_dangling() {
1028 let (at, mut ucmd) = at_and_ucmd!();
1029 at.touch("file");
1030 at.relative_symlink_file("nowhere", "dangling");
1031
1032 ucmd.args(&["-h", "-r", "dangling", "file"]).succeeds();
1033 }
1034
1035 #[test]
1036 fn test_touch_no_dereference_dangling() {
1037 let (at, mut ucmd) = at_and_ucmd!();
1038 at.relative_symlink_file("nowhere", "dangling");
1039
1040 ucmd.args(&["-h", "dangling"]).succeeds();
1041 }
1042
1043 #[test]
1044 #[cfg(not(target_os = "openbsd"))]
1045 #[cfg_attr(wasi_runner, ignore = "WASI: touch - (stdout) is unsupported")]
1046 fn test_touch_dash() {
1047 new_ucmd!().args(&["-h", "-"]).succeeds().no_output();
1048 }
1049
1050 #[test]
1051 #[cfg(wasi_runner)]
1052 fn test_touch_dash_unsupported() {
1053 new_ucmd!()
1054 .arg("-")
1055 .fails_with_code(1)
1056 .stderr_only("touch: touch - (stdout) is not supported on WASI\n");
1057 }
1058
1059 #[test]
1060 fn test_touch_invalid_date_format() {
1061 let file = "test_touch_invalid_date_format";
1062
1063 new_ucmd!()
1064 .args(&["-m", "-t", "+1000000000000 years", file])
1065 .fails()
1066 .stderr_contains("touch: invalid date format '+1000000000000 years'");
1067 }
1068
1069 #[test]
1070 fn test_touch_invalid_timestamp_leading_multibyte_char() {
1071 for ts in ["€123456789", "€23456789012"] {
1072 new_ucmd!()
1073 .args(&["-t", ts, "f"])
1074 .fails_with_code(1)
1075 .stderr_only(format!("touch: invalid date format '{ts}'\n"));
1076 }
1077 }
1078
1079 #[test]
1080 fn test_touch_invalid_timestamp_reports_original_input() {
1081 for ts in ["2026-04-10", "26-04-10", "00000000"] {
1082 new_ucmd!()
1083 .args(&["-t", ts, "f"])
1084 .fails_with_code(1)
1085 .stderr_only(format!("touch: invalid date format '{ts}'\n"));
1086 }
1087 }
1088
1089 #[test]
1090 #[cfg(not(target_os = "freebsd"))]
1091 fn test_touch_symlink_with_no_deref() {
1092 let (at, mut ucmd) = at_and_ucmd!();
1093 let target = "foo.txt";
1094 let symlink = "bar.txt";
1095 let initial_time = FileTime::from_unix_time(123, 0);
1096 let updated_atime = FileTime::from_unix_time(456, 0);
1097
1098 at.touch(target);
1099 let target_times = get_file_times(&at, target);
1100 at.relative_symlink_file(target, symlink);
1101 set_symlink_file_times(at.plus(symlink), initial_time, initial_time).unwrap();
1102
1103 ucmd.args(&["-a", "--no-dereference", "-d", "@456", symlink])
1104 .succeeds();
1105
1106 assert_eq!(
1107 (updated_atime, initial_time),
1108 get_symlink_times(&at, symlink)
1109 );
1110 assert_eq!(target_times, get_file_times(&at, target));
1111 }
1112
1113 #[test]
1114 #[cfg(not(target_os = "freebsd"))]
1115 fn test_touch_reference_symlink_with_no_deref() {
1116 let (at, mut ucmd) = at_and_ucmd!();
1117 let target = "foo.txt";
1118 let symlink = "bar.txt";
1119 let arg = "baz.txt";
1120 let time = FileTime::from_unix_time(123, 0);
1121
1122 at.touch(target);
1123 at.relative_symlink_file(target, symlink);
1124 set_symlink_file_times(at.plus(symlink), time, time).unwrap();
1125 at.touch(arg);
1126
1127 ucmd.args(&["--reference", symlink, "--no-dereference", arg])
1128 .succeeds();
1129 // Times should be taken from the symlink, not the destination
1130 assert_eq!((time, time), get_symlink_times(&at, arg));
1131 }
1132
1133 #[test]
1134 fn test_obsolete_posix_format() {
1135 let (at, mut ucmd) = at_and_ucmd!();
1136 ucmd.env("_POSIX2_VERSION", "199209")
1137 .env("POSIXLY_CORRECT", "1")
1138 .args(&["01010000", "11111111"])
1139 .succeeds()
1140 .no_output();
1141 assert!(at.file_exists("11111111"));
1142 assert!(!at.file_exists("01010000"));
1143 }
1144
1145 #[test]
1146 fn test_obsolete_posix_format_with_year() {
1147 let (at, mut ucmd) = at_and_ucmd!();
1148 ucmd.env("_POSIX2_VERSION", "199209")
1149 .env("POSIXLY_CORRECT", "1")
1150 .args(&["0101000090", "11111111"])
1151 .succeeds()
1152 .no_output();
1153 assert!(at.file_exists("11111111"));
1154 assert!(!at.file_exists("0101000090"));
1155 }
1156
1157 #[test]
1158 fn test_touch_f_option() {
1159 let (at, mut ucmd) = at_and_ucmd!();
1160 let file = "test_f_option.txt";
1161
1162 ucmd.args(&["-f", file]).succeeds().no_output();
1163
1164 assert!(at.file_exists(file));
1165 at.remove(file);
1166 }
1167
1168 #[test]
1169 #[cfg(target_os = "linux")]
1170 #[cfg_attr(wasi_runner, ignore = "WASI: argv/filenames must be valid UTF-8")]
1171 fn test_touch_non_utf8_paths() {
1172 use std::ffi::OsStr;
1173 use std::os::unix::ffi::OsStrExt;
1174
1175 let scene = TestScenario::new(util_name!());
1176 let at = &scene.fixtures;
1177
1178 let non_utf8_bytes = b"test_\xFF\xFE.txt";
1179 let non_utf8_name = OsStr::from_bytes(non_utf8_bytes);
1180
1181 scene.ucmd().arg(non_utf8_name).succeeds().no_output();
1182 assert!(std::fs::metadata(at.plus(non_utf8_name)).is_ok());
1183 }
1184
1185 #[test]
1186 #[cfg(target_os = "linux")]
1187 #[cfg_attr(wasi_runner, ignore = "WASI sandbox: host paths not visible")]
1188 fn test_touch_device_files() {
1189 let (_, mut ucmd) = at_and_ucmd!();
1190 ucmd.args(&["/dev/null", "/dev/zero", "/dev/full", "/dev/random"])
1191 .succeeds()
1192 .no_output();
1193 }
1194
1195 // Touching a symlink to an existing file must not truncate the target, like
1196 // GNU touch. The target exists, so this exercises the update_times path, not
1197 // the create path changed for #10019 — it guards the general "touch never
1198 // truncates" contract. The create-path fix itself is covered by the
1199 // create_without_truncate unit tests in src/touch.rs and the syscall-flag
1200 // check in util/check-safe-traversal.sh.
1201 #[test]
1202 #[cfg(unix)]
1203 #[cfg_attr(
1204 wasi_runner,
1205 ignore = "WASI sandbox: absolute symlink targets cannot be followed"
1206 )]
1207 fn test_touch_does_not_truncate_symlink_target() {
1208 use std::os::unix::fs::symlink;
1209
1210 let (at, mut ucmd) = at_and_ucmd!();
1211 at.write("victim", "do not truncate me");
1212 symlink(at.plus("victim"), at.plus("link")).unwrap();
1213
1214 ucmd.arg("link").succeeds();
1215
1216 assert_eq!(at.read("victim"), "do not truncate me");
1217 }
1218
1219 // Touching a dangling symlink creates its target as an empty file, like GNU.
1220 #[test]
1221 #[cfg(unix)]
1222 #[cfg_attr(
1223 wasi_runner,
1224 ignore = "WASI sandbox: absolute symlink targets cannot be followed"
1225 )]
1226 fn test_touch_through_dangling_symlink_creates_target() {
1227 use std::os::unix::fs::symlink;
1228
1229 let (at, mut ucmd) = at_and_ucmd!();
1230 symlink(at.plus("missing"), at.plus("link")).unwrap();
1231
1232 ucmd.arg("link").succeeds();
1233
1234 assert!(at.file_exists("missing"));
1235 assert_eq!(at.read("missing"), "");
1236 }
1237
1238 // touch must be able to update the times of an owned file that is neither
1239 // readable nor writable (mode 0). Setting explicit times via utimensat-by-path
1240 // only requires ownership, so this succeeds even though the file cannot be
1241 // opened. Regression test: touch should fail gracefully on unwritable directory.
1242 #[test]
1243 #[cfg(unix)]
1244 fn test_touch_set_time_on_unreadable_unwritable_file() {
1245 use std::os::unix::fs::PermissionsExt;
1246
1247 let (at, mut ucmd) = at_and_ucmd!();
1248 let file = "no_rights";
1249 at.touch(file);
1250 std::fs::set_permissions(at.plus(file), std::fs::Permissions::from_mode(0o000)).unwrap();
1251
1252 ucmd.args(&["-d", "2000-01-03 00:00", "-c", file])
1253 .succeeds()
1254 .no_output();
1255
1256 // Restore permissions so the test harness can read back the metadata.
1257 std::fs::set_permissions(at.plus(file), std::fs::Permissions::from_mode(0o644)).unwrap();
1258 let expected = str_to_filetime("%Y-%m-%d %H:%M", "2000-01-03 00:00");
1259 let (atime, mtime) = get_file_times(&at, file);
1260 assert_eq!(atime, expected);
1261 assert_eq!(mtime, expected);
1262 }