Subject: [PATCH 3/3] Clean up chabspath() [':a' word modifier].
From: Daniel Shahaf <[email-masked]>
To: [email-masked]
Date: Fri, 10 Jun 2016 17:36:24 +0000
List-Id: Zsh Workers List <zsh-workers.zsh.org>

Fail fast when the first character isn't "/", and use that to simplify the
'..' handling.

The incumbent code was subtly wrong in various ways (for example,
the first 'else if' branch didn't check that dest[-4] was a slash).
---
 Src/hist.c | 23 +++++++++--------------
 1 file changed, 9 insertions(+), 14 deletions(-)

diff --git a/Src/hist.c b/Src/hist.c
index 07f56b0..2cce970 100644
--- a/Src/hist.c
+++ b/Src/hist.c
@@ -1767,6 +1767,10 @@ chabspath(char **junkptr)
     if (**junkptr != '/') {
 	*junkptr = zhtricat(metafy(zgetcwd(), -1, META_HEAPDUP), "/", *junkptr);
     }
+    if (**junkptr != '/') {
+	/* Can happen after 'rmdir $PWD; zsh' */
+	return 0;
+    }
 
     current = *junkptr;
     dest = *junkptr;
@@ -1783,7 +1787,9 @@ chabspath(char **junkptr)
 
     for (;;) {
 	if (*current == '/') {
+	    /* Contract multiple slashes. */
 #ifdef __CYGWIN__
+	    /* Exception: on Cygwin, two slashes at the very start are significant. */
 	    if (current == *junkptr && current[1] == '/')
 		*dest++ = *current++;
 #endif
@@ -1791,28 +1797,17 @@ chabspath(char **junkptr)
 	    while (*current == '/')
 		current++;
 	} else if (!*current) {
+	    /* Remove trailing slashes. */
 	    while (dest > *junkptr + 1 && dest[-1] == '/')
 		dest--;
 	    *dest = '\0';
 	    break;
 	} else if (current[0] == '.' && current[1] == '.' &&
 		   (!current[2] || current[2] == '/')) {
-		if (current == *junkptr || dest == *junkptr) {
-		    *dest++ = '.';
-		    *dest++ = '.';
-		    current += 2;
-		} else if (dest > *junkptr + 2 &&
-			   !strncmp(dest - 3, "../", 3)) {
-		    *dest++ = '.';
-		    *dest++ = '.';
-		    current += 2;
-		} else if (dest > *junkptr + 1) {
-		    *dest = '\0';
+		if (dest > *junkptr + 1) {
 		    for (dest--;
-			 dest > *junkptr + 1 && dest[-1] != '/';
+			 dest[-1] != '/';
 			 dest--);
-		    if (dest[-1] != '/')
-			dest--;
 		    current += 2;
 		    if (*current == '/')
 			current++;