]> git.proxmox.com Git - libgit2.git/blob - src/message.c
ec0103a339fe15bae684eac1c8107c040cbda023
[libgit2.git] / src / message.c
1 /*
2 * Copyright (C) the libgit2 contributors. All rights reserved.
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 "buf.h"
9
10 #include "git2/message.h"
11
12 static size_t line_length_without_trailing_spaces(const char *line, size_t len)
13 {
14 while (len) {
15 unsigned char c = line[len - 1];
16 if (!git__isspace(c))
17 break;
18 len--;
19 }
20
21 return len;
22 }
23
24 /* Greatly inspired from git.git "stripspace" */
25 /* see https://github.com/git/git/blob/497215d8811ac7b8955693ceaad0899ecd894ed2/builtin/stripspace.c#L4-67 */
26 static int git_message__prettify(
27 git_str *message_out,
28 const char *message,
29 int strip_comments,
30 char comment_char)
31 {
32 const size_t message_len = strlen(message);
33
34 int consecutive_empty_lines = 0;
35 size_t i, line_length, rtrimmed_line_length;
36 char *next_newline;
37
38 for (i = 0; i < strlen(message); i += line_length) {
39 next_newline = memchr(message + i, '\n', message_len - i);
40
41 if (next_newline != NULL) {
42 line_length = next_newline - (message + i) + 1;
43 } else {
44 line_length = message_len - i;
45 }
46
47 if (strip_comments && line_length && message[i] == comment_char)
48 continue;
49
50 rtrimmed_line_length = line_length_without_trailing_spaces(message + i, line_length);
51
52 if (!rtrimmed_line_length) {
53 consecutive_empty_lines++;
54 continue;
55 }
56
57 if (consecutive_empty_lines > 0 && message_out->size > 0)
58 git_str_putc(message_out, '\n');
59
60 consecutive_empty_lines = 0;
61 git_str_put(message_out, message + i, rtrimmed_line_length);
62 git_str_putc(message_out, '\n');
63 }
64
65 return git_str_oom(message_out) ? -1 : 0;
66 }
67
68 int git_message_prettify(
69 git_buf *message_out,
70 const char *message,
71 int strip_comments,
72 char comment_char)
73 {
74 GIT_BUF_WRAP_PRIVATE(message_out, git_message__prettify, message, strip_comments, comment_char);
75 }