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