3 #include "string-list.h"
6 int starts_with(const char *str, const char *prefix)
8 for (; ; str++, prefix++)
11 else if (*str != *prefix)
15 int skip_to_optional_arg_default(const char *str, const char *prefix,
16 const char **arg, const char *def)
20 if (!skip_prefix(str, prefix, &p))
38 * Used as the default ->buf value, so that people can always assume
39 * buf is non NULL and ->buf is NUL terminated even for a freshly
42 char strbuf_slopbuf[1];
44 void strbuf_init(struct strbuf *sb, size_t hint)
46 sb->alloc = sb->len = 0;
47 sb->buf = strbuf_slopbuf;
49 strbuf_grow(sb, hint);
52 void strbuf_release(struct strbuf *sb)
60 char *strbuf_detach(struct strbuf *sb, size_t *sz)
71 void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
78 sb->buf[sb->len] = '\0';
81 void strbuf_grow(struct strbuf *sb, size_t extra)
83 int new_buf = !sb->alloc;
84 if (unsigned_add_overflows(extra, 1) ||
85 unsigned_add_overflows(sb->len, extra + 1))
86 die("you want to use way too much memory");
89 ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
94 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_ltrim(struct strbuf *sb)
109 while (sb->len > 0 && isspace(*b)) {
113 memmove(sb->buf, b, sb->len);
114 sb->buf[sb->len] = '\0';
117 int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)
122 if (same_encoding(from, to))
125 out = reencode_string_len(sb->buf, sb->len, to, from, &len);
129 strbuf_attach(sb, out, len, len);
133 void strbuf_tolower(struct strbuf *sb)
135 char *p = sb->buf, *end = sb->buf + sb->len;
140 struct strbuf **strbuf_split_buf(const char *str, size_t slen,
141 int terminator, int max)
143 struct strbuf **ret = NULL;
144 size_t nr = 0, alloc = 0;
149 if (max <= 0 || nr + 1 < max) {
150 const char *end = memchr(str, terminator, slen);
154 t = xmalloc(sizeof(struct strbuf));
156 strbuf_add(t, str, len);
157 ALLOC_GROW(ret, nr + 2, alloc);
162 ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
167 void strbuf_add_separated_string_list(struct strbuf *str,
169 struct string_list *slist)
171 struct string_list_item *item;
174 for_each_string_list_item(item, slist) {
176 strbuf_addstr(str, sep);
177 strbuf_addstr(str, item->string);
182 void strbuf_list_free(struct strbuf **sbs)
184 struct strbuf **s = sbs;
193 int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
195 int len = a->len < b->len ? a->len: b->len;
196 int cmp = memcmp(a->buf, b->buf, len);
199 return a->len < b->len ? -1: a->len != b->len;
202 void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
203 const void *data, size_t dlen)
205 if (unsigned_add_overflows(pos, len))
206 die("you want to use way too much memory");
208 die("`pos' is too far after the end of the buffer");
209 if (pos + len > sb->len)
210 die("`pos + len' is too far after the end of the buffer");
213 strbuf_grow(sb, dlen - len);
214 memmove(sb->buf + pos + dlen,
216 sb->len - pos - len);
217 memcpy(sb->buf + pos, data, dlen);
218 strbuf_setlen(sb, sb->len + dlen - len);
221 void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
223 strbuf_splice(sb, pos, 0, data, len);
226 void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
228 strbuf_splice(sb, pos, len, "", 0);
231 void strbuf_add(struct strbuf *sb, const void *data, size_t len)
233 strbuf_grow(sb, len);
234 memcpy(sb->buf + sb->len, data, len);
235 strbuf_setlen(sb, sb->len + len);
238 void strbuf_addbuf(struct strbuf *sb, const struct strbuf *sb2)
240 strbuf_grow(sb, sb2->len);
241 memcpy(sb->buf + sb->len, sb2->buf, sb2->len);
242 strbuf_setlen(sb, sb->len + sb2->len);
245 void strbuf_addchars(struct strbuf *sb, int c, size_t n)
248 memset(sb->buf + sb->len, c, n);
249 strbuf_setlen(sb, sb->len + n);
252 void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
256 strbuf_vaddf(sb, fmt, ap);
260 static void add_lines(struct strbuf *out,
263 const char *buf, size_t size)
267 const char *next = memchr(buf, '\n', size);
268 next = next ? (next + 1) : (buf + size);
270 prefix = ((prefix2 && (buf[0] == '\n' || buf[0] == '\t'))
271 ? prefix2 : prefix1);
272 strbuf_addstr(out, prefix);
273 strbuf_add(out, buf, next - buf);
277 strbuf_complete_line(out);
280 void strbuf_add_commented_lines(struct strbuf *out, const char *buf, size_t size)
282 static char prefix1[3];
283 static char prefix2[2];
285 if (prefix1[0] != comment_line_char) {
286 xsnprintf(prefix1, sizeof(prefix1), "%c ", comment_line_char);
287 xsnprintf(prefix2, sizeof(prefix2), "%c", comment_line_char);
289 add_lines(out, prefix1, prefix2, buf, size);
292 void strbuf_commented_addf(struct strbuf *sb, const char *fmt, ...)
295 struct strbuf buf = STRBUF_INIT;
296 int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';
298 va_start(params, fmt);
299 strbuf_vaddf(&buf, fmt, params);
302 strbuf_add_commented_lines(sb, buf.buf, buf.len);
304 sb->buf[--sb->len] = '\0';
306 strbuf_release(&buf);
309 void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
314 if (!strbuf_avail(sb))
317 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
320 die("BUG: your vsnprintf is broken (returned %d)", len);
321 if (len > strbuf_avail(sb)) {
322 strbuf_grow(sb, len);
323 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
324 if (len > strbuf_avail(sb))
325 die("BUG: your vsnprintf is broken (insatiable)");
327 strbuf_setlen(sb, sb->len + len);
330 void strbuf_expand(struct strbuf *sb, const char *format, expand_fn_t fn,
337 percent = strchrnul(format, '%');
338 strbuf_add(sb, format, percent - format);
341 format = percent + 1;
343 if (*format == '%') {
344 strbuf_addch(sb, '%');
349 consumed = fn(sb, format, context);
353 strbuf_addch(sb, '%');
357 size_t strbuf_expand_dict_cb(struct strbuf *sb, const char *placeholder,
360 struct strbuf_expand_dict_entry *e = context;
363 for (; e->placeholder && (len = strlen(e->placeholder)); e++) {
364 if (!strncmp(placeholder, e->placeholder, len)) {
366 strbuf_addstr(sb, e->value);
373 void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
375 int i, len = src->len;
377 for (i = 0; i < len; i++) {
378 if (src->buf[i] == '%')
379 strbuf_addch(dst, '%');
380 strbuf_addch(dst, src->buf[i]);
384 size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
387 size_t oldalloc = sb->alloc;
389 strbuf_grow(sb, size);
390 res = fread(sb->buf + sb->len, 1, size, f);
392 strbuf_setlen(sb, sb->len + res);
393 else if (oldalloc == 0)
398 ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
400 size_t oldlen = sb->len;
401 size_t oldalloc = sb->alloc;
403 strbuf_grow(sb, hint ? hint : 8192);
405 ssize_t want = sb->alloc - sb->len - 1;
406 ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
412 strbuf_setlen(sb, oldlen);
418 strbuf_grow(sb, 8192);
421 sb->buf[sb->len] = '\0';
422 return sb->len - oldlen;
425 ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
427 size_t oldalloc = sb->alloc;
430 strbuf_grow(sb, hint ? hint : 8192);
431 cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
433 strbuf_setlen(sb, sb->len + cnt);
434 else if (oldalloc == 0)
439 ssize_t strbuf_write(struct strbuf *sb, FILE *f)
441 return sb->len ? fwrite(sb->buf, 1, sb->len, f) : 0;
445 #define STRBUF_MAXLINK (2*PATH_MAX)
447 int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
449 size_t oldalloc = sb->alloc;
454 while (hint < STRBUF_MAXLINK) {
457 strbuf_grow(sb, hint);
458 len = readlink(path, sb->buf, hint);
462 } else if (len < hint) {
463 strbuf_setlen(sb, len);
467 /* .. the buffer was too small - try again */
475 int strbuf_getcwd(struct strbuf *sb)
477 size_t oldalloc = sb->alloc;
478 size_t guessed_len = 128;
480 for (;; guessed_len *= 2) {
481 strbuf_grow(sb, guessed_len);
482 if (getcwd(sb->buf, sb->alloc)) {
483 strbuf_setlen(sb, strlen(sb->buf));
488 * If getcwd(3) is implemented as a syscall that falls
489 * back to a regular lookup using readdir(3) etc. then
490 * we may be able to avoid EACCES by providing enough
491 * space to the syscall as it's not necessarily bound
492 * to the same restrictions as the fallback.
494 if (errno == EACCES && guessed_len < PATH_MAX)
508 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
517 /* Translate slopbuf to NULL, as we cannot call realloc on it */
521 r = getdelim(&sb->buf, &sb->alloc, term, fp);
530 * Normally we would have called xrealloc, which will try to free
531 * memory and recover. But we have no way to tell getdelim() to do so.
532 * Worse, we cannot try to recover ENOMEM ourselves, because we have
533 * no idea how many bytes were read by getdelim.
535 * Dying here is reasonable. It mirrors what xrealloc would do on
536 * catastrophic memory failure. We skip the opportunity to free pack
537 * memory and retry, but that's unlikely to help for a malloc small
538 * enough to hold a single line of input, anyway.
541 die("Out of memory, getdelim failed");
544 * Restore strbuf invariants; if getdelim left us with a NULL pointer,
545 * we can just re-init, but otherwise we should make sure that our
546 * length is empty, and that the result is NUL-terminated.
555 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
564 while ((ch = getc_unlocked(fp)) != EOF) {
565 if (!strbuf_avail(sb))
567 sb->buf[sb->len++] = ch;
572 if (ch == EOF && sb->len == 0)
575 sb->buf[sb->len] = '\0';
580 static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)
582 if (strbuf_getwholeline(sb, fp, term))
584 if (sb->buf[sb->len - 1] == term)
585 strbuf_setlen(sb, sb->len - 1);
589 int strbuf_getline(struct strbuf *sb, FILE *fp)
591 if (strbuf_getwholeline(sb, fp, '\n'))
593 if (sb->buf[sb->len - 1] == '\n') {
594 strbuf_setlen(sb, sb->len - 1);
595 if (sb->len && sb->buf[sb->len - 1] == '\r')
596 strbuf_setlen(sb, sb->len - 1);
601 int strbuf_getline_lf(struct strbuf *sb, FILE *fp)
603 return strbuf_getdelim(sb, fp, '\n');
606 int strbuf_getline_nul(struct strbuf *sb, FILE *fp)
608 return strbuf_getdelim(sb, fp, '\0');
611 int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
617 ssize_t len = xread(fd, &ch, 1);
620 strbuf_addch(sb, ch);
627 ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
632 fd = open(path, O_RDONLY);
635 len = strbuf_read(sb, fd, hint);
643 void strbuf_add_lines(struct strbuf *out, const char *prefix,
644 const char *buf, size_t size)
646 add_lines(out, prefix, NULL, buf, size);
649 void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
652 size_t len = strcspn(s, "\"<>&");
653 strbuf_add(buf, s, len);
657 strbuf_addstr(buf, """);
660 strbuf_addstr(buf, "<");
663 strbuf_addstr(buf, ">");
666 strbuf_addstr(buf, "&");
675 static int is_rfc3986_reserved(char ch)
678 case '!': case '*': case '\'': case '(': case ')': case ';':
679 case ':': case '@': case '&': case '=': case '+': case '$':
680 case ',': case '/': case '?': case '#': case '[': case ']':
686 static int is_rfc3986_unreserved(char ch)
688 return isalnum(ch) ||
689 ch == '-' || ch == '_' || ch == '.' || ch == '~';
692 static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
695 strbuf_grow(sb, len);
698 if (is_rfc3986_unreserved(ch) ||
699 (!reserved && is_rfc3986_reserved(ch)))
700 strbuf_addch(sb, ch);
702 strbuf_addf(sb, "%%%02x", (unsigned char)ch);
706 void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
709 strbuf_add_urlencode(sb, s, strlen(s), reserved);
712 void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
714 if (bytes > 1 << 30) {
715 strbuf_addf(buf, "%u.%2.2u GiB",
717 (int)(bytes & ((1 << 30) - 1)) / 10737419);
718 } else if (bytes > 1 << 20) {
719 int x = bytes + 5243; /* for rounding */
720 strbuf_addf(buf, "%u.%2.2u MiB",
721 x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
722 } else if (bytes > 1 << 10) {
723 int x = bytes + 5; /* for rounding */
724 strbuf_addf(buf, "%u.%2.2u KiB",
725 x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
727 strbuf_addf(buf, "%u bytes", (int)bytes);
731 void strbuf_add_absolute_path(struct strbuf *sb, const char *path)
734 die("The empty string is not a valid path");
735 if (!is_absolute_path(path)) {
736 struct stat cwd_stat, pwd_stat;
737 size_t orig_len = sb->len;
738 char *cwd = xgetcwd();
739 char *pwd = getenv("PWD");
740 if (pwd && strcmp(pwd, cwd) &&
741 !stat(cwd, &cwd_stat) &&
742 (cwd_stat.st_dev || cwd_stat.st_ino) &&
743 !stat(pwd, &pwd_stat) &&
744 pwd_stat.st_dev == cwd_stat.st_dev &&
745 pwd_stat.st_ino == cwd_stat.st_ino)
746 strbuf_addstr(sb, pwd);
748 strbuf_addstr(sb, cwd);
749 if (sb->len > orig_len && !is_dir_sep(sb->buf[sb->len - 1]))
750 strbuf_addch(sb, '/');
753 strbuf_addstr(sb, path);
756 void strbuf_add_real_path(struct strbuf *sb, const char *path)
759 struct strbuf resolved = STRBUF_INIT;
760 strbuf_realpath(&resolved, path, 1);
761 strbuf_addbuf(sb, &resolved);
762 strbuf_release(&resolved);
764 strbuf_realpath(sb, path, 1);
767 int printf_ln(const char *fmt, ...)
772 ret = vprintf(fmt, ap);
774 if (ret < 0 || putchar('\n') == EOF)
779 int fprintf_ln(FILE *fp, const char *fmt, ...)
784 ret = vfprintf(fp, fmt, ap);
786 if (ret < 0 || putc('\n', fp) == EOF)
791 char *xstrdup_tolower(const char *string)
796 len = strlen(string);
797 result = xmallocz(len);
798 for (i = 0; i < len; i++)
799 result[i] = tolower(string[i]);
804 char *xstrvfmt(const char *fmt, va_list ap)
806 struct strbuf buf = STRBUF_INIT;
807 strbuf_vaddf(&buf, fmt, ap);
808 return strbuf_detach(&buf, NULL);
811 char *xstrfmt(const char *fmt, ...)
817 ret = xstrvfmt(fmt, ap);
823 void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
824 int tz_offset, int suppress_tz_name)
826 struct strbuf munged_fmt = STRBUF_INIT;
834 * There is no portable way to pass timezone information to
835 * strftime, so we handle %z and %Z here.
838 const char *percent = strchrnul(fmt, '%');
839 strbuf_add(&munged_fmt, fmt, percent - fmt);
845 strbuf_addstr(&munged_fmt, "%%");
849 strbuf_addf(&munged_fmt, "%+05d", tz_offset);
853 if (suppress_tz_name) {
859 strbuf_addch(&munged_fmt, '%');
862 fmt = munged_fmt.buf;
864 strbuf_grow(sb, hint);
865 len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
869 * strftime reports "0" if it could not fit the result in the buffer.
870 * Unfortunately, it also reports "0" if the requested time string
871 * takes 0 bytes. So our strategy is to munge the format so that the
872 * output contains at least one character, and then drop the extra
873 * character before returning.
875 strbuf_addch(&munged_fmt, ' ');
878 strbuf_grow(sb, hint);
879 len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
882 len--; /* drop munged space */
884 strbuf_release(&munged_fmt);
885 strbuf_setlen(sb, sb->len + len);
888 void strbuf_add_unique_abbrev(struct strbuf *sb, const unsigned char *sha1,
892 strbuf_grow(sb, GIT_SHA1_HEXSZ + 1);
893 r = find_unique_abbrev_r(sb->buf + sb->len, sha1, abbrev_len);
894 strbuf_setlen(sb, sb->len + r);
898 * Returns the length of a line, without trailing spaces.
900 * If the line ends with newline, it will be removed too.
902 static size_t cleanup(char *line, size_t len)
905 unsigned char c = line[len - 1];
915 * Remove empty lines from the beginning and end
916 * and also trailing spaces from every line.
918 * Turn multiple consecutive empty lines between paragraphs
919 * into just one empty line.
921 * If the input has only empty lines and spaces,
922 * no output will be produced.
924 * If last line does not have a newline at the end, one is added.
926 * Enable skip_comments to skip every line starting with comment
929 void strbuf_stripspace(struct strbuf *sb, int skip_comments)
932 size_t i, j, len, newlen;
935 /* We may have to add a newline. */
938 for (i = j = 0; i < sb->len; i += len, j += newlen) {
939 eol = memchr(sb->buf + i, '\n', sb->len - i);
940 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
942 if (skip_comments && len && sb->buf[i] == comment_line_char) {
946 newlen = cleanup(sb->buf + i, len);
948 /* Not just an empty line? */
950 if (empties > 0 && j > 0)
953 memmove(sb->buf + j, sb->buf + i, newlen);
954 sb->buf[newlen + j++] = '\n';
960 strbuf_setlen(sb, j);
963 int strbuf_normalize_path(struct strbuf *src)
965 struct strbuf dst = STRBUF_INIT;
967 strbuf_grow(&dst, src->len);
968 if (normalize_path_copy(dst.buf, src->buf) < 0) {
969 strbuf_release(&dst);
974 * normalize_path does not tell us the new length, so we have to
975 * compute it by looking for the new NUL it placed
977 strbuf_setlen(&dst, strlen(dst.buf));
978 strbuf_swap(src, &dst);
979 strbuf_release(&dst);