hash.h: move some oid-related declarations from cache.h
[git/debian.git] / strbuf.c
blobbc4c2c09e6026ad46e502b14f8b181631cc0bbd3
1 #include "git-compat-util.h"
2 #include "alloc.h"
3 #include "refs.h"
4 #include "string-list.h"
5 #include "utf8.h"
6 #include "date.h"
8 int starts_with(const char *str, const char *prefix)
10 for (; ; str++, prefix++)
11 if (!*prefix)
12 return 1;
13 else if (*str != *prefix)
14 return 0;
17 int istarts_with(const char *str, const char *prefix)
19 for (; ; str++, prefix++)
20 if (!*prefix)
21 return 1;
22 else if (tolower(*str) != tolower(*prefix))
23 return 0;
26 int skip_to_optional_arg_default(const char *str, const char *prefix,
27 const char **arg, const char *def)
29 const char *p;
31 if (!skip_prefix(str, prefix, &p))
32 return 0;
34 if (!*p) {
35 if (arg)
36 *arg = def;
37 return 1;
40 if (*p != '=')
41 return 0;
43 if (arg)
44 *arg = p + 1;
45 return 1;
49 * Used as the default ->buf value, so that people can always assume
50 * buf is non NULL and ->buf is NUL terminated even for a freshly
51 * initialized strbuf.
53 char strbuf_slopbuf[1];
55 void strbuf_init(struct strbuf *sb, size_t hint)
57 struct strbuf blank = STRBUF_INIT;
58 memcpy(sb, &blank, sizeof(*sb));
59 if (hint)
60 strbuf_grow(sb, hint);
63 void strbuf_release(struct strbuf *sb)
65 if (sb->alloc) {
66 free(sb->buf);
67 strbuf_init(sb, 0);
71 char *strbuf_detach(struct strbuf *sb, size_t *sz)
73 char *res;
74 strbuf_grow(sb, 0);
75 res = sb->buf;
76 if (sz)
77 *sz = sb->len;
78 strbuf_init(sb, 0);
79 return res;
82 void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
84 strbuf_release(sb);
85 sb->buf = buf;
86 sb->len = len;
87 sb->alloc = alloc;
88 strbuf_grow(sb, 0);
89 sb->buf[sb->len] = '\0';
92 void strbuf_grow(struct strbuf *sb, size_t extra)
94 int new_buf = !sb->alloc;
95 if (unsigned_add_overflows(extra, 1) ||
96 unsigned_add_overflows(sb->len, extra + 1))
97 die("you want to use way too much memory");
98 if (new_buf)
99 sb->buf = NULL;
100 ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
101 if (new_buf)
102 sb->buf[0] = '\0';
105 void strbuf_trim(struct strbuf *sb)
107 strbuf_rtrim(sb);
108 strbuf_ltrim(sb);
111 void strbuf_rtrim(struct strbuf *sb)
113 while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
114 sb->len--;
115 sb->buf[sb->len] = '\0';
118 void strbuf_trim_trailing_dir_sep(struct strbuf *sb)
120 while (sb->len > 0 && is_dir_sep((unsigned char)sb->buf[sb->len - 1]))
121 sb->len--;
122 sb->buf[sb->len] = '\0';
125 void strbuf_trim_trailing_newline(struct strbuf *sb)
127 if (sb->len > 0 && sb->buf[sb->len - 1] == '\n') {
128 if (--sb->len > 0 && sb->buf[sb->len - 1] == '\r')
129 --sb->len;
130 sb->buf[sb->len] = '\0';
134 void strbuf_ltrim(struct strbuf *sb)
136 char *b = sb->buf;
137 while (sb->len > 0 && isspace(*b)) {
138 b++;
139 sb->len--;
141 memmove(sb->buf, b, sb->len);
142 sb->buf[sb->len] = '\0';
145 int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)
147 char *out;
148 size_t len;
150 if (same_encoding(from, to))
151 return 0;
153 out = reencode_string_len(sb->buf, sb->len, to, from, &len);
154 if (!out)
155 return -1;
157 strbuf_attach(sb, out, len, len);
158 return 0;
161 void strbuf_tolower(struct strbuf *sb)
163 char *p = sb->buf, *end = sb->buf + sb->len;
164 for (; p < end; p++)
165 *p = tolower(*p);
168 struct strbuf **strbuf_split_buf(const char *str, size_t slen,
169 int terminator, int max)
171 struct strbuf **ret = NULL;
172 size_t nr = 0, alloc = 0;
173 struct strbuf *t;
175 while (slen) {
176 int len = slen;
177 if (max <= 0 || nr + 1 < max) {
178 const char *end = memchr(str, terminator, slen);
179 if (end)
180 len = end - str + 1;
182 t = xmalloc(sizeof(struct strbuf));
183 strbuf_init(t, len);
184 strbuf_add(t, str, len);
185 ALLOC_GROW(ret, nr + 2, alloc);
186 ret[nr++] = t;
187 str += len;
188 slen -= len;
190 ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
191 ret[nr] = NULL;
192 return ret;
195 void strbuf_add_separated_string_list(struct strbuf *str,
196 const char *sep,
197 struct string_list *slist)
199 struct string_list_item *item;
200 int sep_needed = 0;
202 for_each_string_list_item(item, slist) {
203 if (sep_needed)
204 strbuf_addstr(str, sep);
205 strbuf_addstr(str, item->string);
206 sep_needed = 1;
210 void strbuf_list_free(struct strbuf **sbs)
212 struct strbuf **s = sbs;
214 if (!s)
215 return;
216 while (*s) {
217 strbuf_release(*s);
218 free(*s++);
220 free(sbs);
223 int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
225 size_t len = a->len < b->len ? a->len: b->len;
226 int cmp = memcmp(a->buf, b->buf, len);
227 if (cmp)
228 return cmp;
229 return a->len < b->len ? -1: a->len != b->len;
232 void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
233 const void *data, size_t dlen)
235 if (unsigned_add_overflows(pos, len))
236 die("you want to use way too much memory");
237 if (pos > sb->len)
238 die("`pos' is too far after the end of the buffer");
239 if (pos + len > sb->len)
240 die("`pos + len' is too far after the end of the buffer");
242 if (dlen >= len)
243 strbuf_grow(sb, dlen - len);
244 memmove(sb->buf + pos + dlen,
245 sb->buf + pos + len,
246 sb->len - pos - len);
247 memcpy(sb->buf + pos, data, dlen);
248 strbuf_setlen(sb, sb->len + dlen - len);
251 void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
253 strbuf_splice(sb, pos, 0, data, len);
256 void strbuf_vinsertf(struct strbuf *sb, size_t pos, const char *fmt, va_list ap)
258 int len, len2;
259 char save;
260 va_list cp;
262 if (pos > sb->len)
263 die("`pos' is too far after the end of the buffer");
264 va_copy(cp, ap);
265 len = vsnprintf(sb->buf + sb->len, 0, fmt, cp);
266 va_end(cp);
267 if (len < 0)
268 BUG("your vsnprintf is broken (returned %d)", len);
269 if (!len)
270 return; /* nothing to do */
271 if (unsigned_add_overflows(sb->len, len))
272 die("you want to use way too much memory");
273 strbuf_grow(sb, len);
274 memmove(sb->buf + pos + len, sb->buf + pos, sb->len - pos);
275 /* vsnprintf() will append a NUL, overwriting one of our characters */
276 save = sb->buf[pos + len];
277 len2 = vsnprintf(sb->buf + pos, len + 1, fmt, ap);
278 sb->buf[pos + len] = save;
279 if (len2 != len)
280 BUG("your vsnprintf is broken (returns inconsistent lengths)");
281 strbuf_setlen(sb, sb->len + len);
284 void strbuf_insertf(struct strbuf *sb, size_t pos, const char *fmt, ...)
286 va_list ap;
287 va_start(ap, fmt);
288 strbuf_vinsertf(sb, pos, fmt, ap);
289 va_end(ap);
292 void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
294 strbuf_splice(sb, pos, len, "", 0);
297 void strbuf_add(struct strbuf *sb, const void *data, size_t len)
299 strbuf_grow(sb, len);
300 memcpy(sb->buf + sb->len, data, len);
301 strbuf_setlen(sb, sb->len + len);
304 void strbuf_addbuf(struct strbuf *sb, const struct strbuf *sb2)
306 strbuf_grow(sb, sb2->len);
307 memcpy(sb->buf + sb->len, sb2->buf, sb2->len);
308 strbuf_setlen(sb, sb->len + sb2->len);
311 const char *strbuf_join_argv(struct strbuf *buf,
312 int argc, const char **argv, char delim)
314 if (!argc)
315 return buf->buf;
317 strbuf_addstr(buf, *argv);
318 while (--argc) {
319 strbuf_addch(buf, delim);
320 strbuf_addstr(buf, *(++argv));
323 return buf->buf;
326 void strbuf_addchars(struct strbuf *sb, int c, size_t n)
328 strbuf_grow(sb, n);
329 memset(sb->buf + sb->len, c, n);
330 strbuf_setlen(sb, sb->len + n);
333 void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
335 va_list ap;
336 va_start(ap, fmt);
337 strbuf_vaddf(sb, fmt, ap);
338 va_end(ap);
341 static void add_lines(struct strbuf *out,
342 const char *prefix1,
343 const char *prefix2,
344 const char *buf, size_t size)
346 while (size) {
347 const char *prefix;
348 const char *next = memchr(buf, '\n', size);
349 next = next ? (next + 1) : (buf + size);
351 prefix = ((prefix2 && (buf[0] == '\n' || buf[0] == '\t'))
352 ? prefix2 : prefix1);
353 strbuf_addstr(out, prefix);
354 strbuf_add(out, buf, next - buf);
355 size -= next - buf;
356 buf = next;
358 strbuf_complete_line(out);
361 void strbuf_add_commented_lines(struct strbuf *out, const char *buf, size_t size)
363 static char prefix1[3];
364 static char prefix2[2];
366 if (prefix1[0] != comment_line_char) {
367 xsnprintf(prefix1, sizeof(prefix1), "%c ", comment_line_char);
368 xsnprintf(prefix2, sizeof(prefix2), "%c", comment_line_char);
370 add_lines(out, prefix1, prefix2, buf, size);
373 void strbuf_commented_addf(struct strbuf *sb, const char *fmt, ...)
375 va_list params;
376 struct strbuf buf = STRBUF_INIT;
377 int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';
379 va_start(params, fmt);
380 strbuf_vaddf(&buf, fmt, params);
381 va_end(params);
383 strbuf_add_commented_lines(sb, buf.buf, buf.len);
384 if (incomplete_line)
385 sb->buf[--sb->len] = '\0';
387 strbuf_release(&buf);
390 void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
392 int len;
393 va_list cp;
395 if (!strbuf_avail(sb))
396 strbuf_grow(sb, 64);
397 va_copy(cp, ap);
398 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
399 va_end(cp);
400 if (len < 0)
401 BUG("your vsnprintf is broken (returned %d)", len);
402 if (len > strbuf_avail(sb)) {
403 strbuf_grow(sb, len);
404 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
405 if (len > strbuf_avail(sb))
406 BUG("your vsnprintf is broken (insatiable)");
408 strbuf_setlen(sb, sb->len + len);
411 void strbuf_expand(struct strbuf *sb, const char *format, expand_fn_t fn,
412 void *context)
414 for (;;) {
415 const char *percent;
416 size_t consumed;
418 percent = strchrnul(format, '%');
419 strbuf_add(sb, format, percent - format);
420 if (!*percent)
421 break;
422 format = percent + 1;
424 if (*format == '%') {
425 strbuf_addch(sb, '%');
426 format++;
427 continue;
430 consumed = fn(sb, format, context);
431 if (consumed)
432 format += consumed;
433 else
434 strbuf_addch(sb, '%');
438 size_t strbuf_expand_literal_cb(struct strbuf *sb,
439 const char *placeholder,
440 void *context UNUSED)
442 int ch;
444 switch (placeholder[0]) {
445 case 'n': /* newline */
446 strbuf_addch(sb, '\n');
447 return 1;
448 case 'x':
449 /* %x00 == NUL, %x0a == LF, etc. */
450 ch = hex2chr(placeholder + 1);
451 if (ch < 0)
452 return 0;
453 strbuf_addch(sb, ch);
454 return 3;
456 return 0;
459 size_t strbuf_expand_dict_cb(struct strbuf *sb, const char *placeholder,
460 void *context)
462 struct strbuf_expand_dict_entry *e = context;
463 size_t len;
465 for (; e->placeholder && (len = strlen(e->placeholder)); e++) {
466 if (!strncmp(placeholder, e->placeholder, len)) {
467 if (e->value)
468 strbuf_addstr(sb, e->value);
469 return len;
472 return 0;
475 void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
477 size_t i, len = src->len;
479 for (i = 0; i < len; i++) {
480 if (src->buf[i] == '%')
481 strbuf_addch(dst, '%');
482 strbuf_addch(dst, src->buf[i]);
486 #define URL_UNSAFE_CHARS " <>\"%{}|\\^`:?#[]@!$&'()*+,;="
488 void strbuf_add_percentencode(struct strbuf *dst, const char *src, int flags)
490 size_t i, len = strlen(src);
492 for (i = 0; i < len; i++) {
493 unsigned char ch = src[i];
494 if (ch <= 0x1F || ch >= 0x7F ||
495 (ch == '/' && (flags & STRBUF_ENCODE_SLASH)) ||
496 strchr(URL_UNSAFE_CHARS, ch))
497 strbuf_addf(dst, "%%%02X", (unsigned char)ch);
498 else
499 strbuf_addch(dst, ch);
503 size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
505 size_t res;
506 size_t oldalloc = sb->alloc;
508 strbuf_grow(sb, size);
509 res = fread(sb->buf + sb->len, 1, size, f);
510 if (res > 0)
511 strbuf_setlen(sb, sb->len + res);
512 else if (oldalloc == 0)
513 strbuf_release(sb);
514 return res;
517 ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
519 size_t oldlen = sb->len;
520 size_t oldalloc = sb->alloc;
522 strbuf_grow(sb, hint ? hint : 8192);
523 for (;;) {
524 ssize_t want = sb->alloc - sb->len - 1;
525 ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
527 if (got < 0) {
528 if (oldalloc == 0)
529 strbuf_release(sb);
530 else
531 strbuf_setlen(sb, oldlen);
532 return -1;
534 sb->len += got;
535 if (got < want)
536 break;
537 strbuf_grow(sb, 8192);
540 sb->buf[sb->len] = '\0';
541 return sb->len - oldlen;
544 ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
546 size_t oldalloc = sb->alloc;
547 ssize_t cnt;
549 strbuf_grow(sb, hint ? hint : 8192);
550 cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
551 if (cnt > 0)
552 strbuf_setlen(sb, sb->len + cnt);
553 else if (oldalloc == 0)
554 strbuf_release(sb);
555 return cnt;
558 ssize_t strbuf_write(struct strbuf *sb, FILE *f)
560 return sb->len ? fwrite(sb->buf, 1, sb->len, f) : 0;
563 #define STRBUF_MAXLINK (2*PATH_MAX)
565 int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
567 size_t oldalloc = sb->alloc;
569 if (hint < 32)
570 hint = 32;
572 while (hint < STRBUF_MAXLINK) {
573 ssize_t len;
575 strbuf_grow(sb, hint);
576 len = readlink(path, sb->buf, hint);
577 if (len < 0) {
578 if (errno != ERANGE)
579 break;
580 } else if (len < hint) {
581 strbuf_setlen(sb, len);
582 return 0;
585 /* .. the buffer was too small - try again */
586 hint *= 2;
588 if (oldalloc == 0)
589 strbuf_release(sb);
590 return -1;
593 int strbuf_getcwd(struct strbuf *sb)
595 size_t oldalloc = sb->alloc;
596 size_t guessed_len = 128;
598 for (;; guessed_len *= 2) {
599 strbuf_grow(sb, guessed_len);
600 if (getcwd(sb->buf, sb->alloc)) {
601 strbuf_setlen(sb, strlen(sb->buf));
602 return 0;
606 * If getcwd(3) is implemented as a syscall that falls
607 * back to a regular lookup using readdir(3) etc. then
608 * we may be able to avoid EACCES by providing enough
609 * space to the syscall as it's not necessarily bound
610 * to the same restrictions as the fallback.
612 if (errno == EACCES && guessed_len < PATH_MAX)
613 continue;
615 if (errno != ERANGE)
616 break;
618 if (oldalloc == 0)
619 strbuf_release(sb);
620 else
621 strbuf_reset(sb);
622 return -1;
625 #ifdef HAVE_GETDELIM
626 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
628 ssize_t r;
630 if (feof(fp))
631 return EOF;
633 strbuf_reset(sb);
635 /* Translate slopbuf to NULL, as we cannot call realloc on it */
636 if (!sb->alloc)
637 sb->buf = NULL;
638 errno = 0;
639 r = getdelim(&sb->buf, &sb->alloc, term, fp);
641 if (r > 0) {
642 sb->len = r;
643 return 0;
645 assert(r == -1);
648 * Normally we would have called xrealloc, which will try to free
649 * memory and recover. But we have no way to tell getdelim() to do so.
650 * Worse, we cannot try to recover ENOMEM ourselves, because we have
651 * no idea how many bytes were read by getdelim.
653 * Dying here is reasonable. It mirrors what xrealloc would do on
654 * catastrophic memory failure. We skip the opportunity to free pack
655 * memory and retry, but that's unlikely to help for a malloc small
656 * enough to hold a single line of input, anyway.
658 if (errno == ENOMEM)
659 die("Out of memory, getdelim failed");
662 * Restore strbuf invariants; if getdelim left us with a NULL pointer,
663 * we can just re-init, but otherwise we should make sure that our
664 * length is empty, and that the result is NUL-terminated.
666 if (!sb->buf)
667 strbuf_init(sb, 0);
668 else
669 strbuf_reset(sb);
670 return EOF;
672 #else
673 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
675 int ch;
677 if (feof(fp))
678 return EOF;
680 strbuf_reset(sb);
681 flockfile(fp);
682 while ((ch = getc_unlocked(fp)) != EOF) {
683 if (!strbuf_avail(sb))
684 strbuf_grow(sb, 1);
685 sb->buf[sb->len++] = ch;
686 if (ch == term)
687 break;
689 funlockfile(fp);
690 if (ch == EOF && sb->len == 0)
691 return EOF;
693 sb->buf[sb->len] = '\0';
694 return 0;
696 #endif
698 int strbuf_appendwholeline(struct strbuf *sb, FILE *fp, int term)
700 struct strbuf line = STRBUF_INIT;
701 if (strbuf_getwholeline(&line, fp, term))
702 return EOF;
703 strbuf_addbuf(sb, &line);
704 strbuf_release(&line);
705 return 0;
708 static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)
710 if (strbuf_getwholeline(sb, fp, term))
711 return EOF;
712 if (sb->buf[sb->len - 1] == term)
713 strbuf_setlen(sb, sb->len - 1);
714 return 0;
717 int strbuf_getline(struct strbuf *sb, FILE *fp)
719 if (strbuf_getwholeline(sb, fp, '\n'))
720 return EOF;
721 if (sb->buf[sb->len - 1] == '\n') {
722 strbuf_setlen(sb, sb->len - 1);
723 if (sb->len && sb->buf[sb->len - 1] == '\r')
724 strbuf_setlen(sb, sb->len - 1);
726 return 0;
729 int strbuf_getline_lf(struct strbuf *sb, FILE *fp)
731 return strbuf_getdelim(sb, fp, '\n');
734 int strbuf_getline_nul(struct strbuf *sb, FILE *fp)
736 return strbuf_getdelim(sb, fp, '\0');
739 int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
741 strbuf_reset(sb);
743 while (1) {
744 char ch;
745 ssize_t len = xread(fd, &ch, 1);
746 if (len <= 0)
747 return EOF;
748 strbuf_addch(sb, ch);
749 if (ch == term)
750 break;
752 return 0;
755 ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
757 int fd;
758 ssize_t len;
759 int saved_errno;
761 fd = open(path, O_RDONLY);
762 if (fd < 0)
763 return -1;
764 len = strbuf_read(sb, fd, hint);
765 saved_errno = errno;
766 close(fd);
767 if (len < 0) {
768 errno = saved_errno;
769 return -1;
772 return len;
775 void strbuf_add_lines(struct strbuf *out, const char *prefix,
776 const char *buf, size_t size)
778 add_lines(out, prefix, NULL, buf, size);
781 void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
783 while (*s) {
784 size_t len = strcspn(s, "\"<>&");
785 strbuf_add(buf, s, len);
786 s += len;
787 switch (*s) {
788 case '"':
789 strbuf_addstr(buf, "&quot;");
790 break;
791 case '<':
792 strbuf_addstr(buf, "&lt;");
793 break;
794 case '>':
795 strbuf_addstr(buf, "&gt;");
796 break;
797 case '&':
798 strbuf_addstr(buf, "&amp;");
799 break;
800 case 0:
801 return;
803 s++;
807 int is_rfc3986_reserved_or_unreserved(char ch)
809 if (is_rfc3986_unreserved(ch))
810 return 1;
811 switch (ch) {
812 case '!': case '*': case '\'': case '(': case ')': case ';':
813 case ':': case '@': case '&': case '=': case '+': case '$':
814 case ',': case '/': case '?': case '#': case '[': case ']':
815 return 1;
817 return 0;
820 int is_rfc3986_unreserved(char ch)
822 return isalnum(ch) ||
823 ch == '-' || ch == '_' || ch == '.' || ch == '~';
826 static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
827 char_predicate allow_unencoded_fn)
829 strbuf_grow(sb, len);
830 while (len--) {
831 char ch = *s++;
832 if (allow_unencoded_fn(ch))
833 strbuf_addch(sb, ch);
834 else
835 strbuf_addf(sb, "%%%02x", (unsigned char)ch);
839 void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
840 char_predicate allow_unencoded_fn)
842 strbuf_add_urlencode(sb, s, strlen(s), allow_unencoded_fn);
845 static void strbuf_humanise(struct strbuf *buf, off_t bytes,
846 int humanise_rate)
848 if (bytes > 1 << 30) {
849 strbuf_addf(buf,
850 humanise_rate == 0 ?
851 /* TRANSLATORS: IEC 80000-13:2008 gibibyte */
852 _("%u.%2.2u GiB") :
853 /* TRANSLATORS: IEC 80000-13:2008 gibibyte/second */
854 _("%u.%2.2u GiB/s"),
855 (unsigned)(bytes >> 30),
856 (unsigned)(bytes & ((1 << 30) - 1)) / 10737419);
857 } else if (bytes > 1 << 20) {
858 unsigned x = bytes + 5243; /* for rounding */
859 strbuf_addf(buf,
860 humanise_rate == 0 ?
861 /* TRANSLATORS: IEC 80000-13:2008 mebibyte */
862 _("%u.%2.2u MiB") :
863 /* TRANSLATORS: IEC 80000-13:2008 mebibyte/second */
864 _("%u.%2.2u MiB/s"),
865 x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
866 } else if (bytes > 1 << 10) {
867 unsigned x = bytes + 5; /* for rounding */
868 strbuf_addf(buf,
869 humanise_rate == 0 ?
870 /* TRANSLATORS: IEC 80000-13:2008 kibibyte */
871 _("%u.%2.2u KiB") :
872 /* TRANSLATORS: IEC 80000-13:2008 kibibyte/second */
873 _("%u.%2.2u KiB/s"),
874 x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
875 } else {
876 strbuf_addf(buf,
877 humanise_rate == 0 ?
878 /* TRANSLATORS: IEC 80000-13:2008 byte */
879 Q_("%u byte", "%u bytes", bytes) :
880 /* TRANSLATORS: IEC 80000-13:2008 byte/second */
881 Q_("%u byte/s", "%u bytes/s", bytes),
882 (unsigned)bytes);
886 void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
888 strbuf_humanise(buf, bytes, 0);
891 void strbuf_humanise_rate(struct strbuf *buf, off_t bytes)
893 strbuf_humanise(buf, bytes, 1);
896 void strbuf_add_absolute_path(struct strbuf *sb, const char *path)
898 if (!*path)
899 die("The empty string is not a valid path");
900 if (!is_absolute_path(path)) {
901 struct stat cwd_stat, pwd_stat;
902 size_t orig_len = sb->len;
903 char *cwd = xgetcwd();
904 char *pwd = getenv("PWD");
905 if (pwd && strcmp(pwd, cwd) &&
906 !stat(cwd, &cwd_stat) &&
907 (cwd_stat.st_dev || cwd_stat.st_ino) &&
908 !stat(pwd, &pwd_stat) &&
909 pwd_stat.st_dev == cwd_stat.st_dev &&
910 pwd_stat.st_ino == cwd_stat.st_ino)
911 strbuf_addstr(sb, pwd);
912 else
913 strbuf_addstr(sb, cwd);
914 if (sb->len > orig_len && !is_dir_sep(sb->buf[sb->len - 1]))
915 strbuf_addch(sb, '/');
916 free(cwd);
918 strbuf_addstr(sb, path);
921 void strbuf_add_real_path(struct strbuf *sb, const char *path)
923 if (sb->len) {
924 struct strbuf resolved = STRBUF_INIT;
925 strbuf_realpath(&resolved, path, 1);
926 strbuf_addbuf(sb, &resolved);
927 strbuf_release(&resolved);
928 } else
929 strbuf_realpath(sb, path, 1);
932 int printf_ln(const char *fmt, ...)
934 int ret;
935 va_list ap;
936 va_start(ap, fmt);
937 ret = vprintf(fmt, ap);
938 va_end(ap);
939 if (ret < 0 || putchar('\n') == EOF)
940 return -1;
941 return ret + 1;
944 int fprintf_ln(FILE *fp, const char *fmt, ...)
946 int ret;
947 va_list ap;
948 va_start(ap, fmt);
949 ret = vfprintf(fp, fmt, ap);
950 va_end(ap);
951 if (ret < 0 || putc('\n', fp) == EOF)
952 return -1;
953 return ret + 1;
956 char *xstrdup_tolower(const char *string)
958 char *result;
959 size_t len, i;
961 len = strlen(string);
962 result = xmallocz(len);
963 for (i = 0; i < len; i++)
964 result[i] = tolower(string[i]);
965 return result;
968 char *xstrdup_toupper(const char *string)
970 char *result;
971 size_t len, i;
973 len = strlen(string);
974 result = xmallocz(len);
975 for (i = 0; i < len; i++)
976 result[i] = toupper(string[i]);
977 return result;
980 char *xstrvfmt(const char *fmt, va_list ap)
982 struct strbuf buf = STRBUF_INIT;
983 strbuf_vaddf(&buf, fmt, ap);
984 return strbuf_detach(&buf, NULL);
987 char *xstrfmt(const char *fmt, ...)
989 va_list ap;
990 char *ret;
992 va_start(ap, fmt);
993 ret = xstrvfmt(fmt, ap);
994 va_end(ap);
996 return ret;
999 void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
1000 int tz_offset, int suppress_tz_name)
1002 struct strbuf munged_fmt = STRBUF_INIT;
1003 size_t hint = 128;
1004 size_t len;
1006 if (!*fmt)
1007 return;
1010 * There is no portable way to pass timezone information to
1011 * strftime, so we handle %z and %Z here. Likewise '%s', because
1012 * going back to an epoch time requires knowing the zone.
1014 * Note that tz_offset is in the "[-+]HHMM" decimal form; this is what
1015 * we want for %z, but the computation for %s has to convert to number
1016 * of seconds.
1018 for (;;) {
1019 const char *percent = strchrnul(fmt, '%');
1020 strbuf_add(&munged_fmt, fmt, percent - fmt);
1021 if (!*percent)
1022 break;
1023 fmt = percent + 1;
1024 switch (*fmt) {
1025 case '%':
1026 strbuf_addstr(&munged_fmt, "%%");
1027 fmt++;
1028 break;
1029 case 's':
1030 strbuf_addf(&munged_fmt, "%"PRItime,
1031 (timestamp_t)tm_to_time_t(tm) -
1032 3600 * (tz_offset / 100) -
1033 60 * (tz_offset % 100));
1034 fmt++;
1035 break;
1036 case 'z':
1037 strbuf_addf(&munged_fmt, "%+05d", tz_offset);
1038 fmt++;
1039 break;
1040 case 'Z':
1041 if (suppress_tz_name) {
1042 fmt++;
1043 break;
1045 /* FALLTHROUGH */
1046 default:
1047 strbuf_addch(&munged_fmt, '%');
1050 fmt = munged_fmt.buf;
1052 strbuf_grow(sb, hint);
1053 len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
1055 if (!len) {
1057 * strftime reports "0" if it could not fit the result in the buffer.
1058 * Unfortunately, it also reports "0" if the requested time string
1059 * takes 0 bytes. So our strategy is to munge the format so that the
1060 * output contains at least one character, and then drop the extra
1061 * character before returning.
1063 strbuf_addch(&munged_fmt, ' ');
1064 while (!len) {
1065 hint *= 2;
1066 strbuf_grow(sb, hint);
1067 len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
1068 munged_fmt.buf, tm);
1070 len--; /* drop munged space */
1072 strbuf_release(&munged_fmt);
1073 strbuf_setlen(sb, sb->len + len);
1076 void strbuf_repo_add_unique_abbrev(struct strbuf *sb, struct repository *repo,
1077 const struct object_id *oid, int abbrev_len)
1079 int r;
1080 strbuf_grow(sb, GIT_MAX_HEXSZ + 1);
1081 r = repo_find_unique_abbrev_r(repo, sb->buf + sb->len, oid, abbrev_len);
1082 strbuf_setlen(sb, sb->len + r);
1085 void strbuf_add_unique_abbrev(struct strbuf *sb, const struct object_id *oid,
1086 int abbrev_len)
1088 strbuf_repo_add_unique_abbrev(sb, the_repository, oid, abbrev_len);
1092 * Returns the length of a line, without trailing spaces.
1094 * If the line ends with newline, it will be removed too.
1096 static size_t cleanup(char *line, size_t len)
1098 while (len) {
1099 unsigned char c = line[len - 1];
1100 if (!isspace(c))
1101 break;
1102 len--;
1105 return len;
1109 * Remove empty lines from the beginning and end
1110 * and also trailing spaces from every line.
1112 * Turn multiple consecutive empty lines between paragraphs
1113 * into just one empty line.
1115 * If the input has only empty lines and spaces,
1116 * no output will be produced.
1118 * If last line does not have a newline at the end, one is added.
1120 * Enable skip_comments to skip every line starting with comment
1121 * character.
1123 void strbuf_stripspace(struct strbuf *sb, int skip_comments)
1125 size_t empties = 0;
1126 size_t i, j, len, newlen;
1127 char *eol;
1129 /* We may have to add a newline. */
1130 strbuf_grow(sb, 1);
1132 for (i = j = 0; i < sb->len; i += len, j += newlen) {
1133 eol = memchr(sb->buf + i, '\n', sb->len - i);
1134 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
1136 if (skip_comments && len && sb->buf[i] == comment_line_char) {
1137 newlen = 0;
1138 continue;
1140 newlen = cleanup(sb->buf + i, len);
1142 /* Not just an empty line? */
1143 if (newlen) {
1144 if (empties > 0 && j > 0)
1145 sb->buf[j++] = '\n';
1146 empties = 0;
1147 memmove(sb->buf + j, sb->buf + i, newlen);
1148 sb->buf[newlen + j++] = '\n';
1149 } else {
1150 empties++;
1154 strbuf_setlen(sb, j);
1157 int strbuf_normalize_path(struct strbuf *src)
1159 struct strbuf dst = STRBUF_INIT;
1161 strbuf_grow(&dst, src->len);
1162 if (normalize_path_copy(dst.buf, src->buf) < 0) {
1163 strbuf_release(&dst);
1164 return -1;
1168 * normalize_path does not tell us the new length, so we have to
1169 * compute it by looking for the new NUL it placed
1171 strbuf_setlen(&dst, strlen(dst.buf));
1172 strbuf_swap(src, &dst);
1173 strbuf_release(&dst);
1174 return 0;
1177 int strbuf_edit_interactively(struct strbuf *buffer, const char *path,
1178 const char *const *env)
1180 char *path2 = NULL;
1181 int fd, res = 0;
1183 if (!is_absolute_path(path))
1184 path = path2 = xstrdup(git_path("%s", path));
1186 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
1187 if (fd < 0)
1188 res = error_errno(_("could not open '%s' for writing"), path);
1189 else if (write_in_full(fd, buffer->buf, buffer->len) < 0) {
1190 res = error_errno(_("could not write to '%s'"), path);
1191 close(fd);
1192 } else if (close(fd) < 0)
1193 res = error_errno(_("could not close '%s'"), path);
1194 else {
1195 strbuf_reset(buffer);
1196 if (launch_editor(path, buffer, env) < 0)
1197 res = error_errno(_("could not edit '%s'"), path);
1198 unlink(path);
1201 free(path2);
1202 return res;
1205 void strbuf_strip_file_from_path(struct strbuf *sb)
1207 char *path_sep = find_last_dir_sep(sb->buf);
1208 strbuf_setlen(sb, path_sep ? path_sep - sb->buf + 1 : 0);