merge-recursive: apply necessary modifications for directory renames
[git] / strbuf.c
1 #include "cache.h"
2 #include "refs.h"
3 #include "string-list.h"
4 #include "utf8.h"
5
6 int starts_with(const char *str, const char *prefix)
7 {
8         for (; ; str++, prefix++)
9                 if (!*prefix)
10                         return 1;
11                 else if (*str != *prefix)
12                         return 0;
13 }
14
15 int skip_to_optional_arg_default(const char *str, const char *prefix,
16                                  const char **arg, const char *def)
17 {
18         const char *p;
19
20         if (!skip_prefix(str, prefix, &p))
21                 return 0;
22
23         if (!*p) {
24                 if (arg)
25                         *arg = def;
26                 return 1;
27         }
28
29         if (*p != '=')
30                 return 0;
31
32         if (arg)
33                 *arg = p + 1;
34         return 1;
35 }
36
37 /*
38  * Used as the default ->buf value, so that people can always assume
39  * buf is non NULL and ->buf is NUL terminated even for a freshly
40  * initialized strbuf.
41  */
42 char strbuf_slopbuf[1];
43
44 void strbuf_init(struct strbuf *sb, size_t hint)
45 {
46         sb->alloc = sb->len = 0;
47         sb->buf = strbuf_slopbuf;
48         if (hint)
49                 strbuf_grow(sb, hint);
50 }
51
52 void strbuf_release(struct strbuf *sb)
53 {
54         if (sb->alloc) {
55                 free(sb->buf);
56                 strbuf_init(sb, 0);
57         }
58 }
59
60 char *strbuf_detach(struct strbuf *sb, size_t *sz)
61 {
62         char *res;
63         strbuf_grow(sb, 0);
64         res = sb->buf;
65         if (sz)
66                 *sz = sb->len;
67         strbuf_init(sb, 0);
68         return res;
69 }
70
71 void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
72 {
73         strbuf_release(sb);
74         sb->buf   = buf;
75         sb->len   = len;
76         sb->alloc = alloc;
77         strbuf_grow(sb, 0);
78         sb->buf[sb->len] = '\0';
79 }
80
81 void strbuf_grow(struct strbuf *sb, size_t extra)
82 {
83         int new_buf = !sb->alloc;
84         if (unsigned_add_overflows(extra, 1) ||
85             unsigned_add_overflows(sb->len, extra + 1))
86                 die("you want to use way too much memory");
87         if (new_buf)
88                 sb->buf = NULL;
89         ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
90         if (new_buf)
91                 sb->buf[0] = '\0';
92 }
93
94 void strbuf_trim(struct strbuf *sb)
95 {
96         strbuf_rtrim(sb);
97         strbuf_ltrim(sb);
98 }
99 void strbuf_rtrim(struct strbuf *sb)
100 {
101         while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
102                 sb->len--;
103         sb->buf[sb->len] = '\0';
104 }
105
106 void strbuf_ltrim(struct strbuf *sb)
107 {
108         char *b = sb->buf;
109         while (sb->len > 0 && isspace(*b)) {
110                 b++;
111                 sb->len--;
112         }
113         memmove(sb->buf, b, sb->len);
114         sb->buf[sb->len] = '\0';
115 }
116
117 int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)
118 {
119         char *out;
120         int len;
121
122         if (same_encoding(from, to))
123                 return 0;
124
125         out = reencode_string_len(sb->buf, sb->len, to, from, &len);
126         if (!out)
127                 return -1;
128
129         strbuf_attach(sb, out, len, len);
130         return 0;
131 }
132
133 void strbuf_tolower(struct strbuf *sb)
134 {
135         char *p = sb->buf, *end = sb->buf + sb->len;
136         for (; p < end; p++)
137                 *p = tolower(*p);
138 }
139
140 struct strbuf **strbuf_split_buf(const char *str, size_t slen,
141                                  int terminator, int max)
142 {
143         struct strbuf **ret = NULL;
144         size_t nr = 0, alloc = 0;
145         struct strbuf *t;
146
147         while (slen) {
148                 int len = slen;
149                 if (max <= 0 || nr + 1 < max) {
150                         const char *end = memchr(str, terminator, slen);
151                         if (end)
152                                 len = end - str + 1;
153                 }
154                 t = xmalloc(sizeof(struct strbuf));
155                 strbuf_init(t, len);
156                 strbuf_add(t, str, len);
157                 ALLOC_GROW(ret, nr + 2, alloc);
158                 ret[nr++] = t;
159                 str += len;
160                 slen -= len;
161         }
162         ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
163         ret[nr] = NULL;
164         return ret;
165 }
166
167 void strbuf_add_separated_string_list(struct strbuf *str,
168                                       const char *sep,
169                                       struct string_list *slist)
170 {
171         struct string_list_item *item;
172         int sep_needed = 0;
173
174         for_each_string_list_item(item, slist) {
175                 if (sep_needed)
176                         strbuf_addstr(str, sep);
177                 strbuf_addstr(str, item->string);
178                 sep_needed = 1;
179         }
180 }
181
182 void strbuf_list_free(struct strbuf **sbs)
183 {
184         struct strbuf **s = sbs;
185
186         while (*s) {
187                 strbuf_release(*s);
188                 free(*s++);
189         }
190         free(sbs);
191 }
192
193 int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
194 {
195         int len = a->len < b->len ? a->len: b->len;
196         int cmp = memcmp(a->buf, b->buf, len);
197         if (cmp)
198                 return cmp;
199         return a->len < b->len ? -1: a->len != b->len;
200 }
201
202 void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
203                                    const void *data, size_t dlen)
204 {
205         if (unsigned_add_overflows(pos, len))
206                 die("you want to use way too much memory");
207         if (pos > sb->len)
208                 die("`pos' is too far after the end of the buffer");
209         if (pos + len > sb->len)
210                 die("`pos + len' is too far after the end of the buffer");
211
212         if (dlen >= len)
213                 strbuf_grow(sb, dlen - len);
214         memmove(sb->buf + pos + dlen,
215                         sb->buf + pos + len,
216                         sb->len - pos - len);
217         memcpy(sb->buf + pos, data, dlen);
218         strbuf_setlen(sb, sb->len + dlen - len);
219 }
220
221 void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
222 {
223         strbuf_splice(sb, pos, 0, data, len);
224 }
225
226 void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
227 {
228         strbuf_splice(sb, pos, len, "", 0);
229 }
230
231 void strbuf_add(struct strbuf *sb, const void *data, size_t len)
232 {
233         strbuf_grow(sb, len);
234         memcpy(sb->buf + sb->len, data, len);
235         strbuf_setlen(sb, sb->len + len);
236 }
237
238 void strbuf_addbuf(struct strbuf *sb, const struct strbuf *sb2)
239 {
240         strbuf_grow(sb, sb2->len);
241         memcpy(sb->buf + sb->len, sb2->buf, sb2->len);
242         strbuf_setlen(sb, sb->len + sb2->len);
243 }
244
245 void strbuf_addchars(struct strbuf *sb, int c, size_t n)
246 {
247         strbuf_grow(sb, n);
248         memset(sb->buf + sb->len, c, n);
249         strbuf_setlen(sb, sb->len + n);
250 }
251
252 void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
253 {
254         va_list ap;
255         va_start(ap, fmt);
256         strbuf_vaddf(sb, fmt, ap);
257         va_end(ap);
258 }
259
260 static void add_lines(struct strbuf *out,
261                         const char *prefix1,
262                         const char *prefix2,
263                         const char *buf, size_t size)
264 {
265         while (size) {
266                 const char *prefix;
267                 const char *next = memchr(buf, '\n', size);
268                 next = next ? (next + 1) : (buf + size);
269
270                 prefix = ((prefix2 && (buf[0] == '\n' || buf[0] == '\t'))
271                           ? prefix2 : prefix1);
272                 strbuf_addstr(out, prefix);
273                 strbuf_add(out, buf, next - buf);
274                 size -= next - buf;
275                 buf = next;
276         }
277         strbuf_complete_line(out);
278 }
279
280 void strbuf_add_commented_lines(struct strbuf *out, const char *buf, size_t size)
281 {
282         static char prefix1[3];
283         static char prefix2[2];
284
285         if (prefix1[0] != comment_line_char) {
286                 xsnprintf(prefix1, sizeof(prefix1), "%c ", comment_line_char);
287                 xsnprintf(prefix2, sizeof(prefix2), "%c", comment_line_char);
288         }
289         add_lines(out, prefix1, prefix2, buf, size);
290 }
291
292 void strbuf_commented_addf(struct strbuf *sb, const char *fmt, ...)
293 {
294         va_list params;
295         struct strbuf buf = STRBUF_INIT;
296         int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';
297
298         va_start(params, fmt);
299         strbuf_vaddf(&buf, fmt, params);
300         va_end(params);
301
302         strbuf_add_commented_lines(sb, buf.buf, buf.len);
303         if (incomplete_line)
304                 sb->buf[--sb->len] = '\0';
305
306         strbuf_release(&buf);
307 }
308
309 void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
310 {
311         int len;
312         va_list cp;
313
314         if (!strbuf_avail(sb))
315                 strbuf_grow(sb, 64);
316         va_copy(cp, ap);
317         len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
318         va_end(cp);
319         if (len < 0)
320                 die("BUG: your vsnprintf is broken (returned %d)", len);
321         if (len > strbuf_avail(sb)) {
322                 strbuf_grow(sb, len);
323                 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
324                 if (len > strbuf_avail(sb))
325                         die("BUG: your vsnprintf is broken (insatiable)");
326         }
327         strbuf_setlen(sb, sb->len + len);
328 }
329
330 void strbuf_expand(struct strbuf *sb, const char *format, expand_fn_t fn,
331                    void *context)
332 {
333         for (;;) {
334                 const char *percent;
335                 size_t consumed;
336
337                 percent = strchrnul(format, '%');
338                 strbuf_add(sb, format, percent - format);
339                 if (!*percent)
340                         break;
341                 format = percent + 1;
342
343                 if (*format == '%') {
344                         strbuf_addch(sb, '%');
345                         format++;
346                         continue;
347                 }
348
349                 consumed = fn(sb, format, context);
350                 if (consumed)
351                         format += consumed;
352                 else
353                         strbuf_addch(sb, '%');
354         }
355 }
356
357 size_t strbuf_expand_dict_cb(struct strbuf *sb, const char *placeholder,
358                 void *context)
359 {
360         struct strbuf_expand_dict_entry *e = context;
361         size_t len;
362
363         for (; e->placeholder && (len = strlen(e->placeholder)); e++) {
364                 if (!strncmp(placeholder, e->placeholder, len)) {
365                         if (e->value)
366                                 strbuf_addstr(sb, e->value);
367                         return len;
368                 }
369         }
370         return 0;
371 }
372
373 void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
374 {
375         int i, len = src->len;
376
377         for (i = 0; i < len; i++) {
378                 if (src->buf[i] == '%')
379                         strbuf_addch(dst, '%');
380                 strbuf_addch(dst, src->buf[i]);
381         }
382 }
383
384 size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
385 {
386         size_t res;
387         size_t oldalloc = sb->alloc;
388
389         strbuf_grow(sb, size);
390         res = fread(sb->buf + sb->len, 1, size, f);
391         if (res > 0)
392                 strbuf_setlen(sb, sb->len + res);
393         else if (oldalloc == 0)
394                 strbuf_release(sb);
395         return res;
396 }
397
398 ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
399 {
400         size_t oldlen = sb->len;
401         size_t oldalloc = sb->alloc;
402
403         strbuf_grow(sb, hint ? hint : 8192);
404         for (;;) {
405                 ssize_t want = sb->alloc - sb->len - 1;
406                 ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
407
408                 if (got < 0) {
409                         if (oldalloc == 0)
410                                 strbuf_release(sb);
411                         else
412                                 strbuf_setlen(sb, oldlen);
413                         return -1;
414                 }
415                 sb->len += got;
416                 if (got < want)
417                         break;
418                 strbuf_grow(sb, 8192);
419         }
420
421         sb->buf[sb->len] = '\0';
422         return sb->len - oldlen;
423 }
424
425 ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
426 {
427         size_t oldalloc = sb->alloc;
428         ssize_t cnt;
429
430         strbuf_grow(sb, hint ? hint : 8192);
431         cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
432         if (cnt > 0)
433                 strbuf_setlen(sb, sb->len + cnt);
434         else if (oldalloc == 0)
435                 strbuf_release(sb);
436         return cnt;
437 }
438
439 ssize_t strbuf_write(struct strbuf *sb, FILE *f)
440 {
441         return sb->len ? fwrite(sb->buf, 1, sb->len, f) : 0;
442 }
443
444
445 #define STRBUF_MAXLINK (2*PATH_MAX)
446
447 int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
448 {
449         size_t oldalloc = sb->alloc;
450
451         if (hint < 32)
452                 hint = 32;
453
454         while (hint < STRBUF_MAXLINK) {
455                 int len;
456
457                 strbuf_grow(sb, hint);
458                 len = readlink(path, sb->buf, hint);
459                 if (len < 0) {
460                         if (errno != ERANGE)
461                                 break;
462                 } else if (len < hint) {
463                         strbuf_setlen(sb, len);
464                         return 0;
465                 }
466
467                 /* .. the buffer was too small - try again */
468                 hint *= 2;
469         }
470         if (oldalloc == 0)
471                 strbuf_release(sb);
472         return -1;
473 }
474
475 int strbuf_getcwd(struct strbuf *sb)
476 {
477         size_t oldalloc = sb->alloc;
478         size_t guessed_len = 128;
479
480         for (;; guessed_len *= 2) {
481                 strbuf_grow(sb, guessed_len);
482                 if (getcwd(sb->buf, sb->alloc)) {
483                         strbuf_setlen(sb, strlen(sb->buf));
484                         return 0;
485                 }
486
487                 /*
488                  * If getcwd(3) is implemented as a syscall that falls
489                  * back to a regular lookup using readdir(3) etc. then
490                  * we may be able to avoid EACCES by providing enough
491                  * space to the syscall as it's not necessarily bound
492                  * to the same restrictions as the fallback.
493                  */
494                 if (errno == EACCES && guessed_len < PATH_MAX)
495                         continue;
496
497                 if (errno != ERANGE)
498                         break;
499         }
500         if (oldalloc == 0)
501                 strbuf_release(sb);
502         else
503                 strbuf_reset(sb);
504         return -1;
505 }
506
507 #ifdef HAVE_GETDELIM
508 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
509 {
510         ssize_t r;
511
512         if (feof(fp))
513                 return EOF;
514
515         strbuf_reset(sb);
516
517         /* Translate slopbuf to NULL, as we cannot call realloc on it */
518         if (!sb->alloc)
519                 sb->buf = NULL;
520         errno = 0;
521         r = getdelim(&sb->buf, &sb->alloc, term, fp);
522
523         if (r > 0) {
524                 sb->len = r;
525                 return 0;
526         }
527         assert(r == -1);
528
529         /*
530          * Normally we would have called xrealloc, which will try to free
531          * memory and recover. But we have no way to tell getdelim() to do so.
532          * Worse, we cannot try to recover ENOMEM ourselves, because we have
533          * no idea how many bytes were read by getdelim.
534          *
535          * Dying here is reasonable. It mirrors what xrealloc would do on
536          * catastrophic memory failure. We skip the opportunity to free pack
537          * memory and retry, but that's unlikely to help for a malloc small
538          * enough to hold a single line of input, anyway.
539          */
540         if (errno == ENOMEM)
541                 die("Out of memory, getdelim failed");
542
543         /*
544          * Restore strbuf invariants; if getdelim left us with a NULL pointer,
545          * we can just re-init, but otherwise we should make sure that our
546          * length is empty, and that the result is NUL-terminated.
547          */
548         if (!sb->buf)
549                 strbuf_init(sb, 0);
550         else
551                 strbuf_reset(sb);
552         return EOF;
553 }
554 #else
555 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
556 {
557         int ch;
558
559         if (feof(fp))
560                 return EOF;
561
562         strbuf_reset(sb);
563         flockfile(fp);
564         while ((ch = getc_unlocked(fp)) != EOF) {
565                 if (!strbuf_avail(sb))
566                         strbuf_grow(sb, 1);
567                 sb->buf[sb->len++] = ch;
568                 if (ch == term)
569                         break;
570         }
571         funlockfile(fp);
572         if (ch == EOF && sb->len == 0)
573                 return EOF;
574
575         sb->buf[sb->len] = '\0';
576         return 0;
577 }
578 #endif
579
580 static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)
581 {
582         if (strbuf_getwholeline(sb, fp, term))
583                 return EOF;
584         if (sb->buf[sb->len - 1] == term)
585                 strbuf_setlen(sb, sb->len - 1);
586         return 0;
587 }
588
589 int strbuf_getline(struct strbuf *sb, FILE *fp)
590 {
591         if (strbuf_getwholeline(sb, fp, '\n'))
592                 return EOF;
593         if (sb->buf[sb->len - 1] == '\n') {
594                 strbuf_setlen(sb, sb->len - 1);
595                 if (sb->len && sb->buf[sb->len - 1] == '\r')
596                         strbuf_setlen(sb, sb->len - 1);
597         }
598         return 0;
599 }
600
601 int strbuf_getline_lf(struct strbuf *sb, FILE *fp)
602 {
603         return strbuf_getdelim(sb, fp, '\n');
604 }
605
606 int strbuf_getline_nul(struct strbuf *sb, FILE *fp)
607 {
608         return strbuf_getdelim(sb, fp, '\0');
609 }
610
611 int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
612 {
613         strbuf_reset(sb);
614
615         while (1) {
616                 char ch;
617                 ssize_t len = xread(fd, &ch, 1);
618                 if (len <= 0)
619                         return EOF;
620                 strbuf_addch(sb, ch);
621                 if (ch == term)
622                         break;
623         }
624         return 0;
625 }
626
627 ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
628 {
629         int fd;
630         ssize_t len;
631
632         fd = open(path, O_RDONLY);
633         if (fd < 0)
634                 return -1;
635         len = strbuf_read(sb, fd, hint);
636         close(fd);
637         if (len < 0)
638                 return -1;
639
640         return len;
641 }
642
643 void strbuf_add_lines(struct strbuf *out, const char *prefix,
644                       const char *buf, size_t size)
645 {
646         add_lines(out, prefix, NULL, buf, size);
647 }
648
649 void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
650 {
651         while (*s) {
652                 size_t len = strcspn(s, "\"<>&");
653                 strbuf_add(buf, s, len);
654                 s += len;
655                 switch (*s) {
656                 case '"':
657                         strbuf_addstr(buf, "&quot;");
658                         break;
659                 case '<':
660                         strbuf_addstr(buf, "&lt;");
661                         break;
662                 case '>':
663                         strbuf_addstr(buf, "&gt;");
664                         break;
665                 case '&':
666                         strbuf_addstr(buf, "&amp;");
667                         break;
668                 case 0:
669                         return;
670                 }
671                 s++;
672         }
673 }
674
675 static int is_rfc3986_reserved(char ch)
676 {
677         switch (ch) {
678                 case '!': case '*': case '\'': case '(': case ')': case ';':
679                 case ':': case '@': case '&': case '=': case '+': case '$':
680                 case ',': case '/': case '?': case '#': case '[': case ']':
681                         return 1;
682         }
683         return 0;
684 }
685
686 static int is_rfc3986_unreserved(char ch)
687 {
688         return isalnum(ch) ||
689                 ch == '-' || ch == '_' || ch == '.' || ch == '~';
690 }
691
692 static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
693                                  int reserved)
694 {
695         strbuf_grow(sb, len);
696         while (len--) {
697                 char ch = *s++;
698                 if (is_rfc3986_unreserved(ch) ||
699                     (!reserved && is_rfc3986_reserved(ch)))
700                         strbuf_addch(sb, ch);
701                 else
702                         strbuf_addf(sb, "%%%02x", (unsigned char)ch);
703         }
704 }
705
706 void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
707                              int reserved)
708 {
709         strbuf_add_urlencode(sb, s, strlen(s), reserved);
710 }
711
712 void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
713 {
714         if (bytes > 1 << 30) {
715                 strbuf_addf(buf, "%u.%2.2u GiB",
716                             (int)(bytes >> 30),
717                             (int)(bytes & ((1 << 30) - 1)) / 10737419);
718         } else if (bytes > 1 << 20) {
719                 int x = bytes + 5243;  /* for rounding */
720                 strbuf_addf(buf, "%u.%2.2u MiB",
721                             x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
722         } else if (bytes > 1 << 10) {
723                 int x = bytes + 5;  /* for rounding */
724                 strbuf_addf(buf, "%u.%2.2u KiB",
725                             x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
726         } else {
727                 strbuf_addf(buf, "%u bytes", (int)bytes);
728         }
729 }
730
731 void strbuf_add_absolute_path(struct strbuf *sb, const char *path)
732 {
733         if (!*path)
734                 die("The empty string is not a valid path");
735         if (!is_absolute_path(path)) {
736                 struct stat cwd_stat, pwd_stat;
737                 size_t orig_len = sb->len;
738                 char *cwd = xgetcwd();
739                 char *pwd = getenv("PWD");
740                 if (pwd && strcmp(pwd, cwd) &&
741                     !stat(cwd, &cwd_stat) &&
742                     (cwd_stat.st_dev || cwd_stat.st_ino) &&
743                     !stat(pwd, &pwd_stat) &&
744                     pwd_stat.st_dev == cwd_stat.st_dev &&
745                     pwd_stat.st_ino == cwd_stat.st_ino)
746                         strbuf_addstr(sb, pwd);
747                 else
748                         strbuf_addstr(sb, cwd);
749                 if (sb->len > orig_len && !is_dir_sep(sb->buf[sb->len - 1]))
750                         strbuf_addch(sb, '/');
751                 free(cwd);
752         }
753         strbuf_addstr(sb, path);
754 }
755
756 void strbuf_add_real_path(struct strbuf *sb, const char *path)
757 {
758         if (sb->len) {
759                 struct strbuf resolved = STRBUF_INIT;
760                 strbuf_realpath(&resolved, path, 1);
761                 strbuf_addbuf(sb, &resolved);
762                 strbuf_release(&resolved);
763         } else
764                 strbuf_realpath(sb, path, 1);
765 }
766
767 int printf_ln(const char *fmt, ...)
768 {
769         int ret;
770         va_list ap;
771         va_start(ap, fmt);
772         ret = vprintf(fmt, ap);
773         va_end(ap);
774         if (ret < 0 || putchar('\n') == EOF)
775                 return -1;
776         return ret + 1;
777 }
778
779 int fprintf_ln(FILE *fp, const char *fmt, ...)
780 {
781         int ret;
782         va_list ap;
783         va_start(ap, fmt);
784         ret = vfprintf(fp, fmt, ap);
785         va_end(ap);
786         if (ret < 0 || putc('\n', fp) == EOF)
787                 return -1;
788         return ret + 1;
789 }
790
791 char *xstrdup_tolower(const char *string)
792 {
793         char *result;
794         size_t len, i;
795
796         len = strlen(string);
797         result = xmallocz(len);
798         for (i = 0; i < len; i++)
799                 result[i] = tolower(string[i]);
800         result[i] = '\0';
801         return result;
802 }
803
804 char *xstrvfmt(const char *fmt, va_list ap)
805 {
806         struct strbuf buf = STRBUF_INIT;
807         strbuf_vaddf(&buf, fmt, ap);
808         return strbuf_detach(&buf, NULL);
809 }
810
811 char *xstrfmt(const char *fmt, ...)
812 {
813         va_list ap;
814         char *ret;
815
816         va_start(ap, fmt);
817         ret = xstrvfmt(fmt, ap);
818         va_end(ap);
819
820         return ret;
821 }
822
823 void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
824                      int tz_offset, int suppress_tz_name)
825 {
826         struct strbuf munged_fmt = STRBUF_INIT;
827         size_t hint = 128;
828         size_t len;
829
830         if (!*fmt)
831                 return;
832
833         /*
834          * There is no portable way to pass timezone information to
835          * strftime, so we handle %z and %Z here.
836          */
837         for (;;) {
838                 const char *percent = strchrnul(fmt, '%');
839                 strbuf_add(&munged_fmt, fmt, percent - fmt);
840                 if (!*percent)
841                         break;
842                 fmt = percent + 1;
843                 switch (*fmt) {
844                 case '%':
845                         strbuf_addstr(&munged_fmt, "%%");
846                         fmt++;
847                         break;
848                 case 'z':
849                         strbuf_addf(&munged_fmt, "%+05d", tz_offset);
850                         fmt++;
851                         break;
852                 case 'Z':
853                         if (suppress_tz_name) {
854                                 fmt++;
855                                 break;
856                         }
857                         /* FALLTHROUGH */
858                 default:
859                         strbuf_addch(&munged_fmt, '%');
860                 }
861         }
862         fmt = munged_fmt.buf;
863
864         strbuf_grow(sb, hint);
865         len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
866
867         if (!len) {
868                 /*
869                  * strftime reports "0" if it could not fit the result in the buffer.
870                  * Unfortunately, it also reports "0" if the requested time string
871                  * takes 0 bytes. So our strategy is to munge the format so that the
872                  * output contains at least one character, and then drop the extra
873                  * character before returning.
874                  */
875                 strbuf_addch(&munged_fmt, ' ');
876                 while (!len) {
877                         hint *= 2;
878                         strbuf_grow(sb, hint);
879                         len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
880                                        munged_fmt.buf, tm);
881                 }
882                 len--; /* drop munged space */
883         }
884         strbuf_release(&munged_fmt);
885         strbuf_setlen(sb, sb->len + len);
886 }
887
888 void strbuf_add_unique_abbrev(struct strbuf *sb, const unsigned char *sha1,
889                               int abbrev_len)
890 {
891         int r;
892         strbuf_grow(sb, GIT_SHA1_HEXSZ + 1);
893         r = find_unique_abbrev_r(sb->buf + sb->len, sha1, abbrev_len);
894         strbuf_setlen(sb, sb->len + r);
895 }
896
897 /*
898  * Returns the length of a line, without trailing spaces.
899  *
900  * If the line ends with newline, it will be removed too.
901  */
902 static size_t cleanup(char *line, size_t len)
903 {
904         while (len) {
905                 unsigned char c = line[len - 1];
906                 if (!isspace(c))
907                         break;
908                 len--;
909         }
910
911         return len;
912 }
913
914 /*
915  * Remove empty lines from the beginning and end
916  * and also trailing spaces from every line.
917  *
918  * Turn multiple consecutive empty lines between paragraphs
919  * into just one empty line.
920  *
921  * If the input has only empty lines and spaces,
922  * no output will be produced.
923  *
924  * If last line does not have a newline at the end, one is added.
925  *
926  * Enable skip_comments to skip every line starting with comment
927  * character.
928  */
929 void strbuf_stripspace(struct strbuf *sb, int skip_comments)
930 {
931         int empties = 0;
932         size_t i, j, len, newlen;
933         char *eol;
934
935         /* We may have to add a newline. */
936         strbuf_grow(sb, 1);
937
938         for (i = j = 0; i < sb->len; i += len, j += newlen) {
939                 eol = memchr(sb->buf + i, '\n', sb->len - i);
940                 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
941
942                 if (skip_comments && len && sb->buf[i] == comment_line_char) {
943                         newlen = 0;
944                         continue;
945                 }
946                 newlen = cleanup(sb->buf + i, len);
947
948                 /* Not just an empty line? */
949                 if (newlen) {
950                         if (empties > 0 && j > 0)
951                                 sb->buf[j++] = '\n';
952                         empties = 0;
953                         memmove(sb->buf + j, sb->buf + i, newlen);
954                         sb->buf[newlen + j++] = '\n';
955                 } else {
956                         empties++;
957                 }
958         }
959
960         strbuf_setlen(sb, j);
961 }
962
963 int strbuf_normalize_path(struct strbuf *src)
964 {
965         struct strbuf dst = STRBUF_INIT;
966
967         strbuf_grow(&dst, src->len);
968         if (normalize_path_copy(dst.buf, src->buf) < 0) {
969                 strbuf_release(&dst);
970                 return -1;
971         }
972
973         /*
974          * normalize_path does not tell us the new length, so we have to
975          * compute it by looking for the new NUL it placed
976          */
977         strbuf_setlen(&dst, strlen(dst.buf));
978         strbuf_swap(src, &dst);
979         strbuf_release(&dst);
980         return 0;
981 }