worktree move: accept destination as directory
[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
624         fd = open(path, O_RDONLY);
625         if (fd < 0)
626                 return -1;
627         len = strbuf_read(sb, fd, hint);
628         close(fd);
629         if (len < 0)
630                 return -1;
631
632         return len;
633 }
634
635 void strbuf_add_lines(struct strbuf *out, const char *prefix,
636                       const char *buf, size_t size)
637 {
638         add_lines(out, prefix, NULL, buf, size);
639 }
640
641 void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
642 {
643         while (*s) {
644                 size_t len = strcspn(s, "\"<>&");
645                 strbuf_add(buf, s, len);
646                 s += len;
647                 switch (*s) {
648                 case '"':
649                         strbuf_addstr(buf, "&quot;");
650                         break;
651                 case '<':
652                         strbuf_addstr(buf, "&lt;");
653                         break;
654                 case '>':
655                         strbuf_addstr(buf, "&gt;");
656                         break;
657                 case '&':
658                         strbuf_addstr(buf, "&amp;");
659                         break;
660                 case 0:
661                         return;
662                 }
663                 s++;
664         }
665 }
666
667 static int is_rfc3986_reserved(char ch)
668 {
669         switch (ch) {
670                 case '!': case '*': case '\'': case '(': case ')': case ';':
671                 case ':': case '@': case '&': case '=': case '+': case '$':
672                 case ',': case '/': case '?': case '#': case '[': case ']':
673                         return 1;
674         }
675         return 0;
676 }
677
678 static int is_rfc3986_unreserved(char ch)
679 {
680         return isalnum(ch) ||
681                 ch == '-' || ch == '_' || ch == '.' || ch == '~';
682 }
683
684 static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
685                                  int reserved)
686 {
687         strbuf_grow(sb, len);
688         while (len--) {
689                 char ch = *s++;
690                 if (is_rfc3986_unreserved(ch) ||
691                     (!reserved && is_rfc3986_reserved(ch)))
692                         strbuf_addch(sb, ch);
693                 else
694                         strbuf_addf(sb, "%%%02x", (unsigned char)ch);
695         }
696 }
697
698 void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
699                              int reserved)
700 {
701         strbuf_add_urlencode(sb, s, strlen(s), reserved);
702 }
703
704 void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
705 {
706         if (bytes > 1 << 30) {
707                 strbuf_addf(buf, "%u.%2.2u GiB",
708                             (int)(bytes >> 30),
709                             (int)(bytes & ((1 << 30) - 1)) / 10737419);
710         } else if (bytes > 1 << 20) {
711                 int x = bytes + 5243;  /* for rounding */
712                 strbuf_addf(buf, "%u.%2.2u MiB",
713                             x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
714         } else if (bytes > 1 << 10) {
715                 int x = bytes + 5;  /* for rounding */
716                 strbuf_addf(buf, "%u.%2.2u KiB",
717                             x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
718         } else {
719                 strbuf_addf(buf, "%u bytes", (int)bytes);
720         }
721 }
722
723 void strbuf_add_absolute_path(struct strbuf *sb, const char *path)
724 {
725         if (!*path)
726                 die("The empty string is not a valid path");
727         if (!is_absolute_path(path)) {
728                 struct stat cwd_stat, pwd_stat;
729                 size_t orig_len = sb->len;
730                 char *cwd = xgetcwd();
731                 char *pwd = getenv("PWD");
732                 if (pwd && strcmp(pwd, cwd) &&
733                     !stat(cwd, &cwd_stat) &&
734                     (cwd_stat.st_dev || cwd_stat.st_ino) &&
735                     !stat(pwd, &pwd_stat) &&
736                     pwd_stat.st_dev == cwd_stat.st_dev &&
737                     pwd_stat.st_ino == cwd_stat.st_ino)
738                         strbuf_addstr(sb, pwd);
739                 else
740                         strbuf_addstr(sb, cwd);
741                 if (sb->len > orig_len && !is_dir_sep(sb->buf[sb->len - 1]))
742                         strbuf_addch(sb, '/');
743                 free(cwd);
744         }
745         strbuf_addstr(sb, path);
746 }
747
748 void strbuf_add_real_path(struct strbuf *sb, const char *path)
749 {
750         if (sb->len) {
751                 struct strbuf resolved = STRBUF_INIT;
752                 strbuf_realpath(&resolved, path, 1);
753                 strbuf_addbuf(sb, &resolved);
754                 strbuf_release(&resolved);
755         } else
756                 strbuf_realpath(sb, path, 1);
757 }
758
759 int printf_ln(const char *fmt, ...)
760 {
761         int ret;
762         va_list ap;
763         va_start(ap, fmt);
764         ret = vprintf(fmt, ap);
765         va_end(ap);
766         if (ret < 0 || putchar('\n') == EOF)
767                 return -1;
768         return ret + 1;
769 }
770
771 int fprintf_ln(FILE *fp, const char *fmt, ...)
772 {
773         int ret;
774         va_list ap;
775         va_start(ap, fmt);
776         ret = vfprintf(fp, fmt, ap);
777         va_end(ap);
778         if (ret < 0 || putc('\n', fp) == EOF)
779                 return -1;
780         return ret + 1;
781 }
782
783 char *xstrdup_tolower(const char *string)
784 {
785         char *result;
786         size_t len, i;
787
788         len = strlen(string);
789         result = xmallocz(len);
790         for (i = 0; i < len; i++)
791                 result[i] = tolower(string[i]);
792         result[i] = '\0';
793         return result;
794 }
795
796 char *xstrvfmt(const char *fmt, va_list ap)
797 {
798         struct strbuf buf = STRBUF_INIT;
799         strbuf_vaddf(&buf, fmt, ap);
800         return strbuf_detach(&buf, NULL);
801 }
802
803 char *xstrfmt(const char *fmt, ...)
804 {
805         va_list ap;
806         char *ret;
807
808         va_start(ap, fmt);
809         ret = xstrvfmt(fmt, ap);
810         va_end(ap);
811
812         return ret;
813 }
814
815 void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
816                      int tz_offset, int suppress_tz_name)
817 {
818         struct strbuf munged_fmt = STRBUF_INIT;
819         size_t hint = 128;
820         size_t len;
821
822         if (!*fmt)
823                 return;
824
825         /*
826          * There is no portable way to pass timezone information to
827          * strftime, so we handle %z and %Z here.
828          */
829         for (;;) {
830                 const char *percent = strchrnul(fmt, '%');
831                 strbuf_add(&munged_fmt, fmt, percent - fmt);
832                 if (!*percent)
833                         break;
834                 fmt = percent + 1;
835                 switch (*fmt) {
836                 case '%':
837                         strbuf_addstr(&munged_fmt, "%%");
838                         fmt++;
839                         break;
840                 case 'z':
841                         strbuf_addf(&munged_fmt, "%+05d", tz_offset);
842                         fmt++;
843                         break;
844                 case 'Z':
845                         if (suppress_tz_name) {
846                                 fmt++;
847                                 break;
848                         }
849                         /* FALLTHROUGH */
850                 default:
851                         strbuf_addch(&munged_fmt, '%');
852                 }
853         }
854         fmt = munged_fmt.buf;
855
856         strbuf_grow(sb, hint);
857         len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
858
859         if (!len) {
860                 /*
861                  * strftime reports "0" if it could not fit the result in the buffer.
862                  * Unfortunately, it also reports "0" if the requested time string
863                  * takes 0 bytes. So our strategy is to munge the format so that the
864                  * output contains at least one character, and then drop the extra
865                  * character before returning.
866                  */
867                 strbuf_addch(&munged_fmt, ' ');
868                 while (!len) {
869                         hint *= 2;
870                         strbuf_grow(sb, hint);
871                         len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
872                                        munged_fmt.buf, tm);
873                 }
874                 len--; /* drop munged space */
875         }
876         strbuf_release(&munged_fmt);
877         strbuf_setlen(sb, sb->len + len);
878 }
879
880 void strbuf_add_unique_abbrev(struct strbuf *sb, const unsigned char *sha1,
881                               int abbrev_len)
882 {
883         int r;
884         strbuf_grow(sb, GIT_SHA1_HEXSZ + 1);
885         r = find_unique_abbrev_r(sb->buf + sb->len, sha1, abbrev_len);
886         strbuf_setlen(sb, sb->len + r);
887 }
888
889 /*
890  * Returns the length of a line, without trailing spaces.
891  *
892  * If the line ends with newline, it will be removed too.
893  */
894 static size_t cleanup(char *line, size_t len)
895 {
896         while (len) {
897                 unsigned char c = line[len - 1];
898                 if (!isspace(c))
899                         break;
900                 len--;
901         }
902
903         return len;
904 }
905
906 /*
907  * Remove empty lines from the beginning and end
908  * and also trailing spaces from every line.
909  *
910  * Turn multiple consecutive empty lines between paragraphs
911  * into just one empty line.
912  *
913  * If the input has only empty lines and spaces,
914  * no output will be produced.
915  *
916  * If last line does not have a newline at the end, one is added.
917  *
918  * Enable skip_comments to skip every line starting with comment
919  * character.
920  */
921 void strbuf_stripspace(struct strbuf *sb, int skip_comments)
922 {
923         int empties = 0;
924         size_t i, j, len, newlen;
925         char *eol;
926
927         /* We may have to add a newline. */
928         strbuf_grow(sb, 1);
929
930         for (i = j = 0; i < sb->len; i += len, j += newlen) {
931                 eol = memchr(sb->buf + i, '\n', sb->len - i);
932                 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
933
934                 if (skip_comments && len && sb->buf[i] == comment_line_char) {
935                         newlen = 0;
936                         continue;
937                 }
938                 newlen = cleanup(sb->buf + i, len);
939
940                 /* Not just an empty line? */
941                 if (newlen) {
942                         if (empties > 0 && j > 0)
943                                 sb->buf[j++] = '\n';
944                         empties = 0;
945                         memmove(sb->buf + j, sb->buf + i, newlen);
946                         sb->buf[newlen + j++] = '\n';
947                 } else {
948                         empties++;
949                 }
950         }
951
952         strbuf_setlen(sb, j);
953 }
954
955 int strbuf_normalize_path(struct strbuf *src)
956 {
957         struct strbuf dst = STRBUF_INIT;
958
959         strbuf_grow(&dst, src->len);
960         if (normalize_path_copy(dst.buf, src->buf) < 0) {
961                 strbuf_release(&dst);
962                 return -1;
963         }
964
965         /*
966          * normalize_path does not tell us the new length, so we have to
967          * compute it by looking for the new NUL it placed
968          */
969         strbuf_setlen(&dst, strlen(dst.buf));
970         strbuf_swap(src, &dst);
971         strbuf_release(&dst);
972         return 0;
973 }