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