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