logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git
commit: 328a837b9672224c6dfca20d17845ca8a2655907
parent 63963c4aa2153d2db4a23095526394731f75d754
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Thu, 19 Sep 2024 06:59:05 +0200

cmd/touch: handle empty-string as a file

Diffstat:

Mcmd/touch.c17++++++++++-------
Mtest-cmd/touch7+++++++
2 files changed, 17 insertions(+), 7 deletions(-)

diff --git a/cmd/touch.c b/cmd/touch.c @@ -221,7 +221,7 @@ main(int argc, char *argv[]) if(stat(ref_file, &ref) != 0) { - perror("touch: stat"); + fprintf(stderr, "touch: error: Failed getting status of file '%s': %s\n", ref_file, strerror(errno)); return 1; } @@ -237,34 +237,37 @@ main(int argc, char *argv[]) for(int i = 0; i < argc; i++) { + const char *file = argv[i]; assert(errno == 0); - int fd = open(argv[i], open_flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); + int fd = open(file, open_flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if(fd == -1) { if(errno == EISDIR) { - if(utimensat(AT_FDCWD, argv[i], times, utimensat_flags) != 0) + if(utimensat(AT_FDCWD, file, times, utimensat_flags) != 0) { - perror("touch: utimensat"); + fprintf(stderr, "touch: error: Failed setting new times on directory '%s': %s\n", file, strerror(errno)); return 1; } return 0; } - if(errno != ENOENT) perror("touch: open"); + + if(errno != ENOENT || FIELD_MATCH(open_flags, O_CREAT)) + fprintf(stderr, "touch: error: Failed opening file '%s': %s\n", file, strerror(errno)); return 1; } if(futimens(fd, times) != 0) { - perror("touch: futimens"); + fprintf(stderr, "touch: error: Failed setting new times on file '%s': %s\n", file, strerror(errno)); return 1; } if(close(fd) != 0) { - perror("touch: close"); + fprintf(stderr, "touch: error: Failed closing file-descriptor for file '%s': %s\n", file, strerror(errno)); return 1; } } diff --git a/test-cmd/touch b/test-cmd/touch @@ -171,6 +171,11 @@ optt_body() { atf_check -o 'match:^2003-06-02[T ]13:37:42(\.0+)? ?(Z|[\+\-]00:?00)$' ./stat_mtime ./foo } +atf_test_case empty_str +empty_str_body() { + atf_check -s exit:1 -o empty -e "inline:touch: error: Failed opening file '': No such file or directory\n" ../cmd/touch '' +} + atf_init_test_cases() { cd "$(atf_get_srcdir)" || exit 1 @@ -191,6 +196,8 @@ atf_init_test_cases() { atf_add_test_case optt + atf_add_test_case empty_str + # No support for displaying fractional seconds on FreeBSD stat(1) if uname -s | grep -iq FreeBSD; then # shellcheck disable=SC2317