Introduce commit notes
[git] / notes.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "notes.h"
4 #include "refs.h"
5 #include "utf8.h"
6 #include "strbuf.h"
7
8 static int initialized;
9
10 void get_commit_notes(const struct commit *commit, struct strbuf *sb,
11                 const char *output_encoding)
12 {
13         static const char *utf8 = "utf-8";
14         struct strbuf name = STRBUF_INIT;
15         const char *hex;
16         unsigned char sha1[20];
17         char *msg;
18         unsigned long msgoffset, msglen;
19         enum object_type type;
20
21         if (!initialized) {
22                 const char *env = getenv(GIT_NOTES_REF_ENVIRONMENT);
23                 if (env)
24                         notes_ref_name = getenv(GIT_NOTES_REF_ENVIRONMENT);
25                 else if (!notes_ref_name)
26                         notes_ref_name = GIT_NOTES_DEFAULT_REF;
27                 if (notes_ref_name && read_ref(notes_ref_name, sha1))
28                         notes_ref_name = NULL;
29                 initialized = 1;
30         }
31
32         if (!notes_ref_name)
33                 return;
34
35         strbuf_addf(&name, "%s:%s", notes_ref_name,
36                         sha1_to_hex(commit->object.sha1));
37         if (get_sha1(name.buf, sha1))
38                 return;
39
40         if (!(msg = read_sha1_file(sha1, &type, &msglen)) || !msglen ||
41                         type != OBJ_BLOB)
42                 return;
43
44         if (output_encoding && *output_encoding &&
45                         strcmp(utf8, output_encoding)) {
46                 char *reencoded = reencode_string(msg, output_encoding, utf8);
47                 if (reencoded) {
48                         free(msg);
49                         msg = reencoded;
50                         msglen = strlen(msg);
51                 }
52         }
53
54         /* we will end the annotation by a newline anyway */
55         if (msglen && msg[msglen - 1] == '\n')
56                 msglen--;
57
58         strbuf_addstr(sb, "\nNotes:\n");
59
60         for (msgoffset = 0; msgoffset < msglen;) {
61                 int linelen = strchrnul(msg, '\n') - msg;
62
63                 strbuf_addstr(sb, "    ");
64                 strbuf_add(sb, msg + msgoffset, linelen);
65                 msgoffset += linelen;
66         }
67         free(msg);
68 }