notes: disallow reusing non-blob as a note object

Currently "git notes add -C $object" will read the raw bytes from $object, and then copy those bytes into the note object, which is hardcoded to be of type blob. This means that if the given $object is a non-blob (e.g. tree or commit), the raw bytes from that object is copied into a blob object. This is probably not useful, and certainly not what any sane user would expect. So disallow it, by erroring out if the $object passed to the -C option is not a blob. The fix also applies to the -c option (in which the user is prompted to edit/verify the note contents in a text editor), and also when -c/-C is passed to "git notes append" (which appends the $object contents to an existing note object). In both cases, passing a non-blob $object does not make sense. Also add a couple of tests demonstrating expected behavior. Suggested-by: Junio C Hamano <gitster@pobox.com> Signed-off-by: Johan Herland <johan@herland.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Johan Herland committed Feb 12, 2014 at 10:54 UTC ce8daa1eb863c9cdefb06feae2ee7c742ea89847
2 files changed +32 -1
builtin/notes.c
+5 -1
@@ -269,7 +269,11 @@ static int parse_reuse_arg(const struct option *opt, const char *arg, int unset)
269 die(_("Failed to resolve '%s' as a valid ref."), arg);
270 if (!(buf = read_sha1_file(object, &type, &len)) || !len) {
271 free(buf);
272 - die(_("Failed to read object '%s'."), arg);;
272 + die(_("Failed to read object '%s'."), arg);
273 + }
274 + if (type != OBJ_BLOB) {
275 + free(buf);
276 + die(_("Cannot read note data from non-blob object '%s'."), arg);
277 }
278 strbuf_add(&(msg->buf), buf, len);
279 free(buf);
t/t3301-notes.sh
+27
@@ -812,6 +812,33 @@ test_expect_success 'create note from non-existing note with "git notes add -C"
812 test_must_fail git notes list HEAD
813 '
814
815 +test_expect_success 'create note from non-blob with "git notes add -C" fails' '
816 + commit=$(git rev-parse --verify HEAD) &&
817 + tree=$(git rev-parse --verify HEAD:) &&
818 + test_must_fail git notes add -C $commit &&
819 + test_must_fail git notes add -C $tree &&
820 + test_must_fail git notes list HEAD
821 +'
822 +
823 +cat > expect << EOF
824 +commit 80d796defacd5db327b7a4e50099663902fbdc5c
825 +Author: A U Thor <author@example.com>
826 +Date: Thu Apr 7 15:20:13 2005 -0700
827 +
828 + 8th
829 +
830 +Notes (other):
831 + This is a blob object
832 +EOF
833 +
834 +test_expect_success 'create note from blob with "git notes add -C" reuses blob id' '
835 + blob=$(echo "This is a blob object" | git hash-object -w --stdin) &&
836 + git notes add -C $blob &&
837 + git log -1 > actual &&
838 + test_cmp expect actual &&
839 + test "$(git notes list HEAD)" = "$blob"
840 +'
841 +
842 cat > expect << EOF
843 commit 016e982bad97eacdbda0fcbd7ce5b0ba87c81f1b
844 Author: A U Thor <author@example.com>