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