commit: 918aa6275a5478e825763321d1e44ab537d08d01
parent d4813137797801fe715b0d0b6d20d2ebdc031f30
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Fri, 11 Feb 2022 19:45:34 +0100
bin/humanize: Improve argument handling
Diffstat:
2 files changed, 37 insertions(+), 5 deletions(-)
diff --git a/bin/humanize.c b/bin/humanize.c
@@ -29,7 +29,7 @@ main(int argc, char *argv[])
int divisor = HN_DIVISOR_1000;
size_t buflen = 6;
- while((c = getopt(argc, argv, "bd")) != -1)
+ while((c = getopt(argc, argv, ":bd")) != -1)
{
switch(c)
{
@@ -41,6 +41,10 @@ main(int argc, char *argv[])
divisor = HN_DIVISOR_1000;
buflen = 6; // 4 digits, 2 letters for suffix, NUL byte
break;
+ case ':':
+ fprintf(stderr, "Error: Missing operand for option: '-%c'\n", optopt);
+ usage();
+ return 1;
case '?':
fprintf(stderr, "Error: Unrecognised option: '-%c'\n", optopt);
usage();
@@ -48,16 +52,25 @@ main(int argc, char *argv[])
}
}
- for(; optind < argc; optind++)
+ argc -= optind;
+ argv += optind;
+
+ if(argc < 1)
+ {
+ usage();
+ return 1;
+ }
+
+ for(int argi = 0; argi < argc; argi++)
{
const char *errstr = NULL;
char buffer[7] = "-";
// 1024^(6+1) goes higher than long long; don't ask for the moon
- long long n = strtonum(argv[optind], LLONG_MIN, LLONG_MAX, &errstr);
+ long long n = strtonum(argv[argi], LLONG_MIN, LLONG_MAX, &errstr);
if(errstr)
{
- errx(1, "strtonum: %s is %s", argv[optind], errstr);
+ errx(1, "strtonum: %s is %s", argv[argi], errstr);
}
int err = humanize_number(buffer, buflen, n, "", HN_AUTOSCALE, flags | divisor);
@@ -73,7 +86,7 @@ main(int argc, char *argv[])
return 1;
case 0: fprintf(stderr, "humanize_number: Unknown error.\n"); return 1;
default:
- fprintf(stderr, "humanize_number: %s is %s\n", argv[optind], strerror(errno));
+ fprintf(stderr, "humanize_number: %s is %s\n", argv[argi], strerror(errno));
return 1;
}
}
diff --git a/test-bin/humanize b/test-bin/humanize
@@ -57,10 +57,29 @@ noarg_body() {
atf_check -s exit:1 -e 'inline:Usage: humanize [-bd] number\n' ../bin/humanize
}
+atf_test_case badflag
+badflag_body() {
+ atf_check -s exit:1 -e "inline:Error: Unrecognised option: '-f'\n"'Usage: humanize [-bd] number\n' ../bin/humanize -f
+ atf_check -s exit:1 -e "inline:Error: Unrecognised option: '-f'\n"'Usage: humanize [-bd] number\n' ../bin/humanize -f 123
+}
+
+atf_test_case limits
+limits_body() {
+ atf_check -o 'inline:9223P \n' ../bin/humanize 9223372036854775807
+ atf_check -s exit:1 -e 'inline:humanize: strtonum: 9223372036854775808 is too large\n' ../bin/humanize 9223372036854775808
+
+ # The fuck is this result
+ atf_check -o 'inline:-9223 \n' ../bin/humanize -- -9223372036854775808
+
+ atf_check -s exit:1 -e 'inline:humanize: strtonum: -9223372036854775809 is too small\n' ../bin/humanize -- -9223372036854775809
+}
+
atf_init_test_cases() {
cd "$(atf_get_srcdir)"
atf_add_test_case noarg
+ atf_add_test_case badflag
+ atf_add_test_case limits
atf_add_test_case one
atf_add_test_case two