logo

utils

~/.local/bin tools and git-hooks git clone https://hacktivis.me/git/utils.git
commit: 99691c19f2f3cb46181b148ba8b2414555d33449
parent b601112926e6b29c7e08def3b4e6bf27c8b87072
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Fri, 11 Feb 2022 19:43:01 +0100

bin/basename: Handle write errors

Diffstat:

Mbin/basename.c22++++++++++++++++------
Mtest-bin/basename25+++++++++++++++++++++++++
2 files changed, 41 insertions(+), 6 deletions(-)

diff --git a/bin/basename.c b/bin/basename.c @@ -4,7 +4,7 @@ #include <assert.h> // assert() #include <libgen.h> // basename() -#include <stdio.h> // fputs(), puts() +#include <stdio.h> // fprintf(), puts(), perror() #include <string.h> // strlen(), strcmp() static char * @@ -28,6 +28,8 @@ suffix_basename(char *name, char *suffix) int main(int argc, char *argv[]) { + int ret = 0; + if((argc > 1) && (strcmp(argv[1], "--") == 0)) { argv++; @@ -36,11 +38,19 @@ main(int argc, char *argv[]) switch(argc) { - case 1: puts("."); break; - case 2: puts(basename(argv[1])); break; - case 3: puts(suffix_basename(argv[1], argv[2])); break; - default: fputs("usage: basename string [suffix]", stderr); return 1; + case 1: ret = printf(".\n"); break; + case 2: ret = puts(basename(argv[1])); break; + case 3: ret = puts(suffix_basename(argv[1], argv[2])); break; + default: fprintf(stderr, "usage: basename string [suffix]\n"); return 1; } - return 0; + if(ret <= 0) + { + perror("basename: puts"); + return 1; + } + else + { + return 0; + } } diff --git a/test-bin/basename b/test-bin/basename @@ -25,6 +25,24 @@ testopt_body() { atf_check -o "inline:bin\n" ../bin/basename "/usr//bin-test" "-test" } +atf_test_case usage +usage_body() { + atf_check -s exit:1 -e "inline:usage: basename string [suffix]\n" ../bin/basename 1 2 3 +} + +atf_test_case devfull +devfull_body() { + atf_check -s exit:1 -e 'inline:Error writing: No space left on device\n' sh -c '../bin/basename >/dev/full' + atf_check -s exit:1 -e 'inline:Error writing: No space left on device\n' sh -c '../bin/basename "/usr/bin" >/dev/full' + atf_check -s exit:1 -e 'inline:Error writing: No space left on device\n' sh -c '../bin/baename "/usr//bin-test" "-test" >/dev/full' +} + +atf_test_case nullarg +nullarg_body() { + atf_check -e "inline:.\n" ../bin/basename "$(printf '\x00')" + atf_check -e "inline:bin\n" ../bin/basename "/usr/bin" "$(printf '\x00')" +} + atf_init_test_cases() { cd "$(atf_get_srcdir)" atf_add_test_case noargs @@ -32,4 +50,11 @@ atf_init_test_cases() { atf_add_test_case two_slash atf_add_test_case two_dash atf_add_test_case testopt + atf_add_test_case usage + + # puts in glibc doesn't returns -1 on failure + #atf_add_test_case devfull + + # Broken behavior in ATF, might be caused by stripping out \x00 + #atf_add_test_case nullarg }