Add mailmap.file as configurational option for mailmap location
[git/gitbuild.git] / mailmap.c
blobd006dad673169dfc727621112aea1ff5a31fb61a
1 #include "cache.h"
2 #include "string-list.h"
3 #include "mailmap.h"
5 const char *git_mailmap_file;
6 static int read_single_mailmap(struct string_list *map, const char *filename, char **repo_abbrev)
8 char buffer[1024];
9 FILE *f = (filename == NULL ? NULL : fopen(filename, "r"));
11 if (f == NULL)
12 return 1;
13 while (fgets(buffer, sizeof(buffer), f) != NULL) {
14 char *end_of_name, *left_bracket, *right_bracket;
15 char *name, *email;
16 int i;
17 if (buffer[0] == '#') {
18 static const char abbrev[] = "# repo-abbrev:";
19 int abblen = sizeof(abbrev) - 1;
20 int len = strlen(buffer);
22 if (!repo_abbrev)
23 continue;
25 if (len && buffer[len - 1] == '\n')
26 buffer[--len] = 0;
27 if (!strncmp(buffer, abbrev, abblen)) {
28 char *cp;
30 if (repo_abbrev)
31 free(*repo_abbrev);
32 *repo_abbrev = xmalloc(len);
34 for (cp = buffer + abblen; isspace(*cp); cp++)
35 ; /* nothing */
36 strcpy(*repo_abbrev, cp);
38 continue;
40 if ((left_bracket = strchr(buffer, '<')) == NULL)
41 continue;
42 if ((right_bracket = strchr(left_bracket + 1, '>')) == NULL)
43 continue;
44 if (right_bracket == left_bracket + 1)
45 continue;
46 for (end_of_name = left_bracket;
47 end_of_name != buffer && isspace(end_of_name[-1]);
48 end_of_name--)
49 ; /* keep on looking */
50 if (end_of_name == buffer)
51 continue;
52 name = xmalloc(end_of_name - buffer + 1);
53 strlcpy(name, buffer, end_of_name - buffer + 1);
54 email = xmalloc(right_bracket - left_bracket);
55 for (i = 0; i < right_bracket - left_bracket - 1; i++)
56 email[i] = tolower(left_bracket[i + 1]);
57 email[right_bracket - left_bracket - 1] = '\0';
58 string_list_insert(email, map)->util = name;
60 fclose(f);
61 return 0;
64 int read_mailmap(struct string_list *map, char **repo_abbrev)
66 /* each failure returns 1, so >1 means both calls failed */
67 return read_single_mailmap(map, ".mailmap", repo_abbrev) +
68 read_single_mailmap(map, git_mailmap_file, repo_abbrev) > 1;
71 int map_email(struct string_list *map, const char *email, char *name, int maxlen)
73 char *p;
74 struct string_list_item *item;
75 char buf[1024], *mailbuf;
76 int i;
78 /* autocomplete common developers */
79 p = strchr(email, '>');
80 if (!p)
81 return 0;
82 if (p - email + 1 < sizeof(buf))
83 mailbuf = buf;
84 else
85 mailbuf = xmalloc(p - email + 1);
87 /* downcase the email address */
88 for (i = 0; i < p - email; i++)
89 mailbuf[i] = tolower(email[i]);
90 mailbuf[i] = 0;
91 item = string_list_lookup(mailbuf, map);
92 if (mailbuf != buf)
93 free(mailbuf);
94 if (item != NULL) {
95 const char *realname = (const char *)item->util;
96 strlcpy(name, realname, maxlen);
97 return 1;
99 return 0;