interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / strbuf.c

1131 lines · 25495 bytes Raw Blame History
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
11bool 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
20bool 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
29bool 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
40bool 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 */
67char strbuf_slopbuf[1];
68
69void 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
77void strbuf_release(struct strbuf *sb)
78{
79 if (sb->alloc) {
80 free(sb->buf);
81 strbuf_init(sb, 0);
82 }
83}
84
85char *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
96void 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
106void 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
117void strbuf_trim(struct strbuf *sb)
118{
119 strbuf_rtrim(sb);
120 strbuf_ltrim(sb);
121}
122
123void 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
130void 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
137void 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
146void 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
157int 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
173void 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
180struct 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
207void 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
222void 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
235int 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
244void 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
263void 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
268void 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
296void 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
304void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
305{
306 strbuf_splice(sb, pos, len, "", 0);
307}
308
309void 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
316void 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
325void 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
332const 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
347void 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
354void 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
362void 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
374static 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
393void 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
399void 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
417void 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
438int 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
450size_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
469void 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
489void 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
502void 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
519size_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
533ssize_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
560ssize_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
574ssize_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
581int 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
609int 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
642int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
643{
644 ssize_t r;
645
646 if (feof(fp))
647 return EOF;
648
649 /* Translate slopbuf to NULL, as we cannot call realloc on it */
650 if (!sb->alloc)
651 sb->buf = NULL;
652 errno = 0;
653 r = getdelim(&sb->buf, &sb->alloc, term, fp);
654
655 if (r > 0) {
656 sb->len = r;
657 return 0;
658 }
659 assert(r == -1);
660
661 /*
662 * Normally we would have called xrealloc, which will try to free
663 * memory and recover. But we have no way to tell getdelim() to do so.
664 * Worse, we cannot try to recover ENOMEM ourselves, because we have
665 * no idea how many bytes were read by getdelim.
666 *
667 * Dying here is reasonable. It mirrors what xrealloc would do on
668 * catastrophic memory failure. We skip the opportunity to free pack
669 * memory and retry, but that's unlikely to help for a malloc small
670 * enough to hold a single line of input, anyway.
671 */
672 if (errno == ENOMEM)
673 die("Out of memory, getdelim failed");
674
675 /*
676 * Restore strbuf invariants; if getdelim left us with a NULL pointer,
677 * we can just re-init, but otherwise we should make sure that our
678 * length is empty, and that the result is NUL-terminated.
679 */
680 if (!sb->buf)
681 strbuf_init(sb, 0);
682 else
683 strbuf_reset(sb);
684 return EOF;
685}
686#else
687int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
688{
689 int ch;
690
691 if (feof(fp))
692 return EOF;
693
694 strbuf_reset(sb);
695 flockfile(fp);
696 while ((ch = getc_unlocked(fp)) != EOF) {
697 if (!strbuf_avail(sb))
698 strbuf_grow(sb, 1);
699 sb->buf[sb->len++] = ch;
700 if (ch == term)
701 break;
702 }
703 funlockfile(fp);
704 if (ch == EOF && sb->len == 0)
705 return EOF;
706
707 sb->buf[sb->len] = '\0';
708 return 0;
709}
710#endif
711
712int strbuf_appendwholeline(struct strbuf *sb, FILE *fp, int term)
713{
714 struct strbuf line = STRBUF_INIT;
715 if (strbuf_getwholeline(&line, fp, term)) {
716 strbuf_release(&line);
717 return EOF;
718 }
719 strbuf_addbuf(sb, &line);
720 strbuf_release(&line);
721 return 0;
722}
723
724static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)
725{
726 if (strbuf_getwholeline(sb, fp, term))
727 return EOF;
728 if (sb->buf[sb->len - 1] == term)
729 strbuf_setlen(sb, sb->len - 1);
730 return 0;
731}
732
733int strbuf_getdelim_strip_crlf(struct strbuf *sb, FILE *fp, int term)
734{
735 if (strbuf_getwholeline(sb, fp, term))
736 return EOF;
737 if (term == '\n' && sb->buf[sb->len - 1] == '\n') {
738 strbuf_setlen(sb, sb->len - 1);
739 if (sb->len && sb->buf[sb->len - 1] == '\r')
740 strbuf_setlen(sb, sb->len - 1);
741 }
742 return 0;
743}
744
745int strbuf_getline(struct strbuf *sb, FILE *fp)
746{
747 return strbuf_getdelim_strip_crlf(sb, fp, '\n');
748}
749
750int strbuf_getline_lf(struct strbuf *sb, FILE *fp)
751{
752 return strbuf_getdelim(sb, fp, '\n');
753}
754
755int strbuf_getline_nul(struct strbuf *sb, FILE *fp)
756{
757 return strbuf_getdelim(sb, fp, '\0');
758}
759
760int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
761{
762 strbuf_reset(sb);
763
764 while (1) {
765 char ch;
766 ssize_t len = xread(fd, &ch, 1);
767 if (len <= 0)
768 return EOF;
769 strbuf_addch(sb, ch);
770 if (ch == term)
771 break;
772 }
773 return 0;
774}
775
776ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
777{
778 int fd;
779 ssize_t len;
780 int saved_errno;
781
782 fd = open(path, O_RDONLY);
783 if (fd < 0)
784 return -1;
785 len = strbuf_read(sb, fd, hint);
786 saved_errno = errno;
787 close(fd);
788 if (len < 0) {
789 errno = saved_errno;
790 return -1;
791 }
792
793 return len;
794}
795
796void strbuf_add_lines(struct strbuf *out, const char *prefix,
797 const char *buf, size_t size)
798{
799 add_lines(out, prefix, buf, size, 0);
800}
801
802void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
803{
804 while (*s) {
805 size_t len = strcspn(s, "\"<>&");
806 strbuf_add(buf, s, len);
807 s += len;
808 switch (*s) {
809 case '"':
810 strbuf_addstr(buf, "&quot;");
811 break;
812 case '<':
813 strbuf_addstr(buf, "&lt;");
814 break;
815 case '>':
816 strbuf_addstr(buf, "&gt;");
817 break;
818 case '&':
819 strbuf_addstr(buf, "&amp;");
820 break;
821 case 0:
822 return;
823 }
824 s++;
825 }
826}
827
828static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
829 char_predicate allow_unencoded_fn)
830{
831 strbuf_grow(sb, len);
832 while (len--) {
833 char ch = *s++;
834 if (allow_unencoded_fn(ch))
835 strbuf_addch(sb, ch);
836 else
837 strbuf_addf(sb, "%%%02x", (unsigned char)ch);
838 }
839}
840
841void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
842 char_predicate allow_unencoded_fn)
843{
844 strbuf_add_urlencode(sb, s, strlen(s), allow_unencoded_fn);
845}
846
847void humanise_count(size_t count, char **value, const char **unit)
848{
849 if (count >= 1000000000) {
850 size_t x = count + 5000000; /* for rounding */
851 *value = xstrfmt(_("%u.%2.2u"), (unsigned)(x / 1000000000),
852 (unsigned)(x % 1000000000 / 10000000));
853 /* TRANSLATORS: SI decimal prefix symbol for 10^9 */
854 *unit = _("G");
855 } else if (count >= 1000000) {
856 size_t x = count + 5000; /* for rounding */
857 *value = xstrfmt(_("%u.%2.2u"), (unsigned)(x / 1000000),
858 (unsigned)(x % 1000000 / 10000));
859 /* TRANSLATORS: SI decimal prefix symbol for 10^6 */
860 *unit = _("M");
861 } else if (count >= 1000) {
862 size_t x = count + 5; /* for rounding */
863 *value = xstrfmt(_("%u.%2.2u"), (unsigned)(x / 1000),
864 (unsigned)(x % 1000 / 10));
865 /* TRANSLATORS: SI decimal prefix symbol for 10^3 */
866 *unit = _("k");
867 } else {
868 *value = xstrfmt("%u", (unsigned)count);
869 *unit = NULL;
870 }
871}
872
873void humanise_bytes(off_t bytes, char **value, const char **unit,
874 unsigned flags)
875{
876 int humanise_rate = flags & HUMANISE_RATE;
877
878 if (bytes > 1 << 30) {
879 *value = xstrfmt(_("%u.%2.2u"), (unsigned)(bytes >> 30),
880 (unsigned)(bytes & ((1 << 30) - 1)) / 10737419);
881 /* TRANSLATORS: IEC 80000-13:2008 gibibyte/second and gibibyte */
882 *unit = humanise_rate ? _("GiB/s") : _("GiB");
883 } else if (bytes > 1 << 20) {
884 unsigned x = bytes + 5243; /* for rounding */
885 *value = xstrfmt(_("%u.%2.2u"), x >> 20,
886 ((x & ((1 << 20) - 1)) * 100) >> 20);
887 /* TRANSLATORS: IEC 80000-13:2008 mebibyte/second and mebibyte */
888 *unit = humanise_rate ? _("MiB/s") : _("MiB");
889 } else if (bytes > 1 << 10) {
890 unsigned x = bytes + 5; /* for rounding */
891 *value = xstrfmt(_("%u.%2.2u"), x >> 10,
892 ((x & ((1 << 10) - 1)) * 100) >> 10);
893 /* TRANSLATORS: IEC 80000-13:2008 kibibyte/second and kibibyte */
894 *unit = humanise_rate ? _("KiB/s") : _("KiB");
895 } else {
896 *value = xstrfmt("%u", (unsigned)bytes);
897 if (flags & HUMANISE_COMPACT)
898 /* TRANSLATORS: IEC 80000-13:2008 byte/second and byte */
899 *unit = humanise_rate ? _("B/s") : _("B");
900 else
901 *unit = humanise_rate ?
902 /* TRANSLATORS: IEC 80000-13:2008 byte/second */
903 Q_("byte/s", "bytes/s", bytes) :
904 /* TRANSLATORS: IEC 80000-13:2008 byte */
905 Q_("byte", "bytes", bytes);
906 }
907}
908
909static void strbuf_humanise(struct strbuf *buf, off_t bytes, unsigned flags)
910{
911 char *value;
912 const char *unit;
913
914 humanise_bytes(bytes, &value, &unit, flags);
915
916 /*
917 * TRANSLATORS: The first argument is the number string. The second
918 * argument is the unit string (i.e. "12.34 MiB/s").
919 */
920 strbuf_addf(buf, _("%s %s"), value, unit);
921 free(value);
922}
923
924void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
925{
926 strbuf_humanise(buf, bytes, 0);
927}
928
929void strbuf_humanise_rate(struct strbuf *buf, off_t bytes)
930{
931 strbuf_humanise(buf, bytes, HUMANISE_RATE);
932}
933
934int printf_ln(const char *fmt, ...)
935{
936 int ret;
937 va_list ap;
938 va_start(ap, fmt);
939 ret = vprintf(fmt, ap);
940 va_end(ap);
941 if (ret < 0 || putchar('\n') == EOF)
942 return -1;
943 return ret + 1;
944}
945
946int fprintf_ln(FILE *fp, const char *fmt, ...)
947{
948 int ret;
949 va_list ap;
950 va_start(ap, fmt);
951 ret = vfprintf(fp, fmt, ap);
952 va_end(ap);
953 if (ret < 0 || putc('\n', fp) == EOF)
954 return -1;
955 return ret + 1;
956}
957
958char *xstrdup_tolower(const char *string)
959{
960 char *result;
961 size_t len, i;
962
963 len = strlen(string);
964 result = xmallocz(len);
965 for (i = 0; i < len; i++)
966 result[i] = tolower(string[i]);
967 return result;
968}
969
970char *xstrdup_toupper(const char *string)
971{
972 char *result;
973 size_t len, i;
974
975 len = strlen(string);
976 result = xmallocz(len);
977 for (i = 0; i < len; i++)
978 result[i] = toupper(string[i]);
979 return result;
980}
981
982char *xstrvfmt(const char *fmt, va_list ap)
983{
984 struct strbuf buf = STRBUF_INIT;
985 strbuf_vaddf(&buf, fmt, ap);
986 return strbuf_detach(&buf, NULL);
987}
988
989char *xstrfmt(const char *fmt, ...)
990{
991 va_list ap;
992 char *ret;
993
994 va_start(ap, fmt);
995 ret = xstrvfmt(fmt, ap);
996 va_end(ap);
997
998 return ret;
999}
1000
1001void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
1002 int tz_offset, int suppress_tz_name)
1003{
1004 struct strbuf munged_fmt = STRBUF_INIT;
1005 size_t hint = 128;
1006 size_t len;
1007
1008 if (!*fmt)
1009 return;
1010
1011 /*
1012 * There is no portable way to pass timezone information to
1013 * strftime, so we handle %z and %Z here. Likewise '%s', because
1014 * going back to an epoch time requires knowing the zone.
1015 *
1016 * Note that tz_offset is in the "[-+]HHMM" decimal form; this is what
1017 * we want for %z, but the computation for %s has to convert to number
1018 * of seconds.
1019 */
1020 while (strbuf_expand_step(&munged_fmt, &fmt)) {
1021 if (skip_prefix(fmt, "%", &fmt))
1022 strbuf_addstr(&munged_fmt, "%%");
1023 else if (skip_prefix(fmt, "s", &fmt))
1024 strbuf_addf(&munged_fmt, "%"PRItime,
1025 (timestamp_t)tm_to_time_t(tm) -
1026 60 * tz_to_minutes(tz_offset));
1027 else if (skip_prefix(fmt, "z", &fmt))
1028 strbuf_addf(&munged_fmt, "%+05d", tz_offset);
1029 else if (suppress_tz_name && skip_prefix(fmt, "Z", &fmt))
1030 ; /* nothing */
1031 else
1032 strbuf_addch(&munged_fmt, '%');
1033 }
1034 fmt = munged_fmt.buf;
1035
1036 strbuf_grow(sb, hint);
1037 len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
1038
1039 if (!len) {
1040 /*
1041 * strftime reports "0" if it could not fit the result in the buffer.
1042 * Unfortunately, it also reports "0" if the requested time string
1043 * takes 0 bytes. So our strategy is to munge the format so that the
1044 * output contains at least one character, and then drop the extra
1045 * character before returning.
1046 */
1047 strbuf_addch(&munged_fmt, ' ');
1048 while (!len) {
1049 hint *= 2;
1050 strbuf_grow(sb, hint);
1051 len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
1052 munged_fmt.buf, tm);
1053 }
1054 len--; /* drop munged space */
1055 }
1056 strbuf_release(&munged_fmt);
1057 strbuf_setlen(sb, sb->len + len);
1058}
1059
1060/*
1061 * Returns the length of a line, without trailing spaces.
1062 *
1063 * If the line ends with newline, it will be removed too.
1064 */
1065static size_t cleanup(char *line, size_t len)
1066{
1067 while (len) {
1068 unsigned char c = line[len - 1];
1069 if (!isspace(c))
1070 break;
1071 len--;
1072 }
1073
1074 return len;
1075}
1076
1077/*
1078 * Remove empty lines from the beginning and end
1079 * and also trailing spaces from every line.
1080 *
1081 * Turn multiple consecutive empty lines between paragraphs
1082 * into just one empty line.
1083 *
1084 * If the input has only empty lines and spaces,
1085 * no output will be produced.
1086 *
1087 * If last line does not have a newline at the end, one is added.
1088 *
1089 * Pass a non-NULL comment_prefix to skip every line starting
1090 * with it.
1091 */
1092void strbuf_stripspace(struct strbuf *sb, const char *comment_prefix)
1093{
1094 size_t empties = 0;
1095 size_t i, j, len, newlen;
1096 char *eol;
1097
1098 /* We may have to add a newline. */
1099 strbuf_grow(sb, 1);
1100
1101 for (i = j = 0; i < sb->len; i += len, j += newlen) {
1102 eol = memchr(sb->buf + i, '\n', sb->len - i);
1103 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
1104
1105 if (comment_prefix && len &&
1106 starts_with(sb->buf + i, comment_prefix)) {
1107 newlen = 0;
1108 continue;
1109 }
1110 newlen = cleanup(sb->buf + i, len);
1111
1112 /* Not just an empty line? */
1113 if (newlen) {
1114 if (empties > 0 && j > 0)
1115 sb->buf[j++] = '\n';
1116 empties = 0;
1117 memmove(sb->buf + j, sb->buf + i, newlen);
1118 sb->buf[newlen + j++] = '\n';
1119 } else {
1120 empties++;
1121 }
1122 }
1123
1124 strbuf_setlen(sb, j);
1125}
1126
1127void strbuf_strip_file_from_path(struct strbuf *sb)
1128{
1129 const char *path_sep = find_last_dir_sep(sb->buf);
1130 strbuf_setlen(sb, path_sep ? path_sep - sb->buf + 1 : 0);
1131}