ls-tree: fix expansion of repeated %(path)

expand_show_tree() borrows the base strbuf given to us by read_tree() to build the full path of the current entry when handling %(path). Only its indirect caller, show_tree_fmt(), removes the added entry name. That works fine as long as %(path) is only included once in the format string, but accumulates duplicates if it's repeated: $ git ls-tree --format='%(path) %(path) %(path)' HEAD M* Makefile MakefileMakefile MakefileMakefileMakefile Reset the length after each use to get the same expansion every time; here's the behavior with this patch: $ ./git ls-tree --format='%(path) %(path) %(path)' HEAD M* Makefile Makefile Makefile Signed-off-by: René Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed Jan 14, 2023 at 15:37 UTC 16fb5c54bd91c9714e12c6d742e5a6fd81459b71
2 files changed +9 -3
builtin/ls-tree.c
+3 -3
@@ -97,9 +97,12 @@ static size_t expand_show_tree(struct strbuf *sb, const char *start,
97 const char *prefix = chomp_prefix ? ls_tree_prefix : NULL;
98 struct strbuf quoted = STRBUF_INIT;
99 struct strbuf sbuf = STRBUF_INIT;
100 + size_t baselen = data->base->len;
101 +
102 strbuf_addstr(data->base, data->pathname);
103 name = relative_path(data->base->buf, prefix, &sbuf);
104 quote_c_style(name, &quoted, NULL, 0);
105 + strbuf_setlen(data->base, baselen);
106 strbuf_addbuf(sb, &quoted);
107 strbuf_release(&sbuf);
108 strbuf_release(&quoted);
@@ -143,7 +146,6 @@ static int show_recursive(const char *base, size_t baselen, const char *pathname
146 static int show_tree_fmt(const struct object_id *oid, struct strbuf *base,
147 const char *pathname, unsigned mode, void *context)
148 {
146 - size_t baselen;
149 int recurse = 0;
150 struct strbuf sb = STRBUF_INIT;
151 enum object_type type = object_type(mode);
@@ -163,12 +165,10 @@ static int show_tree_fmt(const struct object_id *oid, struct strbuf *base,
165 if (type == OBJ_BLOB && (ls_options & LS_TREE_ONLY))
166 return 0;
167
166 - baselen = base->len;
168 strbuf_expand(&sb, format, expand_show_tree, &data);
169 strbuf_addch(&sb, line_termination);
170 fwrite(sb.buf, sb.len, 1, stdout);
171 strbuf_release(&sb);
171 - strbuf_setlen(base, baselen);
172 return recurse;
173 }
174
t/t3104-ls-tree-format.sh
+6
@@ -37,6 +37,12 @@ test_ls_tree_format () {
37 '
38 }
39
40 +test_expect_success "ls-tree --format='%(path) %(path) %(path)' HEAD top-file" '
41 + git ls-tree --format="%(path) %(path) %(path)" HEAD top-file.t >actual &&
42 + echo top-file.t top-file.t top-file.t >expect &&
43 + test_cmp expect actual
44 +'
45 +
46 test_ls_tree_format \
47 "%(objectmode) %(objecttype) %(objectname)%x09%(path)" \
48 ""