Merge branch 'rs/userformat-find-requirements-simplify'
[git/gitster.git] / strbuf.c
blobb41d343ed0cbf1112cadde2c6c8ab63bcc26fb36
1 #include "git-compat-util.h"
2 #include "alloc.h"
3 #include "gettext.h"
4 #include "hex.h"
5 #include "strbuf.h"
6 #include "string-list.h"
7 #include "utf8.h"
8 #include "date.h"
9 #include "wrapper.h"
11 int starts_with(const char *str, const char *prefix)
13 for (; ; str++, prefix++)
14 if (!*prefix)
15 return 1;
16 else if (*str != *prefix)
17 return 0;
20 int istarts_with(const char *str, const char *prefix)
22 for (; ; str++, prefix++)
23 if (!*prefix)
24 return 1;
25 else if (tolower(*str) != tolower(*prefix))
26 return 0;
29 int skip_to_optional_arg_default(const char *str, const char *prefix,
30 const char **arg, const char *def)
32 const char *p;
34 if (!skip_prefix(str, prefix, &p))
35 return 0;
37 if (!*p) {
38 if (arg)
39 *arg = def;
40 return 1;
43 if (*p != '=')
44 return 0;
46 if (arg)
47 *arg = p + 1;
48 return 1;
52 * Used as the default ->buf value, so that people can always assume
53 * buf is non NULL and ->buf is NUL terminated even for a freshly
54 * initialized strbuf.
56 char strbuf_slopbuf[1];
58 void strbuf_init(struct strbuf *sb, size_t hint)
60 struct strbuf blank = STRBUF_INIT;
61 memcpy(sb, &blank, sizeof(*sb));
62 if (hint)
63 strbuf_grow(sb, hint);
66 void strbuf_release(struct strbuf *sb)
68 if (sb->alloc) {
69 free(sb->buf);
70 strbuf_init(sb, 0);
74 char *strbuf_detach(struct strbuf *sb, size_t *sz)
76 char *res;
77 strbuf_grow(sb, 0);
78 res = sb->buf;
79 if (sz)
80 *sz = sb->len;
81 strbuf_init(sb, 0);
82 return res;
85 void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
87 strbuf_release(sb);
88 sb->buf = buf;
89 sb->len = len;
90 sb->alloc = alloc;
91 strbuf_grow(sb, 0);
92 sb->buf[sb->len] = '\0';
95 void strbuf_grow(struct strbuf *sb, size_t extra)
97 int new_buf = !sb->alloc;
98 if (unsigned_add_overflows(extra, 1) ||
99 unsigned_add_overflows(sb->len, extra + 1))
100 die("you want to use way too much memory");
101 if (new_buf)
102 sb->buf = NULL;
103 ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
104 if (new_buf)
105 sb->buf[0] = '\0';
108 void strbuf_trim(struct strbuf *sb)
110 strbuf_rtrim(sb);
111 strbuf_ltrim(sb);
114 void strbuf_rtrim(struct strbuf *sb)
116 while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
117 sb->len--;
118 sb->buf[sb->len] = '\0';
121 void strbuf_trim_trailing_dir_sep(struct strbuf *sb)
123 while (sb->len > 0 && is_dir_sep((unsigned char)sb->buf[sb->len - 1]))
124 sb->len--;
125 sb->buf[sb->len] = '\0';
128 void strbuf_trim_trailing_newline(struct strbuf *sb)
130 if (sb->len > 0 && sb->buf[sb->len - 1] == '\n') {
131 if (--sb->len > 0 && sb->buf[sb->len - 1] == '\r')
132 --sb->len;
133 sb->buf[sb->len] = '\0';
137 void strbuf_ltrim(struct strbuf *sb)
139 char *b = sb->buf;
140 while (sb->len > 0 && isspace(*b)) {
141 b++;
142 sb->len--;
144 memmove(sb->buf, b, sb->len);
145 sb->buf[sb->len] = '\0';
148 int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)
150 char *out;
151 size_t len;
153 if (same_encoding(from, to))
154 return 0;
156 out = reencode_string_len(sb->buf, sb->len, to, from, &len);
157 if (!out)
158 return -1;
160 strbuf_attach(sb, out, len, len);
161 return 0;
164 void strbuf_tolower(struct strbuf *sb)
166 char *p = sb->buf, *end = sb->buf + sb->len;
167 for (; p < end; p++)
168 *p = tolower(*p);
171 struct strbuf **strbuf_split_buf(const char *str, size_t slen,
172 int terminator, int max)
174 struct strbuf **ret = NULL;
175 size_t nr = 0, alloc = 0;
176 struct strbuf *t;
178 while (slen) {
179 int len = slen;
180 if (max <= 0 || nr + 1 < max) {
181 const char *end = memchr(str, terminator, slen);
182 if (end)
183 len = end - str + 1;
185 t = xmalloc(sizeof(struct strbuf));
186 strbuf_init(t, len);
187 strbuf_add(t, str, len);
188 ALLOC_GROW(ret, nr + 2, alloc);
189 ret[nr++] = t;
190 str += len;
191 slen -= len;
193 ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
194 ret[nr] = NULL;
195 return ret;
198 void strbuf_add_separated_string_list(struct strbuf *str,
199 const char *sep,
200 struct string_list *slist)
202 struct string_list_item *item;
203 int sep_needed = 0;
205 for_each_string_list_item(item, slist) {
206 if (sep_needed)
207 strbuf_addstr(str, sep);
208 strbuf_addstr(str, item->string);
209 sep_needed = 1;
213 void strbuf_list_free(struct strbuf **sbs)
215 struct strbuf **s = sbs;
217 if (!s)
218 return;
219 while (*s) {
220 strbuf_release(*s);
221 free(*s++);
223 free(sbs);
226 int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
228 size_t len = a->len < b->len ? a->len: b->len;
229 int cmp = memcmp(a->buf, b->buf, len);
230 if (cmp)
231 return cmp;
232 return a->len < b->len ? -1: a->len != b->len;
235 void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
236 const void *data, size_t dlen)
238 if (unsigned_add_overflows(pos, len))
239 die("you want to use way too much memory");
240 if (pos > sb->len)
241 die("`pos' is too far after the end of the buffer");
242 if (pos + len > sb->len)
243 die("`pos + len' is too far after the end of the buffer");
245 if (dlen >= len)
246 strbuf_grow(sb, dlen - len);
247 memmove(sb->buf + pos + dlen,
248 sb->buf + pos + len,
249 sb->len - pos - len);
250 memcpy(sb->buf + pos, data, dlen);
251 strbuf_setlen(sb, sb->len + dlen - len);
254 void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
256 strbuf_splice(sb, pos, 0, data, len);
259 void strbuf_vinsertf(struct strbuf *sb, size_t pos, const char *fmt, va_list ap)
261 int len, len2;
262 char save;
263 va_list cp;
265 if (pos > sb->len)
266 die("`pos' is too far after the end of the buffer");
267 va_copy(cp, ap);
268 len = vsnprintf(sb->buf + sb->len, 0, fmt, cp);
269 va_end(cp);
270 if (len < 0)
271 BUG("your vsnprintf is broken (returned %d)", len);
272 if (!len)
273 return; /* nothing to do */
274 if (unsigned_add_overflows(sb->len, len))
275 die("you want to use way too much memory");
276 strbuf_grow(sb, len);
277 memmove(sb->buf + pos + len, sb->buf + pos, sb->len - pos);
278 /* vsnprintf() will append a NUL, overwriting one of our characters */
279 save = sb->buf[pos + len];
280 len2 = vsnprintf(sb->buf + pos, len + 1, fmt, ap);
281 sb->buf[pos + len] = save;
282 if (len2 != len)
283 BUG("your vsnprintf is broken (returns inconsistent lengths)");
284 strbuf_setlen(sb, sb->len + len);
287 void strbuf_insertf(struct strbuf *sb, size_t pos, const char *fmt, ...)
289 va_list ap;
290 va_start(ap, fmt);
291 strbuf_vinsertf(sb, pos, fmt, ap);
292 va_end(ap);
295 void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
297 strbuf_splice(sb, pos, len, "", 0);
300 void strbuf_add(struct strbuf *sb, const void *data, size_t len)
302 strbuf_grow(sb, len);
303 memcpy(sb->buf + sb->len, data, len);
304 strbuf_setlen(sb, sb->len + len);
307 void strbuf_addbuf(struct strbuf *sb, const struct strbuf *sb2)
309 strbuf_grow(sb, sb2->len);
310 memcpy(sb->buf + sb->len, sb2->buf, sb2->len);
311 strbuf_setlen(sb, sb->len + sb2->len);
314 const char *strbuf_join_argv(struct strbuf *buf,
315 int argc, const char **argv, char delim)
317 if (!argc)
318 return buf->buf;
320 strbuf_addstr(buf, *argv);
321 while (--argc) {
322 strbuf_addch(buf, delim);
323 strbuf_addstr(buf, *(++argv));
326 return buf->buf;
329 void strbuf_addchars(struct strbuf *sb, int c, size_t n)
331 strbuf_grow(sb, n);
332 memset(sb->buf + sb->len, c, n);
333 strbuf_setlen(sb, sb->len + n);
336 void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
338 va_list ap;
339 va_start(ap, fmt);
340 strbuf_vaddf(sb, fmt, ap);
341 va_end(ap);
344 static void add_lines(struct strbuf *out,
345 const char *prefix1,
346 const char *prefix2,
347 const char *buf, size_t size)
349 while (size) {
350 const char *prefix;
351 const char *next = memchr(buf, '\n', size);
352 next = next ? (next + 1) : (buf + size);
354 prefix = ((prefix2 && (buf[0] == '\n' || buf[0] == '\t'))
355 ? prefix2 : prefix1);
356 strbuf_addstr(out, prefix);
357 strbuf_add(out, buf, next - buf);
358 size -= next - buf;
359 buf = next;
361 strbuf_complete_line(out);
364 void strbuf_add_commented_lines(struct strbuf *out, const char *buf,
365 size_t size, char comment_line_char)
367 static char prefix1[3];
368 static char prefix2[2];
370 if (prefix1[0] != comment_line_char) {
371 xsnprintf(prefix1, sizeof(prefix1), "%c ", comment_line_char);
372 xsnprintf(prefix2, sizeof(prefix2), "%c", comment_line_char);
374 add_lines(out, prefix1, prefix2, buf, size);
377 void strbuf_commented_addf(struct strbuf *sb, char comment_line_char,
378 const char *fmt, ...)
380 va_list params;
381 struct strbuf buf = STRBUF_INIT;
382 int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';
384 va_start(params, fmt);
385 strbuf_vaddf(&buf, fmt, params);
386 va_end(params);
388 strbuf_add_commented_lines(sb, buf.buf, buf.len, comment_line_char);
389 if (incomplete_line)
390 sb->buf[--sb->len] = '\0';
392 strbuf_release(&buf);
395 void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
397 int len;
398 va_list cp;
400 if (!strbuf_avail(sb))
401 strbuf_grow(sb, 64);
402 va_copy(cp, ap);
403 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
404 va_end(cp);
405 if (len < 0)
406 BUG("your vsnprintf is broken (returned %d)", len);
407 if (len > strbuf_avail(sb)) {
408 strbuf_grow(sb, len);
409 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
410 if (len > strbuf_avail(sb))
411 BUG("your vsnprintf is broken (insatiable)");
413 strbuf_setlen(sb, sb->len + len);
416 int strbuf_expand_step(struct strbuf *sb, const char **formatp)
418 const char *format = *formatp;
419 const char *percent = strchrnul(format, '%');
421 strbuf_add(sb, format, percent - format);
422 if (!*percent)
423 return 0;
424 *formatp = percent + 1;
425 return 1;
428 size_t strbuf_expand_literal(struct strbuf *sb, const char *placeholder)
430 int ch;
432 switch (placeholder[0]) {
433 case 'n': /* newline */
434 strbuf_addch(sb, '\n');
435 return 1;
436 case 'x':
437 /* %x00 == NUL, %x0a == LF, etc. */
438 ch = hex2chr(placeholder + 1);
439 if (ch < 0)
440 return 0;
441 strbuf_addch(sb, ch);
442 return 3;
444 return 0;
447 void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
449 size_t i, len = src->len;
451 for (i = 0; i < len; i++) {
452 if (src->buf[i] == '%')
453 strbuf_addch(dst, '%');
454 strbuf_addch(dst, src->buf[i]);
458 #define URL_UNSAFE_CHARS " <>\"%{}|\\^`:?#[]@!$&'()*+,;="
460 void strbuf_add_percentencode(struct strbuf *dst, const char *src, int flags)
462 size_t i, len = strlen(src);
464 for (i = 0; i < len; i++) {
465 unsigned char ch = src[i];
466 if (ch <= 0x1F || ch >= 0x7F ||
467 (ch == '/' && (flags & STRBUF_ENCODE_SLASH)) ||
468 strchr(URL_UNSAFE_CHARS, ch))
469 strbuf_addf(dst, "%%%02X", (unsigned char)ch);
470 else
471 strbuf_addch(dst, ch);
475 size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
477 size_t res;
478 size_t oldalloc = sb->alloc;
480 strbuf_grow(sb, size);
481 res = fread(sb->buf + sb->len, 1, size, f);
482 if (res > 0)
483 strbuf_setlen(sb, sb->len + res);
484 else if (oldalloc == 0)
485 strbuf_release(sb);
486 return res;
489 ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
491 size_t oldlen = sb->len;
492 size_t oldalloc = sb->alloc;
494 strbuf_grow(sb, hint ? hint : 8192);
495 for (;;) {
496 ssize_t want = sb->alloc - sb->len - 1;
497 ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
499 if (got < 0) {
500 if (oldalloc == 0)
501 strbuf_release(sb);
502 else
503 strbuf_setlen(sb, oldlen);
504 return -1;
506 sb->len += got;
507 if (got < want)
508 break;
509 strbuf_grow(sb, 8192);
512 sb->buf[sb->len] = '\0';
513 return sb->len - oldlen;
516 ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
518 size_t oldalloc = sb->alloc;
519 ssize_t cnt;
521 strbuf_grow(sb, hint ? hint : 8192);
522 cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
523 if (cnt > 0)
524 strbuf_setlen(sb, sb->len + cnt);
525 else if (oldalloc == 0)
526 strbuf_release(sb);
527 return cnt;
530 ssize_t strbuf_write(struct strbuf *sb, FILE *f)
532 return sb->len ? fwrite(sb->buf, 1, sb->len, f) : 0;
535 #define STRBUF_MAXLINK (2*PATH_MAX)
537 int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
539 size_t oldalloc = sb->alloc;
541 if (hint < 32)
542 hint = 32;
544 while (hint < STRBUF_MAXLINK) {
545 ssize_t len;
547 strbuf_grow(sb, hint);
548 len = readlink(path, sb->buf, hint);
549 if (len < 0) {
550 if (errno != ERANGE)
551 break;
552 } else if (len < hint) {
553 strbuf_setlen(sb, len);
554 return 0;
557 /* .. the buffer was too small - try again */
558 hint *= 2;
560 if (oldalloc == 0)
561 strbuf_release(sb);
562 return -1;
565 int strbuf_getcwd(struct strbuf *sb)
567 size_t oldalloc = sb->alloc;
568 size_t guessed_len = 128;
570 for (;; guessed_len *= 2) {
571 strbuf_grow(sb, guessed_len);
572 if (getcwd(sb->buf, sb->alloc)) {
573 strbuf_setlen(sb, strlen(sb->buf));
574 return 0;
578 * If getcwd(3) is implemented as a syscall that falls
579 * back to a regular lookup using readdir(3) etc. then
580 * we may be able to avoid EACCES by providing enough
581 * space to the syscall as it's not necessarily bound
582 * to the same restrictions as the fallback.
584 if (errno == EACCES && guessed_len < PATH_MAX)
585 continue;
587 if (errno != ERANGE)
588 break;
590 if (oldalloc == 0)
591 strbuf_release(sb);
592 else
593 strbuf_reset(sb);
594 return -1;
597 #ifdef HAVE_GETDELIM
598 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
600 ssize_t r;
602 if (feof(fp))
603 return EOF;
605 strbuf_reset(sb);
607 /* Translate slopbuf to NULL, as we cannot call realloc on it */
608 if (!sb->alloc)
609 sb->buf = NULL;
610 errno = 0;
611 r = getdelim(&sb->buf, &sb->alloc, term, fp);
613 if (r > 0) {
614 sb->len = r;
615 return 0;
617 assert(r == -1);
620 * Normally we would have called xrealloc, which will try to free
621 * memory and recover. But we have no way to tell getdelim() to do so.
622 * Worse, we cannot try to recover ENOMEM ourselves, because we have
623 * no idea how many bytes were read by getdelim.
625 * Dying here is reasonable. It mirrors what xrealloc would do on
626 * catastrophic memory failure. We skip the opportunity to free pack
627 * memory and retry, but that's unlikely to help for a malloc small
628 * enough to hold a single line of input, anyway.
630 if (errno == ENOMEM)
631 die("Out of memory, getdelim failed");
634 * Restore strbuf invariants; if getdelim left us with a NULL pointer,
635 * we can just re-init, but otherwise we should make sure that our
636 * length is empty, and that the result is NUL-terminated.
638 if (!sb->buf)
639 strbuf_init(sb, 0);
640 else
641 strbuf_reset(sb);
642 return EOF;
644 #else
645 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
647 int ch;
649 if (feof(fp))
650 return EOF;
652 strbuf_reset(sb);
653 flockfile(fp);
654 while ((ch = getc_unlocked(fp)) != EOF) {
655 if (!strbuf_avail(sb))
656 strbuf_grow(sb, 1);
657 sb->buf[sb->len++] = ch;
658 if (ch == term)
659 break;
661 funlockfile(fp);
662 if (ch == EOF && sb->len == 0)
663 return EOF;
665 sb->buf[sb->len] = '\0';
666 return 0;
668 #endif
670 int strbuf_appendwholeline(struct strbuf *sb, FILE *fp, int term)
672 struct strbuf line = STRBUF_INIT;
673 if (strbuf_getwholeline(&line, fp, term))
674 return EOF;
675 strbuf_addbuf(sb, &line);
676 strbuf_release(&line);
677 return 0;
680 static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)
682 if (strbuf_getwholeline(sb, fp, term))
683 return EOF;
684 if (sb->buf[sb->len - 1] == term)
685 strbuf_setlen(sb, sb->len - 1);
686 return 0;
689 int strbuf_getdelim_strip_crlf(struct strbuf *sb, FILE *fp, int term)
691 if (strbuf_getwholeline(sb, fp, term))
692 return EOF;
693 if (term == '\n' && sb->buf[sb->len - 1] == '\n') {
694 strbuf_setlen(sb, sb->len - 1);
695 if (sb->len && sb->buf[sb->len - 1] == '\r')
696 strbuf_setlen(sb, sb->len - 1);
698 return 0;
701 int strbuf_getline(struct strbuf *sb, FILE *fp)
703 return strbuf_getdelim_strip_crlf(sb, fp, '\n');
706 int strbuf_getline_lf(struct strbuf *sb, FILE *fp)
708 return strbuf_getdelim(sb, fp, '\n');
711 int strbuf_getline_nul(struct strbuf *sb, FILE *fp)
713 return strbuf_getdelim(sb, fp, '\0');
716 int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
718 strbuf_reset(sb);
720 while (1) {
721 char ch;
722 ssize_t len = xread(fd, &ch, 1);
723 if (len <= 0)
724 return EOF;
725 strbuf_addch(sb, ch);
726 if (ch == term)
727 break;
729 return 0;
732 ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
734 int fd;
735 ssize_t len;
736 int saved_errno;
738 fd = open(path, O_RDONLY);
739 if (fd < 0)
740 return -1;
741 len = strbuf_read(sb, fd, hint);
742 saved_errno = errno;
743 close(fd);
744 if (len < 0) {
745 errno = saved_errno;
746 return -1;
749 return len;
752 void strbuf_add_lines(struct strbuf *out, const char *prefix,
753 const char *buf, size_t size)
755 add_lines(out, prefix, NULL, buf, size);
758 void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
760 while (*s) {
761 size_t len = strcspn(s, "\"<>&");
762 strbuf_add(buf, s, len);
763 s += len;
764 switch (*s) {
765 case '"':
766 strbuf_addstr(buf, "&quot;");
767 break;
768 case '<':
769 strbuf_addstr(buf, "&lt;");
770 break;
771 case '>':
772 strbuf_addstr(buf, "&gt;");
773 break;
774 case '&':
775 strbuf_addstr(buf, "&amp;");
776 break;
777 case 0:
778 return;
780 s++;
784 static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
785 char_predicate allow_unencoded_fn)
787 strbuf_grow(sb, len);
788 while (len--) {
789 char ch = *s++;
790 if (allow_unencoded_fn(ch))
791 strbuf_addch(sb, ch);
792 else
793 strbuf_addf(sb, "%%%02x", (unsigned char)ch);
797 void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
798 char_predicate allow_unencoded_fn)
800 strbuf_add_urlencode(sb, s, strlen(s), allow_unencoded_fn);
803 static void strbuf_humanise(struct strbuf *buf, off_t bytes,
804 int humanise_rate)
806 if (bytes > 1 << 30) {
807 strbuf_addf(buf,
808 humanise_rate == 0 ?
809 /* TRANSLATORS: IEC 80000-13:2008 gibibyte */
810 _("%u.%2.2u GiB") :
811 /* TRANSLATORS: IEC 80000-13:2008 gibibyte/second */
812 _("%u.%2.2u GiB/s"),
813 (unsigned)(bytes >> 30),
814 (unsigned)(bytes & ((1 << 30) - 1)) / 10737419);
815 } else if (bytes > 1 << 20) {
816 unsigned x = bytes + 5243; /* for rounding */
817 strbuf_addf(buf,
818 humanise_rate == 0 ?
819 /* TRANSLATORS: IEC 80000-13:2008 mebibyte */
820 _("%u.%2.2u MiB") :
821 /* TRANSLATORS: IEC 80000-13:2008 mebibyte/second */
822 _("%u.%2.2u MiB/s"),
823 x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
824 } else if (bytes > 1 << 10) {
825 unsigned x = bytes + 5; /* for rounding */
826 strbuf_addf(buf,
827 humanise_rate == 0 ?
828 /* TRANSLATORS: IEC 80000-13:2008 kibibyte */
829 _("%u.%2.2u KiB") :
830 /* TRANSLATORS: IEC 80000-13:2008 kibibyte/second */
831 _("%u.%2.2u KiB/s"),
832 x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
833 } else {
834 strbuf_addf(buf,
835 humanise_rate == 0 ?
836 /* TRANSLATORS: IEC 80000-13:2008 byte */
837 Q_("%u byte", "%u bytes", bytes) :
838 /* TRANSLATORS: IEC 80000-13:2008 byte/second */
839 Q_("%u byte/s", "%u bytes/s", bytes),
840 (unsigned)bytes);
844 void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
846 strbuf_humanise(buf, bytes, 0);
849 void strbuf_humanise_rate(struct strbuf *buf, off_t bytes)
851 strbuf_humanise(buf, bytes, 1);
854 int printf_ln(const char *fmt, ...)
856 int ret;
857 va_list ap;
858 va_start(ap, fmt);
859 ret = vprintf(fmt, ap);
860 va_end(ap);
861 if (ret < 0 || putchar('\n') == EOF)
862 return -1;
863 return ret + 1;
866 int fprintf_ln(FILE *fp, const char *fmt, ...)
868 int ret;
869 va_list ap;
870 va_start(ap, fmt);
871 ret = vfprintf(fp, fmt, ap);
872 va_end(ap);
873 if (ret < 0 || putc('\n', fp) == EOF)
874 return -1;
875 return ret + 1;
878 char *xstrdup_tolower(const char *string)
880 char *result;
881 size_t len, i;
883 len = strlen(string);
884 result = xmallocz(len);
885 for (i = 0; i < len; i++)
886 result[i] = tolower(string[i]);
887 return result;
890 char *xstrdup_toupper(const char *string)
892 char *result;
893 size_t len, i;
895 len = strlen(string);
896 result = xmallocz(len);
897 for (i = 0; i < len; i++)
898 result[i] = toupper(string[i]);
899 return result;
902 char *xstrvfmt(const char *fmt, va_list ap)
904 struct strbuf buf = STRBUF_INIT;
905 strbuf_vaddf(&buf, fmt, ap);
906 return strbuf_detach(&buf, NULL);
909 char *xstrfmt(const char *fmt, ...)
911 va_list ap;
912 char *ret;
914 va_start(ap, fmt);
915 ret = xstrvfmt(fmt, ap);
916 va_end(ap);
918 return ret;
921 void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
922 int tz_offset, int suppress_tz_name)
924 struct strbuf munged_fmt = STRBUF_INIT;
925 size_t hint = 128;
926 size_t len;
928 if (!*fmt)
929 return;
932 * There is no portable way to pass timezone information to
933 * strftime, so we handle %z and %Z here. Likewise '%s', because
934 * going back to an epoch time requires knowing the zone.
936 * Note that tz_offset is in the "[-+]HHMM" decimal form; this is what
937 * we want for %z, but the computation for %s has to convert to number
938 * of seconds.
940 while (strbuf_expand_step(&munged_fmt, &fmt)) {
941 switch (*fmt) {
942 case '%':
943 strbuf_addstr(&munged_fmt, "%%");
944 fmt++;
945 break;
946 case 's':
947 strbuf_addf(&munged_fmt, "%"PRItime,
948 (timestamp_t)tm_to_time_t(tm) -
949 3600 * (tz_offset / 100) -
950 60 * (tz_offset % 100));
951 fmt++;
952 break;
953 case 'z':
954 strbuf_addf(&munged_fmt, "%+05d", tz_offset);
955 fmt++;
956 break;
957 case 'Z':
958 if (suppress_tz_name) {
959 fmt++;
960 break;
962 /* FALLTHROUGH */
963 default:
964 strbuf_addch(&munged_fmt, '%');
967 fmt = munged_fmt.buf;
969 strbuf_grow(sb, hint);
970 len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
972 if (!len) {
974 * strftime reports "0" if it could not fit the result in the buffer.
975 * Unfortunately, it also reports "0" if the requested time string
976 * takes 0 bytes. So our strategy is to munge the format so that the
977 * output contains at least one character, and then drop the extra
978 * character before returning.
980 strbuf_addch(&munged_fmt, ' ');
981 while (!len) {
982 hint *= 2;
983 strbuf_grow(sb, hint);
984 len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
985 munged_fmt.buf, tm);
987 len--; /* drop munged space */
989 strbuf_release(&munged_fmt);
990 strbuf_setlen(sb, sb->len + len);
994 * Returns the length of a line, without trailing spaces.
996 * If the line ends with newline, it will be removed too.
998 static size_t cleanup(char *line, size_t len)
1000 while (len) {
1001 unsigned char c = line[len - 1];
1002 if (!isspace(c))
1003 break;
1004 len--;
1007 return len;
1011 * Remove empty lines from the beginning and end
1012 * and also trailing spaces from every line.
1014 * Turn multiple consecutive empty lines between paragraphs
1015 * into just one empty line.
1017 * If the input has only empty lines and spaces,
1018 * no output will be produced.
1020 * If last line does not have a newline at the end, one is added.
1022 * Pass a non-NUL comment_line_char to skip every line starting
1023 * with it.
1025 void strbuf_stripspace(struct strbuf *sb, char comment_line_char)
1027 size_t empties = 0;
1028 size_t i, j, len, newlen;
1029 char *eol;
1031 /* We may have to add a newline. */
1032 strbuf_grow(sb, 1);
1034 for (i = j = 0; i < sb->len; i += len, j += newlen) {
1035 eol = memchr(sb->buf + i, '\n', sb->len - i);
1036 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
1038 if (comment_line_char && len &&
1039 sb->buf[i] == comment_line_char) {
1040 newlen = 0;
1041 continue;
1043 newlen = cleanup(sb->buf + i, len);
1045 /* Not just an empty line? */
1046 if (newlen) {
1047 if (empties > 0 && j > 0)
1048 sb->buf[j++] = '\n';
1049 empties = 0;
1050 memmove(sb->buf + j, sb->buf + i, newlen);
1051 sb->buf[newlen + j++] = '\n';
1052 } else {
1053 empties++;
1057 strbuf_setlen(sb, j);
1060 void strbuf_strip_file_from_path(struct strbuf *sb)
1062 char *path_sep = find_last_dir_sep(sb->buf);
1063 strbuf_setlen(sb, path_sep ? path_sep - sb->buf + 1 : 0);