Merge branch 'rs/strbuf-addftime-zZ'
[git] / ident.c
1 /*
2  * ident.c
3  *
4  * create git identifier lines of the form "name <email> date"
5  *
6  * Copyright (C) 2005 Linus Torvalds
7  */
8 #include "cache.h"
9
10 static struct strbuf git_default_name = STRBUF_INIT;
11 static struct strbuf git_default_email = STRBUF_INIT;
12 static struct strbuf git_default_date = STRBUF_INIT;
13 static int default_email_is_bogus;
14 static int default_name_is_bogus;
15
16 static int ident_use_config_only;
17
18 #define IDENT_NAME_GIVEN 01
19 #define IDENT_MAIL_GIVEN 02
20 #define IDENT_ALL_GIVEN (IDENT_NAME_GIVEN|IDENT_MAIL_GIVEN)
21 static int committer_ident_explicitly_given;
22 static int author_ident_explicitly_given;
23 static int ident_config_given;
24
25 #ifdef NO_GECOS_IN_PWENT
26 #define get_gecos(ignored) "&"
27 #else
28 #define get_gecos(struct_passwd) ((struct_passwd)->pw_gecos)
29 #endif
30
31 static struct passwd *xgetpwuid_self(int *is_bogus)
32 {
33         struct passwd *pw;
34
35         errno = 0;
36         pw = getpwuid(getuid());
37         if (!pw) {
38                 static struct passwd fallback;
39                 fallback.pw_name = "unknown";
40 #ifndef NO_GECOS_IN_PWENT
41                 fallback.pw_gecos = "Unknown";
42 #endif
43                 pw = &fallback;
44                 if (is_bogus)
45                         *is_bogus = 1;
46         }
47         return pw;
48 }
49
50 static void copy_gecos(const struct passwd *w, struct strbuf *name)
51 {
52         char *src;
53
54         /* Traditionally GECOS field had office phone numbers etc, separated
55          * with commas.  Also & stands for capitalized form of the login name.
56          */
57
58         for (src = get_gecos(w); *src && *src != ','; src++) {
59                 int ch = *src;
60                 if (ch != '&')
61                         strbuf_addch(name, ch);
62                 else {
63                         /* Sorry, Mr. McDonald... */
64                         strbuf_addch(name, toupper(*w->pw_name));
65                         strbuf_addstr(name, w->pw_name + 1);
66                 }
67         }
68 }
69
70 static int add_mailname_host(struct strbuf *buf)
71 {
72         FILE *mailname;
73         struct strbuf mailnamebuf = STRBUF_INIT;
74
75         mailname = fopen_or_warn("/etc/mailname", "r");
76         if (!mailname)
77                 return -1;
78
79         if (strbuf_getline(&mailnamebuf, mailname) == EOF) {
80                 if (ferror(mailname))
81                         warning_errno("cannot read /etc/mailname");
82                 strbuf_release(&mailnamebuf);
83                 fclose(mailname);
84                 return -1;
85         }
86         /* success! */
87         strbuf_addbuf(buf, &mailnamebuf);
88         strbuf_release(&mailnamebuf);
89         fclose(mailname);
90         return 0;
91 }
92
93 static int canonical_name(const char *host, struct strbuf *out)
94 {
95         int status = -1;
96
97 #ifndef NO_IPV6
98         struct addrinfo hints, *ai;
99         memset (&hints, '\0', sizeof (hints));
100         hints.ai_flags = AI_CANONNAME;
101         if (!getaddrinfo(host, NULL, &hints, &ai)) {
102                 if (ai && ai->ai_canonname && strchr(ai->ai_canonname, '.')) {
103                         strbuf_addstr(out, ai->ai_canonname);
104                         status = 0;
105                 }
106                 freeaddrinfo(ai);
107         }
108 #else
109         struct hostent *he = gethostbyname(host);
110         if (he && strchr(he->h_name, '.')) {
111                 strbuf_addstr(out, he->h_name);
112                 status = 0;
113         }
114 #endif /* NO_IPV6 */
115
116         return status;
117 }
118
119 static void add_domainname(struct strbuf *out, int *is_bogus)
120 {
121         char buf[HOST_NAME_MAX + 1];
122
123         if (xgethostname(buf, sizeof(buf))) {
124                 warning_errno("cannot get host name");
125                 strbuf_addstr(out, "(none)");
126                 *is_bogus = 1;
127                 return;
128         }
129         if (strchr(buf, '.'))
130                 strbuf_addstr(out, buf);
131         else if (canonical_name(buf, out) < 0) {
132                 strbuf_addf(out, "%s.(none)", buf);
133                 *is_bogus = 1;
134         }
135 }
136
137 static void copy_email(const struct passwd *pw, struct strbuf *email,
138                        int *is_bogus)
139 {
140         /*
141          * Make up a fake email address
142          * (name + '@' + hostname [+ '.' + domainname])
143          */
144         strbuf_addstr(email, pw->pw_name);
145         strbuf_addch(email, '@');
146
147         if (!add_mailname_host(email))
148                 return; /* read from "/etc/mailname" (Debian) */
149         add_domainname(email, is_bogus);
150 }
151
152 const char *ident_default_name(void)
153 {
154         if (!(ident_config_given & IDENT_NAME_GIVEN) && !git_default_name.len) {
155                 copy_gecos(xgetpwuid_self(&default_name_is_bogus), &git_default_name);
156                 strbuf_trim(&git_default_name);
157         }
158         return git_default_name.buf;
159 }
160
161 const char *ident_default_email(void)
162 {
163         if (!(ident_config_given & IDENT_MAIL_GIVEN) && !git_default_email.len) {
164                 const char *email = getenv("EMAIL");
165
166                 if (email && email[0]) {
167                         strbuf_addstr(&git_default_email, email);
168                         committer_ident_explicitly_given |= IDENT_MAIL_GIVEN;
169                         author_ident_explicitly_given |= IDENT_MAIL_GIVEN;
170                 } else
171                         copy_email(xgetpwuid_self(&default_email_is_bogus),
172                                    &git_default_email, &default_email_is_bogus);
173                 strbuf_trim(&git_default_email);
174         }
175         return git_default_email.buf;
176 }
177
178 static const char *ident_default_date(void)
179 {
180         if (!git_default_date.len)
181                 datestamp(&git_default_date);
182         return git_default_date.buf;
183 }
184
185 void reset_ident_date(void)
186 {
187         strbuf_reset(&git_default_date);
188 }
189
190 static int crud(unsigned char c)
191 {
192         return  c <= 32  ||
193                 c == '.' ||
194                 c == ',' ||
195                 c == ':' ||
196                 c == ';' ||
197                 c == '<' ||
198                 c == '>' ||
199                 c == '"' ||
200                 c == '\\' ||
201                 c == '\'';
202 }
203
204 static int has_non_crud(const char *str)
205 {
206         for (; *str; str++) {
207                 if (!crud(*str))
208                         return 1;
209         }
210         return 0;
211 }
212
213 /*
214  * Copy over a string to the destination, but avoid special
215  * characters ('\n', '<' and '>') and remove crud at the end
216  */
217 static void strbuf_addstr_without_crud(struct strbuf *sb, const char *src)
218 {
219         size_t i, len;
220         unsigned char c;
221
222         /* Remove crud from the beginning.. */
223         while ((c = *src) != 0) {
224                 if (!crud(c))
225                         break;
226                 src++;
227         }
228
229         /* Remove crud from the end.. */
230         len = strlen(src);
231         while (len > 0) {
232                 c = src[len-1];
233                 if (!crud(c))
234                         break;
235                 --len;
236         }
237
238         /*
239          * Copy the rest to the buffer, but avoid the special
240          * characters '\n' '<' and '>' that act as delimiters on
241          * an identification line. We can only remove crud, never add it,
242          * so 'len' is our maximum.
243          */
244         strbuf_grow(sb, len);
245         for (i = 0; i < len; i++) {
246                 c = *src++;
247                 switch (c) {
248                 case '\n': case '<': case '>':
249                         continue;
250                 }
251                 sb->buf[sb->len++] = c;
252         }
253         sb->buf[sb->len] = '\0';
254 }
255
256 /*
257  * Reverse of fmt_ident(); given an ident line, split the fields
258  * to allow the caller to parse it.
259  * Signal a success by returning 0, but date/tz fields of the result
260  * can still be NULL if the input line only has the name/email part
261  * (e.g. reading from a reflog entry).
262  */
263 int split_ident_line(struct ident_split *split, const char *line, int len)
264 {
265         const char *cp;
266         size_t span;
267         int status = -1;
268
269         memset(split, 0, sizeof(*split));
270
271         split->name_begin = line;
272         for (cp = line; *cp && cp < line + len; cp++)
273                 if (*cp == '<') {
274                         split->mail_begin = cp + 1;
275                         break;
276                 }
277         if (!split->mail_begin)
278                 return status;
279
280         for (cp = split->mail_begin - 2; line <= cp; cp--)
281                 if (!isspace(*cp)) {
282                         split->name_end = cp + 1;
283                         break;
284                 }
285         if (!split->name_end) {
286                 /* no human readable name */
287                 split->name_end = split->name_begin;
288         }
289
290         for (cp = split->mail_begin; cp < line + len; cp++)
291                 if (*cp == '>') {
292                         split->mail_end = cp;
293                         break;
294                 }
295         if (!split->mail_end)
296                 return status;
297
298         /*
299          * Look from the end-of-line to find the trailing ">" of the mail
300          * address, even though we should already know it as split->mail_end.
301          * This can help in cases of broken idents with an extra ">" somewhere
302          * in the email address.  Note that we are assuming the timestamp will
303          * never have a ">" in it.
304          *
305          * Note that we will always find some ">" before going off the front of
306          * the string, because will always hit the split->mail_end closing
307          * bracket.
308          */
309         for (cp = line + len - 1; *cp != '>'; cp--)
310                 ;
311
312         for (cp = cp + 1; cp < line + len && isspace(*cp); cp++)
313                 ;
314         if (line + len <= cp)
315                 goto person_only;
316         split->date_begin = cp;
317         span = strspn(cp, "0123456789");
318         if (!span)
319                 goto person_only;
320         split->date_end = split->date_begin + span;
321         for (cp = split->date_end; cp < line + len && isspace(*cp); cp++)
322                 ;
323         if (line + len <= cp || (*cp != '+' && *cp != '-'))
324                 goto person_only;
325         split->tz_begin = cp;
326         span = strspn(cp + 1, "0123456789");
327         if (!span)
328                 goto person_only;
329         split->tz_end = split->tz_begin + 1 + span;
330         return 0;
331
332 person_only:
333         split->date_begin = NULL;
334         split->date_end = NULL;
335         split->tz_begin = NULL;
336         split->tz_end = NULL;
337         return 0;
338 }
339
340 static const char *env_hint =
341 N_("\n"
342    "*** Please tell me who you are.\n"
343    "\n"
344    "Run\n"
345    "\n"
346    "  git config --global user.email \"you@example.com\"\n"
347    "  git config --global user.name \"Your Name\"\n"
348    "\n"
349    "to set your account\'s default identity.\n"
350    "Omit --global to set the identity only in this repository.\n"
351    "\n");
352
353 const char *fmt_ident(const char *name, const char *email,
354                       const char *date_str, int flag)
355 {
356         static struct strbuf ident = STRBUF_INIT;
357         int strict = (flag & IDENT_STRICT);
358         int want_date = !(flag & IDENT_NO_DATE);
359         int want_name = !(flag & IDENT_NO_NAME);
360
361         if (!email) {
362                 if (strict && ident_use_config_only
363                     && !(ident_config_given & IDENT_MAIL_GIVEN)) {
364                         fputs(_(env_hint), stderr);
365                         die(_("no email was given and auto-detection is disabled"));
366                 }
367                 email = ident_default_email();
368                 if (strict && default_email_is_bogus) {
369                         fputs(_(env_hint), stderr);
370                         die(_("unable to auto-detect email address (got '%s')"), email);
371                 }
372         }
373
374         if (want_name) {
375                 int using_default = 0;
376                 if (!name) {
377                         if (strict && ident_use_config_only
378                             && !(ident_config_given & IDENT_NAME_GIVEN)) {
379                                 fputs(_(env_hint), stderr);
380                                 die(_("no name was given and auto-detection is disabled"));
381                         }
382                         name = ident_default_name();
383                         using_default = 1;
384                         if (strict && default_name_is_bogus) {
385                                 fputs(_(env_hint), stderr);
386                                 die(_("unable to auto-detect name (got '%s')"), name);
387                         }
388                 }
389                 if (!*name) {
390                         struct passwd *pw;
391                         if (strict) {
392                                 if (using_default)
393                                         fputs(_(env_hint), stderr);
394                                 die(_("empty ident name (for <%s>) not allowed"), email);
395                         }
396                         pw = xgetpwuid_self(NULL);
397                         name = pw->pw_name;
398                 }
399                 if (strict && !has_non_crud(name))
400                         die(_("name consists only of disallowed characters: %s"), name);
401         }
402
403         strbuf_reset(&ident);
404         if (want_name) {
405                 strbuf_addstr_without_crud(&ident, name);
406                 strbuf_addstr(&ident, " <");
407         }
408         strbuf_addstr_without_crud(&ident, email);
409         if (want_name)
410                         strbuf_addch(&ident, '>');
411         if (want_date) {
412                 strbuf_addch(&ident, ' ');
413                 if (date_str && date_str[0]) {
414                         if (parse_date(date_str, &ident) < 0)
415                                 die(_("invalid date format: %s"), date_str);
416                 }
417                 else
418                         strbuf_addstr(&ident, ident_default_date());
419         }
420
421         return ident.buf;
422 }
423
424 const char *fmt_name(const char *name, const char *email)
425 {
426         return fmt_ident(name, email, NULL, IDENT_STRICT | IDENT_NO_DATE);
427 }
428
429 const char *git_author_info(int flag)
430 {
431         if (getenv("GIT_AUTHOR_NAME"))
432                 author_ident_explicitly_given |= IDENT_NAME_GIVEN;
433         if (getenv("GIT_AUTHOR_EMAIL"))
434                 author_ident_explicitly_given |= IDENT_MAIL_GIVEN;
435         return fmt_ident(getenv("GIT_AUTHOR_NAME"),
436                          getenv("GIT_AUTHOR_EMAIL"),
437                          getenv("GIT_AUTHOR_DATE"),
438                          flag);
439 }
440
441 const char *git_committer_info(int flag)
442 {
443         if (getenv("GIT_COMMITTER_NAME"))
444                 committer_ident_explicitly_given |= IDENT_NAME_GIVEN;
445         if (getenv("GIT_COMMITTER_EMAIL"))
446                 committer_ident_explicitly_given |= IDENT_MAIL_GIVEN;
447         return fmt_ident(getenv("GIT_COMMITTER_NAME"),
448                          getenv("GIT_COMMITTER_EMAIL"),
449                          getenv("GIT_COMMITTER_DATE"),
450                          flag);
451 }
452
453 static int ident_is_sufficient(int user_ident_explicitly_given)
454 {
455 #ifndef WINDOWS
456         return (user_ident_explicitly_given & IDENT_MAIL_GIVEN);
457 #else
458         return (user_ident_explicitly_given == IDENT_ALL_GIVEN);
459 #endif
460 }
461
462 int committer_ident_sufficiently_given(void)
463 {
464         return ident_is_sufficient(committer_ident_explicitly_given);
465 }
466
467 int author_ident_sufficiently_given(void)
468 {
469         return ident_is_sufficient(author_ident_explicitly_given);
470 }
471
472 int git_ident_config(const char *var, const char *value, void *data)
473 {
474         if (!strcmp(var, "user.useconfigonly")) {
475                 ident_use_config_only = git_config_bool(var, value);
476                 return 0;
477         }
478
479         if (!strcmp(var, "user.name")) {
480                 if (!value)
481                         return config_error_nonbool(var);
482                 strbuf_reset(&git_default_name);
483                 strbuf_addstr(&git_default_name, value);
484                 committer_ident_explicitly_given |= IDENT_NAME_GIVEN;
485                 author_ident_explicitly_given |= IDENT_NAME_GIVEN;
486                 ident_config_given |= IDENT_NAME_GIVEN;
487                 return 0;
488         }
489
490         if (!strcmp(var, "user.email")) {
491                 if (!value)
492                         return config_error_nonbool(var);
493                 strbuf_reset(&git_default_email);
494                 strbuf_addstr(&git_default_email, value);
495                 committer_ident_explicitly_given |= IDENT_MAIL_GIVEN;
496                 author_ident_explicitly_given |= IDENT_MAIL_GIVEN;
497                 ident_config_given |= IDENT_MAIL_GIVEN;
498                 return 0;
499         }
500
501         return 0;
502 }
503
504 static int buf_cmp(const char *a_begin, const char *a_end,
505                    const char *b_begin, const char *b_end)
506 {
507         int a_len = a_end - a_begin;
508         int b_len = b_end - b_begin;
509         int min = a_len < b_len ? a_len : b_len;
510         int cmp;
511
512         cmp = memcmp(a_begin, b_begin, min);
513         if (cmp)
514                 return cmp;
515
516         return a_len - b_len;
517 }
518
519 int ident_cmp(const struct ident_split *a,
520               const struct ident_split *b)
521 {
522         int cmp;
523
524         cmp = buf_cmp(a->mail_begin, a->mail_end,
525                       b->mail_begin, b->mail_end);
526         if (cmp)
527                 return cmp;
528
529         return buf_cmp(a->name_begin, a->name_end,
530                        b->name_begin, b->name_end);
531 }