5 int starts_with(const char *str
, const char *prefix
)
7 for (; ; str
++, prefix
++)
10 else if (*str
!= *prefix
)
14 int skip_to_optional_arg_default(const char *str
, const char *prefix
,
15 const char **arg
, const char *def
)
19 if (!skip_prefix(str
, prefix
, &p
))
37 * Used as the default ->buf value, so that people can always assume
38 * buf is non NULL and ->buf is NUL terminated even for a freshly
41 char strbuf_slopbuf
[1];
43 void strbuf_init(struct strbuf
*sb
, size_t hint
)
45 sb
->alloc
= sb
->len
= 0;
46 sb
->buf
= strbuf_slopbuf
;
48 strbuf_grow(sb
, hint
);
51 void strbuf_release(struct strbuf
*sb
)
59 char *strbuf_detach(struct strbuf
*sb
, size_t *sz
)
70 void strbuf_attach(struct strbuf
*sb
, void *buf
, size_t len
, size_t alloc
)
77 sb
->buf
[sb
->len
] = '\0';
80 void strbuf_grow(struct strbuf
*sb
, size_t extra
)
82 int new_buf
= !sb
->alloc
;
83 if (unsigned_add_overflows(extra
, 1) ||
84 unsigned_add_overflows(sb
->len
, extra
+ 1))
85 die("you want to use way too much memory");
88 ALLOC_GROW(sb
->buf
, sb
->len
+ extra
+ 1, sb
->alloc
);
93 void strbuf_trim(struct strbuf
*sb
)
99 void strbuf_rtrim(struct strbuf
*sb
)
101 while (sb
->len
> 0 && isspace((unsigned char)sb
->buf
[sb
->len
- 1]))
103 sb
->buf
[sb
->len
] = '\0';
106 void strbuf_trim_trailing_dir_sep(struct strbuf
*sb
)
108 while (sb
->len
> 0 && is_dir_sep((unsigned char)sb
->buf
[sb
->len
- 1]))
110 sb
->buf
[sb
->len
] = '\0';
113 void strbuf_ltrim(struct strbuf
*sb
)
116 while (sb
->len
> 0 && isspace(*b
)) {
120 memmove(sb
->buf
, b
, sb
->len
);
121 sb
->buf
[sb
->len
] = '\0';
124 int strbuf_reencode(struct strbuf
*sb
, const char *from
, const char *to
)
129 if (same_encoding(from
, to
))
132 out
= reencode_string_len(sb
->buf
, sb
->len
, to
, from
, &len
);
136 strbuf_attach(sb
, out
, len
, len
);
140 void strbuf_tolower(struct strbuf
*sb
)
142 char *p
= sb
->buf
, *end
= sb
->buf
+ sb
->len
;
147 struct strbuf
**strbuf_split_buf(const char *str
, size_t slen
,
148 int terminator
, int max
)
150 struct strbuf
**ret
= NULL
;
151 size_t nr
= 0, alloc
= 0;
156 if (max
<= 0 || nr
+ 1 < max
) {
157 const char *end
= memchr(str
, terminator
, slen
);
161 t
= xmalloc(sizeof(struct strbuf
));
163 strbuf_add(t
, str
, len
);
164 ALLOC_GROW(ret
, nr
+ 2, alloc
);
169 ALLOC_GROW(ret
, nr
+ 1, alloc
); /* In case string was empty */
174 void strbuf_list_free(struct strbuf
**sbs
)
176 struct strbuf
**s
= sbs
;
185 int strbuf_cmp(const struct strbuf
*a
, const struct strbuf
*b
)
187 int len
= a
->len
< b
->len
? a
->len
: b
->len
;
188 int cmp
= memcmp(a
->buf
, b
->buf
, len
);
191 return a
->len
< b
->len
? -1: a
->len
!= b
->len
;
194 void strbuf_splice(struct strbuf
*sb
, size_t pos
, size_t len
,
195 const void *data
, size_t dlen
)
197 if (unsigned_add_overflows(pos
, len
))
198 die("you want to use way too much memory");
200 die("`pos' is too far after the end of the buffer");
201 if (pos
+ len
> sb
->len
)
202 die("`pos + len' is too far after the end of the buffer");
205 strbuf_grow(sb
, dlen
- len
);
206 memmove(sb
->buf
+ pos
+ dlen
,
208 sb
->len
- pos
- len
);
209 memcpy(sb
->buf
+ pos
, data
, dlen
);
210 strbuf_setlen(sb
, sb
->len
+ dlen
- len
);
213 void strbuf_insert(struct strbuf
*sb
, size_t pos
, const void *data
, size_t len
)
215 strbuf_splice(sb
, pos
, 0, data
, len
);
218 void strbuf_remove(struct strbuf
*sb
, size_t pos
, size_t len
)
220 strbuf_splice(sb
, pos
, len
, "", 0);
223 void strbuf_add(struct strbuf
*sb
, const void *data
, size_t len
)
225 strbuf_grow(sb
, len
);
226 memcpy(sb
->buf
+ sb
->len
, data
, len
);
227 strbuf_setlen(sb
, sb
->len
+ len
);
230 void strbuf_addbuf(struct strbuf
*sb
, const struct strbuf
*sb2
)
232 strbuf_grow(sb
, sb2
->len
);
233 memcpy(sb
->buf
+ sb
->len
, sb2
->buf
, sb2
->len
);
234 strbuf_setlen(sb
, sb
->len
+ sb2
->len
);
237 void strbuf_addchars(struct strbuf
*sb
, int c
, size_t n
)
240 memset(sb
->buf
+ sb
->len
, c
, n
);
241 strbuf_setlen(sb
, sb
->len
+ n
);
244 void strbuf_addf(struct strbuf
*sb
, const char *fmt
, ...)
248 strbuf_vaddf(sb
, fmt
, ap
);
252 static void add_lines(struct strbuf
*out
,
255 const char *buf
, size_t size
)
259 const char *next
= memchr(buf
, '\n', size
);
260 next
= next
? (next
+ 1) : (buf
+ size
);
262 prefix
= ((prefix2
&& (buf
[0] == '\n' || buf
[0] == '\t'))
263 ? prefix2
: prefix1
);
264 strbuf_addstr(out
, prefix
);
265 strbuf_add(out
, buf
, next
- buf
);
269 strbuf_complete_line(out
);
272 void strbuf_add_commented_lines(struct strbuf
*out
, const char *buf
, size_t size
)
274 static char prefix1
[3];
275 static char prefix2
[2];
277 if (prefix1
[0] != comment_line_char
) {
278 xsnprintf(prefix1
, sizeof(prefix1
), "%c ", comment_line_char
);
279 xsnprintf(prefix2
, sizeof(prefix2
), "%c", comment_line_char
);
281 add_lines(out
, prefix1
, prefix2
, buf
, size
);
284 void strbuf_commented_addf(struct strbuf
*sb
, const char *fmt
, ...)
287 struct strbuf buf
= STRBUF_INIT
;
288 int incomplete_line
= sb
->len
&& sb
->buf
[sb
->len
- 1] != '\n';
290 va_start(params
, fmt
);
291 strbuf_vaddf(&buf
, fmt
, params
);
294 strbuf_add_commented_lines(sb
, buf
.buf
, buf
.len
);
296 sb
->buf
[--sb
->len
] = '\0';
298 strbuf_release(&buf
);
301 void strbuf_vaddf(struct strbuf
*sb
, const char *fmt
, va_list ap
)
306 if (!strbuf_avail(sb
))
309 len
= vsnprintf(sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
, fmt
, cp
);
312 die("BUG: your vsnprintf is broken (returned %d)", len
);
313 if (len
> strbuf_avail(sb
)) {
314 strbuf_grow(sb
, len
);
315 len
= vsnprintf(sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
, fmt
, ap
);
316 if (len
> strbuf_avail(sb
))
317 die("BUG: your vsnprintf is broken (insatiable)");
319 strbuf_setlen(sb
, sb
->len
+ len
);
322 void strbuf_expand(struct strbuf
*sb
, const char *format
, expand_fn_t fn
,
329 percent
= strchrnul(format
, '%');
330 strbuf_add(sb
, format
, percent
- format
);
333 format
= percent
+ 1;
335 if (*format
== '%') {
336 strbuf_addch(sb
, '%');
341 consumed
= fn(sb
, format
, context
);
345 strbuf_addch(sb
, '%');
349 size_t strbuf_expand_dict_cb(struct strbuf
*sb
, const char *placeholder
,
352 struct strbuf_expand_dict_entry
*e
= context
;
355 for (; e
->placeholder
&& (len
= strlen(e
->placeholder
)); e
++) {
356 if (!strncmp(placeholder
, e
->placeholder
, len
)) {
358 strbuf_addstr(sb
, e
->value
);
365 void strbuf_addbuf_percentquote(struct strbuf
*dst
, const struct strbuf
*src
)
367 int i
, len
= src
->len
;
369 for (i
= 0; i
< len
; i
++) {
370 if (src
->buf
[i
] == '%')
371 strbuf_addch(dst
, '%');
372 strbuf_addch(dst
, src
->buf
[i
]);
376 size_t strbuf_fread(struct strbuf
*sb
, size_t size
, FILE *f
)
379 size_t oldalloc
= sb
->alloc
;
381 strbuf_grow(sb
, size
);
382 res
= fread(sb
->buf
+ sb
->len
, 1, size
, f
);
384 strbuf_setlen(sb
, sb
->len
+ res
);
385 else if (oldalloc
== 0)
390 ssize_t
strbuf_read(struct strbuf
*sb
, int fd
, size_t hint
)
392 size_t oldlen
= sb
->len
;
393 size_t oldalloc
= sb
->alloc
;
395 strbuf_grow(sb
, hint
? hint
: 8192);
397 ssize_t want
= sb
->alloc
- sb
->len
- 1;
398 ssize_t got
= read_in_full(fd
, sb
->buf
+ sb
->len
, want
);
404 strbuf_setlen(sb
, oldlen
);
410 strbuf_grow(sb
, 8192);
413 sb
->buf
[sb
->len
] = '\0';
414 return sb
->len
- oldlen
;
417 ssize_t
strbuf_read_once(struct strbuf
*sb
, int fd
, size_t hint
)
419 size_t oldalloc
= sb
->alloc
;
422 strbuf_grow(sb
, hint
? hint
: 8192);
423 cnt
= xread(fd
, sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
- 1);
425 strbuf_setlen(sb
, sb
->len
+ cnt
);
426 else if (oldalloc
== 0)
431 ssize_t
strbuf_write(struct strbuf
*sb
, FILE *f
)
433 return sb
->len
? fwrite(sb
->buf
, 1, sb
->len
, f
) : 0;
437 #define STRBUF_MAXLINK (2*PATH_MAX)
439 int strbuf_readlink(struct strbuf
*sb
, const char *path
, size_t hint
)
441 size_t oldalloc
= sb
->alloc
;
446 while (hint
< STRBUF_MAXLINK
) {
449 strbuf_grow(sb
, hint
);
450 len
= readlink(path
, sb
->buf
, hint
);
454 } else if (len
< hint
) {
455 strbuf_setlen(sb
, len
);
459 /* .. the buffer was too small - try again */
467 int strbuf_getcwd(struct strbuf
*sb
)
469 size_t oldalloc
= sb
->alloc
;
470 size_t guessed_len
= 128;
472 for (;; guessed_len
*= 2) {
473 strbuf_grow(sb
, guessed_len
);
474 if (getcwd(sb
->buf
, sb
->alloc
)) {
475 strbuf_setlen(sb
, strlen(sb
->buf
));
480 * If getcwd(3) is implemented as a syscall that falls
481 * back to a regular lookup using readdir(3) etc. then
482 * we may be able to avoid EACCES by providing enough
483 * space to the syscall as it's not necessarily bound
484 * to the same restrictions as the fallback.
486 if (errno
== EACCES
&& guessed_len
< PATH_MAX
)
500 int strbuf_getwholeline(struct strbuf
*sb
, FILE *fp
, int term
)
509 /* Translate slopbuf to NULL, as we cannot call realloc on it */
513 r
= getdelim(&sb
->buf
, &sb
->alloc
, term
, fp
);
522 * Normally we would have called xrealloc, which will try to free
523 * memory and recover. But we have no way to tell getdelim() to do so.
524 * Worse, we cannot try to recover ENOMEM ourselves, because we have
525 * no idea how many bytes were read by getdelim.
527 * Dying here is reasonable. It mirrors what xrealloc would do on
528 * catastrophic memory failure. We skip the opportunity to free pack
529 * memory and retry, but that's unlikely to help for a malloc small
530 * enough to hold a single line of input, anyway.
533 die("Out of memory, getdelim failed");
536 * Restore strbuf invariants; if getdelim left us with a NULL pointer,
537 * we can just re-init, but otherwise we should make sure that our
538 * length is empty, and that the result is NUL-terminated.
547 int strbuf_getwholeline(struct strbuf
*sb
, FILE *fp
, int term
)
556 while ((ch
= getc_unlocked(fp
)) != EOF
) {
557 if (!strbuf_avail(sb
))
559 sb
->buf
[sb
->len
++] = ch
;
564 if (ch
== EOF
&& sb
->len
== 0)
567 sb
->buf
[sb
->len
] = '\0';
572 static int strbuf_getdelim(struct strbuf
*sb
, FILE *fp
, int term
)
574 if (strbuf_getwholeline(sb
, fp
, term
))
576 if (sb
->buf
[sb
->len
- 1] == term
)
577 strbuf_setlen(sb
, sb
->len
- 1);
581 int strbuf_getline(struct strbuf
*sb
, FILE *fp
)
583 if (strbuf_getwholeline(sb
, fp
, '\n'))
585 if (sb
->buf
[sb
->len
- 1] == '\n') {
586 strbuf_setlen(sb
, sb
->len
- 1);
587 if (sb
->len
&& sb
->buf
[sb
->len
- 1] == '\r')
588 strbuf_setlen(sb
, sb
->len
- 1);
593 int strbuf_getline_lf(struct strbuf
*sb
, FILE *fp
)
595 return strbuf_getdelim(sb
, fp
, '\n');
598 int strbuf_getline_nul(struct strbuf
*sb
, FILE *fp
)
600 return strbuf_getdelim(sb
, fp
, '\0');
603 int strbuf_getwholeline_fd(struct strbuf
*sb
, int fd
, int term
)
609 ssize_t len
= xread(fd
, &ch
, 1);
612 strbuf_addch(sb
, ch
);
619 ssize_t
strbuf_read_file(struct strbuf
*sb
, const char *path
, size_t hint
)
625 fd
= open(path
, O_RDONLY
);
628 len
= strbuf_read(sb
, fd
, hint
);
639 void strbuf_add_lines(struct strbuf
*out
, const char *prefix
,
640 const char *buf
, size_t size
)
642 add_lines(out
, prefix
, NULL
, buf
, size
);
645 void strbuf_addstr_xml_quoted(struct strbuf
*buf
, const char *s
)
648 size_t len
= strcspn(s
, "\"<>&");
649 strbuf_add(buf
, s
, len
);
653 strbuf_addstr(buf
, """);
656 strbuf_addstr(buf
, "<");
659 strbuf_addstr(buf
, ">");
662 strbuf_addstr(buf
, "&");
671 static int is_rfc3986_reserved(char ch
)
674 case '!': case '*': case '\'': case '(': case ')': case ';':
675 case ':': case '@': case '&': case '=': case '+': case '$':
676 case ',': case '/': case '?': case '#': case '[': case ']':
682 static int is_rfc3986_unreserved(char ch
)
684 return isalnum(ch
) ||
685 ch
== '-' || ch
== '_' || ch
== '.' || ch
== '~';
688 static void strbuf_add_urlencode(struct strbuf
*sb
, const char *s
, size_t len
,
691 strbuf_grow(sb
, len
);
694 if (is_rfc3986_unreserved(ch
) ||
695 (!reserved
&& is_rfc3986_reserved(ch
)))
696 strbuf_addch(sb
, ch
);
698 strbuf_addf(sb
, "%%%02x", (unsigned char)ch
);
702 void strbuf_addstr_urlencode(struct strbuf
*sb
, const char *s
,
705 strbuf_add_urlencode(sb
, s
, strlen(s
), reserved
);
708 void strbuf_humanise_bytes(struct strbuf
*buf
, off_t bytes
)
710 if (bytes
> 1 << 30) {
711 strbuf_addf(buf
, "%u.%2.2u GiB",
713 (int)(bytes
& ((1 << 30) - 1)) / 10737419);
714 } else if (bytes
> 1 << 20) {
715 int x
= bytes
+ 5243; /* for rounding */
716 strbuf_addf(buf
, "%u.%2.2u MiB",
717 x
>> 20, ((x
& ((1 << 20) - 1)) * 100) >> 20);
718 } else if (bytes
> 1 << 10) {
719 int x
= bytes
+ 5; /* for rounding */
720 strbuf_addf(buf
, "%u.%2.2u KiB",
721 x
>> 10, ((x
& ((1 << 10) - 1)) * 100) >> 10);
723 strbuf_addf(buf
, "%u bytes", (int)bytes
);
727 void strbuf_add_absolute_path(struct strbuf
*sb
, const char *path
)
730 die("The empty string is not a valid path");
731 if (!is_absolute_path(path
)) {
732 struct stat cwd_stat
, pwd_stat
;
733 size_t orig_len
= sb
->len
;
734 char *cwd
= xgetcwd();
735 char *pwd
= getenv("PWD");
736 if (pwd
&& strcmp(pwd
, cwd
) &&
737 !stat(cwd
, &cwd_stat
) &&
738 (cwd_stat
.st_dev
|| cwd_stat
.st_ino
) &&
739 !stat(pwd
, &pwd_stat
) &&
740 pwd_stat
.st_dev
== cwd_stat
.st_dev
&&
741 pwd_stat
.st_ino
== cwd_stat
.st_ino
)
742 strbuf_addstr(sb
, pwd
);
744 strbuf_addstr(sb
, cwd
);
745 if (sb
->len
> orig_len
&& !is_dir_sep(sb
->buf
[sb
->len
- 1]))
746 strbuf_addch(sb
, '/');
749 strbuf_addstr(sb
, path
);
752 void strbuf_add_real_path(struct strbuf
*sb
, const char *path
)
755 struct strbuf resolved
= STRBUF_INIT
;
756 strbuf_realpath(&resolved
, path
, 1);
757 strbuf_addbuf(sb
, &resolved
);
758 strbuf_release(&resolved
);
760 strbuf_realpath(sb
, path
, 1);
763 int printf_ln(const char *fmt
, ...)
768 ret
= vprintf(fmt
, ap
);
770 if (ret
< 0 || putchar('\n') == EOF
)
775 int fprintf_ln(FILE *fp
, const char *fmt
, ...)
780 ret
= vfprintf(fp
, fmt
, ap
);
782 if (ret
< 0 || putc('\n', fp
) == EOF
)
787 char *xstrdup_tolower(const char *string
)
792 len
= strlen(string
);
793 result
= xmallocz(len
);
794 for (i
= 0; i
< len
; i
++)
795 result
[i
] = tolower(string
[i
]);
800 char *xstrvfmt(const char *fmt
, va_list ap
)
802 struct strbuf buf
= STRBUF_INIT
;
803 strbuf_vaddf(&buf
, fmt
, ap
);
804 return strbuf_detach(&buf
, NULL
);
807 char *xstrfmt(const char *fmt
, ...)
813 ret
= xstrvfmt(fmt
, ap
);
819 void strbuf_addftime(struct strbuf
*sb
, const char *fmt
, const struct tm
*tm
,
820 int tz_offset
, int suppress_tz_name
)
822 struct strbuf munged_fmt
= STRBUF_INIT
;
830 * There is no portable way to pass timezone information to
831 * strftime, so we handle %z and %Z here.
834 const char *percent
= strchrnul(fmt
, '%');
835 strbuf_add(&munged_fmt
, fmt
, percent
- fmt
);
841 strbuf_addstr(&munged_fmt
, "%%");
845 strbuf_addf(&munged_fmt
, "%+05d", tz_offset
);
849 if (suppress_tz_name
) {
855 strbuf_addch(&munged_fmt
, '%');
858 fmt
= munged_fmt
.buf
;
860 strbuf_grow(sb
, hint
);
861 len
= strftime(sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
, fmt
, tm
);
865 * strftime reports "0" if it could not fit the result in the buffer.
866 * Unfortunately, it also reports "0" if the requested time string
867 * takes 0 bytes. So our strategy is to munge the format so that the
868 * output contains at least one character, and then drop the extra
869 * character before returning.
871 strbuf_addch(&munged_fmt
, ' ');
874 strbuf_grow(sb
, hint
);
875 len
= strftime(sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
,
878 len
--; /* drop munged space */
880 strbuf_release(&munged_fmt
);
881 strbuf_setlen(sb
, sb
->len
+ len
);
884 void strbuf_add_unique_abbrev(struct strbuf
*sb
, const unsigned char *sha1
,
888 strbuf_grow(sb
, GIT_SHA1_HEXSZ
+ 1);
889 r
= find_unique_abbrev_r(sb
->buf
+ sb
->len
, sha1
, abbrev_len
);
890 strbuf_setlen(sb
, sb
->len
+ r
);
894 * Returns the length of a line, without trailing spaces.
896 * If the line ends with newline, it will be removed too.
898 static size_t cleanup(char *line
, size_t len
)
901 unsigned char c
= line
[len
- 1];
911 * Remove empty lines from the beginning and end
912 * and also trailing spaces from every line.
914 * Turn multiple consecutive empty lines between paragraphs
915 * into just one empty line.
917 * If the input has only empty lines and spaces,
918 * no output will be produced.
920 * If last line does not have a newline at the end, one is added.
922 * Enable skip_comments to skip every line starting with comment
925 void strbuf_stripspace(struct strbuf
*sb
, int skip_comments
)
928 size_t i
, j
, len
, newlen
;
931 /* We may have to add a newline. */
934 for (i
= j
= 0; i
< sb
->len
; i
+= len
, j
+= newlen
) {
935 eol
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
936 len
= eol
? eol
- (sb
->buf
+ i
) + 1 : sb
->len
- i
;
938 if (skip_comments
&& len
&& sb
->buf
[i
] == comment_line_char
) {
942 newlen
= cleanup(sb
->buf
+ i
, len
);
944 /* Not just an empty line? */
946 if (empties
> 0 && j
> 0)
949 memmove(sb
->buf
+ j
, sb
->buf
+ i
, newlen
);
950 sb
->buf
[newlen
+ j
++] = '\n';
956 strbuf_setlen(sb
, j
);
959 int strbuf_normalize_path(struct strbuf
*src
)
961 struct strbuf dst
= STRBUF_INIT
;
963 strbuf_grow(&dst
, src
->len
);
964 if (normalize_path_copy(dst
.buf
, src
->buf
) < 0) {
965 strbuf_release(&dst
);
970 * normalize_path does not tell us the new length, so we have to
971 * compute it by looking for the new NUL it placed
973 strbuf_setlen(&dst
, strlen(dst
.buf
));
974 strbuf_swap(src
, &dst
);
975 strbuf_release(&dst
);