Subject: [PATCH v2 0/1] worktree add: sanitize worktree names

From: Nguyễn Thái Ngọc Duy <[email-masked]>
Date: Thu, 21 Feb 2019 19:19:42 +0700

v2 fixes bad ".lock" handling in v1. I keep the "name->len == 0" part
though because I found another valid case that could end up there.

Nguyễn Thái Ngọc Duy (1):
  worktree add: sanitize worktree names

 builtin/worktree.c      | 51 ++++++++++++++++++++++++++++++++++++++++-
 t/t2025-worktree-add.sh |  7 ++++++
 2 files changed, 57 insertions(+), 1 deletion(-)

Range-diff dựa trên v1:
1:  42a3144874 ! 1:  d1b6e1c55b worktree add: sanitize worktree names
    @@ -13,7 +13,7 @@
         be able to specify the worktree name by themselves if they're not
         happy with this dumb character substitution.
     
    -    Reported-by: [email-masked]
    +    Reported-by: Konstantin Kharlamov <[email-masked]>
         Signed-off-by: Nguyễn Thái Ngọc Duy <[email-masked]>
     
      diff --git a/builtin/worktree.c b/builtin/worktree.c
    @@ -30,16 +30,14 @@
     + */
     +static void sanitize_worktree_name(struct strbuf *name)
     +{
    ++	char *orig_name = xstrdup(name->buf);
     +	int i;
     +
    -+	/* no ending with .lock */
    -+	if (ends_with(name->buf, ".lock"))
    -+		strbuf_remove(name, name->len - strlen(".lock"),
    -+			      strlen(".lock"));
    -+
     +	/*
     +	 * All special chars replaced with dashes. See
     +	 * check_refname_component() for reference.
    ++	 * Note that .lock is also turned to -lock, removing its
    ++	 * special status.
     +	 */
     +	for (i = 0; i < name->len; i++) {
     +		if (strchr(":?[]\\~ \t@{}*/.", name->buf[i]))
    @@ -55,12 +53,18 @@
     +			strbuf_remove(name, i, 1);
     +	}
     +
    -+	/* last resort, should never ever happen in practice */
    ++	/*
    ++	 * a worktree name of only special chars would be reduced to
    ++	 * an empty string
    ++	 */
     +	if (name->len == 0)
     +		strbuf_addstr(name, "worktree");
     +
     +	if (check_refname_format(name->buf, REFNAME_ALLOW_ONELEVEL))
    -+		BUG("worktree name '%s' is not a valid refname", name->buf);
    ++		BUG("worktree name '%s' (from '%s') is not a valid refname",
    ++		    name->buf, orig_name);
    ++
    ++	free(orig_name);
     +}
     +
      static int add_worktree(const char *path, const char *refname,
    @@ -103,8 +107,10 @@
      '
      
     +test_expect_success 'sanitize generated worktree name' '
    -+	git worktree add --detach ".  weird*..?.lock" &&
    -+	test -d .git/worktrees/weird
    ++	git worktree add --detach ".  weird*..?.lock.lock" &&
    ++	test -d .git/worktrees/weird-lock-lock &&
    ++	git worktree add --detach .... &&
    ++	test -d .git/worktrees/worktree
     +'
     +
      test_done
-- 
2.21.0.rc1.337.gdf7f8d0522