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