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