Re: [RFC PATCH] quote: make sq_quote_buf_pretty() prettier
- From
D. Ben Knoble <ben.knoble@gmail.com>
- Date
- Nov 30, 2026, 15:19 UTC
- Message-ID
- <CALnO6CDyTh+O_S6Q6Nq46wckLGXdvTKJmU6uK_SKn5S=p4X20g@mail.gmail.com>
- In-Reply-To
- <ee7de58093c69fbbab686a68b5b781bc60d90a2b.1795798429.git.phillip.wood@dunelm.org.uk>
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 }band 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