threads / rfc / 66945

RFC patchquote: make sq_quote_buf_pretty() prettier

Subject: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

## tl;dr

The RFC would drop unnecessary quotes in human-readable shell quoting, but reviewers found cases where the output is wrong or unsafe to paste. Read the story.

replies: 9people: 4as markdown or json

Phillip Wood· Nov 27, 2026, 16:54 UTC · lore
From: Phillip Wood <phillip.wood@dunelm.org.uk>

The output of sq_quote_buf_pretty() is intended for human consumption and as such it tries to avoid unnecessary quoting. However, it is over enthusiastic about adding quotes to multibyte strings and strings containing '~', '{' or '}'. It also adds unnecessary pairs of empty quotes when a string starts or ends with a single quote. Fix this by using a dedicated quoting routine that tries to avoid adding unnecessary quotes, rather than reusing sq_quote_buf(). Tilde is only quoted if it is the first character. Braces are only quoted if there is a mismatch between the number of opening and closing braces, or they contain a comma or a character that needs quoting. Sections between backslash escapes are only quoted if they contain characters that need to be quoted. The table below shows the change in output for various inputs. The aim is to make the output more readable without changing the meaning of the quoted output were it to be evaluated by the shell.

We could further improve the readability by dropping support for csh which requires that '!' is backslash escaped. It is not clear to me how widely used csh is these days, none of the big three BSD distributions seem to have used it as the default shell for a number of years.

Text Current output New output danger! 'danger'\!'' danger\! 'look out!' ''\''look out'\!''\''' \''look out'\!\' Dvořák 'Dvořák' Dvořák HEAD~3 'HEAD~3' HEAD~3 HEAD@{1} 'HEAD@{1}' HEAD@{1} HEAD^{/,} 'HEAD^{/,}' 'HEAD^{/,}'

Signed-off-by: Phillip Wood <phillip.wood@dunelm.org.uk>
---
Following on from the discussion at [1] this tries to improve the
readability of the output without changing which shells we support
which is a bigger change that requires more thought and discussion. If
we do decide to go the route of per-shell quoting the changes here
will be useful for supporting POSIX shells.

There aren't any tests yet, though I have tested it manually by looking at the trace output from commands like

   GIT_TRACE=1 git -c alias.z='log -1 HEAD~1' z

I'll add some tests if there is interest in this patch. On that subject, does anyone know how to easily write table driven unit tests in clar with a separate test for each input?

[1] https://lore.kernel.org/git/02A50A47-A048-417E-9D1E-0C12D8FB1476@gmail.com
base-commit: 77904e546de3bd940621092ecec47a88d0cede5d
Published-As: https://github.com/phillipwood/git/releases/tag/pw%2Fsq-quote-prettier%2Frfc-v1
View-Changes-At: https://github.com/phillipwood/git/compare/77904e546...ee7de5809
Fetch-It-Via: git fetch https://github.com/phillipwood/git pw/sq-quote-prettier/rfc-v1
 quote.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++--------
 1 file changed, 63 insertions(+), 10 deletions(-)
Show changes to quote.c +63 −10
diff --git a/quote.c b/quote.c
index 235fac8e470..dfd379a102f 100644
--- a/quote.c
+++ b/quote.c
@@ -47,26 +47,79 @@ void sq_quote_buf(struct strbuf *dst, const char *src)
 	free(to_free);
 }
 
+static bool needs_sq_quote(char c, unsigned brace)
+{
+	if (isalnum(c) || (unsigned char)c > 0x7f)
+		return false;
+
+	switch (c) {
+	case ',':
+		return brace > 0; /* Prevent brace expansion */
+	case '}':
+		return !brace; /* Quote unpaired '}' */
+	case '~':
+	case '+':
+	case '-':
+	case '.':
+	case '/':
+	case ':':
+	case '=':
+	case '@':
+	case '_':
+	case '^':
+		return false;
+	default:
+		return true;
+	}
+}
+
 void sq_quote_buf_pretty(struct strbuf *dst, const char *src)
 {
-	static const char ok_punct[] = "+,-./:=@_^";
-	const char *p;
+	const char *p = src, *q;
+	bool quote_it = false;
+	unsigned brace = 0;
 
 	/* Avoid losing a zero-length string by adding '' */
-	if (!*src) {
+	if (!*p) {
 		strbuf_addstr(dst, "''");
 		return;
 	}
 
-	for (p = src; *p; p++) {
-		if (!isalnum(*p) && !strchr(ok_punct, *p)) {
-			sq_quote_buf(dst, src);
-			return;
-		}
+	/* '~' is only special if it is the first character */
+	if (*p == '~') {
+		quote_it = true;
+		p++;
 	}
 
-	/* if we get here, we did not need quoting */
-	strbuf_addstr(dst, src);
+	for (q = p; *q; q++) {
+		if (need_bs_quote(*q)) {
+			if (brace)
+				quote_it = true;
+			if (quote_it)
+				strbuf_addch(dst, '\'');
+			strbuf_add(dst, p, q - p);
+			p = q + 1;
+			if (quote_it)
+				strbuf_addch(dst, '\'');
+			strbuf_addch(dst, '\\');
+			strbuf_addch(dst, *q);
+			if (!brace)
+				quote_it = false;
+		} else if (*q == '{') {
+			brace++;
+		} else if (*q == '}' && brace) {
+			brace--;
+		} else if (!quote_it && needs_sq_quote(*q, brace)) {
+			quote_it = true;
+		}
+	}
+	if (brace && !quote_it)
+		quote_it = true; /* Quote unpaired '{' */
+	if (quote_it)
+		strbuf_addch(dst, '\'');
+	strbuf_add(dst, p, q - p);
+	if (quote_it)
+		strbuf_addch(dst, '\'');
 }
 
 void sq_quotef(struct strbuf *dst, const char *fmt, ...)
-- 
2.56.1.576.g0cfbda1d5c7.dirty
Nahid hasan Sagor· Nov 27, 2026, 18:25 UTC · re: Phillip Wood · lore

Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

Show 5 quoted lines
> +       /* '~' is only special if it is the first character */
> +       if (*p == '~') {
> +               quote_it = true;
> +               p++;
>         }

I may be misreading, but I think a leading '~' gets lost after the 'p++', so it never gets copied by strbuf_add(dst, p, q - p) later. That would make "~foo" come out as "'foo'".

Phillip Wood· Nov 30, 2026, 14:51 UTC · re: Nahid hasan Sagor · lore

Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

Hi Nahid
On 27/11/2026 18:25, Nahid hasan Sagor wrote:
Show 8 quoted lines
>> +       /* '~' is only special if it is the first character */
>> +       if (*p == '~') {
>> +               quote_it = true;
>> +               p++;
>>          }
> > I may be misreading, but I think a leading '~' gets lost after the
> 'p++', so it never gets copied by strbuf_add(dst, p, q - p) later. That
> would make "~foo" come out as "'foo'".
You're right - good catch. Junio has pointed out some other problems with the handling of '~' as well so I'll rework this.
Thanks
Phillip
Junio C Hamano· Nov 27, 2026, 20:31 UTC · re: Phillip Wood · lore

Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

Phillip Wood <phillip.wood123@gmail.com> writes:
Show 8 quoted lines
> +static bool needs_sq_quote(char c, unsigned brace)
> +{
> +	if (isalnum(c) || (unsigned char)c > 0x7f)
> +		return false;
> +
> +	switch (c) {
> +	case ',':
> +		return brace > 0; /* Prevent brace expansion */

Web search tells me that bash, zsh, and ksh93 expands sequence expressions such as "{1..5}" or "{a..z}" without any comma in the pair of braces. Because '.' returns false unconditionally here and no other check triggers quoting for "..", sq_quote_buf_pretty() leaves "{1..5}" unquoted, which expands to five arguments if pasted into those shells.

Show 25 quoted lines
>  void sq_quote_buf_pretty(struct strbuf *dst, const char *src)
>  {
> -	static const char ok_punct[] = "+,-./:=@_^";
> -	const char *p;
> +	const char *p = src, *q;
> +	bool quote_it = false;
> +	unsigned brace = 0;
>  
>  	/* Avoid losing a zero-length string by adding '' */
> -	if (!*src) {
> +	if (!*p) {
>  		strbuf_addstr(dst, "''");
>  		return;
>  	}
>  
> -	for (p = src; *p; p++) {
> -		if (!isalnum(*p) && !strchr(ok_punct, *p)) {
> -			sq_quote_buf(dst, src);
> -			return;
> -		}
> +	/* '~' is only special if it is the first character */
> +	if (*p == '~') {
> +		quote_it = true;
> +		p++;
>  	}

As noticed by Nahid already, this loses the leading '~'. Also, do we want to do something to this corner case?

    $ echo P=A:~/B:C
    P=A:/home/gitster/B:C

i.e., bash and friends seem to expand ~ that is not at the beginning of value when the whole thing looks like a variable assignment. Without "P=" at front, this does not seem to expand.

Thanks.
Phillip Wood· Nov 30, 2026, 16:39 UTC · re: Junio C Hamano · lore

Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

On 27/11/2026 20:31, Junio C Hamano wrote:
Show 14 quoted lines
> Phillip Wood <phillip.wood123@gmail.com> writes:
> >> +static bool needs_sq_quote(char c, unsigned brace)
>> +{
>> +	if (isalnum(c) || (unsigned char)c > 0x7f)
>> +		return false;
>> +
>> +	switch (c) {
>> +	case ',':
>> +		return brace > 0; /* Prevent brace expansion */
> > Web search tells me that bash, zsh, and ksh93 expands sequence
> expressions such as "{1..5}" or "{a..z}" without any comma in the pair
> of braces.  Because '.' returns false unconditionally here and no other
> check triggers quoting for "..", sq_quote_buf_pretty() leaves "{1..5}"
> unquoted, which expands to five arguments if pasted into those shells.
Oh, thanks for pointing that out. I think it should be fairly easy to detect '..' when brace != 0
Show 12 quoted lines
>> +	/* '~' is only special if it is the first character */
>> +	if (*p == '~') {
>> +		quote_it = true;
>> +		p++;
>>   	}
> > As noticed by Nahid already, this loses the leading '~'.  Also, do we
> want to do something to this corner case?
> >      $ echo P=A:~/B:C
>      P=A:/home/gitster/B:C
> > i.e., bash and friends seem to expand ~ that is not at the beginning of
> value when the whole thing looks like a variable assignment.  Without
> "P=" at front, this does not seem to expand.
Thanks, having read the manuals bash, zsh and ksh all have slightly different behaviors (and the zsh behavior depends on which options are set). Quoting strings that start with '~', or contain '=~' or ':~', is sufficient to prevent tilde expansion while avoiding quoting 'HEAD~1'.
zsh has an EXTENDED_GLOB option where '<pattern1>~<pattern2>' matches everything that <pattern1> would match that <pattern2> does not. Luckily, it seems to need another special character in one of the patterns to trigger it so we don't need to quote "HEAD~1". The EXTENDED_GLOB option also treats '^' specially, so to be safe we should be quoting anything containing '^' which we don't at the moment. That's a shame it means we need to quote "HEAD^2". EXTENDED_GLOB is not enabled by default, but I think it is worth making our output safe when it is enabled.
By default, zsh also expands "=cmd" to the absolute path of "cmd" in the same places as '~' would be subject to tilde expansion.
On a related note our treatment of assignments is a bit strange - if the right hand side needs quoting then we quote the whole thing which disables the assignment, but we don't quote it otherwise. When sq_quote_buf_pretty() was introduced the aim seems to have been to be able to copy and paste tracing output to rerun the command being traced, which would imply we don't want to disable assignments when the right hand side needs to be quoted.
I'll try and re-roll later this week
Thanks
Phillip
Junio C Hamano· Nov 28, 2026, 00:26 UTC · re: Phillip Wood · lore

Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

Phillip Wood <phillip.wood123@gmail.com> writes:
I forgot to mention a couple of things.
> ... It also adds unnecessary pairs
> of empty quotes when a string starts or ends with a single quote.

"a single quote or an exclamation point." We can see the example in the table you have below, for the entry for 'danger!'.

Show 14 quoted lines
> +	for (q = p; *q; q++) {
> +		if (need_bs_quote(*q)) {
> +			if (brace)
> +				quote_it = true;
> +			if (quote_it)
> +				strbuf_addch(dst, '\'');
> +			strbuf_add(dst, p, q - p);
> +			p = q + 1;
> +			if (quote_it)
> +				strbuf_addch(dst, '\'');
> +			strbuf_addch(dst, '\\');
> +			strbuf_addch(dst, *q);
> +			if (!brace)
> +				quote_it = false;

When brace > 0, quote_it stays true after emitting the backslash-escaped character.

If the next character also needs backslash quoting (such as "{a'!b}"), or if the string ends right there with an unclosed brace (such as "{!", p == q (i.e., an empty segment) but we emit it in a pair of single quotes.

Show 15 quoted lines
> +		} else if (*q == '{') {
> +			brace++;
> +		} else if (*q == '}' && brace) {
> +			brace--;
> +		} else if (!quote_it && needs_sq_quote(*q, brace)) {
> +			quote_it = true;
> +		}
> +	}
> +	if (brace && !quote_it)
> +		quote_it = true; /* Quote unpaired '{' */
> +	if (quote_it)
> +		strbuf_addch(dst, '\'');
> +	strbuf_add(dst, p, q - p);
> +	if (quote_it)
> +		strbuf_addch(dst, '\'');

After the loop, here also is an instance of single quote pair around potentially an empty segment. Perhaps a short helper or macro that does an equivalent of

	if (p < q) {
		if (quote_it)
			strbuf_addch(dst, '\'');
		strbuf_add(dst, p, q - p);
		if (quote_it)
			strbuf_addch(dst, '\'');
	}		

and use it twice (the bs-quote code path needs to be slightly rewritten if we wanted to share this piece of code that way)?

>  }
>  
>  void sq_quotef(struct strbuf *dst, const char *fmt, ...)
Phillip Wood· Nov 30, 2026, 16:40 UTC · re: Junio C Hamano · lore

Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

On 28/11/2026 00:26, Junio C Hamano wrote:
Show 6 quoted lines
> Phillip Wood <phillip.wood123@gmail.com> writes:
> > I forgot to mention a couple of things.
> >> ... It also adds unnecessary pairs
>> of empty quotes when a string starts or ends with a single quote.
> > "a single quote or an exclamation point."  We can see the example in the
> table you have below, for the entry for 'danger!'.
I'll add that
Show 20 quoted lines
>> +	for (q = p; *q; q++) {
>> +		if (need_bs_quote(*q)) {
>> +			if (brace)
>> +				quote_it = true;
>> +			if (quote_it)
>> +				strbuf_addch(dst, '\'');
>> +			strbuf_add(dst, p, q - p);
>> +			p = q + 1;
>> +			if (quote_it)
>> +				strbuf_addch(dst, '\'');
>> +			strbuf_addch(dst, '\\');
>> +			strbuf_addch(dst, *q);
>> +			if (!brace)
>> +				quote_it = false;
> > When brace > 0, quote_it stays true after emitting the backslash-escaped
> character.
> > If the next character also needs backslash quoting (such as "{a'!b}"),
> or if the string ends right there with an unclosed brace (such as "{!",
> p == q (i.e., an empty segment) but we emit it in a pair of single
> quotes.
Good point
Show 12 quoted lines
> After the loop, here also is an instance of single quote pair around
> potentially an empty segment.  Perhaps a short helper or macro that does
> an equivalent of
> > 	if (p < q) {
> 		if (quote_it)
> 			strbuf_addch(dst, '\'');
> 		strbuf_add(dst, p, q - p);
> 		if (quote_it)
> 			strbuf_addch(dst, '\'');
> 	}		
> > and use it twice (the bs-quote code path needs to be slightly rewritten
> if we wanted to share this piece of code that way)?
That's a good idea
Thanks
Phillip
> >>   }
>>   >>   void sq_quotef(struct strbuf *dst, const char *fmt, ...)
D. Ben Knoble· Nov 30, 2026, 15:19 UTC · re: Phillip Wood · lore

Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

Hi Phillip, thanks for working on this!
On Fri, Nov 27, 2026 at 11:54 AM Phillip Wood <phillip.wood123@gmail.com> wrote:
Show 46 quoted lines
>  void sq_quote_buf_pretty(struct strbuf *dst, const char *src)
>  {
> -       static const char ok_punct[] = "+,-./:=@_^";
> -       const char *p;
> +       const char *p = src, *q;
> +       bool quote_it = false;
> +       unsigned brace = 0;
>
>         /* Avoid losing a zero-length string by adding '' */
> -       if (!*src) {
> +       if (!*p) {
>                 strbuf_addstr(dst, "''");
>                 return;
>         }
>
> -       for (p = src; *p; p++) {
> -               if (!isalnum(*p) && !strchr(ok_punct, *p)) {
> -                       sq_quote_buf(dst, src);
> -                       return;
> -               }
> +       /* '~' is only special if it is the first character */
> +       if (*p == '~') {
> +               quote_it = true;
> +               p++;
>         }
>
> -       /* if we get here, we did not need quoting */
> -       strbuf_addstr(dst, src);
> +       for (q = p; *q; q++) {
> +               if (need_bs_quote(*q)) {
> +                       if (brace)
> +                               quote_it = true;
> +                       if (quote_it)
> +                               strbuf_addch(dst, '\'');
> +                       strbuf_add(dst, p, q - p);
> +                       p = q + 1;
> +                       if (quote_it)
> +                               strbuf_addch(dst, '\'');
> +                       strbuf_addch(dst, '\\');
> +                       strbuf_addch(dst, *q);
> +                       if (!brace)
> +                               quote_it = false;
> +               } else if (*q == '{') {
> +                       brace++;
> +               } else if (*q == '}' && brace) {
> +                       brace--;

I think this simple counter may count wrongly for scenarios like "}{a,b}", but I haven't tried it myself yet. My shells (Zsh and Bash) both do the following:

    $ echo }{a,b}
    }a }b

and I *think* that brace==0 when we see the comma here, even though it would need quoted to avoid expansion.

I think we are unlikely to emit such strange punctuation ourselves, but this would be one corner case of potentially many, I suspect.

Show 17 quoted lines
> +               } else if (!quote_it && needs_sq_quote(*q, brace)) {
> +                       quote_it = true;
> +               }
> +       }
> +       if (brace && !quote_it)
> +               quote_it = true; /* Quote unpaired '{' */
> +       if (quote_it)
> +               strbuf_addch(dst, '\'');
> +       strbuf_add(dst, p, q - p);
> +       if (quote_it)
> +               strbuf_addch(dst, '\'');
>  }
>
>  void sq_quotef(struct strbuf *dst, const char *fmt, ...)
> --
> 2.56.1.576.g0cfbda1d5c7.dirty
>
-- 
D. Ben Knoble
Phillip Wood· Nov 30, 2026, 16:38 UTC · re: D. Ben Knoble · lore

Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

Hi Ben
On 30/11/2026 15:19, D. Ben Knoble wrote:
> Hi Phillip, thanks for working on this!
Thanks
Show 26 quoted lines
> On Fri, Nov 27, 2026 at 11:54 AM Phillip Wood <phillip.wood123@gmail.com> wrote:
> >> +       for (q = p; *q; q++) {
>> +               if (need_bs_quote(*q)) {
>> +                       if (brace)
>> +                               quote_it = true;
>> +                       if (quote_it)
>> +                               strbuf_addch(dst, '\'');
>> +                       strbuf_add(dst, p, q - p);
>> +                       p = q + 1;
>> +                       if (quote_it)
>> +                               strbuf_addch(dst, '\'');
>> +                       strbuf_addch(dst, '\\');
>> +                       strbuf_addch(dst, *q);
>> +                       if (!brace)
>> +                               quote_it = false;
>> +               } else if (*q == '{') {
>> +                       brace++;
>> +               } else if (*q == '}' && brace) {
>> +                       brace--;
> > I think this simple counter may count wrongly for scenarios like
> "}{a,b}", but I haven't tried it myself yet. My shells (Zsh and Bash)
> both do the following:
> >      $ echo }{a,b}
>      }a }b
> > and I *think* that brace==0 when we see the comma here, even though it
> would need quoted to avoid expansion.
We only decrement "brace" when we see '}' if "brace > 0". If we see '}' when "brace == 0" then we quote everything up to the next backslash escape or the end of the string. So we decide to quote this before we see the comma.
Thanks
Phillip
> > I think we are unlikely to emit such strange punctuation ourselves,
> but this would be one corner case of potentially many, I suspect.
Show 18 quoted lines
> >> +               } else if (!quote_it && needs_sq_quote(*q, brace)) {
>> +                       quote_it = true;
>> +               }
>> +       }
>> +       if (brace && !quote_it)
>> +               quote_it = true; /* Quote unpaired '{' */
>> +       if (quote_it)
>> +               strbuf_addch(dst, '\'');
>> +       strbuf_add(dst, p, q - p);
>> +       if (quote_it)
>> +               strbuf_addch(dst, '\'');
>>   }
>>
>>   void sq_quotef(struct strbuf *dst, const char *fmt, ...)
>> --
>> 2.56.1.576.g0cfbda1d5c7.dirty
>>
> > 
D. Ben Knoble· Nov 30, 2026, 17:02 UTC · re: Phillip Wood · lore

Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier

On Mon, Nov 30, 2026 at 11:39 AM Phillip Wood <phillip.wood123@gmail.com> wrote:
> On 30/11/2026 15:19, D. Ben Knoble wrote:
> > On Fri, Nov 27, 2026 at 11:54 AM Phillip Wood <phillip.wood123@gmail.com> wrote:
Show 17 quoted lines
> >> +               } else if (*q == '}' && brace) {
> >> +                       brace--;
> >
> > I think this simple counter may count wrongly for scenarios like
> > "}{a,b}", but I haven't tried it myself yet. My shells (Zsh and Bash)
> > both do the following:
> >
> >      $ echo }{a,b}
> >      }a }b
> >
> > and I *think* that brace==0 when we see the comma here, even though it
> > would need quoted to avoid expansion.
>
> We only decrement "brace" when we see '}' if "brace > 0". If we see '}'
> when "brace == 0" then we quote everything up to the next backslash
> escape or the end of the string. So we decide to quote this before we
> see the comma.
Doh, I missed the "&& brace"---thanks!

Some other time, I (or anyone interested) should throw a fuzzer at this and see what happens ;)

← back to recent threads