]> git.ipfire.org Git - thirdparty/git.git/blame - strbuf.c
strbuf: accept a comment string for strbuf_commented_addf()
[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
afaef55e
CC
27int 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
b315c5c0
PH
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 */
54char strbuf_slopbuf[1];
55
917c9a71
PH
56void strbuf_init(struct strbuf *sb, size_t hint)
57{
5726a6b4
ÆAB
58 struct strbuf blank = STRBUF_INIT;
59 memcpy(sb, &blank, sizeof(*sb));
8c74ef1e 60 if (hint)
f1696ee3 61 strbuf_grow(sb, hint);
d1df5743
JH
62}
63
917c9a71
PH
64void strbuf_release(struct strbuf *sb)
65{
b315c5c0
PH
66 if (sb->alloc) {
67 free(sb->buf);
68 strbuf_init(sb, 0);
69 }
b449f4cf
PH
70}
71
b315c5c0 72char *strbuf_detach(struct strbuf *sb, size_t *sz)
917c9a71 73{
08ad56f3
JK
74 char *res;
75 strbuf_grow(sb, 0);
76 res = sb->buf;
b315c5c0
PH
77 if (sz)
78 *sz = sb->len;
f1696ee3 79 strbuf_init(sb, 0);
b449f4cf
PH
80 return res;
81}
82
917c9a71
PH
83void 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
93void strbuf_grow(struct strbuf *sb, size_t extra)
94{
8c74ef1e 95 int new_buf = !sb->alloc;
1368f650
JN
96 if (unsigned_add_overflows(extra, 1) ||
97 unsigned_add_overflows(sb->len, extra + 1))
b449f4cf 98 die("you want to use way too much memory");
8c74ef1e 99 if (new_buf)
b315c5c0 100 sb->buf = NULL;
b449f4cf 101 ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
8c74ef1e
TR
102 if (new_buf)
103 sb->buf[0] = '\0';
b449f4cf
PH
104}
105
eacd6dc5
LS
106void strbuf_trim(struct strbuf *sb)
107{
3bb55e8a
BG
108 strbuf_rtrim(sb);
109 strbuf_ltrim(sb);
eacd6dc5 110}
c64a8d20 111
f1696ee3
PH
112void 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
c64a8d20
NTND
119void 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
f9573628
PK
126void 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
eacd6dc5
LS
135void 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
d4241f52
JK
146int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)
147{
148 char *out;
c7d017d7 149 size_t len;
d4241f52
JK
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
ffb20ce1
JK
162void 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
17b73dc6
MH
169struct strbuf **strbuf_split_buf(const char *str, size_t slen,
170 int terminator, int max)
eacd6dc5 171{
b8c2c1fa
MH
172 struct strbuf **ret = NULL;
173 size_t nr = 0, alloc = 0;
eacd6dc5
LS
174 struct strbuf *t;
175
1173bb33
MH
176 while (slen) {
177 int len = slen;
178 if (max <= 0 || nr + 1 < max) {
17b73dc6 179 const char *end = memchr(str, terminator, slen);
1173bb33
MH
180 if (end)
181 len = end - str + 1;
182 }
eacd6dc5
LS
183 t = xmalloc(sizeof(struct strbuf));
184 strbuf_init(t, len);
1173bb33 185 strbuf_add(t, str, len);
b8c2c1fa
MH
186 ALLOC_GROW(ret, nr + 2, alloc);
187 ret[nr++] = t;
1173bb33
MH
188 str += len;
189 slen -= len;
eacd6dc5 190 }
b8c2c1fa
MH
191 ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
192 ret[nr] = NULL;
eacd6dc5
LS
193 return ret;
194}
195
f6f77559
EN
196void 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
eacd6dc5
LS
211void strbuf_list_free(struct strbuf **sbs)
212{
213 struct strbuf **s = sbs;
214
f3a96807
AH
215 if (!s)
216 return;
eacd6dc5
LS
217 while (*s) {
218 strbuf_release(*s);
219 free(*s++);
220 }
221 free(sbs);
222}
223
9b200fd6 224int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
45f66f64 225{
26114c00 226 size_t len = a->len < b->len ? a->len: b->len;
8f024655
AR
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;
45f66f64
PH
231}
232
917c9a71
PH
233void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
234 const void *data, size_t dlen)
235{
1368f650 236 if (unsigned_add_overflows(pos, len))
917c9a71
PH
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
c76689df
PH
252void 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
5ef264db
PSU
257void 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
285void 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
c76689df
PH
293void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
294{
a8342a41 295 strbuf_splice(sb, pos, len, "", 0);
c76689df
PH
296}
297
917c9a71
PH
298void strbuf_add(struct strbuf *sb, const void *data, size_t len)
299{
b449f4cf
PH
300 strbuf_grow(sb, len);
301 memcpy(sb->buf + sb->len, data, len);
302 strbuf_setlen(sb, sb->len + len);
303}
304
31471ba2
RS
305void 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
e71c4a88
PSU
312const 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
d07235a0
RS
327void 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
917c9a71
PH
334void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
335{
b449f4cf 336 va_list ap;
ebeb6090
JK
337 va_start(ap, fmt);
338 strbuf_vaddf(sb, fmt, ap);
339 va_end(ap);
340}
341
eff80a9f 342static void add_lines(struct strbuf *out,
db7f9309
JK
343 const char *prefix,
344 const char *buf, size_t size,
345 int space_after_prefix)
eff80a9f
JH
346{
347 while (size) {
eff80a9f
JH
348 const char *next = memchr(buf, '\n', size);
349 next = next ? (next + 1) : (buf + size);
350
eff80a9f 351 strbuf_addstr(out, prefix);
db7f9309
JK
352 if (space_after_prefix && buf[0] != '\n' && buf[0] != '\t')
353 strbuf_addch(out, ' ');
eff80a9f
JH
354 strbuf_add(out, buf, next - buf);
355 size -= next - buf;
356 buf = next;
357 }
358 strbuf_complete_line(out);
359}
360
787cb8a4 361void strbuf_add_commented_lines(struct strbuf *out, const char *buf,
2786d058 362 size_t size, char comment_prefix)
eff80a9f 363{
3b45450d 364 char prefix[2];
eff80a9f 365
2786d058 366 prefix[0] = comment_prefix;
3b45450d 367 prefix[1] = '\0';
db7f9309 368 add_lines(out, prefix, buf, size, 1);
eff80a9f
JH
369}
370
3a35d962 371void strbuf_commented_addf(struct strbuf *sb, const char *comment_prefix,
787cb8a4 372 const char *fmt, ...)
eff80a9f
JH
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
3a35d962
JK
382 /*
383 * TODO Our commented_lines helper does not yet understand
384 * comment strings. But since we know that the strings are
385 * always single-char, we can cheat for the moment, and
386 * fix this later.
387 */
388 strbuf_add_commented_lines(sb, buf.buf, buf.len, comment_prefix[0]);
eff80a9f
JH
389 if (incomplete_line)
390 sb->buf[--sb->len] = '\0';
391
392 strbuf_release(&buf);
393}
394
ebeb6090
JK
395void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
396{
397 int len;
398 va_list cp;
b449f4cf 399
f141bd80
SP
400 if (!strbuf_avail(sb))
401 strbuf_grow(sb, 64);
ebeb6090
JK
402 va_copy(cp, ap);
403 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
404 va_end(cp);
f141bd80 405 if (len < 0)
033abf97 406 BUG("your vsnprintf is broken (returned %d)", len);
f1696ee3 407 if (len > strbuf_avail(sb)) {
b449f4cf 408 strbuf_grow(sb, len);
b449f4cf 409 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
ebeb6090 410 if (len > strbuf_avail(sb))
033abf97 411 BUG("your vsnprintf is broken (insatiable)");
b449f4cf
PH
412 }
413 strbuf_setlen(sb, sb->len + len);
d1df5743
JH
414}
415
44ccb337 416int strbuf_expand_step(struct strbuf *sb, const char **formatp)
cde75e59 417{
44ccb337
RS
418 const char *format = *formatp;
419 const char *percent = strchrnul(format, '%');
0a0416a3 420
44ccb337
RS
421 strbuf_add(sb, format, percent - format);
422 if (!*percent)
423 return 0;
424 *formatp = percent + 1;
425 return 1;
cde75e59
RS
426}
427
4416b86c 428size_t strbuf_expand_literal(struct strbuf *sb, const char *placeholder)
fd2015b3
AW
429{
430 int ch;
431
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;
443 }
444 return 0;
445}
446
361df5df
JK
447void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
448{
26114c00 449 size_t i, len = src->len;
361df5df
JK
450
451 for (i = 0; i < len; i++) {
452 if (src->buf[i] == '%')
453 strbuf_addch(dst, '%');
454 strbuf_addch(dst, src->buf[i]);
455 }
456}
457
b44d0118 458#define URL_UNSAFE_CHARS " <>\"%{}|\\^`:?#[]@!$&'()*+,;="
46fd7b39 459
b44d0118 460void strbuf_add_percentencode(struct strbuf *dst, const char *src, int flags)
46fd7b39 461{
462 size_t i, len = strlen(src);
463
464 for (i = 0; i < len; i++) {
465 unsigned char ch = src[i];
b44d0118 466 if (ch <= 0x1F || ch >= 0x7F ||
467 (ch == '/' && (flags & STRBUF_ENCODE_SLASH)) ||
468 strchr(URL_UNSAFE_CHARS, ch))
46fd7b39 469 strbuf_addf(dst, "%%%02X", (unsigned char)ch);
470 else
471 strbuf_addch(dst, ch);
472 }
473}
474
917c9a71
PH
475size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
476{
b449f4cf 477 size_t res;
2fc64700 478 size_t oldalloc = sb->alloc;
b449f4cf
PH
479
480 strbuf_grow(sb, size);
481 res = fread(sb->buf + sb->len, 1, size, f);
2fc64700 482 if (res > 0)
b449f4cf 483 strbuf_setlen(sb, sb->len + res);
6651c3f7 484 else if (oldalloc == 0)
2fc64700 485 strbuf_release(sb);
b449f4cf 486 return res;
d1df5743
JH
487}
488
f1696ee3 489ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
b449f4cf
PH
490{
491 size_t oldlen = sb->len;
2fc64700 492 size_t oldalloc = sb->alloc;
b449f4cf 493
f1696ee3 494 strbuf_grow(sb, hint ? hint : 8192);
b449f4cf 495 for (;;) {
3ebbd00c
JH
496 ssize_t want = sb->alloc - sb->len - 1;
497 ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
b449f4cf 498
3ebbd00c 499 if (got < 0) {
2fc64700
RS
500 if (oldalloc == 0)
501 strbuf_release(sb);
502 else
503 strbuf_setlen(sb, oldlen);
b449f4cf
PH
504 return -1;
505 }
3ebbd00c
JH
506 sb->len += got;
507 if (got < want)
b449f4cf 508 break;
f1696ee3 509 strbuf_grow(sb, 8192);
b449f4cf
PH
510 }
511
512 sb->buf[sb->len] = '\0';
513 return sb->len - oldlen;
d1df5743
JH
514}
515
b4e04fb6
SB
516ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
517{
c3ff8f6c 518 size_t oldalloc = sb->alloc;
b4e04fb6
SB
519 ssize_t cnt;
520
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);
c3ff8f6c
RS
525 else if (oldalloc == 0)
526 strbuf_release(sb);
b4e04fb6
SB
527 return cnt;
528}
529
2dac9b56
SB
530ssize_t strbuf_write(struct strbuf *sb, FILE *f)
531{
532 return sb->len ? fwrite(sb->buf, 1, sb->len, f) : 0;
533}
534
b11b7e13
LT
535#define STRBUF_MAXLINK (2*PATH_MAX)
536
537int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
538{
2fc64700
RS
539 size_t oldalloc = sb->alloc;
540
b11b7e13
LT
541 if (hint < 32)
542 hint = 32;
543
544 while (hint < STRBUF_MAXLINK) {
f3e76ed2 545 ssize_t len;
b11b7e13
LT
546
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;
555 }
556
557 /* .. the buffer was too small - try again */
558 hint *= 2;
559 }
2fc64700
RS
560 if (oldalloc == 0)
561 strbuf_release(sb);
b11b7e13
LT
562 return -1;
563}
564
f22a76e9
RS
565int strbuf_getcwd(struct strbuf *sb)
566{
567 size_t oldalloc = sb->alloc;
568 size_t guessed_len = 128;
569
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;
575 }
a54e938e
RS
576
577 /*
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.
583 */
584 if (errno == EACCES && guessed_len < PATH_MAX)
585 continue;
586
f22a76e9
RS
587 if (errno != ERANGE)
588 break;
589 }
590 if (oldalloc == 0)
591 strbuf_release(sb);
592 else
593 strbuf_reset(sb);
594 return -1;
595}
596
0cc30e0e
JK
597#ifdef HAVE_GETDELIM
598int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
599{
600 ssize_t r;
601
602 if (feof(fp))
603 return EOF;
604
605 strbuf_reset(sb);
606
607 /* Translate slopbuf to NULL, as we cannot call realloc on it */
608 if (!sb->alloc)
609 sb->buf = NULL;
642956cf 610 errno = 0;
0cc30e0e
JK
611 r = getdelim(&sb->buf, &sb->alloc, term, fp);
612
613 if (r > 0) {
614 sb->len = r;
615 return 0;
616 }
617 assert(r == -1);
618
619 /*
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.
624 *
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.
629 */
630 if (errno == ENOMEM)
631 die("Out of memory, getdelim failed");
632
b7090430
JK
633 /*
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.
637 */
0cc30e0e
JK
638 if (!sb->buf)
639 strbuf_init(sb, 0);
b7090430
JK
640 else
641 strbuf_reset(sb);
0cc30e0e
JK
642 return EOF;
643}
644#else
c7e4f0d7 645int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
917c9a71 646{
d1df5743 647 int ch;
e6c019d0 648
e6c019d0
PH
649 if (feof(fp))
650 return EOF;
b449f4cf
PH
651
652 strbuf_reset(sb);
82912d1d
JK
653 flockfile(fp);
654 while ((ch = getc_unlocked(fp)) != EOF) {
f80c153b
JK
655 if (!strbuf_avail(sb))
656 strbuf_grow(sb, 1);
b449f4cf 657 sb->buf[sb->len++] = ch;
c7e4f0d7
BC
658 if (ch == term)
659 break;
d1df5743 660 }
82912d1d 661 funlockfile(fp);
e6c019d0
PH
662 if (ch == EOF && sb->len == 0)
663 return EOF;
b449f4cf 664
b449f4cf 665 sb->buf[sb->len] = '\0';
e6c019d0 666 return 0;
d1df5743 667}
0cc30e0e 668#endif
a9390b9f 669
bd021f39
PS
670int strbuf_appendwholeline(struct strbuf *sb, FILE *fp, int term)
671{
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;
678}
679
1a0c8dfd 680static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)
c7e4f0d7
BC
681{
682 if (strbuf_getwholeline(sb, fp, term))
683 return EOF;
dce80bd1
JH
684 if (sb->buf[sb->len - 1] == term)
685 strbuf_setlen(sb, sb->len - 1);
c7e4f0d7
BC
686 return 0;
687}
688
af35e56b 689int strbuf_getdelim_strip_crlf(struct strbuf *sb, FILE *fp, int term)
c8aa9fdf 690{
af35e56b 691 if (strbuf_getwholeline(sb, fp, term))
c8aa9fdf 692 return EOF;
af35e56b 693 if (term == '\n' && sb->buf[sb->len - 1] == '\n') {
c8aa9fdf
JH
694 strbuf_setlen(sb, sb->len - 1);
695 if (sb->len && sb->buf[sb->len - 1] == '\r')
696 strbuf_setlen(sb, sb->len - 1);
697 }
698 return 0;
699}
700
af35e56b
PS
701int strbuf_getline(struct strbuf *sb, FILE *fp)
702{
703 return strbuf_getdelim_strip_crlf(sb, fp, '\n');
704}
705
8f309aeb
JH
706int strbuf_getline_lf(struct strbuf *sb, FILE *fp)
707{
1a0c8dfd 708 return strbuf_getdelim(sb, fp, '\n');
8f309aeb
JH
709}
710
711int strbuf_getline_nul(struct strbuf *sb, FILE *fp)
712{
1a0c8dfd 713 return strbuf_getdelim(sb, fp, '\0');
8f309aeb
JH
714}
715
5e8617f5
TR
716int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
717{
718 strbuf_reset(sb);
719
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;
728 }
729 return 0;
730}
731
6c8afe49 732ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
a9390b9f 733{
6c8afe49
MH
734 int fd;
735 ssize_t len;
79f0ba15 736 int saved_errno;
a9390b9f
KH
737
738 fd = open(path, O_RDONLY);
739 if (fd < 0)
740 return -1;
387e7e19 741 len = strbuf_read(sb, fd, hint);
79f0ba15 742 saved_errno = errno;
a9390b9f 743 close(fd);
79f0ba15
JK
744 if (len < 0) {
745 errno = saved_errno;
a9390b9f 746 return -1;
79f0ba15 747 }
a9390b9f
KH
748
749 return len;
750}
895680f0
JH
751
752void strbuf_add_lines(struct strbuf *out, const char *prefix,
753 const char *buf, size_t size)
754{
db7f9309 755 add_lines(out, prefix, buf, size, 0);
895680f0 756}
367d20ec 757
5963c036
MH
758void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
759{
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;
779 }
780 s++;
781 }
782}
783
ea03a8e1 784static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
c2694952 785 char_predicate allow_unencoded_fn)
c505116b
JK
786{
787 strbuf_grow(sb, len);
788 while (len--) {
789 char ch = *s++;
c2694952 790 if (allow_unencoded_fn(ch))
c505116b
JK
791 strbuf_addch(sb, ch);
792 else
4c267f2a 793 strbuf_addf(sb, "%%%02x", (unsigned char)ch);
c505116b
JK
794 }
795}
796
797void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
c2694952 798 char_predicate allow_unencoded_fn)
c505116b 799{
c2694952 800 strbuf_add_urlencode(sb, s, strlen(s), allow_unencoded_fn);
c505116b 801}
9a0a30aa 802
8f354a1f
DR
803static void strbuf_humanise(struct strbuf *buf, off_t bytes,
804 int humanise_rate)
079b546a
AP
805{
806 if (bytes > 1 << 30) {
8f354a1f
DR
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"),
7726d360
JK
813 (unsigned)(bytes >> 30),
814 (unsigned)(bytes & ((1 << 30) - 1)) / 10737419);
079b546a 815 } else if (bytes > 1 << 20) {
7726d360 816 unsigned x = bytes + 5243; /* for rounding */
8f354a1f
DR
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"),
079b546a
AP
823 x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
824 } else if (bytes > 1 << 10) {
7726d360 825 unsigned x = bytes + 5; /* for rounding */
8f354a1f
DR
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"),
079b546a
AP
832 x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
833 } else {
8f354a1f
DR
834 strbuf_addf(buf,
835 humanise_rate == 0 ?
836 /* TRANSLATORS: IEC 80000-13:2008 byte */
6f693252 837 Q_("%u byte", "%u bytes", bytes) :
8f354a1f 838 /* TRANSLATORS: IEC 80000-13:2008 byte/second */
6f693252 839 Q_("%u byte/s", "%u bytes/s", bytes),
8f354a1f 840 (unsigned)bytes);
079b546a
AP
841 }
842}
843
8f354a1f
DR
844void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
845{
846 strbuf_humanise(buf, bytes, 0);
847}
848
849void strbuf_humanise_rate(struct strbuf *buf, off_t bytes)
850{
851 strbuf_humanise(buf, bytes, 1);
852}
853
9a0a30aa
NTND
854int printf_ln(const char *fmt, ...)
855{
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;
864}
865
866int fprintf_ln(FILE *fp, const char *fmt, ...)
867{
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;
876}
88d5a6f6
JK
877
878char *xstrdup_tolower(const char *string)
879{
880 char *result;
881 size_t len, i;
882
883 len = strlen(string);
3733e694 884 result = xmallocz(len);
88d5a6f6
JK
885 for (i = 0; i < len; i++)
886 result[i] = tolower(string[i]);
88d5a6f6
JK
887 return result;
888}
30a0ddb7 889
13ecb463
LS
890char *xstrdup_toupper(const char *string)
891{
892 char *result;
893 size_t len, i;
894
895 len = strlen(string);
896 result = xmallocz(len);
897 for (i = 0; i < len; i++)
898 result[i] = toupper(string[i]);
88d5a6f6
JK
899 return result;
900}
30a0ddb7
JK
901
902char *xstrvfmt(const char *fmt, va_list ap)
903{
904 struct strbuf buf = STRBUF_INIT;
905 strbuf_vaddf(&buf, fmt, ap);
906 return strbuf_detach(&buf, NULL);
907}
908
909char *xstrfmt(const char *fmt, ...)
910{
911 va_list ap;
912 char *ret;
913
914 va_start(ap, fmt);
915 ret = xstrvfmt(fmt, ap);
916 va_end(ap);
917
918 return ret;
919}
aa1462cc 920
c3fbf81a 921void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
3b702239 922 int tz_offset, int suppress_tz_name)
aa1462cc 923{
c3fbf81a 924 struct strbuf munged_fmt = STRBUF_INIT;
e4f031e3 925 size_t hint = 128;
aa1462cc
JK
926 size_t len;
927
e4f031e3
JK
928 if (!*fmt)
929 return;
930
c3fbf81a
RS
931 /*
932 * There is no portable way to pass timezone information to
9b591b94
JK
933 * strftime, so we handle %z and %Z here. Likewise '%s', because
934 * going back to an epoch time requires knowing the zone.
935 *
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.
c3fbf81a 939 */
44ccb337 940 while (strbuf_expand_step(&munged_fmt, &fmt)) {
945c7225 941 if (skip_prefix(fmt, "%", &fmt))
c3fbf81a 942 strbuf_addstr(&munged_fmt, "%%");
945c7225 943 else if (skip_prefix(fmt, "s", &fmt))
9b591b94
JK
944 strbuf_addf(&munged_fmt, "%"PRItime,
945 (timestamp_t)tm_to_time_t(tm) -
946 3600 * (tz_offset / 100) -
947 60 * (tz_offset % 100));
945c7225 948 else if (skip_prefix(fmt, "z", &fmt))
c3fbf81a 949 strbuf_addf(&munged_fmt, "%+05d", tz_offset);
945c7225
RS
950 else if (suppress_tz_name && skip_prefix(fmt, "Z", &fmt))
951 ; /* nothing */
952 else
c3fbf81a 953 strbuf_addch(&munged_fmt, '%');
c3fbf81a
RS
954 }
955 fmt = munged_fmt.buf;
956
e4f031e3 957 strbuf_grow(sb, hint);
aa1462cc
JK
958 len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
959
960 if (!len) {
961 /*
e4f031e3
JK
962 * strftime reports "0" if it could not fit the result in the buffer.
963 * Unfortunately, it also reports "0" if the requested time string
964 * takes 0 bytes. So our strategy is to munge the format so that the
965 * output contains at least one character, and then drop the extra
966 * character before returning.
aa1462cc 967 */
c3fbf81a 968 strbuf_addch(&munged_fmt, ' ');
e4f031e3
JK
969 while (!len) {
970 hint *= 2;
971 strbuf_grow(sb, hint);
972 len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
973 munged_fmt.buf, tm);
974 }
e4f031e3 975 len--; /* drop munged space */
aa1462cc 976 }
c3fbf81a 977 strbuf_release(&munged_fmt);
e4f031e3 978 strbuf_setlen(sb, sb->len + len);
aa1462cc 979}
af49c6d0 980
63af4a84
TK
981/*
982 * Returns the length of a line, without trailing spaces.
983 *
984 * If the line ends with newline, it will be removed too.
985 */
986static size_t cleanup(char *line, size_t len)
987{
988 while (len) {
989 unsigned char c = line[len - 1];
990 if (!isspace(c))
991 break;
992 len--;
993 }
994
995 return len;
996}
997
998/*
999 * Remove empty lines from the beginning and end
1000 * and also trailing spaces from every line.
1001 *
1002 * Turn multiple consecutive empty lines between paragraphs
1003 * into just one empty line.
1004 *
1005 * If the input has only empty lines and spaces,
1006 * no output will be produced.
1007 *
1008 * If last line does not have a newline at the end, one is added.
1009 *
2982b656 1010 * Pass a non-NULL comment_prefix to skip every line starting
787cb8a4 1011 * with it.
63af4a84 1012 */
2982b656 1013void strbuf_stripspace(struct strbuf *sb, const char *comment_prefix)
63af4a84 1014{
26114c00 1015 size_t empties = 0;
63af4a84
TK
1016 size_t i, j, len, newlen;
1017 char *eol;
1018
1019 /* We may have to add a newline. */
1020 strbuf_grow(sb, 1);
1021
1022 for (i = j = 0; i < sb->len; i += len, j += newlen) {
1023 eol = memchr(sb->buf + i, '\n', sb->len - i);
1024 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
1025
2786d058 1026 if (comment_prefix && len &&
2982b656 1027 starts_with(sb->buf + i, comment_prefix)) {
63af4a84
TK
1028 newlen = 0;
1029 continue;
1030 }
1031 newlen = cleanup(sb->buf + i, len);
1032
1033 /* Not just an empty line? */
1034 if (newlen) {
1035 if (empties > 0 && j > 0)
1036 sb->buf[j++] = '\n';
1037 empties = 0;
1038 memmove(sb->buf + j, sb->buf + i, newlen);
1039 sb->buf[newlen + j++] = '\n';
1040 } else {
1041 empties++;
1042 }
1043 }
1044
1045 strbuf_setlen(sb, j);
1046}
670c359d 1047
9ea57964
DS
1048void strbuf_strip_file_from_path(struct strbuf *sb)
1049{
1050 char *path_sep = find_last_dir_sep(sb->buf);
1051 strbuf_setlen(sb, path_sep ? path_sep - sb->buf + 1 : 0);
1052}