Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 28 Dec 2018 10:03:41 -0800
From:      John Baldwin <john@baldwin.cx>
To:        Edward Tomasz Napierala <trasz@FreeBSD.org>, src-committers@freebsd.org, svn-src-all@freebsd.org, svn-src-head@freebsd.org
Subject:   Re: svn commit: r342577 - head/bin/sh
Message-ID:  <7523dc7e-2fdb-bc91-40f9-ab4f760a2e3e@baldwin.cx>
In-Reply-To: <201812281751.wBSHpeVV095681@repo.freebsd.org>
References:  <201812281751.wBSHpeVV095681@repo.freebsd.org>

next in thread | previous in thread | raw e-mail | index | archive | help
On 12/28/18 9:51 AM, Edward Tomasz Napierala wrote:
> Author: trasz
> Date: Fri Dec 28 17:51:40 2018
> New Revision: 342577
> URL: https://svnweb.freebsd.org/changeset/base/342577
> 
> Log:
>   Make sh(1) collapse $HOME into "~" in PS1.
>   
>   Reviewed by:	jilles
>   MFC after:	2 weeks
>   Sponsored by:	DARPA, AFRL
>   Differential Revision:	https://reviews.freebsd.org/D18663
> 
> Modified:
>   head/bin/sh/parser.c
> 
> Modified: head/bin/sh/parser.c
> ==============================================================================
> --- head/bin/sh/parser.c	Fri Dec 28 17:50:40 2018	(r342576)
> +++ head/bin/sh/parser.c	Fri Dec 28 17:51:40 2018	(r342577)
> @@ -1978,7 +1978,9 @@ getprompt(void *unused __unused)
>  {
>  	static char ps[PROMPTLEN];
>  	const char *fmt;
> +	const char *home;
>  	const char *pwd;
> +	size_t homelen;
>  	int i, trim;
>  	static char internal_error[] = "??";
>  
> @@ -2039,8 +2041,24 @@ getprompt(void *unused __unused)
>  				    *pwd == '/' && pwd[1] != '\0')
>  					strlcpy(&ps[i], strrchr(pwd, '/') + 1,
>  					    PROMPTLEN - i);
> -				else
> -					strlcpy(&ps[i], pwd, PROMPTLEN - i);
> +				else {
> +					home = lookupvar("HOME");
> +					if (home != NULL)
> +						homelen = strlen(home);
> +					if (home != NULL &&
> +					    strcmp(home, "/") != 0 &&
> +					    strncmp(pwd, home, homelen) == 0 &&
> +					    (pwd[homelen] == '/' ||
> +					    pwd[homelen] == '\0')) {
> +						strlcpy(&ps[i], "~",
> +						    PROMPTLEN - i);
> +						strlcpy(&ps[i + 1],
> +						    pwd + homelen,
> +						    PROMPTLEN - i - 1);
> +					} else {
> +						strlcpy(&ps[i], pwd, PROMPTLEN - i);
> +					}
> +				}

The existing code already did this, but isn't the fancy math with the size
passed to strlcpy() one of the things strlcpy() tries to prevent?  Using
strlcat would seem to be harder to get wrong, that is:

     if (...) {
         strlcat(ps, "~", PROMPTLEN);
         strlcat(ps, pwd + homelen, PROMPTLEN);
     } else
         strlcat(ps, pwd, PROMPTLEN);

looks simpler to read and seems less error prone.

-- 
John Baldwin

                                                                            



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?7523dc7e-2fdb-bc91-40f9-ab4f760a2e3e>