]> git.proxmox.com Git - libgit2.git/blob - src/message.c
commit/tag: ensure the message is cleaned up
[libgit2.git] / src / message.c
1 /*
2 * Copyright (C) 2009-2012 the libgit2 contributors
3 *
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
6 */
7
8 #include "message.h"
9
10 static size_t line_length_without_trailing_spaces(const char *line, size_t len)
11 {
12 while (len) {
13 unsigned char c = line[len - 1];
14 if (!isspace(c))
15 break;
16 len--;
17 }
18
19 return len;
20 }
21
22 /* Greatly inspired from git.git "stripspace" */
23 /* see https://github.com/git/git/blob/497215d8811ac7b8955693ceaad0899ecd894ed2/builtin/stripspace.c#L4-67 */
24 int git_message_prettify(git_buf *message_out, const char *message, int strip_comments)
25 {
26 int consecutive_empty_lines = 0;
27 size_t i, line_length, rtrimmed_line_length;
28 char *next_newline;
29
30 for (i = 0; i < strlen(message); i += line_length) {
31 next_newline = memchr(message + i, '\n', strlen(message) - i);
32 line_length = next_newline ? next_newline - (message + i) + 1 : strlen(message) - i;
33
34 if (strip_comments && line_length && message[i] == '#')
35 continue;
36
37 rtrimmed_line_length = line_length_without_trailing_spaces(message + i, line_length);
38
39 if (!rtrimmed_line_length) {
40 consecutive_empty_lines++;
41 continue;
42 }
43
44 if (consecutive_empty_lines > 0 && message_out->size > 0)
45 if (git_buf_putc(message_out, '\n') < 0)
46 return -1;
47
48 consecutive_empty_lines = 0;
49 git_buf_put(message_out, message + i, rtrimmed_line_length);
50 git_buf_putc(message_out, '\n');
51 }
52
53 return 0;
54 }