git: a6346c02f646 - main - mktemp: don't double up on trailing slashes for -t paths

From: Kyle Evans <kevans_at_FreeBSD.org>
Date: Thu, 03 Nov 2022 02:43:09 UTC
The branch main has been updated by kevans:

URL: https://cgit.FreeBSD.org/src/commit/?id=a6346c02f646c6b74f007c64a9b546deb06182ae

commit a6346c02f646c6b74f007c64a9b546deb06182ae
Author:     Kyle Evans <kevans@FreeBSD.org>
AuthorDate: 2022-11-02 20:29:16 +0000
Commit:     Kyle Evans <kevans@FreeBSD.org>
CommitDate: 2022-11-03 02:42:57 +0000

    mktemp: don't double up on trailing slashes for -t paths
    
    This is a minor cosmetic change; re-organize slightly to set tmpdir to
    _PATH_TMP if we didn't otherwise have a tmpdir candidate, then check the
    trailing char before appending another slash.
    
    While we're here, remove some bogus whitespace and add a test case for
    this change.
    
    Obtained from:  https://github.com/apple-oss-distributions/shell_cmds
    Sponsored by:   Klara, Inc.
---
 usr.bin/mktemp/mktemp.c             |  8 ++++++--
 usr.bin/mktemp/tests/mktemp_test.sh | 14 ++++++++++++++
 2 files changed, 20 insertions(+), 2 deletions(-)

diff --git a/usr.bin/mktemp/mktemp.c b/usr.bin/mktemp/mktemp.c
index a15e0d776c40..6f5b21ce70d5 100644
--- a/usr.bin/mktemp/mktemp.c
+++ b/usr.bin/mktemp/mktemp.c
@@ -120,6 +120,7 @@ main(int argc, char **argv)
 
 	if (tflag) {
 		const char *envtmp;
+		size_t len;
 
 		envtmp = NULL;
 
@@ -131,7 +132,10 @@ main(int argc, char **argv)
 		if (envtmp != NULL)
 			tmpdir = envtmp;
 		if (tmpdir == NULL)
-			asprintf(&name, "%s%s.XXXXXXXXXX", _PATH_TMP, prefix);
+			tmpdir = _PATH_TMP;
+		len = strlen(tmpdir);
+		if (len > 0 && tmpdir[len - 1] == '/')
+			asprintf(&name, "%s%s.XXXXXXXXXX", tmpdir, prefix);
 		else
 			asprintf(&name, "%s/%s.XXXXXXXXXX", tmpdir, prefix);
 		/* if this fails, the program is in big trouble already */
@@ -142,7 +146,7 @@ main(int argc, char **argv)
 				errx(1, "cannot generate template");
 		}
 	}
-		
+
 	/* generate all requested files */
 	while (name != NULL || argc > 0) {
 		if (name == NULL) {
diff --git a/usr.bin/mktemp/tests/mktemp_test.sh b/usr.bin/mktemp/tests/mktemp_test.sh
index 1138c46ec1d0..60555f1b561b 100755
--- a/usr.bin/mktemp/tests/mktemp_test.sh
+++ b/usr.bin/mktemp/tests/mktemp_test.sh
@@ -109,10 +109,24 @@ tmpdir_pflag_noarg_body()
 	atf_check -o match:"^$tmpdir/foo\..+$" cat tmpname
 }
 
+atf_test_case tmpdir_tflag_oneslash
+tmpdir_tflag_oneslash_body()
+{
+
+	tmpdir="$PWD"
+
+	# Provided a trailing slash, we shouldn't end up with two trailing
+	# slashes.
+	atf_check -o save:tmpname \
+	    env TMPDIR="$tmpdir/" mktemp -t foo
+	atf_check -o match:"^$tmpdir/foo\..+$" cat tmpname
+}
+
 atf_init_test_cases()
 {
 	atf_add_test_case tmpdir_env
 	atf_add_test_case tmpdir_pflag
 	atf_add_test_case tmpdir_pflag_dir
 	atf_add_test_case tmpdir_pflag_noarg
+	atf_add_test_case tmpdir_tflag_oneslash
 }