Split out mailmap handling out of shortlog
[git/fastimport.git] / mailmap.c
blobaf187a38268b7e385885b3d990a99e6de9f569ba
1 #include "cache.h"
2 #include "path-list.h"
4 int read_mailmap(struct path_list *map, const char *filename, char **repo_abbrev)
6 char buffer[1024];
7 FILE *f = fopen(filename, "r");
9 if (f == NULL)
10 return 1;
11 while (fgets(buffer, sizeof(buffer), f) != NULL) {
12 char *end_of_name, *left_bracket, *right_bracket;
13 char *name, *email;
14 int i;
15 if (buffer[0] == '#') {
16 static const char abbrev[] = "# repo-abbrev:";
17 int abblen = sizeof(abbrev) - 1;
18 int len = strlen(buffer);
20 if (len && buffer[len - 1] == '\n')
21 buffer[--len] = 0;
22 if (!strncmp(buffer, abbrev, abblen)) {
23 char *cp;
25 if (repo_abbrev)
26 free(*repo_abbrev);
27 *repo_abbrev = xmalloc(len);
29 for (cp = buffer + abblen; isspace(*cp); cp++)
30 ; /* nothing */
31 strcpy(*repo_abbrev, cp);
33 continue;
35 if ((left_bracket = strchr(buffer, '<')) == NULL)
36 continue;
37 if ((right_bracket = strchr(left_bracket + 1, '>')) == NULL)
38 continue;
39 if (right_bracket == left_bracket + 1)
40 continue;
41 for (end_of_name = left_bracket; end_of_name != buffer
42 && isspace(end_of_name[-1]); end_of_name--)
43 /* keep on looking */
44 if (end_of_name == buffer)
45 continue;
46 name = xmalloc(end_of_name - buffer + 1);
47 strlcpy(name, buffer, end_of_name - buffer + 1);
48 email = xmalloc(right_bracket - left_bracket);
49 for (i = 0; i < right_bracket - left_bracket - 1; i++)
50 email[i] = tolower(left_bracket[i + 1]);
51 email[right_bracket - left_bracket - 1] = '\0';
52 path_list_insert(email, map)->util = name;
54 fclose(f);
55 return 0;
58 int map_email(struct path_list *map, const char *email, char *name, int maxlen)
60 char *p;
61 struct path_list_item *item;
62 char buf[1024], *mailbuf;
63 int i;
65 /* autocomplete common developers */
66 p = strchr(email, '>');
67 if (!p)
68 return 0;
69 if (p - email + 1 < sizeof(buf))
70 mailbuf = buf;
71 else
72 mailbuf = xmalloc(p - email + 1);
74 /* downcase the email address */
75 for (i = 0; i < p - email; i++)
76 mailbuf[i] = tolower(email[i]);
77 mailbuf[i] = 0;
78 item = path_list_lookup(mailbuf, map);
79 if (mailbuf != buf)
80 free(mailbuf);
81 if (item != NULL) {
82 const char *realname = (const char *)item->util;
83 strncpy(name, realname, maxlen);
84 return 1;
86 return 0;